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.

Submitted referrals (#3270)

Tim Wilson5fc6919292e2
diff --git a/apps/web/app/(ee)/api/admin/reset-login-attempts/route.ts b/apps/web/app/(ee)/api/admin/reset-login-attempts/route.ts
index aec41eecbf..3cf14a17fb 100644
--- a/apps/web/app/(ee)/api/admin/reset-login-attempts/route.ts
+++ b/apps/web/app/(ee)/api/admin/reset-login-attempts/route.ts
@@ -7,10 +7,7 @@ export const POST = withAdmin(async ({ req }) => {
const { email } = await req.json();
if (!email) {
- return NextResponse.json(
- { error: "Email is required" },
- { status: 400 },
- );
+ return NextResponse.json({ error: "Email is required" }, { status: 400 });
}
const user = await prisma.user.findUnique({
diff --git a/apps/web/app/(ee)/api/cron/aggregate-clicks/resolve-click-reward-amount.ts b/apps/web/app/(ee)/api/cron/aggregate-clicks/resolve-click-reward-amount.ts
index 8669aeb67c..79e76bda2f 100644
--- a/apps/web/app/(ee)/api/cron/aggregate-clicks/resolve-click-reward-amount.ts
+++ b/apps/web/app/(ee)/api/cron/aggregate-clicks/resolve-click-reward-amount.ts
@@ -23,6 +23,7 @@ export function resolveClickRewardAmount({
context: {
customer: {
country,
+ source: "tracked",
},
},
});
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..bb764946dc
--- /dev/null
+++ b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/referrals/count/route.ts
@@ -0,0 +1,70 @@
+import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
+import { withPartnerProfile } from "@/lib/auth/partner";
+import {
+ getPartnerReferralsCountQuerySchema,
+ partnerReferralsCountResponseSchema,
+} from "@/lib/zod/schemas/partner-profile";
+import { prisma, sanitizeFullTextSearch } from "@dub/prisma";
+import { Prisma, ReferralStatus } from "@dub/prisma/client";
+import { NextResponse } from "next/server";
+
+// GET /api/partner-profile/programs/[programId]/referrals/count - get the count of referrals for the current partner in a program
+export const GET = withPartnerProfile(
+ async ({ partner, params, searchParams }) => {
+ const { programId } = params;
+ const { status, search, groupBy } =
+ getPartnerReferralsCountQuerySchema.parse(searchParams);
+
+ const { program } = await getProgramEnrollmentOrThrow({
+ partnerId: partner.id,
+ programId: programId,
+ include: {
+ program: true,
+ },
+ });
+
+ const commonWhere: Prisma.PartnerReferralWhereInput = {
+ programId: program.id,
+ partnerId: partner.id,
+ ...(status && groupBy !== "status" && { status }),
+ ...(search
+ ? search.includes("@")
+ ? { email: search }
+ : {
+ email: { search: sanitizeFullTextSearch(search) },
+ name: { search: sanitizeFullTextSearch(search) },
+ }
+ : {}),
+ };
+
+ // Get referral count by status
+ if (groupBy === "status") {
+ const data = await prisma.partnerReferral.groupBy({
+ by: ["status"],
+ where: commonWhere,
+ _count: true,
+ orderBy: {
+ _count: {
+ status: "desc",
+ },
+ },
+ });
+
+ // Fill in missing statuses with zero counts
+ Object.values(ReferralStatus).forEach((status) => {
+ if (!data.some((d) => d.status === status)) {
+ data.push({ _count: 0, status });
+ }
+ });
+
+ return NextResponse.json(partnerReferralsCountResponseSchema.parse(data));
+ }
+
+ // Get referral count
+ const count = await prisma.partnerReferral.count({
+ where: commonWhere,
+ });
+
+ return NextResponse.json(partnerReferralsCountResponseSchema.parse(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..68a9dd62d9
--- /dev/null
+++ b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/referrals/route.ts
@@ -0,0 +1,51 @@
+import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
+import { withPartnerProfile } from "@/lib/auth/partner";
+import {
+ getPartnerReferralsQuerySchema,
+ partnerProfileReferralSchema,
+} from "@/lib/zod/schemas/partner-profile";
+import { prisma, sanitizeFullTextSearch } from "@dub/prisma";
+import { NextResponse } from "next/server";
+import * as z from "zod/v4";
+
+// GET /api/partner-profile/programs/[programId]/referrals - get all referrals for the current partner in a program
+export const GET = withPartnerProfile(
+ async ({ partner, params, searchParams }) => {
+ const { programId } = params;
+ const { status, search, page, pageSize } =
+ getPartnerReferralsQuerySchema.parse(searchParams);
+
+ const { program } = await getProgramEnrollmentOrThrow({
+ partnerId: partner.id,
+ programId: programId,
+ include: {
+ program: true,
+ },
+ });
+
+ const referrals = await prisma.partnerReferral.findMany({
+ where: {
+ programId: program.id,
+ partnerId: partner.id,
+ ...(status && { status }),
+ ...(search
+ ? search.includes("@")
+ ? { email: search }
+ : {
+ email: { search: sanitizeFullTextSearch(search) },
+ name: { search: sanitizeFullTextSearch(search) },
+ }
+ : {}),
+ },
+ skip: (page - 1) * pageSize,
+ take: pageSize,
+ orderBy: {
+ createdAt: "desc",
+ },
+ });
+
+ return NextResponse.json(
+ z.array(partnerProfileReferralSchema).parse(referrals),
+ );
+ },
+);
diff --git a/apps/web/app/(ee)/api/programs/referrals/count/route.ts b/apps/web/app/(ee)/api/programs/referrals/count/route.ts
new file mode 100644
index 0000000000..b1f4d26833
--- /dev/null
+++ b/apps/web/app/(ee)/api/programs/referrals/count/route.ts
@@ -0,0 +1,90 @@
+import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { withWorkspace } from "@/lib/auth";
+import {
+ getPartnerReferralsCountQuerySchema,
+ partnerReferralsCountResponseSchema,
+} from "@/lib/zod/schemas/referrals";
+import { prisma, sanitizeFullTextSearch } from "@dub/prisma";
+import { Prisma, ReferralStatus } from "@dub/prisma/client";
+import { NextResponse } from "next/server";
+
+// GET /api/programs/referrals/count - get the count of partner referrals for a program
+export const GET = withWorkspace(
+ async ({ workspace, searchParams }) => {
+ const programId = getDefaultProgramIdOrThrow(workspace);
+
+ const { partnerId, status, search, groupBy } =
+ getPartnerReferralsCountQuerySchema.parse(searchParams);
+
+ const commonWhere: Prisma.PartnerReferralWhereInput = {
+ programId,
+ ...(partnerId && groupBy !== "partnerId" && { partnerId }),
+ ...(status && groupBy !== "status" && { status }),
+ ...(search
+ ? search.includes("@")
+ ? { email: search }
+ : {
+ email: { search: sanitizeFullTextSearch(search) },
+ name: { search: sanitizeFullTextSearch(search) },
+ }
+ : {}),
+ };
+
+ // Get referral count by status
+ if (groupBy === "status") {
+ const data = await prisma.partnerReferral.groupBy({
+ by: ["status"],
+ where: commonWhere,
+ _count: true,
+ orderBy: {
+ _count: {
+ status: "desc",
+ },
+ },
+ });
+
+ // Fill in missing statuses with zero counts
+ Object.values(ReferralStatus).forEach((status) => {
+ if (!data.some((d) => d.status === status)) {
+ data.push({ _count: 0, status });
+ }
+ });
+
+ return NextResponse.json(partnerReferralsCountResponseSchema.parse(data));
+ }
+
+ // Get referral count by partnerId
+ if (groupBy === "partnerId") {
+ const data = await prisma.partnerReferral.groupBy({
+ by: ["partnerId"],
+ where: commonWhere,
+ _count: true,
+ orderBy: {
+ _count: {
+ partnerId: "desc",
+ },
+ },
+ take: 10000,
+ });
+
+ return NextResponse.json(partnerReferralsCountResponseSchema.parse(data));
+ }
+
+ // Get referral count
+ const count = await prisma.partnerReferral.count({
+ where: commonWhere,
+ });
+
+ return NextResponse.json(partnerReferralsCountResponseSchema.parse(count));
+ },
+ {
+ requiredPlan: [
+ "business",
+ "business plus",
+ "business extra",
+ "business max",
+ "advanced",
+ "enterprise",
+ ],
+ },
+);
diff --git a/apps/web/app/(ee)/api/programs/referrals/route.ts b/apps/web/app/(ee)/api/programs/referrals/route.ts
new file mode 100644
index 0000000000..7dbb48565f
--- /dev/null
+++ b/apps/web/app/(ee)/api/programs/referrals/route.ts
@@ -0,0 +1,62 @@
+import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { withWorkspace } from "@/lib/auth";
+import {
+ getPartnerReferralsQuerySchema,
+ referralSchema,
+} from "@/lib/zod/schemas/referrals";
+import { prisma, sanitizeFullTextSearch } from "@dub/prisma";
+import { NextResponse } from "next/server";
+import * as z from "zod/v4";
+
+// GET /api/programs/referrals - get all partner referrals for a program
+export const GET = withWorkspace(
+ async ({ workspace, searchParams }) => {
+ const programId = getDefaultProgramIdOrThrow(workspace);
+
+ const { partnerId, status, search, page, pageSize } =
+ getPartnerReferralsQuerySchema.parse(searchParams);
+
+ const partnerReferrals = await prisma.partnerReferral.findMany({
+ where: {
+ programId,
+ ...(partnerId && { partnerId }),
+ ...(status && { status }),
+ ...(search
+ ? search.includes("@")
+ ? { email: search }
+ : {
+ email: { search: sanitizeFullTextSearch(search) },
+ name: { search: sanitizeFullTextSearch(search) },
+ }
+ : {}),
+ },
+ include: {
+ partner: {
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ image: true,
+ },
+ },
+ },
+ skip: (page - 1) * pageSize,
+ take: pageSize,
+ orderBy: {
+ createdAt: "desc",
+ },
+ });
+
+ return NextResponse.json(z.array(referralSchema).parse(partnerReferrals));
+ },
+ {
+ requiredPlan: [
+ "business",
+ "business plus",
+ "business extra",
+ "business max",
+ "advanced",
+ "enterprise",
+ ],
+ },
+);
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/(index)/layout.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/(index)/layout.tsx
new file mode 100644
index 0000000000..7bcdc88125
--- /dev/null
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/(index)/layout.tsx
@@ -0,0 +1,157 @@
+"use client";
+
+import { REFERRAL_ENABLED_PROGRAM_IDS } from "@/lib/referrals/constants";
+import usePartnerCustomersCount from "@/lib/swr/use-partner-customers-count";
+import usePartnerReferralsCount from "@/lib/swr/use-partner-referrals-count";
+import useProgramEnrollment from "@/lib/swr/use-program-enrollment";
+import { referralFormSchema } from "@/lib/zod/schemas/referral-form";
+import { PageContent } from "@/ui/layout/page-content";
+import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
+import { SubmitReferralSheet } from "@/ui/referrals/submit-referral-sheet";
+import { Button, InfoTooltip } from "@dub/ui";
+import { cn, nFormatter } from "@dub/utils";
+import Link from "next/link";
+import { useParams, usePathname } from "next/navigation";
+import { CSSProperties, ReactNode, useMemo, useState } from "react";
+import * as z from "zod/v4";
+
+export default function PartnerCustomersLayout({
+ children,
+}: {
+ children: ReactNode;
+}) {
+ const pathname = usePathname();
+ const { programEnrollment } = useProgramEnrollment();
+ const { programSlug } = useParams<{ programSlug: string }>();
+ const [showReferralSheet, setShowReferralSheet] = useState(false);
+
+ const { data: customersCount } = usePartnerCustomersCount<number>({
+ includeParams: [],
+ });
+
+ const { data: referralsCount } = usePartnerReferralsCount<number>({
+ includeParams: [],
+ });
+
+ const referralFormDataRaw = programEnrollment?.program?.referralFormData;
+ const programId = programEnrollment?.programId;
+
+ const isEnabled = programId
+ ? REFERRAL_ENABLED_PROGRAM_IDS.includes(programId)
+ : false;
+
+ const referralFormData = useMemo(() => {
+ if (!referralFormDataRaw) {
+ return null;
+ }
+ try {
+ return referralFormSchema.parse(referralFormDataRaw) as z.infer<
+ typeof referralFormSchema
+ >;
+ } catch {
+ return null;
+ }
+ }, [referralFormDataRaw]);
+
+ const tabs = useMemo(() => {
+ if (!isEnabled) {
+ return [];
+ }
+
+ return [
+ {
+ label: "Customers",
+ id: "customers",
+ href: "",
+ info: "Shows both your converted and non-converted customers.",
+ count: customersCount,
+ },
+ {
+ label: "Submitted Referrals",
+ id: "invited",
+ href: "referrals",
+ info: "Shows your submitted referrals and their status.",
+ count: referralsCount,
+ },
+ ];
+ }, [isEnabled, customersCount, referralsCount]);
+
+ return (
+ <PageContent
+ title="Customers"
+ controls={
+ <>
+ {isEnabled && (
+ <Button
+ text="Submit referral"
+ className="h-9 w-fit rounded-lg"
+ disabled={!referralFormData}
+ disabledTooltip={
+ referralFormData
+ ? undefined
+ : "Submitted referrals are not offered."
+ }
+ onClick={() => {
+ setShowReferralSheet(true);
+ }}
+ />
+ )}
+ </>
+ }
+ >
+ {isEnabled && referralFormData && programEnrollment?.programId && (
+ <SubmitReferralSheet
+ isOpen={showReferralSheet}
+ setIsOpen={setShowReferralSheet}
+ programId={programEnrollment.programId}
+ referralFormData={referralFormData}
+ />
+ )}
+
+ <PageWidthWrapper className="flex flex-col gap-3 pb-10">
+ {tabs.length > 0 && (
+ <div
+ className={cn(
+ "grid grid-cols-[repeat(var(--tabs),minmax(0,1fr))] gap-2",
+ )}
+ style={{ "--tabs": tabs.length } as CSSProperties}
+ >
+ {tabs.map((tab) => {
+ const isActive = pathname.endsWith(
+ `/customers${tab.href ? `/${tab.href}` : ""}`,
+ );
+
+ return (
+ <Link
+ key={tab.id}
+ href={`/programs/${programSlug}/customers${tab.href ? `/${tab.href}` : ""}`}
+ className={cn(
+ "border-border-subtle flex flex-col gap-1 rounded-lg border p-4 text-left transition-colors duration-100",
+ isActive
+ ? "border-black ring-1 ring-black"
+ : "hover:bg-bg-muted",
+ )}
+ >
+ <div className="flex items-center gap-2">
+ <span className="text-content-default text-xs font-semibold">
+ {tab.label}
+ </span>
+ {tab.info && <InfoTooltip content={tab.info} />}
+ </div>
+ {tab.count !== undefined ? (
+ <span className="text-content-emphasis text-base font-semibold">
+ {nFormatter(tab.count, { full: true })}
+ </span>
+ ) : (
+ <div className="h-6 w-12 animate-pulse rounded-md bg-neutral-200" />
+ )}
+ </Link>
+ );
+ })}
+ </div>
+ )}
+ {children}
+ </PageWidthWrapper>
+ </PageContent>
+ );
+}
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/page-client.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/(index)/page-client.tsx
similarity index 74%
rename from apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/page-client.tsx
rename to apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/(index)/page-client.tsx
index 21aa26e076..d144d0f0f6 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/page-client.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/(index)/page-client.tsx
@@ -5,7 +5,6 @@ import usePartnerCustomers from "@/lib/swr/use-partner-customers";
import usePartnerCustomersCount from "@/lib/swr/use-partner-customers-count";
import useProgramEnrollment from "@/lib/swr/use-program-enrollment";
import { CustomerRowItem } from "@/ui/customers/customer-row-item";
-import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
import { SearchBoxPersisted } from "@/ui/shared/search-box";
import {
@@ -198,61 +197,59 @@ export function ProgramCustomersPageClient() {
});
return (
- <PageWidthWrapper className="pb-10">
- <div className="flex flex-col gap-3">
- <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}
+ <div className="flex flex-col gap-3">
+ <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}
+ />
+ {Boolean(programEnrollment?.customerDataSharingEnabledAt) && (
+ <SearchBoxPersisted
+ placeholder="Search by email or name"
+ inputClassName="md:w-[16rem]"
/>
- {Boolean(programEnrollment?.customerDataSharingEnabledAt) && (
- <SearchBoxPersisted
- placeholder="Search by email or name"
- inputClassName="md:w-[16rem]"
- />
- )}
- </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>
-
- {customers?.length !== 0 ? (
- <Table {...tableProps} table={table} />
- ) : (
- <AnimatedEmptyState
- title={isFiltered ? "No customers found" : "No customers yet"}
- description={
- isFiltered
- ? "No customers found for the selected filters. Adjust your filters to refine your search results."
- : "No customers have been recorded for this program yet. Once customers start converting through your links, they'll appear here."
- }
- cardContent={() => (
- <>
- <User className="size-4 text-neutral-700" />
- <div className="h-2.5 w-24 min-w-0 rounded-sm bg-neutral-200" />
- </>
+ <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>
- </PageWidthWrapper>
+
+ {customers?.length !== 0 ? (
+ <Table {...tableProps} table={table} />
+ ) : (
+ <AnimatedEmptyState
+ title={isFiltered ? "No customers found" : "No customers yet"}
+ description={
+ isFiltered
+ ? "No customers found for the selected filters. Adjust your filters to refine your search results."
+ : "No customers have been recorded for this program yet. Once customers start converting through your links, they'll appear here."
+ }
+ cardContent={() => (
+ <>
+ <User className="size-4 text-neutral-700" />
+ <div className="h-2.5 w-24 min-w-0 rounded-sm bg-neutral-200" />
+ </>
+ )}
+ />
+ )}
+ </div>
);
}
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/(index)/page.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/(index)/page.tsx
new file mode 100644
index 0000000000..1738b844c5
--- /dev/null
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/(index)/page.tsx
@@ -0,0 +1,5 @@
+import { ProgramCustomersPageClient } from "./page-client";
+
+export default function ProgramCustomers() {
+ return <ProgramCustomersPageClient />;
+}
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/(index)/referrals/page.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/(index)/referrals/page.tsx
new file mode 100644
index 0000000000..7028a3c5ac
--- /dev/null
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/(index)/referrals/page.tsx
@@ -0,0 +1,358 @@
+"use client";
+
+import usePartnerReferrals from "@/lib/swr/use-partner-referrals";
+import usePartnerReferralsCount from "@/lib/swr/use-partner-referrals-count";
+import { PartnerProfileReferralsCountByStatus } from "@/lib/types";
+import { PartnerProfileReferral } from "@/lib/zod/schemas/partner-profile";
+import { PartnerProfileReferralSheet } from "@/ui/referrals/partner-profile-referral-sheet";
+import { PartnerProfileReferralsEmptyState } from "@/ui/referrals/partner-profile-referrals-empty-state";
+import { ReferralStatusBadges } from "@/ui/referrals/referral-status-badges";
+import { getCompanyLogoUrl } from "@/ui/referrals/referral-utils";
+import { SearchBoxPersisted } from "@/ui/shared/search-box";
+import { ReferralStatus } from "@dub/prisma/client";
+import {
+ AnimatedSizeContainer,
+ Filter,
+ StatusBadge,
+ Table,
+ TimestampTooltip,
+ useColumnVisibility,
+ usePagination,
+ useRouterStuff,
+ useTable,
+} from "@dub/ui";
+import { CircleDotted } from "@dub/ui/icons";
+import { cn, formatDate, nFormatter, OG_AVATAR_URL } from "@dub/utils";
+import { Row } from "@tanstack/react-table";
+import { useEffect, useMemo, useState } from "react";
+
+export default function PartnerCustomersReferralsPage() {
+ const { queryParams, searchParams } = useRouterStuff();
+ const { pagination, setPagination } = usePagination();
+
+ const referralIdFromUrl = searchParams.get("referralId");
+
+ const [detailsSheetState, setDetailsSheetState] = useState<{
+ referralId: string | null;
+ open: boolean;
+ }>({
+ referralId: referralIdFromUrl,
+ open: !!referralIdFromUrl,
+ });
+
+ const { searchParamsObj } = useRouterStuff();
+ const status = searchParamsObj.status as ReferralStatus | undefined;
+ const search = searchParamsObj.search as string | undefined;
+
+ const { data: referralsCountByStatus } = usePartnerReferralsCount<
+ PartnerProfileReferralsCountByStatus[] | undefined
+ >({
+ query: {
+ groupBy: "status",
+ },
+ });
+
+ const { data: totalReferralsCount, error: countError } =
+ usePartnerReferralsCount<number>({
+ query: {
+ ...(status && { status }),
+ ...(search && { search }),
+ },
+ });
+
+ const { data: referrals, error, isLoading } = usePartnerReferrals();
+
+ const referralsColumns = {
+ all: ["lead", "name", "company", "submitted", "status"],
+ defaultVisible: ["lead", "name", "company", "submitted", "status"],
+ };
+
+ const { columnVisibility, setColumnVisibility } = useColumnVisibility(
+ "partner-profile-referrals-table-columns",
+ referralsColumns,
+ );
+
+ const filters = useMemo(
+ () => [
+ {
+ key: "status",
+ icon: CircleDotted,
+ label: "Status",
+ options:
+ referralsCountByStatus?.map(({ status, _count }) => {
+ const badge = ReferralStatusBadges[status];
+ const Icon = badge.icon;
+
+ return {
+ value: status,
+ label: badge.label,
+ icon: (
+ <Icon
+ className={cn(badge.className, "size-4 bg-transparent")}
+ />
+ ),
+ right: nFormatter(_count, { full: true }),
+ };
+ }) ?? [],
+ meta: {
+ filterParams: ({ getValue }: { getValue: () => string }) => ({
+ status: getValue(),
+ }),
+ },
+ },
+ ],
+ [referralsCountByStatus],
+ );
+
+ const activeFilters = useMemo(() => {
+ return [...(status ? [{ key: "status", value: status }] : [])];
+ }, [status]);
+
+ const onSelect = (key: string, value: any) =>
+ queryParams({
+ set: {
+ [key]: value,
+ },
+ del: "page",
+ });
+
+ const onRemove = (key: string) =>
+ queryParams({
+ del: [key, "page"],
+ });
+
+ const onRemoveAll = () =>
+ queryParams({
+ del: ["status", "search"],
+ });
+
+ const columns = useMemo(
+ () =>
+ [
+ {
+ id: "lead",
+ header: "Lead",
+ enableHiding: false,
+ minSize: 250,
+ cell: ({ row }: { row: Row<PartnerProfileReferral> }) => {
+ const referral = row.original;
+ const companyLogoUrl = getCompanyLogoUrl(referral.email);
+
+ return (
+ <div className="flex items-center gap-2 truncate">
+ <img
+ alt={referral.email}
+ src={companyLogoUrl || `${OG_AVATAR_URL}${referral.id}`}
+ className="size-5 shrink-0 rounded-full border border-neutral-200"
+ />
+ <span className="truncate" title={referral.email}>
+ {referral.email}
+ </span>
+ </div>
+ );
+ },
+ },
+ {
+ id: "name",
+ header: "Name",
+ accessorKey: "name",
+ minSize: 150,
+ cell: ({ row }: { row: Row<PartnerProfileReferral> }) => {
+ return (
+ <span className="min-w-0 truncate" title={row.original.name}>
+ {row.original.name}
+ </span>
+ );
+ },
+ },
+ {
+ id: "company",
+ header: "Company",
+ accessorKey: "company",
+ minSize: 150,
+ cell: ({ row }: { row: Row<PartnerProfileReferral> }) => {
+ return (
+ <span className="min-w-0 truncate" title={row.original.company}>
+ {row.original.company}
+ </span>
+ );
+ },
+ },
+ {
+ id: "submitted",
+ header: "Submitted",
+ cell: ({ row }: { row: Row<PartnerProfileReferral> }) => (
+ <TimestampTooltip
+ timestamp={row.original.createdAt}
+ rows={["local"]}
+ side="left"
+ delayDuration={150}
+ >
+ <span>
+ {formatDate(row.original.createdAt, { month: "short" })}
+ </span>
+ </TimestampTooltip>
+ ),
+ },
+ {
+ id: "status",
+ header: "Status",
+ accessorKey: "status",
+ cell: ({ row }: { row: Row<PartnerProfileReferral> }) => {
+ const status = row.original.status;
+ const badge = ReferralStatusBadges[status];
+
+ return (
+ <StatusBadge
+ variant={badge.variant}
+ icon={null}
+ className={cn("border-0", badge.className)}
+ >
+ {badge.label}
+ </StatusBadge>
+ );
+ },
+ },
+ ].filter((c) => referralsColumns.all.includes(c.id)),
+ [],
+ );
+
+ const { table, ...tableProps } = useTable({
+ data: referrals || [],
+ columns,
+ pagination,
+ onPaginationChange: setPagination,
+ columnVisibility,
+ onColumnVisibilityChange: setColumnVisibility,
+ thClassName: "border-l-0",
+ tdClassName: "border-l-0",
+ resourceName: (p) => `referral${p ? "s" : ""}`,
+ rowCount: totalReferralsCount || 0,
+ loading: isLoading,
+ error: error || countError ? "Failed to load referrals" : undefined,
+ onRowClick: (row) => {
+ queryParams({
+ set: { referralId: row.original.id },
+ scroll: false,
+ });
+ setDetailsSheetState({
+ referralId: row.original.id,
+ open: true,
+ });
+ },
+ });
+
+ const currentReferral = useMemo(() => {
+ if (!referrals || !detailsSheetState.referralId) return null;
+ return referrals.find((r) => r.id === detailsSheetState.referralId) || null;
+ }, [referrals, detailsSheetState.referralId]);
+
+ const [previousReferralId, nextReferralId] = useMemo(() => {
+ if (!referrals || !detailsSheetState.referralId) return [null, null];
+
+ const currentIndex = referrals.findIndex(
+ ({ id }) => id === detailsSheetState.referralId,
+ );
+ if (currentIndex === -1) return [null, null];
+
+ return [
+ currentIndex > 0 ? referrals[currentIndex - 1].id : null,
+ currentIndex < referrals.length - 1
+ ? referrals[currentIndex + 1].id
+ : null,
+ ];
+ }, [referrals, detailsSheetState.referralId]);
+
+ // Sync state with URL params
+ useEffect(() => {
+ const urlReferralId = searchParams.get("referralId");
+ if (urlReferralId && urlReferralId !== detailsSheetState.referralId) {
+ setDetailsSheetState({
+ referralId: urlReferralId,
+ open: true,
+ });
+ } else if (!urlReferralId && detailsSheetState.referralId) {
+ setDetailsSheetState({
+ referralId: null,
+ open: false,
+ });
+ }
+ }, [searchParams, detailsSheetState.referralId]);
+
+ return (
+ <div className="flex flex-col gap-3">
+ {detailsSheetState.referralId && currentReferral && (
+ <PartnerProfileReferralSheet
+ isOpen={detailsSheetState.open}
+ setIsOpen={(open) =>
+ setDetailsSheetState((s) => ({ ...s, open }) as any)
+ }
+ referral={currentReferral}
+ onPrevious={
+ previousReferralId
+ ? () => {
+ queryParams({
+ set: { referralId: previousReferralId },
+ scroll: false,
+ });
+ setDetailsSheetState({
+ referralId: previousReferralId,
+ open: true,
+ });
+ }
+ : undefined
+ }
+ onNext={
+ nextReferralId
+ ? () => {
+ queryParams({
+ set: { referralId: nextReferralId },
+ scroll: false,
+ });
+ setDetailsSheetState({
+ referralId: nextReferralId,
+ open: true,
+ });
+ }
+ : undefined
+ }
+ />
+ )}
+ <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}
+ />
+ <SearchBoxPersisted
+ placeholder="Search by email or name"
+ inputClassName="md:w-[16rem]"
+ />
+ </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>
+ {referrals && referrals.length !== 0 ? (
+ <Table {...tableProps} table={table} />
+ ) : !isLoading ? (
+ <PartnerProfileReferralsEmptyState />
+ ) : null}
+ </div>
+ );
+}
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/use-partner-customer-filters.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/(index)/use-partner-customer-filters.tsx
similarity index 100%
rename from apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/use-partner-customer-filters.tsx
rename to apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/(index)/use-partner-customer-filters.tsx
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/page.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/page.tsx
deleted file mode 100644
index 111bd173cc..0000000000
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/page.tsx
+++ /dev/null
@@ -1,10 +0,0 @@
-import { PageContent } from "@/ui/layout/page-content";
-import { ProgramCustomersPageClient } from "./page-client";
-
-export default function ProgramCustomers() {
- return (
- <PageContent title="Customers">
- <ProgramCustomersPageClient />
- </PageContent>
- );
-}
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 87ae65974d..f610ef758e 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
@@ -19,7 +19,7 @@ export function ProgramSidebar({
applicationRewards,
applicationDiscount,
}: {
- program: ProgramProps;
+ program: Omit<ProgramProps, "referralFormData">;
applicationRewards: RewardProps[];
applicationDiscount: DiscountProps | null;
}) {
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/invites/accept/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/invites/accept/route.ts
index 83271fbda7..8af85565cf 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/invites/accept/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/invites/accept/route.ts
@@ -1,6 +1,6 @@
import { DubApiError } from "@/lib/api/errors";
-import { onboardingStepCache } from "@/lib/api/workspaces/onboarding-step-cache";
import { assertRoleAllowedForPlan } from "@/lib/api/workspaces/assert-role-plan";
+import { onboardingStepCache } from "@/lib/api/workspaces/onboarding-step-cache";
import { withSession } from "@/lib/auth";
import { exceededLimitError } from "@/lib/exceeded-limit-error";
import { PlanProps } from "@/lib/types";
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/(index)/layout.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/(index)/layout.tsx
new file mode 100644
index 0000000000..7684e43ad3
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/(index)/layout.tsx
@@ -0,0 +1,115 @@
+"use client";
+
+import { REFERRAL_ENABLED_PROGRAM_IDS } from "@/lib/referrals/constants";
+import useCustomersCount from "@/lib/swr/use-customers-count";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { PageContent } from "@/ui/layout/page-content";
+import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
+import { usePartnerReferralsCount } from "@/ui/referrals/use-partner-referrals-count";
+import { InfoTooltip } from "@dub/ui";
+import { cn } from "@dub/utils";
+import Link from "next/link";
+import { usePathname } from "next/navigation";
+import { CSSProperties, ReactNode, useMemo } from "react";
+import { CustomersDropdownMenu } from "../customers-dropdown-menu";
+
+export default function PartnerCustomersLayout({
+ children,
+}: {
+ children: ReactNode;
+}) {
+ const pathname = usePathname();
+ const { slug, defaultProgramId } = useWorkspace();
+
+ const { data: customersCount } = useCustomersCount<number>({
+ includeParams: [],
+ });
+
+ const { data: referralsCount } = usePartnerReferralsCount<number>({
+ includeParams: [],
+ });
+
+ const isEnabled = defaultProgramId
+ ? REFERRAL_ENABLED_PROGRAM_IDS.includes(defaultProgramId)
+ : false;
+
+ const tabs = useMemo(() => {
+ if (!isEnabled) {
+ return [];
+ }
+
+ return [
+ {
+ label: "Customers",
+ id: "customers",
+ href: "",
+ info: "Shows both converted and non-converted customers.",
+ count: customersCount,
+ },
+ {
+ label: "Partner Referrals",
+ id: "invited",
+ href: "referrals",
+ info: "Shows your partners' submitted referrals.",
+ count: referralsCount,
+ },
+ ];
+ }, [isEnabled, customersCount, referralsCount]);
+
+ return (
+ <PageContent
+ title="Customers"
+ titleInfo={{
+ title:
+ "Get deeper, real-time insights about your referred customers' demographics, purchasing behavior, and lifetime value (LTV).",
+ href: "https://dub.co/help/article/customer-insights",
+ }}
+ controls={<CustomersDropdownMenu />}
+ >
+ <PageWidthWrapper className="flex flex-col gap-3 pb-10">
+ {tabs.length > 0 && (
+ <div
+ className={cn(
+ "grid grid-cols-[repeat(var(--tabs),minmax(0,1fr))] gap-2",
+ )}
+ style={{ "--tabs": tabs.length } as CSSProperties}
+ >
+ {tabs.map((tab) => {
+ const isActive = pathname.endsWith(
+ `/customers${tab.href ? `/${tab.href}` : ""}`,
+ );
+
+ return (
+ <Link
+ key={tab.id}
+ href={`/${slug}/program/customers${tab.href ? `/${tab.href}` : ""}`}
+ className={cn(
+ "border-border-subtle flex flex-col gap-1 rounded-lg border p-4 text-left transition-colors duration-100",
+ isActive
+ ? "border-black ring-1 ring-black"
+ : "hover:bg-bg-muted",
+ )}
+ >
+ <div className="flex items-center gap-2">
+ <span className="text-content-default text-xs font-semibold">
+ {tab.label}
+ </span>
+ {tab.info && <InfoTooltip content={tab.info} />}
+ </div>
+ {tab.count !== undefined ? (
+ <span className="text-content-emphasis text-base font-semibold">
+ {tab.count.toLocaleString()}
+ </span>
+ ) : (
+ <div className="h-6 w-12 animate-pulse rounded-md bg-neutral-200" />
+ )}
+ </Link>
+ );
+ })}
+ </div>
+ )}
+ {children}
+ </PageWidthWrapper>
+ </PageContent>
+ );
+}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/(index)/page.tsx
similarity index 86%
rename from apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/page-client.tsx
rename to apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/(index)/page.tsx
index 7fd142e825..190aa6717b 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/(index)/page.tsx
@@ -3,7 +3,7 @@
import useWorkspace from "@/lib/swr/use-workspace";
import { CustomerTable } from "@/ui/customers/customer-table/customer-table";
-export function CustomersPageClient() {
+export default function ProgramCustomersPage() {
const { defaultProgramId } = useWorkspace();
return (
<CustomerTable
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/(index)/referrals/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/(index)/referrals/page.tsx
new file mode 100644
index 0000000000..16f11b406c
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/(index)/referrals/page.tsx
@@ -0,0 +1,7 @@
+"use client";
+
+import { PartnerReferralTable } from "@/ui/referrals/partner-referral-table";
+
+export default function PartnerCustomersReferralsPage() {
+ return <PartnerReferralTable />;
+}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/[customerId]/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/[customerId]/page.tsx
new file mode 100644
index 0000000000..afd6de4d98
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/[customerId]/page.tsx
@@ -0,0 +1,13 @@
+import { redirect } from "next/navigation";
+
+// Handles old customer IDs (pre cus_ prefix) by redirecting to the sales page
+export default async function ProgramCustomerPage({
+ params,
+}: {
+ params: Promise<{ slug: string; customerId: string }>;
+}) {
+ const { slug, customerId } = await params;
+ redirect(`/${slug}/program/customers/${customerId}/sales`);
+
+ return null;
+}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/customers-dropdown-menu.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/customers-dropdown-menu.tsx
new file mode 100644
index 0000000000..db4218818c
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/customers-dropdown-menu.tsx
@@ -0,0 +1,47 @@
+"use client";
+
+import useWorkspace from "@/lib/swr/use-workspace";
+import { ThreeDots } from "@/ui/shared/icons";
+import { Button, IconMenu, Popover } from "@dub/ui";
+import { ExternalLink } from "lucide-react";
+import { useRouter } from "next/navigation";
+import { useState } from "react";
+
+export function CustomersDropdownMenu() {
+ const router = useRouter();
+ const { slug } = useWorkspace();
+ const [openPopover, setOpenPopover] = useState(false);
+
+ return (
+ <Popover
+ content={
+ <div className="w-full md:w-[14rem]">
+ <div className="grid gap-px p-2">
+ <button
+ onClick={() => {
+ setOpenPopover(false);
+ router.push(`/${slug}/program/customers/referrals`);
+ }}
+ className="w-full rounded-md p-2 hover:bg-neutral-100 active:bg-neutral-200"
+ >
+ <IconMenu
+ text="Partner referral form"
+ icon={<ExternalLink className="h-4 w-4" />} // TODO: Fix the icon
+ />
+ </button>
+ </div>
+ </div>
+ }
+ openPopover={openPopover}
+ setOpenPopover={setOpenPopover}
+ align="end"
+ >
+ <Button
+ onClick={() => setOpenPopover(!openPopover)}
+ variant="secondary"
+ className="h-8 w-auto px-1.5 sm:h-9"
+ icon={<ThreeDots className="size-4 text-neutral-500" />}
+ />
+ </Popover>
+ );
+}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/page.tsx
deleted file mode 100644
index 5f94bfd9d1..0000000000
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/page.tsx
+++ /dev/null
@@ -1,20 +0,0 @@
-import { PageContent } from "@/ui/layout/page-content";
-import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
-import { CustomersPageClient } from "./page-client";
-
-export default function CustomersPage() {
- return (
- <PageContent
- title="Customers"
- titleInfo={{
- title:
- "Get deeper, real-time insights about your referred customers' demographics, purchasing behavior, and lifetime value (LTV).",
- href: "https://dub.co/help/article/customer-insights",
- }}
- >
- <PageWidthWrapper>
- <CustomersPageClient />
- </PageWidthWrapper>
- </PageContent>
- );
-}
diff --git a/apps/web/lib/actions/partners/update-program.ts b/apps/web/lib/actions/partners/update-program.ts
index 4cf89a9b65..34b4852c73 100644
--- a/apps/web/lib/actions/partners/update-program.ts
+++ b/apps/web/lib/actions/partners/update-program.ts
@@ -3,6 +3,7 @@
import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { getPlanCapabilities } from "@/lib/plan-capabilities";
+import { referralFormSchema } from "@/lib/zod/schemas/referral-form";
import { prisma } from "@dub/prisma";
import { waitUntil } from "@vercel/functions";
import * as z from "zod/v4";
@@ -14,6 +15,7 @@ import { throwIfNoPermission } from "../throw-if-no-permission";
const schema = updateProgramSchema.partial().extend({
workspaceId: z.string(),
applyHoldingPeriodDaysToAllGroups: z.boolean().optional(),
+ referralFormData: referralFormSchema.optional(),
});
export const updateProgramAction = authActionClient
@@ -26,6 +28,7 @@ export const updateProgramAction = authActionClient
termsUrl,
minPayoutAmount,
messagingEnabledAt,
+ referralFormData,
} = parsedInput;
throwIfNoPermission({
@@ -52,6 +55,9 @@ export const updateProgramAction = authActionClient
...(messagingEnabledAt !== undefined &&
(getPlanCapabilities(workspace.plan).canMessagePartners ||
messagingEnabledAt === null) && { messagingEnabledAt }),
+ ...(referralFormData !== undefined && {
+ referralFormData: referralFormData ?? null,
+ }),
},
});
diff --git a/apps/web/lib/actions/partners/verify-social-account-by-code.ts b/apps/web/lib/actions/partners/verify-social-account-by-code.ts
index d16a704dd0..0e1ac9e215 100644
--- a/apps/web/lib/actions/partners/verify-social-account-by-code.ts
+++ b/apps/web/lib/actions/partners/verify-social-account-by-code.ts
@@ -5,7 +5,7 @@ import { ratelimit } from "@/lib/upstash";
import { redis } from "@/lib/upstash/redis";
import { prisma } from "@dub/prisma";
import { PlatformType } from "@dub/prisma/client";
-import { z } from "zod";
+import * as z from "zod/v4";
import { authPartnerActionClient } from "../safe-action";
const schema = z.object({
diff --git a/apps/web/lib/actions/referrals/mark-referral-closed-lost.ts b/apps/web/lib/actions/referrals/mark-referral-closed-lost.ts
new file mode 100644
index 0000000000..e0e3f287b9
--- /dev/null
+++ b/apps/web/lib/actions/referrals/mark-referral-closed-lost.ts
@@ -0,0 +1,40 @@
+"use server";
+
+import { DubApiError } from "@/lib/api/errors";
+import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { getReferralOrThrow } from "@/lib/api/referrals/get-referral-or-throw";
+import { markReferralClosedLostSchema } from "@/lib/zod/schemas/referrals";
+import { prisma } from "@dub/prisma";
+import { ReferralStatus } from "@dub/prisma/client";
+import { authActionClient } from "../safe-action";
+
+// Mark a partner referral as closed lost
+export const markReferralClosedLostAction = authActionClient
+ .inputSchema(markReferralClosedLostSchema)
+ .action(async ({ parsedInput, ctx }) => {
+ const { workspace } = ctx;
+ const { referralId } = parsedInput;
+
+ const programId = getDefaultProgramIdOrThrow(workspace);
+
+ const partnerReferral = await getReferralOrThrow({
+ referralId,
+ programId,
+ });
+
+ if (partnerReferral.status === ReferralStatus.closedLost) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "This partner referral is already marked as closed lost.",
+ });
+ }
+
+ await prisma.partnerReferral.update({
+ where: {
+ id: referralId,
+ },
+ data: {
+ status: ReferralStatus.closedLost,
+ },
+ });
+ });
diff --git a/apps/web/lib/actions/referrals/mark-referral-closed-won.ts b/apps/web/lib/actions/referrals/mark-referral-closed-won.ts
new file mode 100644
index 0000000000..83d2d6db72
--- /dev/null
+++ b/apps/web/lib/actions/referrals/mark-referral-closed-won.ts
@@ -0,0 +1,75 @@
+"use server";
+
+import { trackSale } from "@/lib/api/conversions/track-sale";
+import { DubApiError } from "@/lib/api/errors";
+import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { getReferralOrThrow } from "@/lib/api/referrals/get-referral-or-throw";
+import { markReferralClosedWonSchema } from "@/lib/zod/schemas/referrals";
+import { prisma } from "@dub/prisma";
+import { ReferralStatus } from "@dub/prisma/client";
+import { waitUntil } from "@vercel/functions";
+import { authActionClient } from "../safe-action";
+
+// Mark a partner referral as closed won
+export const markReferralClosedWonAction = authActionClient
+ .inputSchema(markReferralClosedWonSchema)
+ .action(async ({ parsedInput, ctx }) => {
+ const { workspace } = ctx;
+ const { referralId, saleAmount, stripeCustomerId } = parsedInput;
+
+ const programId = getDefaultProgramIdOrThrow(workspace);
+
+ const referral = await getReferralOrThrow({
+ referralId,
+ programId,
+ });
+
+ if (referral.status === ReferralStatus.closedWon) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "This partner referral is already marked as closed won.",
+ });
+ }
+
+ if (!referral.customer) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "This referral does not have a customer associated with it.",
+ });
+ }
+
+ // Mark the referral as closed won
+ await prisma.partnerReferral.update({
+ where: {
+ id: referralId,
+ status: "qualified",
+ },
+ data: {
+ status: ReferralStatus.closedWon,
+ },
+ });
+
+ await trackSale({
+ customerExternalId: referral.customer.externalId!,
+ amount: saleAmount,
+ eventName: "Closed Won",
+ paymentProcessor: "custom",
+ invoiceId: null,
+ metadata: null,
+ rawBody: {},
+ workspace,
+ source: "submitted",
+ });
+
+ // Update customer with the stripe customer ID
+ waitUntil(
+ prisma.customer.update({
+ where: {
+ id: referral.customerId!,
+ },
+ data: {
+ stripeCustomerId,
+ },
+ }),
+ );
+ });
diff --git a/apps/web/lib/actions/referrals/mark-referral-qualified.ts b/apps/web/lib/actions/referrals/mark-referral-qualified.ts
new file mode 100644
index 0000000000..29d8d7a2b9
--- /dev/null
+++ b/apps/web/lib/actions/referrals/mark-referral-qualified.ts
@@ -0,0 +1,119 @@
+"use server";
+
+import { trackLead } from "@/lib/api/conversions/track-lead";
+import { createId } from "@/lib/api/create-id";
+import { DubApiError } from "@/lib/api/errors";
+import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { getReferralOrThrow } from "@/lib/api/referrals/get-referral-or-throw";
+import { recordFakeClick } from "@/lib/tinybird/record-fake-click";
+import { markReferralQualifiedSchema } from "@/lib/zod/schemas/referrals";
+import { prisma } from "@dub/prisma";
+import { ReferralStatus } from "@dub/prisma/client";
+import { pick } from "@dub/utils";
+import { waitUntil } from "@vercel/functions";
+import { authActionClient } from "../safe-action";
+
+// Mark a partner referral as qualified
+export const markReferralQualifiedAction = authActionClient
+ .inputSchema(markReferralQualifiedSchema)
+ .action(async ({ parsedInput, ctx }) => {
+ const { workspace } = ctx;
+ const { referralId } = parsedInput;
+
+ const programId = getDefaultProgramIdOrThrow(workspace);
+
+ const referral = await getReferralOrThrow({
+ referralId,
+ programId,
+ });
+
+ if (referral.status === ReferralStatus.qualified) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "This partner referral is already qualified.",
+ });
+ }
+
+ // Mark the referral as qualified
+ await prisma.partnerReferral.update({
+ where: {
+ id: referralId,
+ status: ReferralStatus.pending,
+ },
+ data: {
+ status: ReferralStatus.qualified,
+ },
+ });
+
+ waitUntil(
+ (async () => {
+ // Find the default link for the partner
+ const links = await prisma.link.findMany({
+ where: {
+ programId,
+ partnerId: referral.partnerId,
+ partnerGroupDefaultLinkId: {
+ not: null,
+ },
+ },
+ orderBy: {
+ partnerGroupDefaultLinkId: "asc",
+ },
+ });
+
+ if (links.length === 0) {
+ return;
+ }
+
+ const partnerLink = links[0];
+
+ // Record a fake click
+ const clickEvent = await recordFakeClick({
+ link: pick(partnerLink, ["id", "url", "domain", "key", "projectId"]),
+ });
+
+ // Create a customer
+ const customer = await prisma.customer.create({
+ data: {
+ id: createId({ prefix: "cus_" }),
+ name: referral.name,
+ email: referral.email,
+ externalId: referral.email,
+ projectId: workspace.id,
+ projectConnectId: workspace.stripeConnectId,
+ programId,
+ partnerId: referral.partnerId,
+ linkId: clickEvent.link_id,
+ clickId: clickEvent.click_id,
+ },
+ });
+
+ // Track the qualified lead
+ await trackLead({
+ clickId: clickEvent.click_id,
+ eventName: "Qualified Lead",
+ customerExternalId: referral.email,
+ customerName: customer.name,
+ customerEmail: customer.email,
+ mode: "wait",
+ rawBody: {},
+ workspace: pick(workspace, [
+ "id",
+ "stripeConnectId",
+ "webhookEnabled",
+ ]),
+ source: "submitted",
+ });
+
+ // Update the referral with the customer ID
+ await prisma.partnerReferral.update({
+ where: {
+ id: referralId,
+ },
+ data: {
+ customerId: customer.id,
+ },
+ });
+ })(),
+ );
+ });
diff --git a/apps/web/lib/actions/referrals/mark-referral-unqualified.ts b/apps/web/lib/actions/referrals/mark-referral-unqualified.ts
new file mode 100644
index 0000000000..c932a851bf
--- /dev/null
+++ b/apps/web/lib/actions/referrals/mark-referral-unqualified.ts
@@ -0,0 +1,40 @@
+"use server";
+
+import { DubApiError } from "@/lib/api/errors";
+import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { getReferralOrThrow } from "@/lib/api/referrals/get-referral-or-throw";
+import { markReferralUnqualifiedSchema } from "@/lib/zod/schemas/referrals";
+import { prisma } from "@dub/prisma";
+import { ReferralStatus } from "@dub/prisma/client";
+import { authActionClient } from "../safe-action";
+
+// Mark a partner referral as unqualified
+export const markReferralUnqualifiedAction = authActionClient
+ .inputSchema(markReferralUnqualifiedSchema)
+ .action(async ({ parsedInput, ctx }) => {
+ const { workspace } = ctx;
+ const { referralId } = parsedInput;
+
+ const programId = getDefaultProgramIdOrThrow(workspace);
+
+ const partnerReferral = await getReferralOrThrow({
+ referralId,
+ programId,
+ });
+
+ if (partnerReferral.status === ReferralStatus.unqualified) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "This partner referral is already unqualified.",
+ });
+ }
+
+ await prisma.partnerReferral.update({
+ where: {
+ id: referralId,
+ },
+ data: {
+ status: ReferralStatus.unqualified,
+ },
+ });
+ });
diff --git a/apps/web/lib/actions/referrals/submit-referral.ts b/apps/web/lib/actions/referrals/submit-referral.ts
new file mode 100644
index 0000000000..c9270cc3c7
--- /dev/null
+++ b/apps/web/lib/actions/referrals/submit-referral.ts
@@ -0,0 +1,143 @@
+"use server";
+
+import { createId } from "@/lib/api/create-id";
+import { DubApiError } from "@/lib/api/errors";
+import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
+import { REFERRAL_FORM_REQUIRED_FIELD_KEYS } from "@/lib/referrals/constants";
+import {
+ formFieldSchema,
+ referralFormSchema,
+ referralRequiredFieldsSchema,
+} from "@/lib/zod/schemas/referral-form";
+import { createPartnerReferralSchema } from "@/lib/zod/schemas/referrals";
+import { prisma } from "@dub/prisma";
+import { Prisma } from "@dub/prisma/client";
+import { COUNTRIES } from "@dub/utils";
+import * as z from "zod/v4";
+import { authPartnerActionClient } from "../safe-action";
+
+/**
+ * Converts field values based on field type:
+ * - country: converts country code to country name
+ * - select: converts option value to option label
+ * - multiSelect: converts array of option values to array of option labels
+ */
+function convertFieldValue(
+ value: unknown,
+ fieldSchema?: z.infer<typeof formFieldSchema>,
+): unknown {
+ if (!fieldSchema) return value;
+
+ switch (fieldSchema.type) {
+ case "country":
+ return typeof value === "string" && value in COUNTRIES
+ ? COUNTRIES[value]
+ : value;
+
+ case "select": {
+ const option = fieldSchema.options.find((opt) => opt.value === value);
+ return option?.label ?? value;
+ }
+
+ case "multiSelect":
+ return Array.isArray(value)
+ ? value.map(
+ (val) =>
+ fieldSchema.options.find((opt) => opt.value === val)?.label ??
+ val,
+ )
+ : value;
+
+ default:
+ return value;
+ }
+}
+
+// Create a partner referral
+export const submitReferralAction = authPartnerActionClient
+ .inputSchema(createPartnerReferralSchema)
+ .action(async ({ parsedInput, ctx }) => {
+ const { partner } = ctx;
+ const { programId, formData: rawFormData } = parsedInput;
+
+ const programEnrollment = await getProgramEnrollmentOrThrow({
+ partnerId: partner.id,
+ programId,
+ include: {
+ program: true,
+ },
+ });
+
+ // Make sure required fields are present
+ const requiredFieldsResult =
+ referralRequiredFieldsSchema.safeParse(rawFormData);
+
+ if (!requiredFieldsResult.success) {
+ const firstError = requiredFieldsResult.error.issues[0];
+ throw new DubApiError({
+ code: "bad_request",
+ message: firstError.message,
+ });
+ }
+
+ const { name, email, company } = requiredFieldsResult.data;
+
+ // Parse custom fields from formData
+ const customFormData: Array<{
+ key: string;
+ value: unknown;
+ label: string;
+ }> = [];
+
+ // Parse and get form schema fields to extract labels
+ const parsedReferralFormData = programEnrollment.program.referralFormData
+ ? referralFormSchema.safeParse(programEnrollment.program.referralFormData)
+ : null;
+ const formSchemaFields =
+ parsedReferralFormData?.success && parsedReferralFormData.data.fields
+ ? parsedReferralFormData.data.fields
+ : [];
+
+ const fieldMap = new Map<string, z.infer<typeof formFieldSchema>>();
+ for (const field of formSchemaFields) {
+ fieldMap.set(field.key, field);
+ }
+
+ // Process all fields in rawFormData except required ones
+ for (const [key, value] of Object.entries(rawFormData)) {
+ // Skip required fields
+ if (REFERRAL_FORM_REQUIRED_FIELD_KEYS.has(key)) {
+ continue;
+ }
+
+ // Skip undefined/null/empty string values (but allow 0 and false)
+ if (value === undefined || value === null || value === "") {
+ continue;
+ }
+
+ // Get field schema to extract label and handle value conversion
+ const fieldSchema = fieldMap.get(key);
+ const label = fieldSchema?.label || key;
+
+ customFormData.push({
+ key,
+ label,
+ value: convertFieldValue(value, fieldSchema),
+ });
+ }
+
+ await prisma.partnerReferral.create({
+ data: {
+ id: createId({ prefix: "ref_" }),
+ programId,
+ partnerId: partner.id,
+ name,
+ email,
+ company,
+ formData:
+ customFormData.length > 0
+ ? (customFormData as Prisma.InputJsonValue)
+ : undefined,
+ },
+ });
+ });
diff --git a/apps/web/lib/api/audit-logs/schemas.ts b/apps/web/lib/api/audit-logs/schemas.ts
index 5a5374b5e8..81ea5309ae 100644
--- a/apps/web/lib/api/audit-logs/schemas.ts
+++ b/apps/web/lib/api/audit-logs/schemas.ts
@@ -8,6 +8,7 @@ import { GroupSchema } from "@/lib/zod/schemas/groups";
import { PartnerSchema } from "@/lib/zod/schemas/partners";
import { PayoutSchema } from "@/lib/zod/schemas/payouts";
import { ProgramSchema } from "@/lib/zod/schemas/programs";
+import { referralSchema } from "@/lib/zod/schemas/referrals";
import { RewardSchema } from "@/lib/zod/schemas/rewards";
import * as z from "zod/v4";
@@ -190,6 +191,16 @@ export const auditLogTarget = z.union([
id: z.string(),
metadata: BountySubmissionSchema,
}),
+
+ z.object({
+ type: z.literal("partner_referral"),
+ id: z.string(),
+ metadata: referralSchema.pick({
+ email: true,
+ name: true,
+ company: true,
+ }),
+ }),
]);
export const recordAuditLogInputSchema = z.object({
diff --git a/apps/web/lib/api/conversions/track-lead.ts b/apps/web/lib/api/conversions/track-lead.ts
index f06cc6d3f6..ddc78344ad 100644
--- a/apps/web/lib/api/conversions/track-lead.ts
+++ b/apps/web/lib/api/conversions/track-lead.ts
@@ -7,7 +7,7 @@ import { createPartnerCommission } from "@/lib/partners/create-partner-commissio
import { isStored, storage } from "@/lib/storage";
import { getClickEvent, recordLead } from "@/lib/tinybird";
import { logConversionEvent } from "@/lib/tinybird/log-conversion-events";
-import { WorkspaceProps } from "@/lib/types";
+import { CustomerSource, WorkspaceProps } from "@/lib/types";
import { redis } from "@/lib/upstash";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
import { transformLeadEventData } from "@/lib/webhook/transform";
@@ -26,6 +26,7 @@ import { executeWorkflows } from "../workflows/execute-workflows";
type TrackLeadParams = z.input<typeof trackLeadRequestSchema> & {
rawBody: any;
workspace: Pick<WorkspaceProps, "id" | "stripeConnectId" | "webhookEnabled">;
+ source?: CustomerSource; // default is "tracked"
};
export const trackLead = async ({
@@ -40,6 +41,7 @@ export const trackLead = async ({
metadata,
rawBody,
workspace,
+ source = "tracked",
}: TrackLeadParams) => {
// try to find the customer to use if it exists
let customer = await prisma.customer.findUnique({
@@ -312,6 +314,7 @@ export const trackLead = async ({
context: {
customer: {
country: customer.country,
+ source,
},
},
});
diff --git a/apps/web/lib/api/conversions/track-sale.ts b/apps/web/lib/api/conversions/track-sale.ts
index ca7e394b67..0f2fed1087 100644
--- a/apps/web/lib/api/conversions/track-sale.ts
+++ b/apps/web/lib/api/conversions/track-sale.ts
@@ -13,7 +13,12 @@ import {
recordSale,
} from "@/lib/tinybird";
import { logConversionEvent } from "@/lib/tinybird/log-conversion-events";
-import { ClickEventTB, LeadEventTB, WorkspaceProps } from "@/lib/types";
+import {
+ ClickEventTB,
+ CustomerSource,
+ LeadEventTB,
+ WorkspaceProps,
+} from "@/lib/types";
import { redis } from "@/lib/upstash";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
import {
@@ -32,9 +37,11 @@ import * as z from "zod/v4";
import { createId } from "../create-id";
import { syncPartnerLinksStats } from "../partners/sync-partner-links-stats";
import { executeWorkflows } from "../workflows/execute-workflows";
+
type TrackSaleParams = z.input<typeof trackSaleRequestSchema> & {
rawBody: any;
workspace: Pick<WorkspaceProps, "id" | "stripeConnectId" | "webhookEnabled">;
+ source?: CustomerSource; // default is "tracked"
};
export const trackSale = async ({
@@ -52,6 +59,7 @@ export const trackSale = async ({
metadata,
rawBody,
workspace,
+ source = "tracked",
}: TrackSaleParams) => {
let existingCustomer: Customer | null = null;
let newCustomer: Customer | null = null;
@@ -300,6 +308,7 @@ export const trackSale = async ({
workspace,
leadEventData,
customer,
+ source,
}),
]);
@@ -408,6 +417,7 @@ const _trackSale = async ({
workspace,
leadEventData,
customer,
+ source,
}: Omit<TrackSaleParams, "customerExternalId"> & {
leadEventData: LeadEventTB | null;
customer: Customer;
@@ -538,6 +548,7 @@ const _trackSale = async ({
context: {
customer: {
country: customer.country,
+ source: source!,
},
sale: {
productId: metadata?.productId as string,
diff --git a/apps/web/lib/api/create-id.ts b/apps/web/lib/api/create-id.ts
index caa63520d6..9ad67fa22f 100644
--- a/apps/web/lib/api/create-id.ts
+++ b/apps/web/lib/api/create-id.ts
@@ -41,6 +41,7 @@ const prefixes = [
"fr_", // fraud rule
"fre_", // fraud event
"frg_", // fraud event group
+ "ref_", // referral
] as const;
// ULID uses base32 encoding
diff --git a/apps/web/lib/api/referrals/get-referral-or-throw.ts b/apps/web/lib/api/referrals/get-referral-or-throw.ts
new file mode 100644
index 0000000000..f41272cccb
--- /dev/null
+++ b/apps/web/lib/api/referrals/get-referral-or-throw.ts
@@ -0,0 +1,37 @@
+import { prisma } from "@dub/prisma";
+import { DubApiError } from "../errors";
+
+interface GetReferralOrThrowParams {
+ referralId: string;
+ programId: string;
+}
+
+export const getReferralOrThrow = async ({
+ referralId,
+ programId,
+}: GetReferralOrThrowParams) => {
+ const referral = await prisma.partnerReferral.findUnique({
+ where: {
+ id: referralId,
+ },
+ include: {
+ customer: true,
+ },
+ });
+
+ if (!referral) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "Partner referral not found.",
+ });
+ }
+
+ if (referral.programId !== programId) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "You don't have access to this partner referral.",
+ });
+ }
+
+ return referral;
+};
diff --git a/apps/web/lib/middleware/utils/app-redirect.ts b/apps/web/lib/middleware/utils/app-redirect.ts
index 2b38e28fc9..eeabd4c24a 100644
--- a/apps/web/lib/middleware/utils/app-redirect.ts
+++ b/apps/web/lib/middleware/utils/app-redirect.ts
@@ -97,8 +97,9 @@ export const appRedirect = async (path: string) => {
return path.replace(customersPageRegex, "/$1/customers/$2/sales");
// Redirect "/[slug]/program/customers/:customerId" to "/[slug]/program/customers/:customerId/sales"
+ // Only applies when customerId starts with "cus_" (old IDs handled by page redirect)
const programCustomersPageRegex =
- /^\/([^\/]+)\/program\/customers\/([^\/]+)$/;
+ /^\/([^\/]+)\/program\/customers\/(cus_[^\/]+)$/;
if (programCustomersPageRegex.test(path))
return path.replace(
programCustomersPageRegex,
diff --git a/apps/web/lib/partners/create-partner-commission.ts b/apps/web/lib/partners/create-partner-commission.ts
index fab3e419ed..f226b5b92c 100644
--- a/apps/web/lib/partners/create-partner-commission.ts
+++ b/apps/web/lib/partners/create-partner-commission.ts
@@ -3,7 +3,6 @@ import {
Commission,
CommissionStatus,
CommissionType,
- EventType,
Link,
Partner,
ProgramEnrollment,
@@ -102,7 +101,7 @@ export const createPartnerCommission = async ({
amount = 0;
} else {
reward = determinePartnerReward({
- event: event as EventType,
+ event,
programEnrollment,
context,
});
diff --git a/apps/web/lib/referrals/constants.ts b/apps/web/lib/referrals/constants.ts
new file mode 100644
index 0000000000..361dc1f72a
--- /dev/null
+++ b/apps/web/lib/referrals/constants.ts
@@ -0,0 +1,51 @@
+import { textFieldSchema } from "@/lib/zod/schemas/referral-form";
+import * as z from "zod/v4";
+
+// Required fields configuration for referral forms
+export const REFERRAL_FORM_REQUIRED_FIELDS: z.infer<typeof textFieldSchema>[] =
+ [
+ {
+ key: "name",
+ label: "Name",
+ type: "text",
+ required: true,
+ locked: true,
+ position: -3,
+ },
+ {
+ key: "email",
+ label: "Email",
+ type: "text",
+ required: true,
+ locked: true,
+ position: -2,
+ },
+ {
+ key: "company",
+ label: "Company",
+ type: "text",
+ required: true,
+ locked: true,
+ position: -1,
+ },
+ ];
+
+// Set of required field keys for quick lookup (derived from REQUIRED_FIELDS)
+export const REFERRAL_FORM_REQUIRED_FIELD_KEYS = new Set(
+ REFERRAL_FORM_REQUIRED_FIELDS.map((field) => field.key),
+);
+
+// Input props map for required fields
+export const REFERRAL_FORM_FIELD_INPUT_PROPS: Record<
+ string,
+ React.InputHTMLAttributes<HTMLInputElement>
+> = {
+ email: { type: "email", autoComplete: "email" },
+ name: { autoComplete: "name" },
+ company: { autoComplete: "organization" },
+};
+
+export const REFERRAL_ENABLED_PROGRAM_IDS = [
+ "prog_CYCu7IMAapjkRpTnr8F1azjN", // Acme
+ "prog_1K7Y2RGFC4BKZQQZAZEEK9MVE", // SelectCode
+];
diff --git a/apps/web/lib/swr/use-customers-count.ts b/apps/web/lib/swr/use-customers-count.ts
index dec39f0a86..2f4ec8bb6a 100644
--- a/apps/web/lib/swr/use-customers-count.ts
+++ b/apps/web/lib/swr/use-customers-count.ts
@@ -8,9 +8,11 @@ import useWorkspace from "./use-workspace";
export default function useCustomersCount<T = number>({
query,
enabled = true,
+ includeParams = ["country", "partnerId", "linkId", "externalId", "search"],
}: {
query?: z.infer<typeof getCustomersCountQuerySchema>;
enabled?: boolean;
+ includeParams?: string[];
} = {}) {
const { id: workspaceId } = useWorkspace();
const { getQueryString } = useRouterStuff();
@@ -21,7 +23,7 @@ export default function useCustomersCount<T = number>({
`/api/customers/count${getQueryString(
{ workspaceId, ...query },
{
- include: ["country", "partnerId", "linkId", "externalId", "search"],
+ include: includeParams,
},
)}`,
fetcher,
diff --git a/apps/web/lib/swr/use-partner-customers-count.ts b/apps/web/lib/swr/use-partner-customers-count.ts
index 6d222b4e1b..8e156129a8 100644
--- a/apps/web/lib/swr/use-partner-customers-count.ts
+++ b/apps/web/lib/swr/use-partner-customers-count.ts
@@ -7,9 +7,11 @@ import { getPartnerCustomersCountQuerySchema } from "../zod/schemas/partner-prof
export default function usePartnerCustomersCount<T = number>({
query,
+ includeParams = ["country", "linkId", "search"],
enabled = true,
}: {
query?: z.infer<typeof getPartnerCustomersCountQuerySchema>;
+ includeParams?: string[];
enabled?: boolean;
} = {}) {
const { programSlug } = useParams<{ programSlug: string }>();
@@ -20,7 +22,7 @@ export default function usePartnerCustomersCount<T = number>({
`/api/partner-profile/programs/${programSlug}/customers/count${getQueryString(
query,
{
- include: ["country", "linkId", "search"],
+ include: includeParams,
},
)}`,
fetcher,
diff --git a/apps/web/lib/swr/use-partner-referrals-count.ts b/apps/web/lib/swr/use-partner-referrals-count.ts
new file mode 100644
index 0000000000..36036c1145
--- /dev/null
+++ b/apps/web/lib/swr/use-partner-referrals-count.ts
@@ -0,0 +1,45 @@
+import { getPartnerReferralsCountQuerySchema } from "@/lib/zod/schemas/partner-profile";
+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";
+
+export default function usePartnerReferralsCount<T = number>({
+ query,
+ includeParams = ["status", "search"],
+ enabled = true,
+}: {
+ query?: Partial<z.infer<typeof getPartnerReferralsCountQuerySchema>>;
+ 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
+ ? Object.fromEntries(
+ Object.entries(query).filter(
+ ([_, v]) => v !== undefined && v !== null && v !== "",
+ ),
+ )
+ : undefined,
+ {
+ include: includeParams,
+ },
+ )}`,
+ fetcher,
+ {
+ keepPreviousData: true,
+ },
+ );
+
+ return {
+ data,
+ error,
+ };
+}
diff --git a/apps/web/lib/swr/use-partner-referrals.ts b/apps/web/lib/swr/use-partner-referrals.ts
new file mode 100644
index 0000000000..bd64895b2f
--- /dev/null
+++ b/apps/web/lib/swr/use-partner-referrals.ts
@@ -0,0 +1,25 @@
+import { PartnerProfileReferral } from "@/lib/zod/schemas/partner-profile";
+import { useRouterStuff } from "@dub/ui";
+import { fetcher } from "@dub/utils";
+import { useParams } from "next/navigation";
+import useSWR from "swr";
+
+export default function usePartnerReferrals() {
+ const { programSlug } = useParams<{ programSlug: string }>();
+ const { getQueryString } = useRouterStuff();
+
+ const { data, isLoading, error } = useSWR<PartnerProfileReferral[]>(
+ programSlug &&
+ `/api/partner-profile/programs/${programSlug}/referrals${getQueryString()}`,
+ fetcher,
+ {
+ keepPreviousData: true,
+ },
+ );
+
+ return {
+ data,
+ isLoading,
+ error,
+ };
+}
diff --git a/apps/web/lib/tinybird/record-fake-click.ts b/apps/web/lib/tinybird/record-fake-click.ts
index 87cce715fc..fb0216e721 100644
--- a/apps/web/lib/tinybird/record-fake-click.ts
+++ b/apps/web/lib/tinybird/record-fake-click.ts
@@ -37,6 +37,7 @@ export async function recordFakeClick({
key: link.key,
url: link.url,
skipRatelimit: true,
+ shouldCacheClickId: true,
...(timestamp && { timestamp: new Date(timestamp).toISOString() }),
});
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index b77062a5f3..b443db3212 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -3,6 +3,7 @@ import {
PartnerEarningsSchema,
PartnerProfileCustomerSchema,
PartnerProfileLinkSchema,
+ partnerReferralsCountByStatusSchema,
partnerUserSchema,
} from "@/lib/zod/schemas/partner-profile";
import { DirectorySyncProviders } from "@boxyhq/saml-jackson";
@@ -120,7 +121,10 @@ import {
ProgramEnrollmentSchema,
ProgramSchema,
} from "./zod/schemas/programs";
+import { referralFormDataSchema } from "./zod/schemas/referral-form";
+import { referralSchema } from "./zod/schemas/referrals";
import {
+ CUSTOMER_SOURCES,
rewardConditionsArraySchema,
rewardConditionSchema,
rewardConditionsSchema,
@@ -473,6 +477,10 @@ export type PartnerProfileCustomerProps = z.infer<
export type PartnerProfileLinkProps = z.infer<typeof PartnerProfileLinkSchema>;
+export type PartnerProfileReferralsCountByStatus = z.infer<
+ typeof partnerReferralsCountByStatusSchema
+>;
+
export type EnrolledPartnerProps = z.infer<typeof EnrolledPartnerSchema> & {
platforms: PartnerPlatformProps[];
};
@@ -499,7 +507,12 @@ export type DiscountProps = z.infer<typeof DiscountSchema>;
export type DiscountCodeProps = z.infer<typeof DiscountCodeSchema>;
-export type ProgramProps = z.infer<typeof ProgramSchema>;
+export type ProgramProps = Omit<
+ z.infer<typeof ProgramSchema>,
+ "referralFormData"
+> & {
+ referralFormData?: Prisma.JsonValue | null;
+};
export type ProgramInviteEmailData = z.infer<
typeof programInviteEmailDataSchema
@@ -754,3 +767,9 @@ export type CreateFraudEventInput = Pick<
> & {
metadata?: Record<string, unknown> | null;
};
+
+export type ReferralProps = z.infer<typeof referralSchema>;
+
+export type ReferralFormDataField = z.infer<typeof referralFormDataSchema>;
+
+export type CustomerSource = (typeof CUSTOMER_SOURCES)[number];
diff --git a/apps/web/lib/zod/schemas/partner-profile.ts b/apps/web/lib/zod/schemas/partner-profile.ts
index 9b98d95162..4643e85d13 100644
--- a/apps/web/lib/zod/schemas/partner-profile.ts
+++ b/apps/web/lib/zod/schemas/partner-profile.ts
@@ -8,6 +8,7 @@ import {
PartnerProfileType,
PartnerRole,
ProgramEnrollmentStatus,
+ ReferralStatus,
} from "@dub/prisma/client";
import * as z from "zod/v4";
import { analyticsQuerySchema, eventsQuerySchema } from "./analytics";
@@ -22,6 +23,7 @@ import { CustomerEnrichedSchema } from "./customers";
import { LinkSchema } from "./links";
import { getPaginationQuerySchema } from "./misc";
import { payoutsQuerySchema } from "./payouts";
+import { referralFormDataSchema } from "./referral-form";
import { workflowConditionSchema } from "./workflows";
export const PartnerEarningsSchema = CommissionSchema.omit({
@@ -240,3 +242,46 @@ export const getPartnerCustomersCountQuerySchema =
.extend({
groupBy: z.enum(["country", "linkId"]).optional(),
});
+
+export const partnerProfileReferralSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ email: z.email(),
+ company: z.string(),
+ status: z.enum(ReferralStatus),
+ customerId: z.string().nullable(),
+ formData: z.array(referralFormDataSchema).nullable().optional(),
+ createdAt: z.date(),
+ updatedAt: z.date(),
+});
+
+export type PartnerProfileReferral = z.infer<
+ typeof partnerProfileReferralSchema
+>;
+
+export const getPartnerReferralsQuerySchema = z
+ .object({
+ status: z.enum(ReferralStatus).optional(),
+ search: z.string().optional(),
+ })
+ .extend(getPaginationQuerySchema({ pageSize: 100 }));
+
+export const getPartnerReferralsCountQuerySchema =
+ getPartnerReferralsQuerySchema
+ .omit({
+ page: true,
+ pageSize: true,
+ })
+ .extend({
+ groupBy: z.enum(["status"]).optional(),
+ });
+
+export const partnerReferralsCountByStatusSchema = z.object({
+ status: z.enum(ReferralStatus),
+ _count: z.number(),
+});
+
+export const partnerReferralsCountResponseSchema = z.union([
+ z.array(partnerReferralsCountByStatusSchema),
+ z.number(),
+]);
diff --git a/apps/web/lib/zod/schemas/programs.ts b/apps/web/lib/zod/schemas/programs.ts
index 0b358af61b..2080db533f 100644
--- a/apps/web/lib/zod/schemas/programs.ts
+++ b/apps/web/lib/zod/schemas/programs.ts
@@ -20,6 +20,7 @@ import { GroupSchema } from "./groups";
import { LinkSchema } from "./links";
import { programApplicationFormDataWithValuesSchema } from "./program-application-form";
import { programInviteEmailDataSchema } from "./program-invite-email";
+import { referralFormSchema } from "./referral-form";
import { RewardSchema } from "./rewards";
import { UserSchema } from "./users";
import { parseDateSchema } from "./utils";
@@ -46,6 +47,7 @@ export const ProgramSchema = z.object({
supportEmail: z.string().nullish(),
helpUrl: z.string().nullish(),
termsUrl: z.string().nullish(),
+ referralFormData: z.record(z.string(), z.any()).nullish(),
createdAt: z.date(),
updatedAt: z.date(),
startedAt: z.date().nullish(),
@@ -74,6 +76,7 @@ export const updateProgramSchema = z.object({
helpUrl: z.url().max(500).nullish(),
termsUrl: z.url().max(500).nullish(),
messagingEnabledAt: z.coerce.date().nullish(),
+ referralFormData: referralFormSchema.nullish(),
});
export const ProgramPartnerLinkSchema = LinkSchema.pick({
@@ -144,6 +147,7 @@ export const ProgramEnrollmentSchema = z.object({
linkStructure: true,
}).nullish(),
customerDataSharingEnabledAt: z.date().nullable(),
+ referralFormData: referralFormSchema.nullish(),
});
export const ProgramInviteSchema = z.object({
diff --git a/apps/web/lib/zod/schemas/referral-form.ts b/apps/web/lib/zod/schemas/referral-form.ts
new file mode 100644
index 0000000000..ccfb931eba
--- /dev/null
+++ b/apps/web/lib/zod/schemas/referral-form.ts
@@ -0,0 +1,126 @@
+import * as z from "zod/v4";
+
+export const fieldCommonSchema = z.object({
+ key: z.string().min(1),
+ label: z.string().min(1),
+ required: z.boolean(),
+ locked: z.boolean(),
+ position: z.number().int().nonnegative(),
+});
+
+export const selectOptionSchema = z.object({
+ label: z.string().min(1),
+ value: z.string().min(1),
+});
+
+// Text
+export const textFieldSchema = fieldCommonSchema.extend({
+ type: z.literal("text"),
+ constraints: z
+ .object({
+ maxLength: z.number().int().positive().optional(),
+ pattern: z.string().optional(),
+ })
+ .optional(),
+});
+
+// Textarea
+export const textareaFieldSchema = fieldCommonSchema.extend({
+ type: z.literal("textarea"),
+ constraints: z
+ .object({
+ maxLength: z.number().int().positive().optional(),
+ })
+ .optional(),
+});
+
+// Select
+export const selectFieldSchema = fieldCommonSchema.extend({
+ type: z.literal("select"),
+ options: z.array(selectOptionSchema).min(2),
+});
+
+// Country
+export const countryFieldSchema = fieldCommonSchema.extend({
+ type: z.literal("country"),
+});
+
+// Date
+export const dateFieldSchema = fieldCommonSchema.extend({
+ type: z.literal("date"),
+});
+
+// Multiple Choices (Multi-select)
+export const multiSelectFieldSchema = fieldCommonSchema.extend({
+ type: z.literal("multiSelect"),
+ options: z.array(selectOptionSchema).min(2),
+});
+
+// Number
+export const numberFieldSchema = fieldCommonSchema.extend({
+ type: z.literal("number"),
+});
+
+// Phone Number
+export const phoneFieldSchema = fieldCommonSchema.extend({
+ type: z.literal("phone"),
+});
+
+export const formFieldSchema = z.discriminatedUnion("type", [
+ textFieldSchema,
+ textareaFieldSchema,
+ selectFieldSchema,
+ countryFieldSchema,
+ dateFieldSchema,
+ multiSelectFieldSchema,
+ numberFieldSchema,
+ phoneFieldSchema,
+]);
+
+export const formFieldsSchema = z
+ .array(formFieldSchema)
+ .min(1)
+ .superRefine((fields, ctx) => {
+ const keys = new Set<string>();
+ const positions = new Set<number>();
+
+ for (const field of fields) {
+ if (keys.has(field.key)) {
+ ctx.addIssue({
+ path: ["fields"],
+ message: `Duplicate field key: ${field.key}`,
+ code: z.ZodIssueCode.custom,
+ });
+ }
+
+ if (positions.has(field.position)) {
+ ctx.addIssue({
+ path: ["fields"],
+ message: `Duplicate field position: ${field.position}`,
+ code: z.ZodIssueCode.custom,
+ });
+ }
+
+ keys.add(field.key);
+ positions.add(field.position);
+ }
+ });
+
+// Full form schema (builder storage)
+export const referralFormSchema = z.object({
+ fields: formFieldsSchema,
+});
+
+// This is the schema for the submitted form data that is stored in the database
+export const referralFormDataSchema = z.object({
+ key: z.string().min(1),
+ label: z.string().min(1),
+ value: z.unknown(),
+});
+
+// Schema for validating required fields
+export const referralRequiredFieldsSchema = z.object({
+ name: z.string().min(1, "Name is required"),
+ email: z.email("Invalid email address"),
+ company: z.string().min(1, "Company is required"),
+});
diff --git a/apps/web/lib/zod/schemas/referrals.ts b/apps/web/lib/zod/schemas/referrals.ts
new file mode 100644
index 0000000000..ab8df175b5
--- /dev/null
+++ b/apps/web/lib/zod/schemas/referrals.ts
@@ -0,0 +1,87 @@
+import { ReferralStatus } from "@dub/prisma/client";
+import * as z from "zod/v4";
+import { getPaginationQuerySchema } from "./misc";
+import { PartnerSchema } from "./partners";
+import { referralFormDataSchema } from "./referral-form";
+
+export const referralSchema = z.object({
+ id: z.string(),
+ programId: z.string(),
+ partnerId: z.string(),
+ name: z.string(),
+ email: z.email(),
+ company: z.string(),
+ status: z.enum(ReferralStatus),
+ formData: z.array(referralFormDataSchema).nullable().optional(),
+ createdAt: z.date(),
+ updatedAt: z.date(),
+ partner: PartnerSchema.pick({
+ id: true,
+ name: true,
+ email: true,
+ image: true,
+ }),
+});
+
+export const getPartnerReferralsQuerySchema = z
+ .object({
+ partnerId: z.string().optional(),
+ status: z.enum(ReferralStatus).optional(),
+ search: z.string().optional(),
+ })
+ .extend(getPaginationQuerySchema({ pageSize: 100 }));
+
+export const getPartnerReferralsCountQuerySchema =
+ getPartnerReferralsQuerySchema
+ .omit({
+ page: true,
+ pageSize: true,
+ })
+ .extend({
+ groupBy: z.enum(["status", "partnerId"]).optional(),
+ });
+
+export const partnerReferralsCountByStatusSchema = z.object({
+ status: z.enum(ReferralStatus),
+ _count: z.number(),
+});
+
+export const partnerReferralsCountByPartnerIdSchema = z.object({
+ partnerId: z.string(),
+ _count: z.number(),
+});
+
+export const partnerReferralsCountResponseSchema = z.union([
+ z.array(partnerReferralsCountByStatusSchema),
+ z.array(partnerReferralsCountByPartnerIdSchema),
+ z.number(),
+]);
+
+export const createPartnerReferralSchema = z.object({
+ programId: z.string(),
+ formData: z.record(z.string(), z.unknown()), // Contains all form fields including name, email, company
+});
+
+export const markReferralQualifiedSchema = z.object({
+ referralId: z.string(),
+ workspaceId: z.string(),
+});
+
+export const markReferralUnqualifiedSchema = z.object({
+ referralId: z.string(),
+ workspaceId: z.string(),
+});
+
+export const markReferralClosedWonSchema = z.object({
+ referralId: z.string(),
+ workspaceId: z.string(),
+ saleAmount: z
+ .number()
+ .min(0, "Sale amount must be greater than or equal to 0"),
+ stripeCustomerId: z.string().optional(),
+});
+
+export const markReferralClosedLostSchema = z.object({
+ referralId: z.string(),
+ workspaceId: z.string(),
+});
diff --git a/apps/web/lib/zod/schemas/rewards.ts b/apps/web/lib/zod/schemas/rewards.ts
index 97e4685739..4a0a36f1ff 100644
--- a/apps/web/lib/zod/schemas/rewards.ts
+++ b/apps/web/lib/zod/schemas/rewards.ts
@@ -17,54 +17,169 @@ export const COMMISSION_TYPES = [
},
] as const;
-export const CONDITION_ENTITIES = ["customer", "sale", "partner"] as const;
-
-export const CONDITION_CUSTOMER_ATTRIBUTES = ["country"] as const;
+export type RewardConditionEntityAttribute = {
+ id: string;
+ label: string;
+ type: "string" | "number" | "currency";
+ options?: {
+ id: string;
+ label: string;
+ }[];
+};
-export const CONDITION_SALE_ATTRIBUTES = ["productId", "amount"] as const;
+export type RewardConditionEntity = {
+ id: "partner" | "customer" | "sale";
+ label: string;
+ attributes: RewardConditionEntityAttribute[];
+};
-export const CONDITION_PARTNER_ATTRIBUTES = [
- "country",
- "totalClicks",
- "totalLeads",
- "totalConversions",
- "totalSaleAmount",
- "totalCommissions",
-] as const;
+const PARTNER_ENTITY: RewardConditionEntity = {
+ id: "partner",
+ label: "Partner",
+ attributes: [
+ {
+ id: "country",
+ label: "Country",
+ type: "string",
+ },
+ {
+ id: "totalClicks",
+ label: "Total clicks",
+ type: "number",
+ },
+ {
+ id: "totalLeads",
+ label: "Total leads",
+ type: "number",
+ },
+ {
+ id: "totalConversions",
+ label: "Total conversions",
+ type: "number",
+ },
+ {
+ id: "totalSaleAmount",
+ label: "Total revenue",
+ type: "currency",
+ },
+ {
+ id: "totalCommissions",
+ label: "Total commissions",
+ type: "currency",
+ },
+ ],
+};
-export const CONDITION_ATTRIBUTES = [
- ...CONDITION_CUSTOMER_ATTRIBUTES,
- ...CONDITION_SALE_ATTRIBUTES,
- ...CONDITION_PARTNER_ATTRIBUTES,
-] as const;
+const CUSTOMER_ENTITY: RewardConditionEntity = {
+ id: "customer",
+ label: "Customer",
+ attributes: [
+ {
+ id: "country",
+ label: "Country",
+ type: "string",
+ },
+ ],
+};
-export const ENTITY_ATTRIBUTE_TYPES: Partial<
- Record<
- (typeof CONDITION_ENTITIES)[number],
- Partial<
- Record<
- (typeof CONDITION_ATTRIBUTES)[number],
- "string" | "number" | "currency"
- >
- >
- >
+export const REWARD_CONDITIONS: Record<
+ EventType,
+ {
+ entities: RewardConditionEntity[];
+ }
> = {
- customer: {
- country: "string",
+ // Click reward
+ click: {
+ entities: [CUSTOMER_ENTITY],
},
- partner: {
- country: "string",
- totalClicks: "number",
- totalLeads: "number",
- totalConversions: "number",
- totalSaleAmount: "currency",
- totalCommissions: "currency",
+
+ // Lead reward
+ lead: {
+ entities: [
+ {
+ ...CUSTOMER_ENTITY,
+ attributes: [
+ ...CUSTOMER_ENTITY.attributes,
+ {
+ id: "source",
+ label: "Source",
+ type: "string",
+ options: [
+ {
+ id: "tracked",
+ label: "tracked lead",
+ },
+ {
+ id: "submitted",
+ label: "qualified lead",
+ },
+ ],
+ },
+ ],
+ },
+ PARTNER_ENTITY,
+ ],
},
+
+ // Sale reward
sale: {
- amount: "currency",
+ entities: [
+ {
+ ...CUSTOMER_ENTITY,
+ attributes: [
+ ...CUSTOMER_ENTITY.attributes,
+ {
+ id: "source",
+ label: "Source",
+ type: "string",
+ options: [
+ {
+ id: "tracked",
+ label: "tracked sale",
+ },
+ {
+ id: "submitted",
+ label: "closed won deal",
+ },
+ ],
+ },
+ ],
+ },
+ PARTNER_ENTITY,
+ {
+ id: "sale",
+ label: "Sale",
+ attributes: [
+ {
+ id: "productId",
+ label: "Product ID",
+ type: "string",
+ },
+ {
+ id: "amount",
+ label: "Amount",
+ type: "currency",
+ },
+ ],
+ },
+ ],
},
};
+export const REWARD_CONDITION_ENTITIES = [
+ ...new Set(
+ Object.values(REWARD_CONDITIONS).flatMap(({ entities }) => entities),
+ ),
+];
+
+export const REWARD_CONDITION_ATTRIBUTES = [
+ ...new Set(
+ Object.values(REWARD_CONDITIONS).flatMap(({ entities }) =>
+ entities.flatMap(({ attributes }) => attributes),
+ ),
+ ),
+];
+
export const CONDITION_OPERATORS = [
"equals_to",
"not_equals",
@@ -91,17 +206,6 @@ export const NUMBER_CONDITION_OPERATORS: (typeof CONDITION_OPERATORS)[number][]
"less_than_or_equal",
];
-export const ATTRIBUTE_LABELS = {
- country: "Country",
- productId: "Product ID",
- amount: "Amount",
- totalClicks: "Total clicks",
- totalLeads: "Total leads",
- totalConversions: "Total conversions",
- totalSaleAmount: "Total revenue",
- totalCommissions: "Total commissions",
-} as const;
-
export const CONDITION_OPERATOR_LABELS = {
equals_to: "is",
not_equals: "is not",
@@ -116,8 +220,12 @@ export const CONDITION_OPERATOR_LABELS = {
} as const;
export const rewardConditionSchema = z.object({
- entity: z.enum(CONDITION_ENTITIES),
- attribute: z.enum(CONDITION_ATTRIBUTES),
+ entity: z.enum(
+ REWARD_CONDITION_ENTITIES.map(({ id }) => id) as [string, ...string[]],
+ ),
+ attribute: z.enum(
+ REWARD_CONDITION_ATTRIBUTES.map(({ id }) => id) as [string, ...string[]],
+ ),
operator: z.enum(CONDITION_OPERATORS),
value: z.union([
z.string(),
@@ -226,10 +334,13 @@ export const REWARD_EVENT_COLUMN_MAPPING = Object.freeze({
sale: "saleRewardId",
});
+export const CUSTOMER_SOURCES = ["tracked", "submitted"] as const;
+
export const rewardContextSchema = z.object({
customer: z
.object({
country: z.string().nullish(),
+ source: z.enum(CUSTOMER_SOURCES).default("tracked").nullish(),
})
.optional(),
diff --git a/apps/web/scripts/referral-form-sample.json b/apps/web/scripts/referral-form-sample.json
new file mode 100644
index 0000000000..5e64f42328
--- /dev/null
+++ b/apps/web/scripts/referral-form-sample.json
@@ -0,0 +1,107 @@
+{
+ "fields": [
+ {
+ "key": "department",
+ "label": "Department",
+ "type": "text",
+ "required": true,
+ "locked": false,
+ "position": 0,
+ "constraints": {
+ "maxLength": 100,
+ "pattern": "^[a-zA-Z0-9\\s-]+$"
+ }
+ },
+ {
+ "key": "description",
+ "label": "Description",
+ "type": "textarea",
+ "required": true,
+ "locked": false,
+ "position": 1,
+ "constraints": {
+ "maxLength": 500
+ }
+ },
+ {
+ "key": "referralType",
+ "label": "Referral Type",
+ "type": "select",
+ "required": true,
+ "locked": false,
+ "position": 2,
+ "options": [
+ {
+ "label": "Enterprise",
+ "value": "enterprise"
+ },
+ {
+ "label": "SMB",
+ "value": "smb"
+ },
+ {
+ "label": "Startup",
+ "value": "startup"
+ }
+ ]
+ },
+ {
+ "key": "country",
+ "label": "Country",
+ "type": "country",
+ "required": false,
+ "locked": false,
+ "position": 3
+ },
+ {
+ "key": "startDate",
+ "label": "Start Date",
+ "type": "date",
+ "required": false,
+ "locked": false,
+ "position": 4
+ },
+ {
+ "key": "interests",
+ "label": "Interests",
+ "type": "multiSelect",
+ "required": false,
+ "locked": false,
+ "position": 5,
+ "options": [
+ {
+ "label": "Technology",
+ "value": "technology"
+ },
+ {
+ "label": "Marketing",
+ "value": "marketing"
+ },
+ {
+ "label": "Sales",
+ "value": "sales"
+ },
+ {
+ "label": "Support",
+ "value": "support"
+ }
+ ]
+ },
+ {
+ "key": "employeeCount",
+ "label": "Employee Count",
+ "type": "number",
+ "required": false,
+ "locked": false,
+ "position": 6
+ },
+ {
+ "key": "phoneNumber",
+ "label": "Phone Number",
+ "type": "phone",
+ "required": false,
+ "locked": false,
+ "position": 7
+ }
+ ]
+}
diff --git a/apps/web/scripts/update-referral-form-data.ts b/apps/web/scripts/update-referral-form-data.ts
new file mode 100644
index 0000000000..5aa609374f
--- /dev/null
+++ b/apps/web/scripts/update-referral-form-data.ts
@@ -0,0 +1,40 @@
+import { referralFormSchema } from "@/lib/zod/schemas/referral-form";
+import { prisma } from "@dub/prisma";
+import { ACME_PROGRAM_ID } from "@dub/utils";
+import "dotenv-flow/config";
+import { readFileSync } from "fs";
+
+async function main() {
+ const programId = ACME_PROGRAM_ID;
+ const jsonFilePath = "./scripts/referral-form-sample.json";
+
+ // Read and parse JSON file
+ let formData;
+ try {
+ const fileContent = readFileSync(jsonFilePath, "utf-8");
+ formData = JSON.parse(fileContent);
+ } catch (error) {
+ console.error(`Error reading JSON file: ${error}`);
+ process.exit(1);
+ }
+
+ // Validate JSON against schema
+ let validatedData;
+ try {
+ validatedData = referralFormSchema.parse(formData);
+ } catch (error) {
+ console.error("Validation failed:", error);
+ process.exit(1);
+ }
+
+ await prisma.program.update({
+ where: {
+ id: programId,
+ },
+ data: {
+ referralFormData: validatedData,
+ },
+ });
+}
+
+main();
diff --git a/apps/web/ui/analytics/analytics-export-button.tsx b/apps/web/ui/analytics/analytics-export-button.tsx
index 2f96b050fe..dbe64d605e 100644
--- a/apps/web/ui/analytics/analytics-export-button.tsx
+++ b/apps/web/ui/analytics/analytics-export-button.tsx
@@ -10,7 +10,8 @@ export function AnalyticsExportButton({
setOpenPopover: Dispatch<SetStateAction<boolean>>;
}) {
const [loading, setLoading] = useState(false);
- const { queryString, baseApiPath, partnerPage } = useContext(AnalyticsContext);
+ const { queryString, baseApiPath, partnerPage } =
+ useContext(AnalyticsContext);
async function exportData() {
setLoading(true);
diff --git a/apps/web/ui/layout/page-content/index.tsx b/apps/web/ui/layout/page-content/index.tsx
index aed6ce90ee..fe21aefd00 100644
--- a/apps/web/ui/layout/page-content/index.tsx
+++ b/apps/web/ui/layout/page-content/index.tsx
@@ -21,7 +21,7 @@ export function PageContent({
return (
<div
className={cn(
- "min-h-full flex flex-col rounded-t-[inherit] bg-neutral-100 md:bg-white",
+ "flex min-h-full flex-col rounded-t-[inherit] bg-neutral-100 md:bg-white",
className,
)}
>
diff --git a/apps/web/ui/modals/bulk-archive-partners-modal.tsx b/apps/web/ui/modals/bulk-archive-partners-modal.tsx
index efb831e64d..183dcbafff 100644
--- a/apps/web/ui/modals/bulk-archive-partners-modal.tsx
+++ b/apps/web/ui/modals/bulk-archive-partners-modal.tsx
@@ -52,9 +52,7 @@ function BulkArchivePartnersModal({
setShowBulkArchivePartnersModal(false);
await onConfirm?.();
- toast.success(
- `${partners.length} ${partnerWord} archived successfully!`,
- );
+ toast.success(`${partners.length} ${partnerWord} archived successfully!`);
}, [
executeAsync,
partners,
diff --git a/apps/web/ui/modals/mark-partner-referral-closed-lost-modal.tsx b/apps/web/ui/modals/mark-partner-referral-closed-lost-modal.tsx
new file mode 100644
index 0000000000..4ce69adf7e
--- /dev/null
+++ b/apps/web/ui/modals/mark-partner-referral-closed-lost-modal.tsx
@@ -0,0 +1,56 @@
+"use client";
+
+import { markReferralClosedLostAction } from "@/lib/actions/referrals/mark-referral-closed-lost";
+import { mutatePrefix } from "@/lib/swr/mutate";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { referralSchema } from "@/lib/zod/schemas/referrals";
+import { useConfirmModal } from "@/ui/modals/confirm-modal";
+import { useAction } from "next-safe-action/hooks";
+import { toast } from "sonner";
+import * as z from "zod/v4";
+
+type PartnerReferralProps = z.infer<typeof referralSchema>;
+
+export function useMarkPartnerReferralClosedLostModal({
+ referral,
+}: {
+ referral: PartnerReferralProps;
+}) {
+ const { id: workspaceId } = useWorkspace();
+
+ const { executeAsync, isPending } = useAction(markReferralClosedLostAction, {
+ onSuccess: async () => {
+ toast.success("Partner referral marked as closed lost successfully!");
+ mutatePrefix("/api/programs/referrals");
+ },
+ onError({ error }) {
+ toast.error(error.serverError);
+ },
+ });
+
+ const { setShowConfirmModal, confirmModal } = useConfirmModal({
+ title: "Lead closed lost",
+ description:
+ "Are you sure you want to mark this partner referral as closed lost?",
+ confirmText: "Closed lost",
+ cancelText: "Cancel",
+ confirmShortcut: "L",
+ confirmShortcutOptions: { modal: true },
+ onConfirm: async () => {
+ if (!workspaceId || !referral.id) {
+ return;
+ }
+
+ await executeAsync({
+ workspaceId,
+ referralId: referral.id,
+ });
+ },
+ });
+
+ return {
+ setShowClosedLostModal: setShowConfirmModal,
+ ClosedLostModal: confirmModal,
+ isMarkingClosedLost: isPending,
+ };
+}
diff --git a/apps/web/ui/modals/mark-partner-referral-closed-won-modal.tsx b/apps/web/ui/modals/mark-partner-referral-closed-won-modal.tsx
new file mode 100644
index 0000000000..5d5db73756
--- /dev/null
+++ b/apps/web/ui/modals/mark-partner-referral-closed-won-modal.tsx
@@ -0,0 +1,204 @@
+"use client";
+
+import { markReferralClosedWonAction } from "@/lib/actions/referrals/mark-referral-closed-won";
+import { handleMoneyInputChange, handleMoneyKeyDown } from "@/lib/form-utils";
+import { mutatePrefix } from "@/lib/swr/mutate";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { referralSchema } from "@/lib/zod/schemas/referrals";
+import { Button, Modal } from "@dub/ui";
+import { cn } from "@dub/utils";
+import { useAction } from "next-safe-action/hooks";
+import { useCallback, useMemo, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import * as z from "zod/v4";
+
+type PartnerReferralProps = z.infer<typeof referralSchema>;
+
+type MarkPartnerReferralClosedWonFormData = {
+ saleAmount: number | null;
+ stripeCustomerId: string;
+};
+
+export function useMarkPartnerReferralClosedWonModal({
+ referral,
+}: {
+ referral: PartnerReferralProps;
+}) {
+ const { id: workspaceId } = useWorkspace();
+ const [showModal, setShowModal] = useState(false);
+
+ const {
+ register,
+ handleSubmit,
+ formState: { errors, isSubmitting },
+ reset,
+ } = useForm<MarkPartnerReferralClosedWonFormData>({
+ defaultValues: {
+ saleAmount: null,
+ stripeCustomerId: "",
+ },
+ });
+
+ const { executeAsync, isPending } = useAction(markReferralClosedWonAction, {
+ onSuccess: async () => {
+ toast.success("Partner referral marked as closed won successfully!");
+ mutatePrefix("/api/programs/referrals");
+ setShowModal(false);
+ reset();
+ },
+ onError({ error }) {
+ toast.error(error.serverError);
+ },
+ });
+
+ const onSubmit = useCallback(
+ async (data: MarkPartnerReferralClosedWonFormData) => {
+ if (!workspaceId || !referral.id || data.saleAmount === null) {
+ return;
+ }
+
+ // Convert sale amount from dollars to cents
+ const saleAmountInCents = Math.round(data.saleAmount * 100);
+
+ await executeAsync({
+ workspaceId,
+ referralId: referral.id,
+ saleAmount: saleAmountInCents,
+ stripeCustomerId: data.stripeCustomerId || undefined,
+ });
+ },
+ [executeAsync, referral.id, workspaceId],
+ );
+
+ const closedWonModal = useMemo(
+ () => (
+ <Modal showModal={showModal} setShowModal={setShowModal}>
+ <form onSubmit={handleSubmit(onSubmit)}>
+ <div className="flex flex-col gap-1 border-b border-neutral-200 px-[18px] py-5 text-left">
+ <h3 className="text-content-emphasis text-base font-semibold">
+ Lead closed won
+ </h3>
+ <p className="text-content-subtle text-sm">
+ Are you sure you want to mark this partner referral as closed won?
+ </p>
+ </div>
+
+ <div className="flex flex-col gap-5 p-5">
+ <div className="flex flex-col gap-2">
+ <label className="text-content-emphasis block text-sm font-medium">
+ Sale Amount (required)
+ </label>
+ <div className="relative rounded-md shadow-sm">
+ <span className="absolute inset-y-0 left-0 flex items-center pl-3 text-sm text-neutral-400">
+ $
+ </span>
+ <input
+ type="number"
+ step="0.01"
+ min="0"
+ className={cn(
+ "block w-full rounded-md border-neutral-300 pl-6 pr-12 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",
+ errors.saleAmount &&
+ "border-red-600 focus:border-red-500 focus:ring-red-600",
+ )}
+ placeholder="50000"
+ {...register("saleAmount", {
+ required: "Sale amount is required",
+ min: {
+ value: 0,
+ message: "Sale amount must be greater than or equal to 0",
+ },
+ valueAsNumber: true,
+ onChange: handleMoneyInputChange,
+ })}
+ onKeyDown={handleMoneyKeyDown}
+ />
+ <span className="absolute inset-y-0 right-0 flex items-center pr-3 text-sm text-neutral-400">
+ USD
+ </span>
+ </div>
+
+ {errors.saleAmount && (
+ <p className="text-xs text-red-600">
+ {errors.saleAmount.message}
+ </p>
+ )}
+
+ <p className="text-xs text-neutral-500">
+ This will be also recorded as a sale commission (if applicable)
+ </p>
+ </div>
+
+ <div className="flex flex-col gap-2">
+ <label className="text-content-emphasis block text-sm font-medium">
+ Stripe Customer ID
+ </label>
+ <div className="relative rounded-md shadow-sm">
+ <input
+ type="text"
+ className={cn(
+ "block w-full rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",
+ errors.stripeCustomerId &&
+ "border-red-600 focus:border-red-500 focus:ring-red-600",
+ )}
+ placeholder="cus_NffrFeUfNV2Hib"
+ {...register("stripeCustomerId", {
+ required: false,
+ })}
+ />
+ </div>
+
+ {errors.stripeCustomerId && (
+ <p className="text-xs text-red-600">
+ {errors.stripeCustomerId.message}
+ </p>
+ )}
+
+ <p className="text-xs text-neutral-500">
+ The customer's Stripe Customer ID (optional)
+ </p>
+ </div>
+ </div>
+
+ <div className="border-border-subtle flex items-center justify-end gap-2 border-t px-5 py-4">
+ <Button
+ variant="secondary"
+ className="h-8 w-fit px-3"
+ text="Cancel"
+ shortcut="C"
+ onClick={() => {
+ setShowModal(false);
+ reset();
+ }}
+ />
+ <Button
+ type="submit"
+ variant="primary"
+ className="h-8 w-fit px-3"
+ text="Closed won"
+ shortcut="W"
+ loading={isPending || isSubmitting}
+ />
+ </div>
+ </form>
+ </Modal>
+ ),
+ [
+ showModal,
+ handleSubmit,
+ onSubmit,
+ register,
+ errors,
+ isPending,
+ isSubmitting,
+ reset,
+ ],
+ );
+
+ return {
+ setShowModal,
+ ClosedWonModal: closedWonModal,
+ isMarkingClosedWon: isPending || isSubmitting,
+ };
+}
diff --git a/apps/web/ui/modals/qualify-partner-referral-modal.tsx b/apps/web/ui/modals/qualify-partner-referral-modal.tsx
new file mode 100644
index 0000000000..f253b5c4bd
--- /dev/null
+++ b/apps/web/ui/modals/qualify-partner-referral-modal.tsx
@@ -0,0 +1,55 @@
+"use client";
+
+import { markReferralQualifiedAction } from "@/lib/actions/referrals/mark-referral-qualified";
+import { mutatePrefix } from "@/lib/swr/mutate";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { referralSchema } from "@/lib/zod/schemas/referrals";
+import { useConfirmModal } from "@/ui/modals/confirm-modal";
+import { useAction } from "next-safe-action/hooks";
+import { toast } from "sonner";
+import * as z from "zod/v4";
+
+type PartnerReferralProps = z.infer<typeof referralSchema>;
+
+export function useQualifyPartnerReferralModal({
+ referral,
+}: {
+ referral: PartnerReferralProps;
+}) {
+ const { id: workspaceId } = useWorkspace();
+
+ const { executeAsync, isPending } = useAction(markReferralQualifiedAction, {
+ onSuccess: async () => {
+ toast.success("Partner referral qualified successfully!");
+ mutatePrefix("/api/programs/referrals");
+ },
+ onError({ error }) {
+ toast.error(error.serverError);
+ },
+ });
+
+ const { setShowConfirmModal, confirmModal } = useConfirmModal({
+ title: "Qualify lead",
+ description: "Are you sure you want to qualify this partner referral?",
+ confirmText: "Qualify",
+ cancelText: "Cancel",
+ confirmShortcut: "Q",
+ confirmShortcutOptions: { modal: true },
+ onConfirm: async () => {
+ if (!workspaceId || !referral.id) {
+ return;
+ }
+
+ await executeAsync({
+ workspaceId,
+ referralId: referral.id,
+ });
+ },
+ });
+
+ return {
+ setShowQualifyModal: setShowConfirmModal,
+ QualifyModal: confirmModal,
+ isQualifying: isPending,
+ };
+}
diff --git a/apps/web/ui/modals/unqualify-partner-referral-modal.tsx b/apps/web/ui/modals/unqualify-partner-referral-modal.tsx
new file mode 100644
index 0000000000..5d80d9c3ab
--- /dev/null
+++ b/apps/web/ui/modals/unqualify-partner-referral-modal.tsx
@@ -0,0 +1,55 @@
+"use client";
+
+import { markReferralUnqualifiedAction } from "@/lib/actions/referrals/mark-referral-unqualified";
+import { mutatePrefix } from "@/lib/swr/mutate";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { referralSchema } from "@/lib/zod/schemas/referrals";
+import { useConfirmModal } from "@/ui/modals/confirm-modal";
+import { useAction } from "next-safe-action/hooks";
+import { toast } from "sonner";
+import * as z from "zod/v4";
+
+type PartnerReferralProps = z.infer<typeof referralSchema>;
+
+export function useUnqualifyPartnerReferralModal({
+ referral,
+}: {
+ referral: PartnerReferralProps;
+}) {
+ const { id: workspaceId } = useWorkspace();
+
+ const { executeAsync, isPending } = useAction(markReferralUnqualifiedAction, {
+ onSuccess: async () => {
+ toast.success("Partner referral unqualified successfully!");
+ mutatePrefix("/api/programs/referrals");
+ },
+ onError({ error }) {
+ toast.error(error.serverError);
+ },
+ });
+
+ const { setShowConfirmModal, confirmModal } = useConfirmModal({
+ title: "Unqualify lead",
+ description: "Are you sure you want to unqualify this partner referral?",
+ confirmText: "Unqualify",
+ cancelText: "Cancel",
+ confirmShortcut: "U",
+ confirmShortcutOptions: { modal: true },
+ onConfirm: async () => {
+ if (!workspaceId || !referral.id) {
+ return;
+ }
+
+ await executeAsync({
+ workspaceId,
+ referralId: referral.id,
+ });
+ },
+ });
+
+ return {
+ setShowUnqualifyModal: setShowConfirmModal,
+ UnqualifyModal: confirmModal,
+ isUnqualifying: isPending,
+ };
+}
diff --git a/apps/web/ui/partners/program-marketplace/program-marketplace-logos.tsx b/apps/web/ui/partners/program-marketplace/program-marketplace-logos.tsx
index 37e3433379..0bf53c92d4 100644
--- a/apps/web/ui/partners/program-marketplace/program-marketplace-logos.tsx
+++ b/apps/web/ui/partners/program-marketplace/program-marketplace-logos.tsx
@@ -27,7 +27,7 @@ const LOGOS = [
// Granola
{ x: 26, y: 70, r: 4, s: 0.8 },
];
-const LOGO_COUNT = LOGOS.length;
+export const PROGRAM_MARKETPLACE_LOGO_COUNT = LOGOS.length;
export function ProgramMarketplaceLogos({ className }: { className?: string }) {
return (
@@ -60,9 +60,12 @@ export function ProgramMarketplaceLogos({ className }: { className?: string }) {
zIndex: z,
backgroundImage:
"url(https://assets.dub.co/misc/program-marketplace-logos.png)",
- backgroundSize: `${LOGO_COUNT * 100}%`,
+ backgroundSize: `${PROGRAM_MARKETPLACE_LOGO_COUNT * 100}%`,
backgroundPositionX:
- (LOGO_COUNT - (index % LOGO_COUNT)) * 100 + "%",
+ (PROGRAM_MARKETPLACE_LOGO_COUNT -
+ (index % PROGRAM_MARKETPLACE_LOGO_COUNT)) *
+ 100 +
+ "%",
}}
/>
</div>
diff --git a/apps/web/ui/partners/program-reward-modifiers-tooltip.tsx b/apps/web/ui/partners/program-reward-modifiers-tooltip.tsx
index 99ef293433..7dc126c0d1 100644
--- a/apps/web/ui/partners/program-reward-modifiers-tooltip.tsx
+++ b/apps/web/ui/partners/program-reward-modifiers-tooltip.tsx
@@ -4,9 +4,9 @@ import { constructRewardAmount } from "@/lib/api/sales/construct-reward-amount";
import { getRewardAmount } from "@/lib/partners/get-reward-amount";
import { RewardProps } from "@/lib/types";
import {
- ATTRIBUTE_LABELS,
CONDITION_OPERATOR_LABELS,
- ENTITY_ATTRIBUTE_TYPES,
+ REWARD_CONDITIONS,
+ rewardConditionSchema,
rewardConditionsArraySchema,
rewardConditionsSchema,
} from "@/lib/zod/schemas/rewards";
@@ -20,11 +20,6 @@ import {
import { useRef } from "react";
import * as z from "zod/v4";
-const REWARD_MODIFIER_LABELS = {
- ...ATTRIBUTE_LABELS,
- productId: "Product",
-};
-
type ProgramRewardModifiersTooltipProps = {
reward?: Omit<RewardProps, "id"> | null;
};
@@ -108,9 +103,7 @@ const RewardItem = ({
operator = "AND",
}: {
reward: Omit<RewardProps, "id">;
- conditions?: z.infer<
- typeof rewardConditionsArraySchema
- >[number]["conditions"];
+ conditions?: z.infer<typeof rewardConditionSchema>[];
operator?: z.infer<typeof rewardConditionsSchema>["operator"];
}) => {
const rewardAmount = constructRewardAmount({
@@ -142,13 +135,20 @@ const RewardItem = ({
{conditions && conditions.length > 0 && (
<ul className="ml-1 text-xs font-medium text-neutral-600">
{conditions.map((condition, idx) => {
+ const entity = REWARD_CONDITIONS[reward.event].entities.find(
+ (e) => e.id === condition.entity,
+ );
+ const attribute = entity?.attributes?.find(
+ (a) => a.id === condition.attribute,
+ );
+
return (
<li key={idx} className="flex items-start gap-1">
<span className="shrink-0 text-lg leading-none">&bull;</span>
<span className="min-w-0">
{idx === 0 ? "If" : capitalize(operator.toLowerCase())}{" "}
{condition.entity}{" "}
- {REWARD_MODIFIER_LABELS[condition.attribute].toLowerCase()}{" "}
+ {(attribute?.label ?? condition.attribute)?.toLowerCase()}{" "}
{CONDITION_OPERATOR_LABELS[condition.operator]}{" "}
{condition.value &&
(condition.attribute === "country"
@@ -162,17 +162,26 @@ const RewardItem = ({
: // Non-country value(s)
Array.isArray(condition.value)
? // Basic array
- condition.value.join(", ")
+ (attribute?.options
+ ? (condition.value as string[] | number[]).map(
+ (v) =>
+ attribute.options?.find((o) => o.id === v)
+ ?.label ?? v,
+ )
+ : condition.value
+ ).join(", ")
: condition.attribute === "productId" && condition.label
? // Product label
condition.label
- : ENTITY_ATTRIBUTE_TYPES[condition.entity]?.[
- condition.attribute
- ] === "currency"
+ : attribute?.type === "currency"
? // Currency value
currencyFormatter(Number(condition.value))
: // Everything else
- condition.value.toString())}
+ attribute?.options
+ ? attribute.options.find(
+ (o) => o.id === condition.value,
+ )?.label ?? condition.value.toString()
+ : condition.value.toString())}
</span>
</li>
);
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 cc66d43bf4..36acea3ea1 100644
--- a/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
+++ b/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
@@ -14,7 +14,7 @@ import { RewardConditionsArray, RewardProps } from "@/lib/types";
import { RECURRING_MAX_DURATIONS } from "@/lib/zod/schemas/misc";
import {
createOrUpdateRewardSchema,
- ENTITY_ATTRIBUTE_TYPES,
+ REWARD_CONDITION_ATTRIBUTES,
REWARD_DESCRIPTION_MAX_LENGTH,
REWARD_TOOLTIP_DESCRIPTION_MAX_LENGTH,
rewardConditionsArraySchema,
@@ -101,7 +101,8 @@ export const getRewardPayload = ({ data }: { data: FormData }) => {
value:
c.entity &&
c.attribute &&
- ENTITY_ATTRIBUTE_TYPES[c.entity]?.[c.attribute] === "currency"
+ REWARD_CONDITION_ATTRIBUTES.find((a) => a.id === c.attribute)
+ ?.type === "currency"
? c.value === "" ||
c.value == null ||
Number.isNaN(Number(c.value))
@@ -191,7 +192,8 @@ function RewardSheetContent({
conditions: m.conditions.map((c) => ({
...c,
value:
- ENTITY_ATTRIBUTE_TYPES[c.entity]?.[c.attribute] === "currency" &&
+ REWARD_CONDITION_ATTRIBUTES.find((a) => a.id === c.attribute)
+ ?.type === "currency" &&
c.value !== "" &&
c.value != null &&
!Number.isNaN(Number(c.value))
diff --git a/apps/web/ui/partners/rewards/rewards-logic.tsx b/apps/web/ui/partners/rewards/rewards-logic.tsx
index 71620b85b8..4fbc1f48ea 100644
--- a/apps/web/ui/partners/rewards/rewards-logic.tsx
+++ b/apps/web/ui/partners/rewards/rewards-logic.tsx
@@ -6,19 +6,15 @@ import { getPlanCapabilities } from "@/lib/plan-capabilities";
import useWorkspace from "@/lib/swr/use-workspace";
import { RECURRING_MAX_DURATIONS } from "@/lib/zod/schemas/misc";
import {
- ATTRIBUTE_LABELS,
- CONDITION_ATTRIBUTES,
- CONDITION_CUSTOMER_ATTRIBUTES,
CONDITION_OPERATOR_LABELS,
CONDITION_OPERATORS,
- CONDITION_PARTNER_ATTRIBUTES,
- CONDITION_SALE_ATTRIBUTES,
- ENTITY_ATTRIBUTE_TYPES,
NUMBER_CONDITION_OPERATORS,
+ REWARD_CONDITIONS,
+ RewardConditionEntityAttribute,
STRING_CONDITION_OPERATORS,
} from "@/lib/zod/schemas/rewards";
import { X } from "@/ui/shared/icons";
-import { EventType, RewardStructure } from "@dub/prisma/client";
+import { RewardStructure } from "@dub/prisma/client";
import {
ArrowTurnRight2,
Button,
@@ -215,28 +211,12 @@ function ConditionalGroup({
);
}
-const ENTITIES = {
- customer: {
- attributes: CONDITION_CUSTOMER_ATTRIBUTES,
- },
- sale: {
- attributes: CONDITION_SALE_ATTRIBUTES,
- },
- partner: {
- attributes: CONDITION_PARTNER_ATTRIBUTES,
- },
-} as const;
-
-const EVENT_ENTITIES: Record<EventType, (keyof typeof ENTITIES)[]> = {
- sale: ["sale", "customer", "partner"],
- lead: ["customer", "partner"],
- click: ["customer"],
-};
-
const formatValue = (
value: string | number | string[] | number[] | undefined,
- type: "number" | "currency" | "string" = "string",
+ attribute?: Pick<RewardConditionEntityAttribute, "type" | "options">,
) => {
+ const type = attribute?.type ?? "string";
+
if (
["number", "currency"].includes(type)
? value === "" || isNaN(Number(value))
@@ -251,12 +231,25 @@ const formatValue = (
return (
filtered
- .map((v) => truncate(v.toString(), 16))
+ .map((v) =>
+ truncate(
+ attribute?.options
+ ? attribute.options.find((o) => o.id === v)?.label ?? v.toString()
+ : v.toString(),
+ 16,
+ ),
+ )
.slice(0, 2)
.join(", ") + (filtered.length > 2 ? ` +${filtered.length - 2}` : "")
);
}
+ // Return matching option label
+ if (attribute?.options) {
+ const option = attribute.options.find((o) => o.id === value);
+ if (option) return option.label;
+ }
+
// For numeric values, show the number as is
if (["number", "currency"].includes(type)) {
return type === "number"
@@ -288,14 +281,20 @@ function ConditionLogic({
name: ["event", conditionKey, `${modifierKey}.operator`],
});
- const attributeType =
- condition.entity && condition.attribute
- ? ENTITY_ATTRIBUTE_TYPES[condition.entity]?.[condition.attribute] ??
- "string"
- : "string";
+ const entities = REWARD_CONDITIONS[event].entities;
+ const entity = condition.entity
+ ? entities.find((e) => e.id === condition.entity)
+ : undefined;
- const icon = condition.entity
- ? { customer: User, sale: InvoiceDollar, partner: Users }[condition.entity]
+ const attribute =
+ entity && condition.attribute
+ ? entity.attributes.find((a) => a.id === condition.attribute)
+ : undefined;
+
+ const attributeType = attribute?.type ?? "string";
+
+ const icon = entity
+ ? { customer: User, sale: InvoiceDollar, partner: Users }[entity.id] ?? User
: ArrowTurnRight2;
const isArrayValue =
@@ -320,7 +319,7 @@ function ConditionLogic({
setValue(
conditionKey,
{
- entity: value as keyof typeof ENTITIES,
+ entity: value,
// Clear dependent fields when entity changes
attribute: undefined,
operator: undefined,
@@ -331,23 +330,20 @@ function ConditionLogic({
},
)
}
- items={Object.keys(ENTITIES)
- .filter((e) =>
- EVENT_ENTITIES[event]?.includes(e as keyof typeof ENTITIES),
- )
- .map((entity) => ({
- text: capitalize(entity) || entity,
- value: entity,
- }))}
+ items={entities.map((entity) => ({
+ text: entity.label,
+ value: entity.id,
+ }))}
/>
</InlineBadgePopover>{" "}
- {condition.entity && (
+ {entity && (
<>
<InlineBadgePopover
text={
condition.attribute
- ? ATTRIBUTE_LABELS?.[condition.attribute] ||
- capitalize(condition.attribute)
+ ? entity.attributes.find(
+ (a) => a.id === condition.attribute,
+ )?.label || capitalize(condition.attribute)
: "Detail"
}
invalid={!condition.attribute}
@@ -359,23 +355,17 @@ function ConditionLogic({
conditionKey,
{
entity: condition.entity,
- attribute:
- value as (typeof CONDITION_ATTRIBUTES)[number],
+ attribute: value,
},
{
shouldDirty: true,
},
)
}
- items={ENTITIES[condition.entity].attributes.map(
- (attribute) => ({
- text:
- ATTRIBUTE_LABELS?.[attribute] ||
- capitalize(attribute) ||
- attribute,
- value: attribute,
- }),
- )}
+ items={entity.attributes.map((attribute) => ({
+ text: attribute.label,
+ value: attribute.id,
+ }))}
/>
</InlineBadgePopover>{" "}
<InlineBadgePopover
@@ -425,7 +415,7 @@ function ConditionLogic({
{condition.operator && (
<>
<InlineBadgePopover
- text={formatValue(condition.value, attributeType)}
+ text={formatValue(condition.value, attribute)}
invalid={
Array.isArray(condition.value)
? condition.value.filter(Boolean).length === 0
@@ -443,6 +433,7 @@ function ConditionLogic({
!["starts_with", "ends_with"].includes(
condition.operator,
) ? (
+ // Country selector
<InlineBadgePopoverMenu
search
selectedValue={
@@ -479,6 +470,38 @@ function ConditionLogic({
});
}}
/>
+ ) : attribute?.options &&
+ !["starts_with", "ends_with"].includes(
+ condition.operator,
+ ) ? (
+ // Select option selector
+ <InlineBadgePopoverMenu
+ search={attribute.options.length > 4}
+ selectedValue={
+ (condition.value as string[] | undefined) ??
+ (isArrayValue ? [] : undefined)
+ }
+ items={attribute.options.map(({ id, label }) => ({
+ text: label,
+ value: id,
+ }))}
+ onSelect={(value) => {
+ setValue(conditionKey, {
+ ...condition,
+ value: isArrayValue
+ ? Array.isArray(condition.value)
+ ? (condition.value as string[]).includes(
+ value,
+ )
+ ? (condition.value.filter(
+ (v) => v !== value,
+ ) as string[])
+ : ([...condition.value, value] as string[])
+ : [value]
+ : value,
+ });
+ }}
+ />
) : isArrayValue ? (
// String array input
<InlineBadgePopoverInputs
@@ -497,6 +520,7 @@ function ConditionLogic({
}}
/>
) : ["number", "currency"].includes(attributeType) ? (
+ // Number/currency input
<AmountInput
fieldKey={`${conditionKey}.value`}
type={attributeType as "number" | "currency"}
diff --git a/apps/web/ui/referrals/form-fields/country-field.tsx b/apps/web/ui/referrals/form-fields/country-field.tsx
new file mode 100644
index 0000000000..0fca2ec5e7
--- /dev/null
+++ b/apps/web/ui/referrals/form-fields/country-field.tsx
@@ -0,0 +1,50 @@
+import { countryFieldSchema } from "@/lib/zod/schemas/referral-form";
+import { CountryCombobox } from "@/ui/partners/country-combobox";
+import { Controller, useFormContext } from "react-hook-form";
+import * as z from "zod/v4";
+import { FormControl } from "./form-control";
+
+type CountryFieldData = z.infer<typeof countryFieldSchema>;
+
+export function CountryField({
+ keyPath: keyPathProp,
+ field,
+}: {
+ keyPath?: string;
+ field: CountryFieldData;
+}) {
+ const { getFieldState, control } = useFormContext<any>();
+ const keyPath = keyPathProp || `formData.${field.key}`;
+ const state = getFieldState(keyPath);
+ const error = !!state.error;
+
+ return (
+ <FormControl
+ label={field.label}
+ required={field.required}
+ error={state.error?.message}
+ labelDir="auto"
+ >
+ <Controller
+ control={control}
+ name={keyPath}
+ rules={{
+ validate: (val: any) => {
+ if (field.required && (!val || val === "")) {
+ return "Please select a country";
+ }
+ return true;
+ },
+ }}
+ render={({ field: formField }) => (
+ <CountryCombobox
+ value={formField.value || ""}
+ onChange={formField.onChange}
+ error={error}
+ className="focus:border-[var(--brand)] focus:ring-[var(--brand)]"
+ />
+ )}
+ />
+ </FormControl>
+ );
+}
diff --git a/apps/web/ui/referrals/form-fields/date-field.tsx b/apps/web/ui/referrals/form-fields/date-field.tsx
new file mode 100644
index 0000000000..00f3012596
--- /dev/null
+++ b/apps/web/ui/referrals/form-fields/date-field.tsx
@@ -0,0 +1,42 @@
+import { dateFieldSchema } from "@/lib/zod/schemas/referral-form";
+import { cn } from "@dub/utils";
+import { useFormContext } from "react-hook-form";
+import * as z from "zod/v4";
+import { FormControl } from "./form-control";
+
+type DateFieldData = z.infer<typeof dateFieldSchema>;
+
+export function DateField({
+ keyPath: keyPathProp,
+ field,
+}: {
+ keyPath?: string;
+ field: DateFieldData;
+}) {
+ const { register, getFieldState } = useFormContext<any>();
+ const keyPath = keyPathProp || `formData.${field.key}`;
+ const state = getFieldState(keyPath);
+ const error = !!state.error;
+
+ return (
+ <FormControl
+ label={field.label}
+ required={field.required}
+ error={state.error?.message}
+ labelDir="auto"
+ >
+ <input
+ type="date"
+ className={cn(
+ "mt-2 block w-full rounded-md text-sm focus:outline-none",
+ error
+ ? "border-red-400 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-[var(--brand)] focus:ring-[var(--brand)]",
+ )}
+ {...register(keyPath, {
+ required: field.required,
+ })}
+ />
+ </FormControl>
+ );
+}
diff --git a/apps/web/ui/referrals/form-fields/form-control.tsx b/apps/web/ui/referrals/form-fields/form-control.tsx
new file mode 100644
index 0000000000..351e5c0e90
--- /dev/null
+++ b/apps/web/ui/referrals/form-fields/form-control.tsx
@@ -0,0 +1,54 @@
+import { cn } from "@dub/utils";
+import { HTMLAttributes } from "react";
+
+export type FormControlProps = {
+ label: string;
+ required?: boolean;
+ helperText?: string;
+ error?: string;
+ labelDir?: string;
+} & HTMLAttributes<HTMLLabelElement>;
+
+export const FormControlRequiredBadge = () => {
+ return (
+ <span className="min-h-4 rounded-md bg-orange-100 px-1 text-xs font-semibold text-orange-600">
+ Required
+ </span>
+ );
+};
+
+export const FormControl = ({
+ label,
+ required,
+ children,
+ error,
+ helperText,
+ labelDir,
+ ...rest
+}: FormControlProps) => {
+ return (
+ <label {...rest}>
+ <div className="flex items-center gap-1" dir={labelDir}>
+ <span className="text-content-emphasis text-sm font-medium">
+ {label}
+ </span>
+ {required && <FormControlRequiredBadge />}
+ </div>
+
+ <div className="mt-2">
+ {children}
+
+ {(error || helperText) && (
+ <div
+ className={cn(
+ "mt-2 text-xs",
+ error ? "text-red-500" : "text-neutral-500",
+ )}
+ >
+ {error || helperText}
+ </div>
+ )}
+ </div>
+ </label>
+ );
+};
diff --git a/apps/web/ui/referrals/form-fields/index.tsx b/apps/web/ui/referrals/form-fields/index.tsx
new file mode 100644
index 0000000000..bcec1f7f4d
--- /dev/null
+++ b/apps/web/ui/referrals/form-fields/index.tsx
@@ -0,0 +1,54 @@
+import { formFieldSchema } from "@/lib/zod/schemas/referral-form";
+import * as z from "zod/v4";
+import { CountryField } from "./country-field";
+import { DateField } from "./date-field";
+import { MultiSelectField } from "./multi-select-field";
+import { NumberField } from "./number-field";
+import { PhoneField } from "./phone-field";
+import { SelectField } from "./select-field";
+import { TextField } from "./text-field";
+import { TextareaField } from "./textarea-field";
+
+const FIELD_COMPONENTS: Record<
+ Exclude<z.infer<typeof formFieldSchema>["type"], "text">,
+ React.ComponentType<any>
+> = {
+ textarea: TextareaField,
+ select: SelectField,
+ country: CountryField,
+ date: DateField,
+ multiSelect: MultiSelectField,
+ number: NumberField,
+ phone: PhoneField,
+};
+
+interface ReferralFormFieldProps {
+ field: z.infer<typeof formFieldSchema>;
+ keyPath?: string;
+ inputProps?: React.InputHTMLAttributes<HTMLInputElement>;
+}
+
+export const ReferralFormField = ({
+ field,
+ keyPath,
+ inputProps,
+}: ReferralFormFieldProps) => {
+ // Handle text fields specially to pass inputProps
+ if (field.type === "text") {
+ return (
+ <TextField
+ field={field}
+ keyPath={keyPath}
+ {...(inputProps && { inputProps })}
+ />
+ );
+ }
+
+ const Component = FIELD_COMPONENTS[field.type];
+
+ if (!Component) {
+ return null;
+ }
+
+ return <Component field={field} keyPath={keyPath} />;
+};
diff --git a/apps/web/ui/referrals/form-fields/max-character-count.tsx b/apps/web/ui/referrals/form-fields/max-character-count.tsx
new file mode 100644
index 0000000000..f02570c7b6
--- /dev/null
+++ b/apps/web/ui/referrals/form-fields/max-character-count.tsx
@@ -0,0 +1,22 @@
+import { cn } from "@dub/utils";
+
+export const MaxCharacterCount = ({
+ currentLength,
+ maxLength,
+}: {
+ currentLength: number;
+ maxLength: number;
+}) => {
+ const isOverLimit = currentLength > maxLength;
+
+ return (
+ <span
+ className={cn(
+ "mt-1 block text-xs transition-colors duration-75",
+ isOverLimit ? "text-red-500" : "text-neutral-500",
+ )}
+ >
+ {currentLength}/{maxLength}
+ </span>
+ );
+};
diff --git a/apps/web/ui/referrals/form-fields/multi-select-field.tsx b/apps/web/ui/referrals/form-fields/multi-select-field.tsx
new file mode 100644
index 0000000000..45757ee476
--- /dev/null
+++ b/apps/web/ui/referrals/form-fields/multi-select-field.tsx
@@ -0,0 +1,83 @@
+import { multiSelectFieldSchema } from "@/lib/zod/schemas/referral-form";
+import { Checkbox } from "@dub/ui";
+import { Controller, useFormContext } from "react-hook-form";
+import * as z from "zod/v4";
+import { FormControl } from "./form-control";
+
+type MultiSelectFieldData = z.infer<typeof multiSelectFieldSchema>;
+
+export function MultiSelectField({
+ keyPath: keyPathProp,
+ field,
+}: {
+ keyPath?: string;
+ field: MultiSelectFieldData;
+}) {
+ const { getFieldState, control } = useFormContext<any>();
+ const keyPath = keyPathProp || `formData.${field.key}`;
+ const state = getFieldState(keyPath);
+ const options = field.options;
+
+ return (
+ <FormControl
+ label={field.label}
+ required={field.required}
+ error={state.error?.message}
+ labelDir="auto"
+ >
+ <Controller
+ control={control}
+ name={keyPath}
+ rules={{
+ validate: (val: any) => {
+ if (field.required && (!Array.isArray(val) || !val.length)) {
+ return "Please select at least one option";
+ }
+ return true;
+ },
+ }}
+ render={({ field: formField }) => (
+ <div className="mt-2 space-y-2">
+ {options.map((option) => {
+ const isSelected = formField.value?.includes(option.value);
+
+ return (
+ <label
+ key={option.value}
+ className="flex w-full items-center gap-2.5 text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ dir="auto"
+ >
+ <Checkbox
+ checked={isSelected}
+ className="border-border-default size-4 rounded focus:border-[var(--brand)] focus:ring-[var(--brand)] focus-visible:border-[var(--brand)] focus-visible:ring-[var(--brand)] data-[state=checked]:bg-black data-[state=indeterminate]:bg-black"
+ onCheckedChange={(checked) => {
+ if (checked) {
+ formField.onChange([
+ ...(formField.value || []),
+ option.value,
+ ]);
+ } else {
+ if (
+ Array.isArray(formField.value) &&
+ formField.value.includes(option.value)
+ ) {
+ formField.onChange(
+ formField.value.filter((v) => v !== option.value),
+ );
+ }
+ }
+ }}
+ />
+
+ <span className="text-content-emphasis text-sm">
+ {option.label}
+ </span>
+ </label>
+ );
+ })}
+ </div>
+ )}
+ />
+ </FormControl>
+ );
+}
diff --git a/apps/web/ui/referrals/form-fields/number-field.tsx b/apps/web/ui/referrals/form-fields/number-field.tsx
new file mode 100644
index 0000000000..a6c1e58aa3
--- /dev/null
+++ b/apps/web/ui/referrals/form-fields/number-field.tsx
@@ -0,0 +1,43 @@
+import { numberFieldSchema } from "@/lib/zod/schemas/referral-form";
+import { cn } from "@dub/utils";
+import { useFormContext } from "react-hook-form";
+import * as z from "zod/v4";
+import { FormControl } from "./form-control";
+
+type NumberFieldData = z.infer<typeof numberFieldSchema>;
+
+export function NumberField({
+ keyPath: keyPathProp,
+ field,
+}: {
+ keyPath?: string;
+ field: NumberFieldData;
+}) {
+ const { register, getFieldState } = useFormContext<any>();
+ const keyPath = keyPathProp || `formData.${field.key}`;
+ const state = getFieldState(keyPath);
+ const error = !!state.error;
+
+ return (
+ <FormControl
+ label={field.label}
+ required={field.required}
+ error={state.error?.message}
+ labelDir="auto"
+ >
+ <input
+ type="number"
+ className={cn(
+ "mt-2 block w-full rounded-md text-sm focus:outline-none",
+ error
+ ? "border-red-400 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-[var(--brand)] focus:ring-[var(--brand)]",
+ )}
+ {...register(keyPath, {
+ required: field.required,
+ valueAsNumber: true,
+ })}
+ />
+ </FormControl>
+ );
+}
diff --git a/apps/web/ui/referrals/form-fields/phone-field.tsx b/apps/web/ui/referrals/form-fields/phone-field.tsx
new file mode 100644
index 0000000000..8afe08c079
--- /dev/null
+++ b/apps/web/ui/referrals/form-fields/phone-field.tsx
@@ -0,0 +1,42 @@
+import { phoneFieldSchema } from "@/lib/zod/schemas/referral-form";
+import { cn } from "@dub/utils";
+import { useFormContext } from "react-hook-form";
+import * as z from "zod/v4";
+import { FormControl } from "./form-control";
+
+type PhoneFieldData = z.infer<typeof phoneFieldSchema>;
+
+export function PhoneField({
+ keyPath: keyPathProp,
+ field,
+}: {
+ keyPath?: string;
+ field: PhoneFieldData;
+}) {
+ const { register, getFieldState } = useFormContext<any>();
+ const keyPath = keyPathProp || `formData.${field.key}`;
+ const state = getFieldState(keyPath);
+ const error = !!state.error;
+
+ return (
+ <FormControl
+ label={field.label}
+ required={field.required}
+ error={state.error?.message}
+ labelDir="auto"
+ >
+ <input
+ type="tel"
+ className={cn(
+ "mt-2 block w-full rounded-md text-sm focus:outline-none",
+ error
+ ? "border-red-400 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-[var(--brand)] focus:ring-[var(--brand)]",
+ )}
+ {...register(keyPath, {
+ required: field.required,
+ })}
+ />
+ </FormControl>
+ );
+}
diff --git a/apps/web/ui/referrals/form-fields/select-field.tsx b/apps/web/ui/referrals/form-fields/select-field.tsx
new file mode 100644
index 0000000000..b99b637bc0
--- /dev/null
+++ b/apps/web/ui/referrals/form-fields/select-field.tsx
@@ -0,0 +1,71 @@
+import { selectFieldSchema } from "@/lib/zod/schemas/referral-form";
+import { Combobox } from "@dub/ui";
+import { cn } from "@dub/utils";
+import { Controller, useFormContext } from "react-hook-form";
+import * as z from "zod/v4";
+import { FormControl } from "./form-control";
+
+type SelectFieldData = z.infer<typeof selectFieldSchema>;
+
+export function SelectField({
+ keyPath: keyPathProp,
+ field,
+}: {
+ keyPath?: string;
+ field: SelectFieldData;
+}) {
+ const { getFieldState, control } = useFormContext<any>();
+ const keyPath = keyPathProp || `formData.${field.key}`;
+ const state = getFieldState(keyPath);
+ const error = !!state.error;
+
+ const options = field.options.map((option) => ({
+ label: option.label,
+ value: option.value,
+ }));
+
+ return (
+ <FormControl
+ label={field.label}
+ required={field.required}
+ error={state.error?.message}
+ labelDir="auto"
+ >
+ <Controller
+ control={control}
+ name={keyPath}
+ rules={{
+ validate: (val: any) => {
+ if (field.required && (!val || val === "")) {
+ return "Please select an option";
+ }
+ return true;
+ },
+ }}
+ render={({ field: formField }) => (
+ <Combobox
+ selected={options.find((o) => o.value === formField.value) ?? null}
+ setSelected={(option) => {
+ if (!option) return;
+ formField.onChange(option.value);
+ }}
+ options={options}
+ caret={true}
+ placeholder="Select"
+ matchTriggerWidth
+ buttonProps={{
+ className: cn(
+ "mt-1.5 w-full justify-start border-neutral-300 px-3",
+ "data-[state=open]:ring-1 data-[state=open]:ring-neutral-500 data-[state=open]:border-neutral-500",
+ "focus:ring-1 focus:ring-neutral-500 focus:border-neutral-500 focus:border-[var(--brand)] focus:ring-[var(--brand)] transition-none",
+ !formField.value && "text-neutral-400",
+ error && "border-red-500 ring-red-500 ring-1",
+ ),
+ }}
+ hideSearch
+ />
+ )}
+ />
+ </FormControl>
+ );
+}
diff --git a/apps/web/ui/referrals/form-fields/text-field.tsx b/apps/web/ui/referrals/form-fields/text-field.tsx
new file mode 100644
index 0000000000..050f26b6d9
--- /dev/null
+++ b/apps/web/ui/referrals/form-fields/text-field.tsx
@@ -0,0 +1,68 @@
+import { textFieldSchema } from "@/lib/zod/schemas/referral-form";
+import { cn } from "@dub/utils";
+import { useFormContext } from "react-hook-form";
+import * as z from "zod/v4";
+import { FormControl } from "./form-control";
+import { MaxCharacterCount } from "./max-character-count";
+
+type TextFieldData = z.infer<typeof textFieldSchema>;
+
+export function TextField({
+ keyPath: keyPathProp,
+ field,
+ inputProps,
+}: {
+ keyPath?: string;
+ field: TextFieldData;
+ inputProps?: React.InputHTMLAttributes<HTMLInputElement>;
+}) {
+ const { register, getFieldState, watch } = useFormContext<any>();
+ const keyPath = keyPathProp || `formData.${field.key}`;
+ const value = watch(keyPath);
+ const state = getFieldState(keyPath);
+ const currentLength = value?.length || 0;
+ const maxLength = field.constraints?.maxLength;
+ const exceedsMaxLength = maxLength && currentLength > maxLength;
+ const error = !!state.error || exceedsMaxLength;
+
+ // Determine input type - use email for email fields, text otherwise
+ const inputType = inputProps?.type || "text";
+
+ return (
+ <FormControl label={field.label} required={field.required} dir="auto">
+ <input
+ type={inputType}
+ className={cn(
+ "mt-2 block w-full rounded-md text-sm focus:outline-none",
+ error
+ ? "border-red-400 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-[var(--brand)] focus:ring-[var(--brand)]",
+ )}
+ {...inputProps}
+ {...register(keyPath, {
+ required: field.required,
+ maxLength: maxLength,
+ pattern: field.constraints?.pattern
+ ? new RegExp(field.constraints.pattern)
+ : undefined,
+ ...(inputType === "email" && {
+ validate: (value: string) => {
+ if (!value) return true; // required check handles empty
+ return (
+ /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value) ||
+ "Please enter a valid email address"
+ );
+ },
+ }),
+ })}
+ />
+
+ {maxLength && (
+ <MaxCharacterCount
+ currentLength={currentLength}
+ maxLength={maxLength}
+ />
+ )}
+ </FormControl>
+ );
+}
diff --git a/apps/web/ui/referrals/form-fields/textarea-field.tsx b/apps/web/ui/referrals/form-fields/textarea-field.tsx
new file mode 100644
index 0000000000..b84c0c5c01
--- /dev/null
+++ b/apps/web/ui/referrals/form-fields/textarea-field.tsx
@@ -0,0 +1,50 @@
+import { textareaFieldSchema } from "@/lib/zod/schemas/referral-form";
+import { cn } from "@dub/utils";
+import { useFormContext } from "react-hook-form";
+import * as z from "zod/v4";
+import { FormControl } from "./form-control";
+import { MaxCharacterCount } from "./max-character-count";
+
+type TextareaFieldData = z.infer<typeof textareaFieldSchema>;
+
+export function TextareaField({
+ keyPath: keyPathProp,
+ field,
+}: {
+ keyPath?: string;
+ field: TextareaFieldData;
+}) {
+ const { register, getFieldState, watch } = useFormContext<any>();
+ const keyPath = keyPathProp || `formData.${field.key}`;
+ const value = watch(keyPath);
+ const state = getFieldState(keyPath);
+ const currentLength = value?.length || 0;
+ const maxLength = field.constraints?.maxLength;
+ const exceedsMaxLength = maxLength && currentLength > maxLength;
+ const error = !!state.error || exceedsMaxLength;
+
+ return (
+ <FormControl label={field.label} required={field.required} dir="auto">
+ <textarea
+ className={cn(
+ "mt-2 block w-full rounded-md text-sm focus:outline-none",
+ error
+ ? "border-red-400 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-[var(--brand)] focus:ring-[var(--brand)]",
+ )}
+ rows={4}
+ {...register(keyPath, {
+ required: field.required,
+ maxLength: maxLength,
+ })}
+ />
+
+ {maxLength && (
+ <MaxCharacterCount
+ currentLength={currentLength}
+ maxLength={maxLength}
+ />
+ )}
+ </FormControl>
+ );
+}
diff --git a/apps/web/ui/referrals/partner-profile-referral-sheet.tsx b/apps/web/ui/referrals/partner-profile-referral-sheet.tsx
new file mode 100644
index 0000000000..a2b87fe5a1
--- /dev/null
+++ b/apps/web/ui/referrals/partner-profile-referral-sheet.tsx
@@ -0,0 +1,120 @@
+import { PartnerProfileReferral } from "@/lib/zod/schemas/partner-profile";
+import { X } from "@/ui/shared/icons";
+import {
+ Button,
+ ChevronLeft,
+ ChevronRight,
+ Sheet,
+ useKeyboardShortcut,
+ useRouterStuff,
+} from "@dub/ui";
+import { Dispatch, SetStateAction } from "react";
+import { ReferralDetails } from "./referral-details";
+import { ReferralLeadDetails } from "./referral-lead-details";
+
+type PartnerProfileReferralSheetProps = {
+ referral: PartnerProfileReferral;
+ onNext?: () => void;
+ onPrevious?: () => void;
+ setIsOpen: Dispatch<SetStateAction<boolean>>;
+};
+
+function PartnerProfileReferralSheetContent({
+ referral,
+ onPrevious,
+ onNext,
+}: Omit<PartnerProfileReferralSheetProps, "setIsOpen">) {
+ // right arrow key onNext
+ useKeyboardShortcut(
+ "ArrowRight",
+ () => {
+ if (onNext) {
+ onNext();
+ }
+ },
+ { sheet: true },
+ );
+
+ // left arrow key onPrevious
+ useKeyboardShortcut(
+ "ArrowLeft",
+ () => {
+ if (onPrevious) {
+ onPrevious();
+ }
+ },
+ { sheet: true },
+ );
+
+ return (
+ <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">
+ <Sheet.Title className="text-lg font-semibold">
+ Referral details
+ </Sheet.Title>
+ <div className="flex items-center gap-4">
+ <div className="flex items-center">
+ <Button
+ type="button"
+ disabled={!onPrevious}
+ onClick={onPrevious}
+ variant="secondary"
+ className="size-9 rounded-l-lg rounded-r-none p-0"
+ icon={<ChevronLeft className="size-3.5" />}
+ />
+ <Button
+ type="button"
+ disabled={!onNext}
+ onClick={onNext}
+ variant="secondary"
+ className="-ml-px size-9 rounded-l-none rounded-r-lg p-0"
+ icon={<ChevronRight className="size-3.5" />}
+ />
+ </div>
+ <Sheet.Close asChild>
+ <Button
+ variant="outline"
+ icon={<X className="size-5" />}
+ className="h-auto w-fit p-1"
+ />
+ </Sheet.Close>
+ </div>
+ </div>
+
+ <div className="@3xl/sheet:grid-cols-[minmax(440px,1fr)_minmax(0,360px)] scrollbar-hide grid min-h-0 grow grid-cols-1 gap-x-6 gap-y-2 overflow-y-auto p-4 sm:gap-y-4 sm:p-6">
+ {/* Left side - Referral details */}
+ <ReferralDetails referral={{ formData: referral.formData }} />
+
+ {/* Right side - Customer details */}
+ <div className="@3xl/sheet:order-2 flex flex-col gap-2 sm:gap-4">
+ <ReferralLeadDetails referral={referral} />
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export function PartnerProfileReferralSheet({
+ isOpen,
+ nested,
+ ...rest
+}: PartnerProfileReferralSheetProps & {
+ isOpen: boolean;
+ nested?: boolean;
+}) {
+ const { queryParams } = useRouterStuff();
+ return (
+ <Sheet
+ open={isOpen}
+ onOpenChange={rest.setIsOpen}
+ onClose={() => queryParams({ del: "referralId", scroll: false })}
+ nested={nested}
+ contentProps={{
+ // 540px - 1170px width based on viewport
+ className: "md:w-[max(min(calc(100vw-334px),1170px),540px)]",
+ }}
+ >
+ <PartnerProfileReferralSheetContent {...rest} />
+ </Sheet>
+ );
+}
diff --git a/apps/web/ui/referrals/partner-profile-referrals-empty-state.tsx b/apps/web/ui/referrals/partner-profile-referrals-empty-state.tsx
new file mode 100644
index 0000000000..75dd18e4e1
--- /dev/null
+++ b/apps/web/ui/referrals/partner-profile-referrals-empty-state.tsx
@@ -0,0 +1,139 @@
+"use client";
+
+import useProgramEnrollment from "@/lib/swr/use-program-enrollment";
+import { referralFormSchema } from "@/lib/zod/schemas/referral-form";
+import { PROGRAM_MARKETPLACE_LOGO_COUNT } from "@/ui/partners/program-marketplace/program-marketplace-logos";
+import { SubmitReferralSheet } from "@/ui/referrals/submit-referral-sheet";
+import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
+import { Button } from "@dub/ui";
+import { cn } from "@dub/utils";
+import { useMemo, useState } from "react";
+import * as z from "zod/v4";
+
+const EMPTY_STATE_CARDS = [
+ {
+ logo: 2,
+ programName: "Tella",
+ name: "John Doe",
+ status: "Qualified",
+ statusClassName: "text-violet-700 bg-violet-100",
+ },
+ {
+ logo: 7,
+ programName: "Fillout",
+ name: "John Doe",
+ status: "Closed won",
+ statusClassName: "text-green-700 bg-green-100",
+ },
+ {
+ logo: 11,
+ programName: "Granola",
+ name: "John Doe",
+ status: "New",
+ statusClassName: "text-blue-700 bg-blue-100",
+ },
+];
+
+export function PartnerProfileReferralsEmptyState() {
+ const { programEnrollment } = useProgramEnrollment();
+ const [showReferralSheet, setShowReferralSheet] = useState(false);
+
+ const referralFormDataRaw = programEnrollment?.program?.referralFormData;
+ const submittedReferralsEnabled = referralFormDataRaw !== null;
+
+ const referralFormData = useMemo(() => {
+ if (!referralFormDataRaw) {
+ return null;
+ }
+ try {
+ return referralFormSchema.parse(referralFormDataRaw) as z.infer<
+ typeof referralFormSchema
+ >;
+ } catch {
+ return null;
+ }
+ }, [referralFormDataRaw]);
+
+ return (
+ <>
+ <AnimatedEmptyState
+ title={
+ submittedReferralsEnabled
+ ? "No referrals submitted"
+ : "Submitted referrals not offered"
+ }
+ description={
+ submittedReferralsEnabled
+ ? "Submit leads and track their progress through the sales process."
+ : "You can still earn from regular referrals using your links and codes."
+ }
+ // TODO: Add "learn more" URLs
+ learnMoreHref={
+ submittedReferralsEnabled
+ ? "https://dub.co/help/article/partner-rewards"
+ : "https://dub.co/help/article/partner-rewards"
+ }
+ addButton={
+ submittedReferralsEnabled ? (
+ <Button
+ type="button"
+ text="Submit referral"
+ onClick={() => setShowReferralSheet(true)}
+ className="h-9 rounded-lg"
+ />
+ ) : undefined
+ }
+ cardCount={3}
+ cardContent={(index) => {
+ const card = EMPTY_STATE_CARDS[index];
+ return (
+ <div className="flex grow items-center justify-between gap-4">
+ <div className="flex items-center gap-4">
+ <div
+ className="size-8"
+ style={{
+ backgroundImage:
+ "url(https://assets.dub.co/misc/program-marketplace-logos.png)",
+ backgroundSize: `${PROGRAM_MARKETPLACE_LOGO_COUNT * 100}%`,
+ backgroundPositionX:
+ (PROGRAM_MARKETPLACE_LOGO_COUNT -
+ (card.logo % PROGRAM_MARKETPLACE_LOGO_COUNT)) *
+ 100 +
+ "%",
+ }}
+ />
+ <div className="flex flex-col">
+ <div className="text-content-default text-sm font-semibold">
+ {card.programName}
+ </div>
+ <div className="text-content-subtle text-xs font-medium">
+ {card.name}
+ </div>
+ </div>
+ </div>
+
+ <div
+ className={cn(
+ "text-content-subtle flex h-5 items-center rounded-md px-2 text-xs font-medium",
+ card.statusClassName,
+ )}
+ >
+ {card.status}
+ </div>
+ </div>
+ );
+ }}
+ cardContainerClassName="max-w-96"
+ cardClassName="rounded-xl"
+ />
+ {referralFormData && programEnrollment?.programId && (
+ <SubmitReferralSheet
+ isOpen={showReferralSheet}
+ setIsOpen={setShowReferralSheet}
+ programId={programEnrollment.programId}
+ referralFormData={referralFormData}
+ />
+ )}
+ </>
+ );
+}
diff --git a/apps/web/ui/referrals/partner-referral-sheet.tsx b/apps/web/ui/referrals/partner-referral-sheet.tsx
new file mode 100644
index 0000000000..3d80b51472
--- /dev/null
+++ b/apps/web/ui/referrals/partner-referral-sheet.tsx
@@ -0,0 +1,257 @@
+import { ReferralProps } from "@/lib/types";
+import { useMarkPartnerReferralClosedLostModal } from "@/ui/modals/mark-partner-referral-closed-lost-modal";
+import { useMarkPartnerReferralClosedWonModal } from "@/ui/modals/mark-partner-referral-closed-won-modal";
+import { useQualifyPartnerReferralModal } from "@/ui/modals/qualify-partner-referral-modal";
+import { useUnqualifyPartnerReferralModal } from "@/ui/modals/unqualify-partner-referral-modal";
+import { X } from "@/ui/shared/icons";
+import {
+ Button,
+ ChevronLeft,
+ ChevronRight,
+ Sheet,
+ useKeyboardShortcut,
+ useRouterStuff,
+} from "@dub/ui";
+import { Dispatch, SetStateAction } from "react";
+import { ReferralDetails } from "./referral-details";
+import { ReferralLeadDetails } from "./referral-lead-details";
+import { ReferralPartnerDetails } from "./referral-partner-details";
+
+type ReferralSheetProps = {
+ referral: ReferralProps;
+ onNext?: () => void;
+ onPrevious?: () => void;
+ setIsOpen: Dispatch<SetStateAction<boolean>>;
+};
+
+function ReferralSheetContent({
+ referral,
+ onPrevious,
+ onNext,
+ setIsOpen,
+}: ReferralSheetProps) {
+ const { setShowQualifyModal, QualifyModal, isQualifying } =
+ useQualifyPartnerReferralModal({ referral });
+
+ const { setShowUnqualifyModal, UnqualifyModal, isUnqualifying } =
+ useUnqualifyPartnerReferralModal({ referral });
+
+ const {
+ setShowModal: setShowClosedWonModal,
+ ClosedWonModal,
+ isMarkingClosedWon,
+ } = useMarkPartnerReferralClosedWonModal({ referral });
+
+ const { setShowClosedLostModal, ClosedLostModal, isMarkingClosedLost } =
+ useMarkPartnerReferralClosedLostModal({ referral });
+
+ // right arrow key onNext
+ useKeyboardShortcut(
+ "ArrowRight",
+ () => {
+ if (onNext) {
+ onNext();
+ }
+ },
+ { sheet: true },
+ );
+
+ // left arrow key onPrevious
+ useKeyboardShortcut(
+ "ArrowLeft",
+ () => {
+ if (onPrevious) {
+ onPrevious();
+ }
+ },
+ { sheet: true },
+ );
+
+ // Determine which buttons to show based on status
+ const showQualifyButtons = referral.status === "pending";
+ const showClosedButtons = referral.status === "qualified";
+ const showNoActions = ["unqualified", "closedWon", "closedLost"].includes(
+ referral.status,
+ );
+
+ // Keyboard shortcuts for action buttons
+ useKeyboardShortcut(
+ "u",
+ () => {
+ if (showQualifyButtons && !isUnqualifying) {
+ setShowUnqualifyModal(true);
+ }
+ },
+ { sheet: true },
+ );
+
+ useKeyboardShortcut(
+ "q",
+ () => {
+ if (showQualifyButtons && !isQualifying) {
+ setShowQualifyModal(true);
+ }
+ },
+ { sheet: true },
+ );
+
+ useKeyboardShortcut(
+ "l",
+ () => {
+ if (showClosedButtons && !isMarkingClosedLost) {
+ setShowClosedLostModal(true);
+ }
+ },
+ { sheet: true },
+ );
+
+ useKeyboardShortcut(
+ "w",
+ () => {
+ if (showClosedButtons && !isMarkingClosedWon) {
+ setShowClosedWonModal(true);
+ }
+ },
+ { sheet: true },
+ );
+
+ // Escape key to close sheet
+ useKeyboardShortcut(
+ "Escape",
+ () => {
+ setIsOpen(false);
+ },
+ { sheet: true },
+ );
+
+ return (
+ <>
+ {QualifyModal}
+ {UnqualifyModal}
+ {ClosedWonModal}
+ {ClosedLostModal}
+ <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">
+ <Sheet.Title className="text-lg font-semibold">
+ Partner referral
+ </Sheet.Title>
+ <div className="flex items-center gap-4">
+ <div className="flex items-center">
+ <Button
+ type="button"
+ disabled={!onPrevious}
+ onClick={onPrevious}
+ variant="secondary"
+ className="size-9 rounded-l-lg rounded-r-none p-0"
+ icon={<ChevronLeft className="size-3.5" />}
+ />
+ <Button
+ type="button"
+ disabled={!onNext}
+ onClick={onNext}
+ variant="secondary"
+ className="-ml-px size-9 rounded-l-none rounded-r-lg p-0"
+ icon={<ChevronRight className="size-3.5" />}
+ />
+ </div>
+ <Sheet.Close asChild>
+ <Button
+ variant="outline"
+ icon={<X className="size-5" />}
+ className="h-auto w-fit p-1"
+ />
+ </Sheet.Close>
+ </div>
+ </div>
+
+ <div className="@3xl/sheet:grid-cols-[minmax(440px,1fr)_minmax(0,360px)] scrollbar-hide grid min-h-0 grow grid-cols-1 gap-x-6 gap-y-4 overflow-y-auto p-4 sm:p-6">
+ {/* Left side - Referral details */}
+ <ReferralDetails referral={{ formData: referral.formData }} />
+
+ {/* Right side - Two cards */}
+ <div className="@3xl/sheet:order-2 flex flex-col gap-4">
+ <ReferralLeadDetails referral={referral} />
+ <ReferralPartnerDetails referral={referral} />
+ </div>
+ </div>
+
+ {!showNoActions && (
+ <div className="shrink-0 border-t border-neutral-200 p-5">
+ <div className="flex justify-end gap-2">
+ {showQualifyButtons && (
+ <>
+ <Button
+ type="button"
+ variant="secondary"
+ text="Unqualify"
+ shortcut="U"
+ onClick={() => setShowUnqualifyModal(true)}
+ disabled={isUnqualifying}
+ className="h-9 w-fit shrink-0"
+ />
+ <Button
+ type="button"
+ variant="primary"
+ text="Qualify"
+ shortcut="Q"
+ onClick={() => setShowQualifyModal(true)}
+ disabled={isQualifying}
+ className="h-9 w-fit shrink-0"
+ />
+ </>
+ )}
+
+ {showClosedButtons && (
+ <>
+ <Button
+ type="button"
+ variant="secondary"
+ text="Closed lost"
+ shortcut="L"
+ onClick={() => setShowClosedLostModal(true)}
+ disabled={isMarkingClosedLost}
+ className="h-9 w-fit shrink-0"
+ />
+ <Button
+ type="button"
+ variant="primary"
+ text="Closed won"
+ shortcut="W"
+ onClick={() => setShowClosedWonModal(true)}
+ disabled={isMarkingClosedWon}
+ className="h-9 w-fit shrink-0"
+ />
+ </>
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+ </>
+ );
+}
+
+export function ReferralSheet({
+ isOpen,
+ nested,
+ ...rest
+}: ReferralSheetProps & {
+ isOpen: boolean;
+ nested?: boolean;
+}) {
+ const { queryParams } = useRouterStuff();
+ return (
+ <Sheet
+ open={isOpen}
+ onOpenChange={rest.setIsOpen}
+ onClose={() => queryParams({ del: "referralId", scroll: false })}
+ nested={nested}
+ contentProps={{
+ // 540px - 1170px width based on viewport
+ className: "md:w-[max(min(calc(100vw-334px),1170px),540px)]",
+ }}
+ >
+ <ReferralSheetContent {...rest} />
+ </Sheet>
+ );
+}
diff --git a/apps/web/ui/referrals/partner-referral-table.tsx b/apps/web/ui/referrals/partner-referral-table.tsx
new file mode 100644
index 0000000000..2763e16a2d
--- /dev/null
+++ b/apps/web/ui/referrals/partner-referral-table.tsx
@@ -0,0 +1,334 @@
+"use client";
+
+import useWorkspace from "@/lib/swr/use-workspace";
+import {
+ getPartnerReferralsQuerySchema,
+ referralSchema,
+} from "@/lib/zod/schemas/referrals";
+import { PartnerRowItem } from "@/ui/partners/partner-row-item";
+import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
+import { SearchBoxPersisted } from "@/ui/shared/search-box";
+import {
+ AnimatedSizeContainer,
+ Filter,
+ StatusBadge,
+ Table,
+ TimestampTooltip,
+ useColumnVisibility,
+ usePagination,
+ useRouterStuff,
+ useTable,
+} from "@dub/ui";
+import { cn, fetcher, formatDate, OG_AVATAR_URL } from "@dub/utils";
+import { Row } from "@tanstack/react-table";
+import { useEffect, useMemo, useState } from "react";
+import useSWR from "swr";
+import * as z from "zod/v4";
+import { ReferralSheet } from "./partner-referral-sheet";
+import { ReferralStatusBadges } from "./referral-status-badges";
+import { getCompanyLogoUrl } from "./referral-utils";
+import { usePartnerReferralFilters } from "./use-partner-referral-filters";
+import { usePartnerReferralsCount } from "./use-partner-referrals-count";
+
+type PartnerReferralProps = z.infer<typeof referralSchema>;
+
+export function PartnerReferralTable({
+ query,
+}: {
+ query?: Partial<z.infer<typeof getPartnerReferralsQuerySchema>>;
+}) {
+ const { getQueryString, queryParams, searchParams } = useRouterStuff();
+ const { pagination, setPagination } = usePagination();
+ const { id: workspaceId, slug: workspaceSlug } = useWorkspace();
+
+ const referralIdFromUrl = searchParams.get("referralId");
+
+ const [detailsSheetState, setDetailsSheetState] = useState<{
+ referralId: string | null;
+ open: boolean;
+ }>({
+ referralId: referralIdFromUrl,
+ open: !!referralIdFromUrl,
+ });
+
+ const {
+ filters,
+ activeFilters,
+ onSelect,
+ onRemove,
+ onRemoveAll,
+ setSearch,
+ setSelectedFilter,
+ } = usePartnerReferralFilters({});
+
+ const { data: referralsCount, error: countError } = usePartnerReferralsCount({
+ query,
+ });
+
+ const {
+ data: referrals,
+ error,
+ isLoading,
+ } = useSWR<PartnerReferralProps[]>(
+ `/api/programs/referrals${getQueryString({
+ workspaceId,
+ ...query,
+ })}`,
+ fetcher,
+ {
+ keepPreviousData: true,
+ },
+ );
+
+ const referralsColumns = {
+ all: ["lead", "company", "partner", "submitted", "status"],
+ defaultVisible: ["lead", "company", "partner", "submitted", "status"],
+ };
+
+ const { columnVisibility, setColumnVisibility } = useColumnVisibility(
+ "partner-referrals-table-columns",
+ referralsColumns,
+ );
+
+ const columns = useMemo(
+ () =>
+ [
+ {
+ id: "lead",
+ header: "Lead",
+ enableHiding: false,
+ minSize: 250,
+ cell: ({ row }: { row: Row<PartnerReferralProps> }) => {
+ const referral = row.original;
+ const companyLogoUrl = getCompanyLogoUrl(referral.email);
+
+ return (
+ <div className="flex items-center gap-2 truncate">
+ <img
+ alt={referral.email}
+ src={companyLogoUrl || `${OG_AVATAR_URL}${referral.id}`}
+ className="size-5 shrink-0 rounded-full border border-neutral-200"
+ />
+ <span className="truncate" title={referral.email}>
+ {referral.email}
+ </span>
+ </div>
+ );
+ },
+ },
+ {
+ id: "company",
+ header: "Company",
+ accessorKey: "company",
+ minSize: 150,
+ cell: ({ row }: { row: Row<PartnerReferralProps> }) => {
+ return (
+ <span className="min-w-0 truncate" title={row.original.company}>
+ {row.original.company}
+ </span>
+ );
+ },
+ },
+ {
+ id: "partner",
+ header: "Partner",
+ minSize: 200,
+ cell: ({ row }: { row: Row<PartnerReferralProps> }) => {
+ return (
+ <PartnerRowItem
+ partner={row.original.partner}
+ showPermalink={true}
+ showFraudIndicator={false}
+ />
+ );
+ },
+ },
+ {
+ id: "submitted",
+ header: "Submitted",
+ cell: ({ row }: { row: Row<PartnerReferralProps> }) => (
+ <TimestampTooltip
+ timestamp={row.original.createdAt}
+ rows={["local"]}
+ side="left"
+ delayDuration={150}
+ >
+ <span>
+ {formatDate(row.original.createdAt, { month: "short" })}
+ </span>
+ </TimestampTooltip>
+ ),
+ },
+ {
+ id: "status",
+ header: "Status",
+ accessorKey: "status",
+ cell: ({ row }: { row: Row<PartnerReferralProps> }) => {
+ const status = row.original.status;
+ const badge = ReferralStatusBadges[status];
+
+ return (
+ <StatusBadge
+ variant={badge.variant}
+ icon={null}
+ className={cn("border-0", badge.className)}
+ >
+ {badge.label}
+ </StatusBadge>
+ );
+ },
+ },
+ ].filter((c) => referralsColumns.all.includes(c.id)),
+ [workspaceSlug],
+ );
+
+ const { table, ...tableProps } = useTable({
+ data: referrals || [],
+ columns,
+ pagination,
+ onPaginationChange: setPagination,
+ columnVisibility,
+ onColumnVisibilityChange: setColumnVisibility,
+ thClassName: "border-l-0",
+ tdClassName: "border-l-0",
+ resourceName: (p) => `partner referral${p ? "s" : ""}`,
+ rowCount: referralsCount || 0,
+ loading: isLoading,
+ error: error || countError ? "Failed to load referrals" : undefined,
+ onRowClick: (row) => {
+ queryParams({
+ set: { referralId: row.original.id },
+ scroll: false,
+ });
+ setDetailsSheetState({
+ referralId: row.original.id,
+ open: true,
+ });
+ },
+ });
+
+ const currentReferral = useMemo(() => {
+ if (!referrals || !detailsSheetState.referralId) return null;
+ return referrals.find((r) => r.id === detailsSheetState.referralId) || null;
+ }, [referrals, detailsSheetState.referralId]);
+
+ const [previousReferralId, nextReferralId] = useMemo(() => {
+ if (!referrals || !detailsSheetState.referralId) return [null, null];
+
+ const currentIndex = referrals.findIndex(
+ ({ id }) => id === detailsSheetState.referralId,
+ );
+ if (currentIndex === -1) return [null, null];
+
+ return [
+ currentIndex > 0 ? referrals[currentIndex - 1].id : null,
+ currentIndex < referrals.length - 1
+ ? referrals[currentIndex + 1].id
+ : null,
+ ];
+ }, [referrals, detailsSheetState.referralId]);
+
+ // Sync state with URL params
+ useEffect(() => {
+ const urlReferralId = searchParams.get("referralId");
+ if (urlReferralId && urlReferralId !== detailsSheetState.referralId) {
+ setDetailsSheetState({
+ referralId: urlReferralId,
+ open: true,
+ });
+ } else if (!urlReferralId && detailsSheetState.referralId) {
+ setDetailsSheetState({
+ referralId: null,
+ open: false,
+ });
+ }
+ }, [searchParams, detailsSheetState.referralId]);
+
+ return (
+ <div className="flex flex-col gap-3">
+ {detailsSheetState.referralId && currentReferral && (
+ <ReferralSheet
+ isOpen={detailsSheetState.open}
+ setIsOpen={(open) =>
+ setDetailsSheetState((s) => ({ ...s, open }) as any)
+ }
+ referral={currentReferral}
+ onPrevious={
+ previousReferralId
+ ? () => {
+ queryParams({
+ set: { referralId: previousReferralId },
+ scroll: false,
+ });
+ setDetailsSheetState({
+ referralId: previousReferralId,
+ open: true,
+ });
+ }
+ : undefined
+ }
+ onNext={
+ nextReferralId
+ ? () => {
+ queryParams({
+ set: { referralId: nextReferralId },
+ scroll: false,
+ });
+ setDetailsSheetState({
+ referralId: nextReferralId,
+ open: true,
+ });
+ }
+ : undefined
+ }
+ />
+ )}
+ <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}
+ onSearchChange={setSearch}
+ onSelectedFilterChange={setSelectedFilter}
+ />
+ <SearchBoxPersisted
+ placeholder="Search by email or name"
+ inputClassName="md:w-[16rem]"
+ />
+ </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>
+ {referrals?.length !== 0 ? (
+ <Table {...tableProps} table={table} />
+ ) : (
+ <AnimatedEmptyState
+ title="No referrals submitted"
+ description="Allow partners to submit leads and track their progress through the sales process."
+ learnMoreHref="https://dub.co/help/article/partner-rewards"
+ cardContent={
+ <>
+ <div className="bg-bg-emphasis h-2.5 w-24 min-w-0 rounded-sm" />
+ </>
+ }
+ />
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/ui/referrals/referral-details.tsx b/apps/web/ui/referrals/referral-details.tsx
new file mode 100644
index 0000000000..19e172c3d6
--- /dev/null
+++ b/apps/web/ui/referrals/referral-details.tsx
@@ -0,0 +1,35 @@
+import { ReferralFormDataField, ReferralProps } from "@/lib/types";
+import { formatFormDataValue } from "./referral-utils";
+
+interface ReferralDetailsProps {
+ referral: Pick<ReferralProps, "formData">;
+}
+
+export function ReferralDetails({ referral }: ReferralDetailsProps) {
+ const formData = referral.formData as
+ | ReferralFormDataField[]
+ | null
+ | undefined;
+
+ return (
+ <div className="@3xl/sheet:order-1">
+ <div className="border-border-subtle overflow-hidden rounded-xl border bg-white p-4">
+ <h3 className="text-content-emphasis mb-4 text-lg font-semibold">
+ Referral details
+ </h3>
+ <div className="grid grid-cols-1 gap-4 text-sm text-neutral-600">
+ {formData?.map((field) => (
+ <div key={field.key}>
+ <div className="text-content-default text-sm font-semibold">
+ {field.label}
+ </div>
+ <div className="text-content-default text-sm">
+ {formatFormDataValue(field.value)}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/ui/referrals/referral-form.tsx b/apps/web/ui/referrals/referral-form.tsx
new file mode 100644
index 0000000000..78a234e5b6
--- /dev/null
+++ b/apps/web/ui/referrals/referral-form.tsx
@@ -0,0 +1,43 @@
+"use client";
+
+import {
+ REFERRAL_FORM_FIELD_INPUT_PROPS,
+ REFERRAL_FORM_REQUIRED_FIELDS,
+} from "@/lib/referrals/constants";
+import { referralFormSchema } from "@/lib/zod/schemas/referral-form";
+import { useMemo } from "react";
+import * as z from "zod/v4";
+import { ReferralFormField } from "./form-fields";
+
+export function ReferralForm({
+ referralFormData,
+}: {
+ referralFormData: z.infer<typeof referralFormSchema>;
+}) {
+ // Combine required fields with custom fields and sort by position
+ const allFields = useMemo(() => {
+ const customFields = referralFormData.fields || [];
+
+ return [...REFERRAL_FORM_REQUIRED_FIELDS, ...customFields].sort(
+ (a, b) => a.position - b.position,
+ );
+ }, [referralFormData.fields]);
+
+ return (
+ <div className="flex flex-col gap-5">
+ {allFields.map((field) => {
+ const keyPath = `formData.${field.key}`;
+ const inputProps = REFERRAL_FORM_FIELD_INPUT_PROPS[field.key];
+
+ return (
+ <ReferralFormField
+ key={field.key}
+ field={field}
+ keyPath={keyPath}
+ {...(inputProps && { inputProps })}
+ />
+ );
+ })}
+ </div>
+ );
+}
diff --git a/apps/web/ui/referrals/referral-lead-details.tsx b/apps/web/ui/referrals/referral-lead-details.tsx
new file mode 100644
index 0000000000..368cdc1ff3
--- /dev/null
+++ b/apps/web/ui/referrals/referral-lead-details.tsx
@@ -0,0 +1,54 @@
+import { ReferralProps } from "@/lib/types";
+import { Envelope, OfficeBuilding } from "@dub/ui";
+import { OG_AVATAR_URL } from "@dub/utils";
+import { ReferralStatusBadge } from "./referral-status-badge";
+import { getCompanyLogoUrl } from "./referral-utils";
+
+interface ReferralCustomerDetailsProps {
+ referral: Pick<ReferralProps, "id" | "name" | "email" | "company" | "status">;
+}
+
+export function ReferralLeadDetails({
+ referral,
+}: ReferralCustomerDetailsProps) {
+ const companyLogoUrl = getCompanyLogoUrl(referral.email);
+
+ return (
+ <div className="border-border-subtle overflow-hidden rounded-xl border bg-white p-4">
+ <div className="flex items-start justify-between">
+ <div className="relative w-fit shrink-0">
+ <img
+ src={companyLogoUrl || `${OG_AVATAR_URL}${referral.id}`}
+ alt={referral.company}
+ className="size-10 rounded-full"
+ />
+ </div>
+
+ <ReferralStatusBadge status={referral.status} />
+ </div>
+
+ <div className="mt-2">
+ <div className="text-content-emphasis text-base font-semibold">
+ {referral.name}
+ </div>
+ </div>
+
+ <div className="mt-2 flex flex-col gap-2">
+ {[
+ { icon: Envelope, value: referral.email },
+ { icon: OfficeBuilding, value: referral.company },
+ ].map(({ icon: Icon, value }, index) => (
+ <div
+ key={index}
+ className="text-content-subtle flex items-center gap-1.5"
+ >
+ <Icon className="size-3.5 shrink-0" />
+ <span className="text-xs font-medium text-neutral-700">
+ {value}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/ui/referrals/referral-partner-details.tsx b/apps/web/ui/referrals/referral-partner-details.tsx
new file mode 100644
index 0000000000..1e8236c8f7
--- /dev/null
+++ b/apps/web/ui/referrals/referral-partner-details.tsx
@@ -0,0 +1,38 @@
+import { ReferralProps } from "@/lib/types";
+import { OG_AVATAR_URL } from "@dub/utils";
+import Link from "next/link";
+import { useParams } from "next/navigation";
+
+interface ReferralPartnerDetailsProps {
+ referral: ReferralProps;
+}
+
+export function ReferralPartnerDetails({
+ referral,
+}: ReferralPartnerDetailsProps) {
+ const { slug } = useParams();
+
+ return (
+ <div className="border-border-subtle overflow-hidden rounded-xl border bg-white p-4">
+ <h3 className="text-content-emphasis mb-4 text-sm font-semibold">
+ Referral partner
+ </h3>
+ <Link
+ href={`/${slug}/program/partners/${referral.partner.id}`}
+ target="_blank"
+ className="flex items-center gap-2 transition-opacity hover:opacity-80"
+ >
+ <img
+ src={
+ referral.partner.image || `${OG_AVATAR_URL}${referral.partner.id}`
+ }
+ alt={referral.partner.name}
+ className="size-5 rounded-full border border-neutral-100"
+ />
+ <div className="text-content-emphasis cursor-alias text-sm font-semibold decoration-dotted hover:underline">
+ {referral.partner.name}
+ </div>
+ </Link>
+ </div>
+ );
+}
diff --git a/apps/web/ui/referrals/referral-status-badge.tsx b/apps/web/ui/referrals/referral-status-badge.tsx
new file mode 100644
index 0000000000..f1a87897c7
--- /dev/null
+++ b/apps/web/ui/referrals/referral-status-badge.tsx
@@ -0,0 +1,25 @@
+import { ReferralStatus } from "@dub/prisma/client";
+import { StatusBadge } from "@dub/ui";
+import { ReferralStatusBadges } from "./referral-status-badges";
+
+interface ReferralStatusBadgeProps {
+ status: ReferralStatus;
+ className?: string;
+}
+
+export function ReferralStatusBadge({
+ status,
+ className,
+}: ReferralStatusBadgeProps) {
+ const badge = ReferralStatusBadges[status];
+
+ return (
+ <StatusBadge
+ variant={badge.variant}
+ icon={null}
+ className={`border-0 ${badge.className} ${className || ""}`}
+ >
+ {badge.label}
+ </StatusBadge>
+ );
+}
diff --git a/apps/web/ui/referrals/referral-status-badges.ts b/apps/web/ui/referrals/referral-status-badges.ts
new file mode 100644
index 0000000000..352204af42
--- /dev/null
+++ b/apps/web/ui/referrals/referral-status-badges.ts
@@ -0,0 +1,43 @@
+import { ReferralStatus } from "@dub/prisma/client";
+import { CircleCheck, CircleHalfDottedClock, CircleXmark } from "@dub/ui/icons";
+
+export const ReferralStatusBadges: Record<
+ ReferralStatus,
+ {
+ label: string;
+ variant: "new" | "success" | "pending" | "error" | "neutral";
+ className: string;
+ icon: typeof CircleCheck;
+ }
+> = {
+ pending: {
+ label: "New",
+ variant: "new",
+ className: "text-blue-600 bg-blue-100",
+ icon: CircleHalfDottedClock,
+ },
+ qualified: {
+ label: "Qualified",
+ variant: "new",
+ className: "text-purple-600 bg-purple-100",
+ icon: CircleCheck,
+ },
+ unqualified: {
+ label: "Unqualified",
+ variant: "error",
+ className: "text-red-600 bg-red-100",
+ icon: CircleXmark,
+ },
+ closedWon: {
+ label: "Closed won",
+ variant: "success",
+ className: "text-green-600 bg-green-100",
+ icon: CircleCheck,
+ },
+ closedLost: {
+ label: "Closed lost",
+ variant: "error",
+ className: "text-red-600 bg-red-100",
+ icon: CircleXmark,
+ },
+};
diff --git a/apps/web/ui/referrals/referral-utils.ts b/apps/web/ui/referrals/referral-utils.ts
new file mode 100644
index 0000000000..af1f1b6447
--- /dev/null
+++ b/apps/web/ui/referrals/referral-utils.ts
@@ -0,0 +1,32 @@
+import { GOOGLE_FAVICON_URL } from "@dub/utils";
+
+// Formats a formData field value for display
+export function formatFormDataValue(value: unknown): string {
+ if (value === null || value === undefined || value === "") {
+ return "";
+ }
+
+ if (Array.isArray(value)) {
+ return value.map((v) => String(v)).join(", ");
+ }
+
+ if (typeof value === "object" && "toISOString" in value) {
+ try {
+ return new Date(value as Date).toLocaleDateString();
+ } catch {
+ return String(value);
+ }
+ }
+
+ if (typeof value === "number") {
+ return value.toLocaleString();
+ }
+
+ return String(value);
+}
+
+// Gets company logo URL from email domain
+export function getCompanyLogoUrl(email: string): string | null {
+ const emailDomain = email.split("@")[1];
+ return emailDomain ? `${GOOGLE_FAVICON_URL}${emailDomain}` : null;
+}
diff --git a/apps/web/ui/referrals/submit-referral-sheet.tsx b/apps/web/ui/referrals/submit-referral-sheet.tsx
new file mode 100644
index 0000000000..ba62f88730
--- /dev/null
+++ b/apps/web/ui/referrals/submit-referral-sheet.tsx
@@ -0,0 +1,167 @@
+"use client";
+
+import { submitReferralAction } from "@/lib/actions/referrals/submit-referral";
+import { mutatePrefix } from "@/lib/swr/mutate";
+import { referralFormSchema } from "@/lib/zod/schemas/referral-form";
+import { X } from "@/ui/shared/icons";
+import { Button, CircleCheckFill, Sheet } from "@dub/ui";
+import { cn } from "@dub/utils";
+import { useAction } from "next-safe-action/hooks";
+import { useParams } from "next/navigation";
+import { Dispatch, SetStateAction, useEffect, useMemo, useState } from "react";
+import { FormProvider, useForm } from "react-hook-form";
+import { toast } from "sonner";
+import * as z from "zod/v4";
+import { ReferralForm } from "./referral-form";
+
+interface SubmitReferralSheetProps {
+ isOpen: boolean;
+ setIsOpen: Dispatch<SetStateAction<boolean>>;
+ programId: string;
+ referralFormData: z.infer<typeof referralFormSchema>;
+ onSuccess?: () => void;
+}
+
+type ReferralFormData = {
+ formData: Record<string, any>;
+};
+
+export function SubmitReferralSheet({
+ isOpen,
+ setIsOpen,
+ programId,
+ referralFormData,
+ onSuccess,
+}: SubmitReferralSheetProps) {
+ const [isSubmitSuccessful, setIsSubmitSuccessful] = useState(false);
+ const { programSlug } = useParams<{ programSlug: string }>();
+
+ const validatedFormData = useMemo(() => {
+ try {
+ return referralFormSchema.parse(referralFormData);
+ } catch {
+ return null;
+ }
+ }, [referralFormData]);
+
+ const form = useForm<ReferralFormData>({
+ defaultValues: {
+ formData: {},
+ },
+ });
+
+ const { handleSubmit, setError, reset } = form;
+
+ const { executeAsync, isPending } = useAction(submitReferralAction, {
+ onSuccess: async () => {
+ toast.success("Referral submitted successfully");
+ reset();
+ setIsSubmitSuccessful(true);
+ onSuccess?.();
+
+ if (programSlug) {
+ await mutatePrefix([
+ `/api/partner-profile/programs/${programSlug}/referrals`,
+ `/api/partner-profile/programs/${programSlug}/referrals/count`,
+ ]);
+ }
+ },
+ onError: ({ error }) => {
+ const errorMessage = error.serverError || "Failed to submit referral";
+ toast.error(errorMessage);
+ setError("root.serverError", {
+ message: errorMessage,
+ });
+ setIsSubmitSuccessful(false);
+ },
+ });
+
+ const onSubmit = async (data: ReferralFormData) => {
+ if (!validatedFormData) {
+ return;
+ }
+
+ await executeAsync({
+ programId,
+ formData: data.formData,
+ });
+ };
+
+ // Reset success state when sheet closes
+ useEffect(() => {
+ if (!isOpen) {
+ setIsSubmitSuccessful(false);
+ }
+ }, [isOpen]);
+
+ if (!validatedFormData) {
+ return null;
+ }
+
+ return (
+ <Sheet open={isOpen} onOpenChange={setIsOpen}>
+ <FormProvider {...form}>
+ <form
+ onSubmit={handleSubmit(onSubmit)}
+ className={cn(
+ "flex h-full flex-col transition-opacity duration-200",
+ isSubmitSuccessful && "pointer-events-none opacity-0",
+ )}
+ {...{
+ inert: isSubmitSuccessful,
+ }}
+ >
+ <div className="sticky top-0 z-10 border-b border-neutral-200 bg-neutral-50">
+ <div className="flex h-16 items-center justify-between px-6 py-4">
+ <Sheet.Title className="text-lg font-semibold">
+ Submit Referral
+ </Sheet.Title>
+ <Sheet.Close asChild>
+ <Button
+ variant="outline"
+ icon={<X className="size-5" />}
+ className="h-auto w-fit p-1"
+ />
+ </Sheet.Close>
+ </div>
+ </div>
+
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ <div className="flex flex-col gap-6 p-5 sm:p-6">
+ <ReferralForm referralFormData={validatedFormData} />
+ </div>
+ </div>
+
+ <div className="sticky bottom-0 z-10 border-t border-neutral-200 bg-white p-5">
+ <Button
+ type="submit"
+ variant="primary"
+ text="Submit Referral"
+ loading={isPending}
+ />
+ </div>
+ </form>
+
+ {isSubmitSuccessful && (
+ <div className="absolute inset-0 flex items-center justify-center bg-white">
+ <div className="flex flex-col items-center">
+ <CircleCheckFill className="size-8 text-green-500" />
+ <span className="mt-4 block text-base font-semibold text-neutral-900">
+ Referral submitted
+ </span>
+ <p className="mt-2 text-center text-sm text-neutral-500">
+ Your referral has been submitted successfully.
+ </p>
+ <Button
+ text="Close"
+ variant="primary"
+ className="mt-6"
+ onClick={() => setIsOpen(false)}
+ />
+ </div>
+ </div>
+ )}
+ </FormProvider>
+ </Sheet>
+ );
+}
diff --git a/apps/web/ui/referrals/use-partner-referral-filters.tsx b/apps/web/ui/referrals/use-partner-referral-filters.tsx
new file mode 100644
index 0000000000..e90d95c975
--- /dev/null
+++ b/apps/web/ui/referrals/use-partner-referral-filters.tsx
@@ -0,0 +1,208 @@
+import usePartners from "@/lib/swr/use-partners";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { EnrolledPartnerProps } from "@/lib/types";
+import {
+ partnerReferralsCountByPartnerIdSchema,
+ partnerReferralsCountByStatusSchema,
+} from "@/lib/zod/schemas/referrals";
+import { CircleDotted, useRouterStuff } from "@dub/ui";
+import { Users } from "@dub/ui/icons";
+import { cn, nFormatter, OG_AVATAR_URL } from "@dub/utils";
+import { useCallback, useMemo, useState } from "react";
+import { useDebounce } from "use-debounce";
+import * as z from "zod/v4";
+import { ReferralStatusBadges } from "./referral-status-badges";
+import { usePartnerReferralsCount } from "./use-partner-referrals-count";
+
+export function usePartnerReferralFilters(
+ extraSearchParams: Record<string, string>,
+) {
+ const [search, setSearch] = useState("");
+ const { id: workspaceId } = useWorkspace();
+ const [debouncedSearch] = useDebounce(search, 500);
+ const { searchParamsObj, queryParams } = useRouterStuff();
+ const [selectedFilter, setSelectedFilter] = useState<string | null>(null);
+
+ const { partners } = usePartnerFilterOptions(
+ selectedFilter === "partnerId" ? debouncedSearch : "",
+ );
+
+ const { data: statusCount } = usePartnerReferralsCount<
+ z.infer<typeof partnerReferralsCountByStatusSchema>[] | undefined
+ >({
+ query: {
+ groupBy: "status",
+ },
+ });
+
+ const { data: partnersCount } = usePartnerReferralsCount<
+ z.infer<typeof partnerReferralsCountByPartnerIdSchema>[] | undefined
+ >({
+ query: {
+ groupBy: "partnerId",
+ },
+ });
+
+ const partnersCountMap = useMemo(
+ () => new Map(partnersCount?.map((p) => [p.partnerId, p._count]) ?? []),
+ [partnersCount],
+ );
+
+ const filters = useMemo(
+ () => [
+ {
+ key: "partnerId",
+ icon: Users,
+ label: "Partner",
+ shouldFilter: false,
+ options:
+ partners?.map(({ id, name, image }) => {
+ const count = partnersCountMap.get(id);
+
+ return {
+ value: id,
+ label: name,
+ icon: (
+ <img
+ src={image || `${OG_AVATAR_URL}${id}`}
+ alt={`${name} image`}
+ className="size-4 rounded-full"
+ />
+ ),
+ ...(count !== undefined && {
+ right: nFormatter(count, { full: true }),
+ }),
+ };
+ }) ?? null,
+ },
+ {
+ key: "status",
+ icon: CircleDotted,
+ label: "Status",
+ options:
+ statusCount?.map(({ status, _count }) => {
+ const badge = ReferralStatusBadges[status];
+ const Icon = badge.icon;
+
+ return {
+ value: status,
+ label: badge.label,
+ icon: (
+ <Icon
+ className={cn(badge.className, "size-4 bg-transparent")}
+ />
+ ),
+ right: nFormatter(_count, { full: true }),
+ };
+ }) ?? [],
+ meta: {
+ filterParams: ({ getValue }) => ({
+ status: getValue(),
+ }),
+ },
+ },
+ ],
+ [partners, statusCount, partnersCount],
+ );
+
+ const activeFilters = useMemo(() => {
+ const { partnerId, status } = searchParamsObj;
+
+ return [
+ ...(partnerId ? [{ key: "partnerId", value: partnerId }] : []),
+ ...(status ? [{ key: "status", value: status }] : []),
+ ];
+ }, [searchParamsObj]);
+
+ const onSelect = useCallback(
+ (key: string, value: any) =>
+ queryParams({
+ set: {
+ [key]: value,
+ },
+ del: "page",
+ }),
+ [queryParams],
+ );
+
+ const onRemove = useCallback(
+ (key: string) =>
+ queryParams({
+ del: [key, "page"],
+ }),
+ [queryParams],
+ );
+
+ const onRemoveAll = useCallback(
+ () =>
+ queryParams({
+ del: ["partnerId", "status", "search"],
+ }),
+ [queryParams],
+ );
+
+ const searchQuery = useMemo(
+ () =>
+ new URLSearchParams({
+ ...Object.fromEntries(
+ activeFilters.map(({ key, value }) => [key, value]),
+ ),
+ ...(searchParamsObj.search && { search: searchParamsObj.search }),
+ workspaceId: workspaceId || "",
+ ...extraSearchParams,
+ }).toString(),
+ [activeFilters, workspaceId, extraSearchParams, searchParamsObj.search],
+ );
+
+ const isFiltered = useMemo(
+ () => activeFilters.length > 0 || searchParamsObj.search,
+ [activeFilters, searchParamsObj.search],
+ );
+
+ return {
+ filters,
+ activeFilters,
+ onSelect,
+ onRemove,
+ onRemoveAll,
+ searchQuery,
+ isFiltered,
+ setSearch,
+ setSelectedFilter,
+ };
+}
+
+function usePartnerFilterOptions(search: string) {
+ const { searchParamsObj } = useRouterStuff();
+
+ const { partners, loading: partnersLoading } = usePartners({
+ query: { search },
+ });
+
+ const { partners: selectedPartners } = usePartners({
+ query: {
+ partnerIds: searchParamsObj.partnerId
+ ? [searchParamsObj.partnerId]
+ : undefined,
+ },
+ });
+
+ const result = useMemo(() => {
+ return partnersLoading ||
+ // Consider partners loading if we can't find the currently filtered partner
+ (searchParamsObj.partnerId &&
+ ![...(selectedPartners ?? []), ...(partners ?? [])].some(
+ (p) => p.id === searchParamsObj.partnerId,
+ ))
+ ? null
+ : ([
+ ...(partners ?? []),
+ // Add selected partner to list if not already in partners
+ ...(selectedPartners
+ ?.filter((st) => !partners?.some((t) => t.id === st.id))
+ ?.map((st) => ({ ...st, hideDuringSearch: true })) ?? []),
+ ] as (EnrolledPartnerProps & { hideDuringSearch?: boolean })[]);
+ }, [partnersLoading, partners, selectedPartners, searchParamsObj.partnerId]);
+
+ return { partners: result };
+}
diff --git a/apps/web/ui/referrals/use-partner-referrals-count.ts b/apps/web/ui/referrals/use-partner-referrals-count.ts
new file mode 100644
index 0000000000..9f692bd3ab
--- /dev/null
+++ b/apps/web/ui/referrals/use-partner-referrals-count.ts
@@ -0,0 +1,37 @@
+import useWorkspace from "@/lib/swr/use-workspace";
+import { getPartnerReferralsCountQuerySchema } from "@/lib/zod/schemas/referrals";
+import { useRouterStuff } from "@dub/ui";
+import { fetcher } from "@dub/utils";
+import useSWR from "swr";
+import * as z from "zod/v4";
+
+export function usePartnerReferralsCount<T = number>({
+ query,
+ includeParams = ["partnerId", "status", "search"],
+}: {
+ query?: z.infer<typeof getPartnerReferralsCountQuerySchema>;
+ includeParams?: string[];
+} = {}) {
+ const { id: workspaceId } = useWorkspace();
+ const { getQueryString } = useRouterStuff();
+
+ const { data, error, isLoading } = useSWR<T>(
+ workspaceId &&
+ `/api/programs/referrals/count${getQueryString(
+ { workspaceId, ...query },
+ {
+ include: includeParams,
+ },
+ )}`,
+ fetcher,
+ {
+ keepPreviousData: true,
+ },
+ );
+
+ return {
+ data,
+ error,
+ loading: isLoading,
+ };
+}
diff --git a/apps/web/ui/shared/animated-empty-state.tsx b/apps/web/ui/shared/animated-empty-state.tsx
index 0bceeefc07..c65a5e1005 100644
--- a/apps/web/ui/shared/animated-empty-state.tsx
+++ b/apps/web/ui/shared/animated-empty-state.tsx
@@ -18,6 +18,7 @@ export function AnimatedEmptyState({
learnMoreText,
className,
cardClassName,
+ cardContainerClassName,
}: {
title: string;
description: ReactNode;
@@ -31,6 +32,7 @@ export function AnimatedEmptyState({
learnMoreText?: string;
className?: string;
cardClassName?: string;
+ cardContainerClassName?: string;
}) {
return (
<div
@@ -39,7 +41,12 @@ export function AnimatedEmptyState({
className,
)}
>
- <div className="animate-fade-in h-36 w-full max-w-64 overflow-hidden px-4 [mask-image:linear-gradient(transparent,black_10%,black_90%,transparent)]">
+ <div
+ className={cn(
+ "animate-fade-in h-36 w-full max-w-64 overflow-hidden px-4 [mask-image:linear-gradient(transparent,black_10%,black_90%,transparent)]",
+ cardContainerClassName,
+ )}
+ >
<div
style={{ "--scroll": "-50%" } as CSSProperties}
className="animate-infinite-scroll-y flex flex-col [animation-duration:10s]"
diff --git a/packages/prisma/schema/customer.prisma b/packages/prisma/schema/customer.prisma
index 4c119699d3..7997ff7419 100644
--- a/packages/prisma/schema/customer.prisma
+++ b/packages/prisma/schema/customer.prisma
@@ -30,6 +30,7 @@ model Customer {
programEnrollment ProgramEnrollment? @relation(fields: [programId, partnerId], references: [programId, partnerId])
commissions Commission[]
fraudEvents FraudEvent[]
+ referrals PartnerReferral[]
@@unique([projectId, externalId])
@@unique([projectConnectId, externalId])
diff --git a/packages/prisma/schema/partner.prisma b/packages/prisma/schema/partner.prisma
index cf8a9ac97c..0d43ad86c2 100644
--- a/packages/prisma/schema/partner.prisma
+++ b/packages/prisma/schema/partner.prisma
@@ -83,6 +83,7 @@ model Partner {
fraudEvents FraudEvent[]
partnerRewinds PartnerRewind[]
platforms PartnerPlatform[]
+ referrals PartnerReferral[]
@@index(country)
@@index(discoverableAt)
diff --git a/packages/prisma/schema/program.prisma b/packages/prisma/schema/program.prisma
index 5d9c8205f9..3d57db00d8 100644
--- a/packages/prisma/schema/program.prisma
+++ b/packages/prisma/schema/program.prisma
@@ -39,12 +39,13 @@ model Program {
minPayoutAmount Int @default(0) // Default minimum payout amount of $0
payoutMode ProgramPayoutMode @default(internal)
- inviteEmailData Json? @db.Json
- embedData Json? @db.Json
- resources Json? @db.Json
- termsUrl String? @db.Text
- helpUrl String? @db.Text
- supportEmail String?
+ inviteEmailData Json? @db.Json
+ embedData Json? @db.Json
+ resources Json? @db.Json
+ referralFormData Json? @db.Json
+ termsUrl String? @db.Text
+ helpUrl String? @db.Text
+ supportEmail String?
messagingEnabledAt DateTime?
partnerNetworkEnabledAt DateTime?
@@ -84,6 +85,7 @@ model Program {
fraudRules FraudRule[]
fraudEventGroups FraudEventGroup[]
sourceFraudEvents FraudEvent[] @relation("SourceFraudEvents")
+ referrals PartnerReferral[]
@@index(workspaceId)
@@index(addedToMarketplaceAt)
@@ -144,6 +146,7 @@ model ProgramEnrollment {
payouts Payout[]
messages Message[]
fraudEventGroups FraudEventGroup[]
+ referrals PartnerReferral[]
// unique constraints
@@unique([partnerId, programId])
diff --git a/packages/prisma/schema/referral.prisma b/packages/prisma/schema/referral.prisma
new file mode 100644
index 0000000000..08937fd8cd
--- /dev/null
+++ b/packages/prisma/schema/referral.prisma
@@ -0,0 +1,31 @@
+enum ReferralStatus {
+ pending
+ qualified
+ unqualified
+ closedWon
+ closedLost
+}
+
+model PartnerReferral {
+ id String @id @default(cuid())
+ programId String
+ partnerId String
+ customerId String?
+ name String
+ email String
+ company String
+ formData Json? @db.Json
+ status ReferralStatus @default(pending)
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ program Program @relation(fields: [programId], references: [id])
+ partner Partner @relation(fields: [partnerId], references: [id])
+ programEnrollment ProgramEnrollment @relation(fields: [programId, partnerId], references: [programId, partnerId])
+ customer Customer? @relation(fields: [customerId], references: [id])
+
+ @@index([programId, partnerId])
+ @@index(partnerId)
+ @@index(customerId)
+ @@fulltext([email, name])
+}