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.

Country Application Eligibility (#3562)

Pedro Ladeira3f57dddaf04c
diff --git a/apps/web/app/(ee)/api/cron/partners/auto-approve/route.ts b/apps/web/app/(ee)/api/cron/partners/auto-approve/route.ts
index a2f1d672b3..3eaa1da65d 100644
--- a/apps/web/app/(ee)/api/cron/partners/auto-approve/route.ts
+++ b/apps/web/app/(ee)/api/cron/partners/auto-approve/route.ts
@@ -1,6 +1,7 @@
import { getPartnerApplicationRisks } from "@/lib/api/fraud/get-partner-application-risks";
import { withCron } from "@/lib/cron/with-cron";
import { approvePartnerEnrollment } from "@/lib/partners/approve-partner-enrollment";
+import { evaluateApplicationRequirements } from "@/lib/partners/evaluate-application-requirements";
import { getPlanCapabilities } from "@/lib/plan-capabilities";
import { prisma } from "@dub/prisma";
import * as z from "zod/v4";
@@ -96,6 +97,28 @@ export const POST = withCron(async ({ rawBody }) => {
}
}
+ const result = evaluateApplicationRequirements({
+ applicationRequirements: program.applicationRequirements,
+ context: {
+ country: programEnrollment.partner.country,
+ email: programEnrollment.partner.email,
+ },
+ });
+
+ if (!result.valid) {
+ switch (result.reason) {
+ case "invalidRequirements":
+ return logAndRespond(
+ `Invalid applicationRequirements for program ${programId}. Skipping auto-approval.`,
+ );
+
+ case "requirementsNotMet":
+ return logAndRespond(
+ `Partner ${partnerId} does not meet eligibility requirements. Skipping auto-approval.`,
+ );
+ }
+ }
+
await approvePartnerEnrollment({
programId,
partnerId,
diff --git a/apps/web/app/(ee)/api/cron/partners/auto-reject/route.ts b/apps/web/app/(ee)/api/cron/partners/auto-reject/route.ts
new file mode 100644
index 0000000000..38c7f85237
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/partners/auto-reject/route.ts
@@ -0,0 +1,131 @@
+import { resolveFraudGroups } from "@/lib/api/fraud/resolve-fraud-groups";
+import { withCron } from "@/lib/cron/with-cron";
+import { evaluateApplicationRequirements } from "@/lib/partners/evaluate-application-requirements";
+import { sendEmail } from "@dub/email";
+import PartnerApplicationRejected from "@dub/email/templates/partner-application-rejected";
+import { prisma } from "@dub/prisma";
+import { ProgramEnrollmentStatus } from "@dub/prisma/client";
+import * as z from "zod/v4";
+import { logAndRespond } from "../../utils";
+
+export const dynamic = "force-dynamic";
+
+const inputSchema = z.object({
+ programId: z.string(),
+ partnerId: z.string(),
+});
+
+// POST /api/cron/partners/auto-reject
+// This route is used to auto-reject a partner enrollment (e.g. when eligibility requirements are not met)
+export const POST = withCron(async ({ rawBody }) => {
+ const { programId, partnerId } = inputSchema.parse(JSON.parse(rawBody));
+
+ const programEnrollment = await prisma.programEnrollment.findUnique({
+ where: {
+ partnerId_programId: {
+ partnerId,
+ programId,
+ },
+ },
+ include: {
+ partner: {
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ country: true,
+ },
+ },
+ program: {
+ select: {
+ id: true,
+ name: true,
+ slug: true,
+ supportEmail: true,
+ applicationRequirements: true,
+ },
+ },
+ },
+ });
+
+ if (!programEnrollment) {
+ return logAndRespond(
+ `Partner ${partnerId} not found in program ${programId}. Skipping auto-reject.`,
+ );
+ }
+
+ if (programEnrollment.status !== "pending") {
+ return logAndRespond(
+ `Partner ${partnerId} is in ${programEnrollment.status} status. Skipping auto-reject.`,
+ );
+ }
+
+ const result = evaluateApplicationRequirements({
+ applicationRequirements: programEnrollment.program.applicationRequirements,
+ context: {
+ country: programEnrollment.partner.country,
+ email: programEnrollment.partner.email,
+ },
+ });
+
+ if (result.reason !== "requirementsNotMet") {
+ return logAndRespond(
+ `Partner ${partnerId} now meets requirements for program ${programId} (reason: ${result.reason}). Skipping auto-reject.`,
+ );
+ }
+
+ const { count } = await prisma.programEnrollment.updateMany({
+ where: {
+ id: programEnrollment.id,
+ status: ProgramEnrollmentStatus.pending,
+ },
+ data: {
+ status: ProgramEnrollmentStatus.rejected,
+ clickRewardId: null,
+ leadRewardId: null,
+ saleRewardId: null,
+ discountId: null,
+ },
+ });
+
+ if (count === 0) {
+ return logAndRespond(
+ `Partner ${partnerId} is no longer pending in program ${programId}. Skipping auto-reject.`,
+ );
+ }
+
+ await resolveFraudGroups({
+ where: {
+ programId,
+ partnerId,
+ },
+ resolutionReason:
+ "Resolved automatically because the partner application was automatically rejected.",
+ });
+
+ const { partner, program } = programEnrollment;
+
+ if (partner.email) {
+ await sendEmail({
+ to: partner.email,
+ subject: `Your application to ${program.name} was not approved`,
+ variant: "notifications",
+ replyTo: program.supportEmail || "noreply",
+ react: PartnerApplicationRejected({
+ partner: {
+ name: partner.name ?? "there",
+ email: partner.email,
+ },
+ program: {
+ name: program.name,
+ slug: program.slug,
+ supportEmail: program.supportEmail ?? undefined,
+ },
+ }),
+ });
+ }
+
+ return logAndRespond(
+ `Successfully auto-rejected partner ${partnerId} in program ${programId}.`,
+ );
+});
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 031cd515e3..d523927be2 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
@@ -1,5 +1,7 @@
"use client";
+import { evaluateApplicationRequirements } from "@/lib/partners/evaluate-application-requirements";
+import usePartnerProfile from "@/lib/swr/use-partner-profile";
import useProgramEnrollment from "@/lib/swr/use-program-enrollment";
import {
DiscountProps,
@@ -7,9 +9,11 @@ import {
ProgramProps,
RewardProps,
} from "@/lib/types";
+import { applicationRequirementsSchema } from "@/lib/zod/schemas/programs";
import { LanderRewards } from "@/ui/partners/lander/lander-rewards";
import { PartnerStatusBadges } from "@/ui/partners/partner-status-badges";
import { useProgramApplicationSheet } from "@/ui/partners/program-application-sheet";
+import { ProgramEligibilityCard } from "@/ui/partners/program-eligibility-card";
import { BlurImage, Button, CircleCheck, Link4, StatusBadge } from "@dub/ui";
import { capitalize, cn, OG_AVATAR_URL } from "@dub/utils";
import { redirect } from "next/navigation";
@@ -20,7 +24,7 @@ export function ProgramSidebar({
applicationRewards,
applicationDiscount,
}: {
- program: Omit<ProgramProps, "referralFormData"> & {
+ program: ProgramProps & {
group?: {
id: string;
bounties?: GroupBountySummaryProps[];
@@ -29,6 +33,7 @@ export function ProgramSidebar({
applicationRewards: RewardProps[];
applicationDiscount: DiscountProps | null;
}) {
+ const { partner } = usePartnerProfile();
const { programEnrollment } = useProgramEnrollment({
swrOpts: {
keepPreviousData: true,
@@ -37,6 +42,23 @@ export function ProgramSidebar({
},
});
+ const applicationRequirements = program.applicationRequirements
+ ? applicationRequirementsSchema.parse(program.applicationRequirements)
+ : null;
+
+ const { reason } = evaluateApplicationRequirements({
+ applicationRequirements,
+ context: {
+ country: partner?.country,
+ email: partner?.email,
+ },
+ });
+
+ const requirementsNotMet =
+ reason === "requirementsNotMet"
+ ? "You do not meet the eligibility requirements for this program"
+ : undefined;
+
const statusBadge = programEnrollment
? {
...PartnerStatusBadges,
@@ -128,11 +150,20 @@ export function ProgramSidebar({
/>
</div>
+ {applicationRequirements && applicationRequirements.length ? (
+ <ProgramEligibilityCard requirements={applicationRequirements} />
+ ) : null}
+
<Button
- className={cn("mt-8", justApplied && "text-green-600")}
+ className={cn("mt-4", justApplied && "text-green-600")}
text={buttonText}
icon={justApplied ? <CircleCheck className="size-4" /> : undefined}
- disabled={programEnrollment || justApplied ? true : undefined}
+ disabled={
+ !!programEnrollment || justApplied || !!requirementsNotMet
+ ? true
+ : undefined
+ }
+ disabledTooltip={requirementsNotMet}
onClick={() => setIsApplicationSheetOpen(true)}
/>
</div>
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/invite/page.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/invite/page.tsx
index b66b61b6ab..60bbbf4e77 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/invite/page.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/invite/page.tsx
@@ -1,6 +1,6 @@
-import { getGroupBountySummaries } from "@/lib/bounty/api/get-group-bounty-summaries";
import { serializeReward } from "@/lib/api/partners/serialize-reward";
import { getSession } from "@/lib/auth";
+import { getGroupBountySummaries } from "@/lib/bounty/api/get-group-bounty-summaries";
import { programLanderSchema } from "@/lib/zod/schemas/program-lander";
import { PageContent } from "@/ui/layout/page-content";
import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/marketplace/[programSlug]/header-controls.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/marketplace/[programSlug]/header-controls.tsx
index 790ff847bc..d2dc7734ee 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/marketplace/[programSlug]/header-controls.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/marketplace/[programSlug]/header-controls.tsx
@@ -2,6 +2,7 @@
import { acceptProgramInviteAction } from "@/lib/actions/partners/accept-program-invite";
import { getPartnerProfileChecklistProgress } from "@/lib/network/get-partner-profile-checklist-progress";
+import { evaluateApplicationRequirements } from "@/lib/partners/evaluate-application-requirements";
import { mutatePrefix } from "@/lib/swr/mutate";
import usePartnerProfile from "@/lib/swr/use-partner-profile";
import useProgramEnrollment from "@/lib/swr/use-program-enrollment";
@@ -62,6 +63,19 @@ function ApplyButton({ program }: { program: NetworkProgramProps }) {
: undefined;
}, [partner]);
+ const { reason } = evaluateApplicationRequirements({
+ applicationRequirements: program.applicationRequirements,
+ context: {
+ country: partner?.country,
+ email: partner?.email,
+ },
+ });
+
+ const requirementsNotMet =
+ reason === "requirementsNotMet"
+ ? "You do not meet the eligibility requirements for this program"
+ : undefined;
+
const disabledTooltip: ReactNode =
programEnrollment?.status === "pending" ? (
"Your application is under review"
@@ -91,7 +105,9 @@ function ApplyButton({ program }: { program: NetworkProgramProps }) {
</span>
</Link>
</div>
- ) : undefined;
+ ) : (
+ requirementsNotMet
+ );
useKeyboardShortcut("a", () => setIsApplicationSheetOpen(true), {
enabled: !disabledTooltip,
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/marketplace/[programSlug]/page.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/marketplace/[programSlug]/page.tsx
index 121f5ccb27..ef867fc920 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/marketplace/[programSlug]/page.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/marketplace/[programSlug]/page.tsx
@@ -4,6 +4,7 @@ import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
import { BLOCK_COMPONENTS } from "@/ui/partners/lander/blocks";
import { LanderHero } from "@/ui/partners/lander/lander-hero";
import { LanderRewards } from "@/ui/partners/lander/lander-rewards";
+import { ProgramEligibilityCard } from "@/ui/partners/program-eligibility-card";
import { ProgramCategory } from "@/ui/partners/program-marketplace/program-category";
import { ProgramRewardsDisplay } from "@/ui/partners/program-marketplace/program-rewards-display";
import { prisma } from "@dub/prisma";
@@ -240,6 +241,12 @@ export default async function MarketplaceProgramPage(props: {
bounties={program.bounties}
/>
+ {program.applicationRequirements?.length ? (
+ <ProgramEligibilityCard
+ requirements={program.applicationRequirements}
+ />
+ ) : null}
+
{program.landerData && (
<div className="mt-16 grid grid-cols-1 gap-10">
{program.landerData.blocks.map((block, idx) => {
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/marketplace/program-status-badge.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/marketplace/program-status-badge.tsx
index 47766a0849..b275d0e058 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/marketplace/program-status-badge.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/marketplace/program-status-badge.tsx
@@ -1,9 +1,12 @@
"use client";
+import { evaluateApplicationRequirements } from "@/lib/partners/evaluate-application-requirements";
+import usePartnerProfile from "@/lib/swr/use-partner-profile";
import useProgramEnrollments from "@/lib/swr/use-program-enrollments";
import { NetworkProgramProps } from "@/lib/types";
import { PartnerStatusBadges } from "@/ui/partners/partner-status-badges";
import { StatusBadge } from "@dub/ui";
+import { Lock } from "@dub/ui/icons";
export const ProgramNetworkStatusBadges = {
...PartnerStatusBadges,
@@ -17,19 +20,38 @@ export const ProgramNetworkStatusBadges = {
},
};
+const notEligibleBadge = {
+ variant: "new" as const,
+ className: "text-blue-600 bg-blue-100",
+ icon: Lock,
+ label: "Not eligible",
+};
+
export function ProgramStatusBadge({
program,
}: {
- program: Pick<NetworkProgramProps, "slug">;
+ program: Pick<NetworkProgramProps, "slug" | "applicationRequirements">;
}) {
const { programEnrollments } = useProgramEnrollments();
+ const { partner } = usePartnerProfile();
+
const programEnrollmentStatus = programEnrollments?.find(
(programEnrollment) => programEnrollment.program.slug === program.slug,
)?.status;
+ const { reason } = evaluateApplicationRequirements({
+ applicationRequirements: program.applicationRequirements,
+ context: {
+ country: partner?.country,
+ email: partner?.email,
+ },
+ });
+
const statusBadge = programEnrollmentStatus
? ProgramNetworkStatusBadges[programEnrollmentStatus]
- : null;
+ : reason === "requirementsNotMet"
+ ? notEligibleBadge
+ : null;
return statusBadge ? (
<StatusBadge {...statusBadge} className="px-1.5 py-0.5">
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/[customerId]/layout.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/[customerId]/layout.tsx
index 0bf75b4174..56cdfcb466 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/[customerId]/layout.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/[customerId]/layout.tsx
@@ -14,7 +14,13 @@ import { Button } from "@dub/ui";
import { ChevronRight, Users } from "@dub/ui/icons";
import { fetcher } from "@dub/utils";
import Link from "next/link";
-import { redirect, useParams, usePathname, useRouter, useSearchParams } from "next/navigation";
+import {
+ redirect,
+ useParams,
+ usePathname,
+ useRouter,
+ useSearchParams,
+} from "next/navigation";
import { ReactNode } from "react";
import useSWR from "swr";
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/links/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/links/page.tsx
index 202f788a9b..b9ecfb2184 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/links/page.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/links/page.tsx
@@ -1,10 +1,10 @@
"use client";
+import { constructPartnerLink } from "@/lib/partners/construct-partner-link";
import useDiscountCodes from "@/lib/swr/use-discount-codes";
import useGroup from "@/lib/swr/use-group";
import usePartner from "@/lib/swr/use-partner";
import useWorkspace from "@/lib/swr/use-workspace";
-import { constructPartnerLink } from "@/lib/partners/construct-partner-link";
import { DiscountCodeProps, EnrolledPartnerProps } from "@/lib/types";
import { useAddDiscountCodeModal } from "@/ui/modals/add-discount-code-modal";
import { useAddPartnerLinkModal } from "@/ui/modals/add-partner-link-modal";
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/applications/applications-menu.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/applications/applications-menu.tsx
index 6b66669d27..7201e40a33 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/applications/applications-menu.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/applications/applications-menu.tsx
@@ -2,13 +2,11 @@
import useProgram from "@/lib/swr/use-program";
import useWorkspace from "@/lib/swr/use-workspace";
-import { DEFAULT_PARTNER_GROUP } from "@/lib/zod/schemas/groups";
import { useApplicationSettingsModal } from "@/ui/modals/application-settings-modal";
import { useExportApplicationsModal } from "@/ui/modals/export-applications-modal";
import { ThreeDots } from "@/ui/shared/icons";
-import { Button, Gear, Popover, UserCheck, UserXmark } from "@dub/ui";
+import { Button, Popover, useMediaQuery, UserXmark } from "@dub/ui";
import { Download } from "@dub/ui/icons";
-import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
@@ -26,93 +24,51 @@ export function ApplicationsMenu() {
const { setShowApplicationSettingsModal, ApplicationSettingsModal } =
useApplicationSettingsModal();
+ const { isMobile } = useMediaQuery();
+
return (
<>
+ <ApplicationSettingsModal />
<ExportApplicationsModal />
- {program?.addedToMarketplaceAt && (
- <>
- <ApplicationSettingsModal />
- <Button
- text="Application settings"
- onClick={() => setShowApplicationSettingsModal(true)}
- variant="secondary"
- className="hidden sm:flex"
- />
- </>
- )}
+ <Button
+ text={isMobile ? "Settings" : "Application settings"}
+ onClick={() => setShowApplicationSettingsModal(true)}
+ variant="secondary"
+ />
<Popover
openPopover={isOpen}
setOpenPopover={setIsOpen}
content={
- <div className="w-full md:w-56">
- <div className="grid gap-px p-2">
- <p className="mb-1.5 mt-1 flex items-center gap-2 px-1 text-xs font-medium text-neutral-500">
- Application Settings
- </p>
- {program?.addedToMarketplaceAt && (
- <button
- onClick={() => {
- setShowApplicationSettingsModal(true);
- setIsOpen(false);
- }}
- className="w-full rounded-md p-2 hover:bg-neutral-100 active:bg-neutral-200 sm:hidden"
- >
- <div className="flex items-center gap-2 text-left">
- <Gear className="size-4 shrink-0" />
- <span className="text-sm font-medium">
- Application settings
- </span>
- </div>
- </button>
- )}
- <Link
- href={`/${workspaceSlug}/program/groups/${DEFAULT_PARTNER_GROUP.slug}/settings`}
- className="w-full rounded-md p-2 hover:bg-neutral-100 active:bg-neutral-200"
- >
- <div className="flex items-center gap-2 text-left">
- <UserCheck className="size-4 shrink-0" />
- <span className="text-sm font-medium">
- Auto-approval settings
- </span>
- </div>
- </Link>
- <button
- onClick={() => {
- router.push(
- `/${workspaceSlug}/program/partners/applications/rejected`,
- );
- setIsOpen(false);
- }}
- className="w-full rounded-md p-2 hover:bg-neutral-100 active:bg-neutral-200"
- >
- <div className="flex items-center gap-2 text-left">
- <UserXmark className="size-4 shrink-0" />
- <span className="text-sm font-medium">
- View rejected partners
- </span>
- </div>
- </button>
- </div>
-
- <div className="border-t border-neutral-200" />
+ <div className="grid w-full gap-px p-2 md:w-56">
+ <button
+ onClick={() => {
+ router.push(
+ `/${workspaceSlug}/program/partners/applications/rejected`,
+ );
+ setIsOpen(false);
+ }}
+ className="w-full rounded-md p-2 hover:bg-neutral-100 active:bg-neutral-200"
+ >
+ <div className="flex items-center gap-2 text-left">
+ <UserXmark className="size-4 shrink-0" />
+ <span className="text-sm font-medium">
+ View rejected partners
+ </span>
+ </div>
+ </button>
- <div className="grid gap-px p-2">
- <p className="mb-1.5 mt-1 flex items-center gap-2 px-1 text-xs font-medium text-neutral-500">
- Export Applications
- </p>
- <button
- onClick={() => {
- setShowExportApplicationsModal(true);
- setIsOpen(false);
- }}
- className="w-full rounded-md p-2 hover:bg-neutral-100 active:bg-neutral-200"
- >
- <div className="flex items-center gap-2 text-left">
- <Download className="size-4 shrink-0" />
- <span className="text-sm font-medium">Export as CSV</span>
- </div>
- </button>
- </div>
+ <button
+ onClick={() => {
+ setShowExportApplicationsModal(true);
+ setIsOpen(false);
+ }}
+ className="w-full rounded-md p-2 hover:bg-neutral-100 active:bg-neutral-200"
+ >
+ <div className="flex items-center gap-2 text-left">
+ <Download className="size-4 shrink-0" />
+ <span className="text-sm font-medium">Export as CSV</span>
+ </div>
+ </button>
</div>
}
align="end"
diff --git a/apps/web/lib/actions/partners/create-program-application.ts b/apps/web/lib/actions/partners/create-program-application.ts
index a1aeb264c2..9711afdea5 100644
--- a/apps/web/lib/actions/partners/create-program-application.ts
+++ b/apps/web/lib/actions/partners/create-program-application.ts
@@ -7,6 +7,7 @@ import { getIP } from "@/lib/api/utils/get-ip";
import { getSession } from "@/lib/auth";
import { qstash } from "@/lib/cron";
import { getPartnerProfileChecklistProgress } from "@/lib/network/get-partner-profile-checklist-progress";
+import { evaluateApplicationRequirements } from "@/lib/partners/evaluate-application-requirements";
import {
formatApplicationFormData,
formatWebsiteAndSocialsFields,
@@ -206,6 +207,7 @@ export const createProgramApplicationAction = actionClient
partner: existingPartner,
group,
data: parsedInput,
+ inAppApplication,
});
}
@@ -232,18 +234,59 @@ async function createApplicationAndEnrollment({
partner,
group,
data,
+ inAppApplication,
}: {
workspace: Pick<Project, "id" | "webhookEnabled">;
program: Program;
partner: Partner & { programs: ProgramEnrollment[] };
group: PartnerGroup;
data: z.infer<typeof createProgramApplicationSchema>;
+ inAppApplication?: boolean;
}) {
// Check if ProgramEnrollment already exists
if (partner.programs.some((p) => p.programId === program.id)) {
throw new Error("You have already applied to this program.");
}
+ const sanitizedData = sanitizeData(data, group);
+
+ const result = evaluateApplicationRequirements({
+ applicationRequirements: program.applicationRequirements,
+ context: {
+ // Always use the partner's country from their profile, if available
+ country: partner.country ?? sanitizedData.country,
+ email: partner.email,
+ },
+ });
+
+ if (result.reason === "requirementsNotMet") {
+ if (inAppApplication) {
+ throw new Error(
+ "Unfortunately, you do not meet the eligibility requirements for this program.",
+ );
+ }
+
+ const qstashResponse = await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/partners/auto-reject`,
+ delay: 30 * 60, // 30 minutes
+ body: {
+ programId: program.id,
+ partnerId: partner.id,
+ },
+ });
+
+ if (qstashResponse.messageId) {
+ console.log(
+ `The partner did not meet the eligibility requirements for this program. Auto-reject job enqueued successfully.`,
+ {
+ ...qstashResponse,
+ programId: program.id,
+ partnerId: partner.id,
+ },
+ );
+ }
+ }
+
const applicationId = createId({ prefix: "pga_" });
const enrollmentId = createId({ prefix: "pge_" });
diff --git a/apps/web/lib/actions/partners/update-application-settings.ts b/apps/web/lib/actions/partners/update-application-settings.ts
index f82a5e9a91..4a34e37cef 100644
--- a/apps/web/lib/actions/partners/update-application-settings.ts
+++ b/apps/web/lib/actions/partners/update-application-settings.ts
@@ -1,6 +1,7 @@
"use server";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { applicationRequirementsSchema } from "@/lib/zod/schemas/programs";
import { prisma } from "@dub/prisma";
import { Category } from "@dub/prisma/client";
import * as z from "zod/v4";
@@ -11,13 +12,14 @@ const schema = z.object({
workspaceId: z.string(),
description: z.string().optional(),
categories: z.array(z.enum(Category)).optional(),
+ eligibilityConditions: applicationRequirementsSchema.optional(),
});
export const updateApplicationSettingsAction = authActionClient
.inputSchema(schema)
.action(async ({ parsedInput, ctx }) => {
const { workspace } = ctx;
- const { description, categories } = parsedInput;
+ const { description, categories, eligibilityConditions } = parsedInput;
throwIfNoPermission({
role: workspace.role,
@@ -31,13 +33,16 @@ export const updateApplicationSettingsAction = authActionClient
id: programId,
},
data: {
- ...(description && { description }),
+ ...(description !== undefined && { description }),
...(categories && {
categories: {
deleteMany: {},
create: categories.map((category) => ({ category })),
},
}),
+ ...(eligibilityConditions !== undefined && {
+ applicationRequirements: eligibilityConditions,
+ }),
},
});
diff --git a/apps/web/lib/partners/complete-program-applications.ts b/apps/web/lib/partners/complete-program-applications.ts
index 7d77cfce82..909a80ab9b 100644
--- a/apps/web/lib/partners/complete-program-applications.ts
+++ b/apps/web/lib/partners/complete-program-applications.ts
@@ -8,6 +8,7 @@ import { qstash } from "../cron";
import { buildSocialPlatformLookup } from "../social-utils";
import { sendWorkspaceWebhook } from "../webhook/publish";
import { partnerApplicationWebhookSchema } from "../zod/schemas/program-application";
+import { evaluateApplicationRequirements } from "./evaluate-application-requirements";
import {
formatApplicationFormData,
formatWebsiteAndSocialsFields,
@@ -85,6 +86,8 @@ export async function completeProgramApplications(userEmail: string) {
},
);
+ const partner = user.partners[0].partner;
+
// Program enrollments to create
const programEnrollments: Prisma.ProgramEnrollmentCreateManyInput[] =
filteredProgramApplications.map((programApplication) => ({
@@ -124,7 +127,6 @@ export async function completeProgramApplications(userEmail: string) {
);
for (const programApplication of filteredProgramApplications) {
- const partner = user.partners[0].partner;
const application = programApplication;
const program = programApplication.program;
const group = programApplication.partnerGroup;
@@ -172,13 +174,65 @@ export async function completeProgramApplications(userEmail: string) {
}),
);
+ const { valid: validApplication } = evaluateApplicationRequirements({
+ applicationRequirements: program.applicationRequirements,
+ context: {
+ country: partner.country,
+ email: partner.email,
+ },
+ });
+
await Promise.allSettled([
- notifyPartnerApplication({
- partner,
- program,
- group,
- application,
- }),
+ ...(validApplication
+ ? [
+ notifyPartnerApplication({
+ partner,
+ program,
+ group,
+ application,
+ }),
+
+ // Auto-approve the partner if the group has auto-approval enabled
+ group?.autoApprovePartnersEnabledAt
+ ? qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/partners/auto-approve`,
+ delay: 5 * 60,
+ body: {
+ programId: program.id,
+ partnerId: partner.id,
+ },
+ })
+ : Promise.resolve(null),
+
+ // Send "partner.application_submitted" webhook
+ workspacesByProgramId.has(program.id) &&
+ sendWorkspaceWebhook({
+ workspace: workspacesByProgramId.get(program.id)!,
+ trigger: "partner.application_submitted",
+ data: partnerApplicationWebhookSchema.parse({
+ id: application.id,
+ createdAt: application.createdAt,
+ partner: {
+ ...partner,
+ ...programEnrollment,
+ id: partner.id,
+ status: "pending",
+ ...formatWebsiteAndSocialsFields(application),
+ },
+ applicationFormData,
+ }),
+ }),
+ ]
+ : [
+ qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/partners/auto-reject`,
+ delay: 5 * 60, // 5 minutes
+ body: {
+ programId: program.id,
+ partnerId: partner.id,
+ },
+ }),
+ ]),
// if the application has any website or social fields but the partner doesn't have the corresponding one (maybe they forgot to add during onboarding)
// update the partner to use the website they applied with
@@ -194,37 +248,6 @@ export async function completeProgramApplications(userEmail: string) {
skipDuplicates: true,
}),
- // Auto-approve the partner if the group has auto-approval enabled
- group?.autoApprovePartnersEnabledAt
- ? qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/partners/auto-approve`,
- delay: 5 * 60,
- body: {
- programId: program.id,
- partnerId: partner.id,
- },
- })
- : Promise.resolve(null),
-
- // Send "partner.application_submitted" webhook
- workspacesByProgramId.has(program.id) &&
- sendWorkspaceWebhook({
- workspace: workspacesByProgramId.get(program.id)!,
- trigger: "partner.application_submitted",
- data: partnerApplicationWebhookSchema.parse({
- id: application.id,
- createdAt: application.createdAt,
- partner: {
- ...partner,
- ...programEnrollment,
- id: partner.id,
- status: "pending",
- ...formatWebsiteAndSocialsFields(application),
- },
- applicationFormData,
- }),
- }),
-
// Detect and record fraud events for the partner when they apply to a program
detectAndRecordFraudApplication({
context: {
diff --git a/apps/web/lib/partners/evaluate-application-requirements.ts b/apps/web/lib/partners/evaluate-application-requirements.ts
new file mode 100644
index 0000000000..f6b128ea5c
--- /dev/null
+++ b/apps/web/lib/partners/evaluate-application-requirements.ts
@@ -0,0 +1,133 @@
+import { EligibilityConditionDB } from "../types";
+import { applicationRequirementsSchema } from "../zod/schemas/programs";
+
+interface Context {
+ country?: string | null;
+ email?: string | null;
+}
+
+interface Result {
+ valid: boolean;
+ reason:
+ | "invalidRequirements"
+ | "noRequirements"
+ | "requirementsMet"
+ | "requirementsNotMet";
+}
+
+// valid: @domain.com, @*.edu, @*.acme.com, @sub.domain.co.uk
+// wildcard: @*.<optional-segments.>tld e.g. @*.edu, @*.acme.com
+// exact: @<segment.>+tld e.g. @acme.com, @mail.acme.com
+const DOMAIN_PATTERN =
+ /^@(\*\.([a-z0-9][a-z0-9-]*\.)*[a-z]{2,}|[a-z0-9][a-z0-9-]*(\.[a-z0-9][a-z0-9-]*)*\.[a-z]{2,})$/i;
+
+export function isValidDomainPattern(v: string): boolean {
+ return DOMAIN_PATTERN.test(v.trim());
+}
+
+function getEmailDomain(email: string): string {
+ const parts = email.split("@");
+ return parts.length === 2 ? `@${parts[1].toLowerCase()}` : "";
+}
+
+function emailMatchesPattern(email: string, pattern: string): boolean {
+ const domain = getEmailDomain(email);
+ if (!domain) return false;
+
+ if (pattern.startsWith("@*")) {
+ const suffix = pattern.slice(2);
+ return domain.endsWith(suffix);
+ }
+
+ return domain === pattern;
+}
+
+export function evaluateApplicationRequirements({
+ applicationRequirements,
+ context,
+}: {
+ applicationRequirements: unknown;
+ context: Context;
+}): Result {
+ if (applicationRequirements == null) {
+ return {
+ valid: true,
+ reason: "noRequirements",
+ };
+ }
+
+ const parsed = applicationRequirementsSchema.safeParse(
+ applicationRequirements,
+ );
+
+ if (!parsed.success) {
+ return {
+ valid: false,
+ reason: "invalidRequirements",
+ };
+ }
+
+ const requirements = parsed.data;
+
+ if (!requirements?.length) {
+ return {
+ valid: true,
+ reason: "noRequirements",
+ };
+ }
+
+ const allMet = requirements.every((condition) =>
+ evaluateCondition({
+ condition,
+ context,
+ }),
+ );
+
+ return {
+ valid: allMet,
+ reason: allMet ? "requirementsMet" : "requirementsNotMet",
+ };
+}
+
+export function evaluateCondition({
+ condition,
+ context,
+}: {
+ condition: EligibilityConditionDB;
+ context: Context;
+}): boolean {
+ if (!context) {
+ return false;
+ }
+
+ let matches = false;
+
+ switch (condition.key) {
+ case "country": {
+ if (!context.country) {
+ return false;
+ }
+
+ matches = condition.value.includes(context.country);
+
+ break;
+ }
+
+ case "emailDomain": {
+ if (!context.email) {
+ return false;
+ }
+
+ matches = condition.value.some((pattern) =>
+ emailMatchesPattern(context.email!, pattern),
+ );
+
+ break;
+ }
+
+ default:
+ return false;
+ }
+
+ return condition.operator === "is" ? matches : !matches;
+}
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index 4564591e68..a10fefe763 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -138,6 +138,8 @@ import {
} from "./zod/schemas/program-network";
import { programDataSchema } from "./zod/schemas/program-onboarding";
import {
+ applicationRequirementsSchema,
+ eligibilityConditionSchema,
PartnerCommentSchema,
ProgramEnrollmentSchema,
ProgramSchema,
@@ -542,9 +544,10 @@ export type DiscountCodeProps = z.infer<typeof DiscountCodeSchema>;
export type ProgramProps = Omit<
z.infer<typeof ProgramSchema>,
- "referralFormData"
+ "referralFormData" | "applicationRequirements"
> & {
referralFormData?: Prisma.JsonValue | null;
+ applicationRequirements?: Prisma.JsonValue | null;
};
export type ProgramInviteEmailData = z.infer<
@@ -565,6 +568,10 @@ export type ProgramApplicationFormFieldWithValues = z.infer<
typeof programApplicationFormFieldWithValuesSchema
>;
export type ProgramEnrollmentProps = z.infer<typeof ProgramEnrollmentSchema>;
+export type EligibilityConditionDB = z.infer<typeof eligibilityConditionSchema>;
+export type ApplicationRequirementsDB = z.infer<
+ typeof applicationRequirementsSchema
+>;
export type PayoutsCount = {
status: PayoutStatus;
diff --git a/apps/web/lib/zod/schemas/program-network.ts b/apps/web/lib/zod/schemas/program-network.ts
index 6e2a864300..ae7b400507 100644
--- a/apps/web/lib/zod/schemas/program-network.ts
+++ b/apps/web/lib/zod/schemas/program-network.ts
@@ -17,6 +17,7 @@ export const NetworkProgramSchema = ProgramSchema.pick({
description: true,
rewards: true,
termsUrl: true,
+ applicationRequirements: true,
}).extend({
discount: DiscountSchema.nullish(),
categories: z.array(z.enum(Category)),
diff --git a/apps/web/lib/zod/schemas/programs.ts b/apps/web/lib/zod/schemas/programs.ts
index 9597522c62..6d84a03799 100644
--- a/apps/web/lib/zod/schemas/programs.ts
+++ b/apps/web/lib/zod/schemas/programs.ts
@@ -25,6 +25,35 @@ import { RewardSchema } from "./rewards";
import { UserSchema } from "./users";
import { centsSchemaWithDefault, parseDateSchema } from "./utils";
+export const eligibilityConditionSchema = z
+ .object({
+ key: z.enum(["country", "emailDomain"]),
+ operator: z.enum(["is", "is_not"]),
+ value: z.array(z.string()).min(1),
+ })
+ .transform((data) => {
+ if (data.key === "emailDomain") {
+ return {
+ ...data,
+ value: data.value.map((v) => {
+ const t = v.trim().toLowerCase();
+ return t.startsWith("@") ? t : `@${t}`;
+ }),
+ };
+ }
+ return data;
+ })
+ .refine(
+ (data) =>
+ data.key !== "emailDomain" ||
+ data.value.every((v) => v.length > 1 && v !== "@"),
+ { message: "Email domain values must be valid domain patterns" },
+ );
+
+export const applicationRequirementsSchema = z
+ .array(eligibilityConditionSchema)
+ .max(2);
+
export const ProgramSchema = z.object({
id: z.string(),
name: z.string(),
@@ -48,6 +77,7 @@ export const ProgramSchema = z.object({
helpUrl: z.string().nullish(),
termsUrl: z.string().nullish(),
referralFormData: z.record(z.string(), z.any()).nullish(),
+ applicationRequirements: applicationRequirementsSchema.nullish(),
createdAt: z.date(),
updatedAt: z.date(),
startedAt: z.date().nullish(),
diff --git a/apps/web/tests/misc/check-eligibility-requirements.test.ts b/apps/web/tests/misc/check-eligibility-requirements.test.ts
new file mode 100644
index 0000000000..0826402579
--- /dev/null
+++ b/apps/web/tests/misc/check-eligibility-requirements.test.ts
@@ -0,0 +1,243 @@
+import { evaluateApplicationRequirements } from "@/lib/partners/evaluate-application-requirements";
+import { describe, expect, it } from "vitest";
+
+function evaluate(
+ applicationRequirements: unknown,
+ context: { country?: string | null; email?: string | null },
+) {
+ return evaluateApplicationRequirements({ applicationRequirements, context });
+}
+
+describe("evaluateApplicationRequirements", () => {
+ describe("country — is", () => {
+ const condition = {
+ key: "country" as const,
+ operator: "is" as const,
+ value: ["US", "CA"],
+ };
+
+ it("returns valid when country is in the list", () => {
+ const result = evaluate([condition], { country: "US" });
+ expect(result.valid).toBe(true);
+ expect(result.reason).toBe("requirementsMet");
+ });
+
+ it("returns invalid when country is not in the list", () => {
+ const result = evaluate([condition], { country: "GB" });
+ expect(result.valid).toBe(false);
+ expect(result.reason).toBe("requirementsNotMet");
+ });
+
+ it("returns invalid when context has no country or is null", () => {
+ const resultNull = evaluate([condition], { country: null });
+ expect(resultNull.valid).toBe(false);
+ expect(resultNull.reason).toBe("requirementsNotMet");
+
+ const resultEmpty = evaluate([condition], {});
+ expect(resultEmpty.valid).toBe(false);
+ expect(resultEmpty.reason).toBe("requirementsNotMet");
+ });
+ });
+
+ describe("country — is_not", () => {
+ const condition = {
+ key: "country" as const,
+ operator: "is_not" as const,
+ value: ["US"],
+ };
+
+ it("returns invalid when country is in the exclusion list", () => {
+ const result = evaluate([condition], { country: "US" });
+ expect(result.valid).toBe(false);
+ expect(result.reason).toBe("requirementsNotMet");
+ });
+
+ it("returns valid when country is not in the exclusion list", () => {
+ const result = evaluate([condition], { country: "GB" });
+ expect(result.valid).toBe(true);
+ expect(result.reason).toBe("requirementsMet");
+ });
+ });
+
+ describe("emailDomain — is (exact match)", () => {
+ const condition = {
+ key: "emailDomain" as const,
+ operator: "is" as const,
+ value: ["@acme.com"],
+ };
+
+ it("returns valid when domain matches exactly", () => {
+ const result = evaluate([condition], { email: "[email protected]" });
+ expect(result.valid).toBe(true);
+ expect(result.reason).toBe("requirementsMet");
+ });
+
+ it("returns invalid for a subdomain — exact match is strict", () => {
+ const result = evaluate([condition], { email: "[email protected]" });
+ expect(result.valid).toBe(false);
+ expect(result.reason).toBe("requirementsNotMet");
+ });
+
+ it("returns invalid when domain contains the pattern as a suffix but is a different domain", () => {
+ const result = evaluate([condition], { email: "[email protected]" });
+ expect(result.valid).toBe(false);
+ expect(result.reason).toBe("requirementsNotMet");
+ });
+ });
+
+ describe("emailDomain — is (wildcard)", () => {
+ it("@*.edu matches any .edu email", () => {
+ const condition = {
+ key: "emailDomain" as const,
+ operator: "is" as const,
+ value: ["@*.edu"],
+ };
+ const resultMatch = evaluate([condition], { email: "[email protected]" });
+ expect(resultMatch.valid).toBe(true);
+ expect(resultMatch.reason).toBe("requirementsMet");
+
+ const resultNoMatch = evaluate([condition], { email: "[email protected]" });
+ expect(resultNoMatch.valid).toBe(false);
+ expect(resultNoMatch.reason).toBe("requirementsNotMet");
+ });
+
+ it("@*.acme.com matches subdomains but not the root domain", () => {
+ const condition = {
+ key: "emailDomain" as const,
+ operator: "is" as const,
+ value: ["@*.acme.com"],
+ };
+ const resultMatch = evaluate([condition], {
+ email: "[email protected]",
+ });
+ expect(resultMatch.valid).toBe(true);
+ expect(resultMatch.reason).toBe("requirementsMet");
+
+ const resultNoMatch = evaluate([condition], { email: "[email protected]" });
+ expect(resultNoMatch.valid).toBe(false);
+ expect(resultNoMatch.reason).toBe("requirementsNotMet");
+ });
+ });
+
+ describe("emailDomain — is_not", () => {
+ const condition = {
+ key: "emailDomain" as const,
+ operator: "is_not" as const,
+ value: ["@gmail.com"],
+ };
+
+ it("returns invalid when domain matches, valid when it does not", () => {
+ const resultMatch = evaluate([condition], { email: "[email protected]" });
+ expect(resultMatch.valid).toBe(false);
+ expect(resultMatch.reason).toBe("requirementsNotMet");
+
+ const resultNoMatch = evaluate([condition], { email: "[email protected]" });
+ expect(resultNoMatch.valid).toBe(true);
+ expect(resultNoMatch.reason).toBe("requirementsMet");
+ });
+ });
+
+ describe("emailDomain — missing or malformed data", () => {
+ const condition = {
+ key: "emailDomain" as const,
+ operator: "is" as const,
+ value: ["@acme.com"],
+ };
+
+ it("returns invalid when context has no email", () => {
+ const result = evaluate([condition], { email: null });
+ expect(result.valid).toBe(false);
+ expect(result.reason).toBe("requirementsNotMet");
+ });
+
+ it("returns invalid when email has no @ sign", () => {
+ const result = evaluate([condition], { email: "notanemail" });
+ expect(result.valid).toBe(false);
+ expect(result.reason).toBe("requirementsNotMet");
+ });
+ });
+
+ describe("case insensitivity", () => {
+ it("matches uppercase email domain against a lowercase pattern", () => {
+ const condition = {
+ key: "emailDomain" as const,
+ operator: "is" as const,
+ value: ["@acme.com"],
+ };
+ const result = evaluate([condition], { email: "[email protected]" });
+ expect(result.valid).toBe(true);
+ expect(result.reason).toBe("requirementsMet");
+ });
+ });
+
+ describe("multiple requirements (all must be met)", () => {
+ const countryCondition = {
+ key: "country" as const,
+ operator: "is" as const,
+ value: ["US"],
+ };
+ const emailCondition = {
+ key: "emailDomain" as const,
+ operator: "is" as const,
+ value: ["@acme.com"],
+ };
+ const requirements = [countryCondition, emailCondition];
+
+ it("returns valid when all conditions are met", () => {
+ const result = evaluate(requirements, {
+ country: "US",
+ email: "[email protected]",
+ });
+ expect(result.valid).toBe(true);
+ expect(result.reason).toBe("requirementsMet");
+ });
+
+ it("returns invalid when one condition is unmet", () => {
+ const result = evaluate(requirements, {
+ country: "GB",
+ email: "[email protected]",
+ });
+ expect(result.valid).toBe(false);
+ expect(result.reason).toBe("requirementsNotMet");
+ });
+ });
+
+ describe("no requirements", () => {
+ it("returns valid when requirements array is empty", () => {
+ const result = evaluate([], {
+ country: "US",
+ email: "[email protected]",
+ });
+ expect(result.valid).toBe(true);
+ expect(result.reason).toBe("noRequirements");
+ });
+
+ it("returns valid when applicationRequirements is null", () => {
+ const result = evaluate(null, {
+ country: "US",
+ email: "[email protected]",
+ });
+ expect(result.valid).toBe(true);
+ expect(result.reason).toBe("noRequirements");
+ });
+
+ it("returns valid when applicationRequirements is undefined", () => {
+ const result = evaluate(undefined, {
+ country: "US",
+ email: "[email protected]",
+ });
+ expect(result.valid).toBe(true);
+ expect(result.reason).toBe("noRequirements");
+ });
+ });
+
+ describe("invalid requirements", () => {
+ it("returns invalid with reason invalidRequirements when schema parsing fails", () => {
+ const result = evaluate([{ key: "country", operator: "is", value: [] }], {
+ country: "US",
+ });
+ expect(result.valid).toBe(false);
+ expect(result.reason).toBe("invalidRequirements");
+ });
+ });
+});
diff --git a/apps/web/tests/misc/eligibility-condition-schema.test.ts b/apps/web/tests/misc/eligibility-condition-schema.test.ts
new file mode 100644
index 0000000000..bcc4d1a096
--- /dev/null
+++ b/apps/web/tests/misc/eligibility-condition-schema.test.ts
@@ -0,0 +1,87 @@
+import { eligibilityConditionSchema } from "@/lib/zod/schemas/programs";
+import { describe, expect, it } from "vitest";
+
+describe("eligibilityConditionSchema — emailDomain normalization", () => {
+ it("prepends @ when missing", () => {
+ const result = eligibilityConditionSchema.parse({
+ key: "emailDomain",
+ operator: "is",
+ value: ["domain.com"],
+ });
+ expect(result.value).toEqual(["@domain.com"]);
+ });
+
+ it("lowercases the domain", () => {
+ const result = eligibilityConditionSchema.parse({
+ key: "emailDomain",
+ operator: "is",
+ value: ["@ACME.COM"],
+ });
+ expect(result.value).toEqual(["@acme.com"]);
+ });
+
+ it("normalizes each entry in the array independently", () => {
+ const result = eligibilityConditionSchema.parse({
+ key: "emailDomain",
+ operator: "is_not",
+ value: ["ACME.COM", " @Sub.Acme.Com ", "@already.com"],
+ });
+ expect(result.value).toEqual([
+ "@acme.com",
+ "@sub.acme.com",
+ "@already.com",
+ ]);
+ });
+
+ it("preserves and lowercases wildcard patterns", () => {
+ const result = eligibilityConditionSchema.parse({
+ key: "emailDomain",
+ operator: "is",
+ value: ["@*.EDU", "*.Acme.Com"],
+ });
+ expect(result.value).toEqual(["@*.edu", "@*.acme.com"]);
+ });
+});
+
+describe("eligibilityConditionSchema — country (no normalization)", () => {
+ it("does not alter country codes", () => {
+ const result = eligibilityConditionSchema.parse({
+ key: "country",
+ operator: "is",
+ value: ["US", "CA"],
+ });
+ expect(result.value).toEqual(["US", "CA"]);
+ });
+});
+
+describe("eligibilityConditionSchema — validation", () => {
+ it("rejects an empty value array", () => {
+ expect(() =>
+ eligibilityConditionSchema.parse({
+ key: "emailDomain",
+ operator: "is",
+ value: [],
+ }),
+ ).toThrow();
+ });
+
+ it("rejects a whitespace-only domain entry (normalizes to '@')", () => {
+ expect(() =>
+ eligibilityConditionSchema.parse({
+ key: "emailDomain",
+ operator: "is",
+ value: [" "],
+ }),
+ ).toThrow();
+ });
+
+ it("rejects an unknown key", () => {
+ expect(() =>
+ eligibilityConditionSchema.parse({
+ key: "unknownKey",
+ operator: "is",
+ value: ["@acme.com"],
+ }),
+ ).toThrow();
+ });
+});
diff --git a/apps/web/tests/misc/email-domain-validation.test.ts b/apps/web/tests/misc/email-domain-validation.test.ts
new file mode 100644
index 0000000000..efc1b330c5
--- /dev/null
+++ b/apps/web/tests/misc/email-domain-validation.test.ts
@@ -0,0 +1,33 @@
+import { isValidDomainPattern } from "@/lib/partners/evaluate-application-requirements";
+import { describe, expect, it } from "vitest";
+
+describe("isValidDomainPattern", () => {
+ it.each([
+ ["@acme.com", "simple domain"],
+ ["@sub.acme.com", "subdomain"],
+ ["@acme.co.uk", "multi-part TLD"],
+ ["@*.edu", "wildcard with TLD only"],
+ ["@*.acme.com", "wildcard with domain + TLD"],
+ ])("valid: %s — %s", (pattern) => {
+ expect(isValidDomainPattern(pattern)).toBe(true);
+ });
+
+ it.each([
+ ["acme.com", "missing @ prefix"],
+ ["@acme", "no TLD"],
+ ["@acme.*", "wildcard at end, not start"],
+ ["@*.", "wildcard with no TLD"],
+ ["", "empty string"],
+ ["@*.c", "TLD too short (1 char)"],
+ ])("invalid: %s — %s", (pattern) => {
+ expect(isValidDomainPattern(pattern)).toBe(false);
+ });
+
+ it("trims leading/trailing whitespace before validating", () => {
+ expect(isValidDomainPattern(" @acme.com ")).toBe(true);
+ });
+
+ it("is case-insensitive", () => {
+ expect(isValidDomainPattern("@ACME.COM")).toBe(true);
+ });
+});
diff --git a/apps/web/tests/misc/filter-active-group-bounties.test.ts b/apps/web/tests/misc/filter-active-group-bounties.test.ts
index 2978d33a30..c140f559ab 100644
--- a/apps/web/tests/misc/filter-active-group-bounties.test.ts
+++ b/apps/web/tests/misc/filter-active-group-bounties.test.ts
@@ -32,56 +32,89 @@ function makeCandidate(
describe("filterActiveGroupBounties", () => {
it("excludes archived bounties", () => {
- const bounty = makeCandidate({ archivedAt: new Date("2025-05-01T00:00:00.000Z") });
- const result = filterActiveGroupBounties([bounty], { groupId: GROUP_ID, now: NOW });
+ const bounty = makeCandidate({
+ archivedAt: new Date("2025-05-01T00:00:00.000Z"),
+ });
+ const result = filterActiveGroupBounties([bounty], {
+ groupId: GROUP_ID,
+ now: NOW,
+ });
expect(result).toHaveLength(0);
});
it("excludes bounties that have not started yet (startsAt > now)", () => {
- const bounty = makeCandidate({ startsAt: new Date("2025-06-02T00:00:00.000Z") });
- const result = filterActiveGroupBounties([bounty], { groupId: GROUP_ID, now: NOW });
+ const bounty = makeCandidate({
+ startsAt: new Date("2025-06-02T00:00:00.000Z"),
+ });
+ const result = filterActiveGroupBounties([bounty], {
+ groupId: GROUP_ID,
+ now: NOW,
+ });
expect(result).toHaveLength(0);
});
it("includes bounties that start exactly at now (startsAt === now, boundary is exclusive >)", () => {
const bounty = makeCandidate({ startsAt: NOW });
- const result = filterActiveGroupBounties([bounty], { groupId: GROUP_ID, now: NOW });
+ const result = filterActiveGroupBounties([bounty], {
+ groupId: GROUP_ID,
+ now: NOW,
+ });
expect(result).toHaveLength(1);
});
it("excludes bounties whose endsAt is exactly now (endsAt === now, exclusive boundary)", () => {
const bounty = makeCandidate({ endsAt: NOW });
- const result = filterActiveGroupBounties([bounty], { groupId: GROUP_ID, now: NOW });
+ const result = filterActiveGroupBounties([bounty], {
+ groupId: GROUP_ID,
+ now: NOW,
+ });
expect(result).toHaveLength(0);
});
it("excludes bounties that expired before now (endsAt < now)", () => {
- const bounty = makeCandidate({ endsAt: new Date("2025-05-31T00:00:00.000Z") });
- const result = filterActiveGroupBounties([bounty], { groupId: GROUP_ID, now: NOW });
+ const bounty = makeCandidate({
+ endsAt: new Date("2025-05-31T00:00:00.000Z"),
+ });
+ const result = filterActiveGroupBounties([bounty], {
+ groupId: GROUP_ID,
+ now: NOW,
+ });
expect(result).toHaveLength(0);
});
it("includes bounties with no endsAt (never expires)", () => {
const bounty = makeCandidate({ endsAt: null });
- const result = filterActiveGroupBounties([bounty], { groupId: GROUP_ID, now: NOW });
+ const result = filterActiveGroupBounties([bounty], {
+ groupId: GROUP_ID,
+ now: NOW,
+ });
expect(result).toHaveLength(1);
});
it("includes global bounties (groups is empty) regardless of groupId", () => {
const bounty = makeCandidate({ groups: [] });
- const result = filterActiveGroupBounties([bounty], { groupId: GROUP_ID, now: NOW });
+ const result = filterActiveGroupBounties([bounty], {
+ groupId: GROUP_ID,
+ now: NOW,
+ });
expect(result).toHaveLength(1);
});
it("includes group-scoped bounties when groups contains the matching groupId", () => {
const bounty = makeCandidate({ groups: [{ groupId: GROUP_ID }] });
- const result = filterActiveGroupBounties([bounty], { groupId: GROUP_ID, now: NOW });
+ const result = filterActiveGroupBounties([bounty], {
+ groupId: GROUP_ID,
+ now: NOW,
+ });
expect(result).toHaveLength(1);
});
it("excludes group-scoped bounties when groups contains only a different groupId", () => {
const bounty = makeCandidate({ groups: [{ groupId: OTHER_GROUP_ID }] });
- const result = filterActiveGroupBounties([bounty], { groupId: GROUP_ID, now: NOW });
+ const result = filterActiveGroupBounties([bounty], {
+ groupId: GROUP_ID,
+ now: NOW,
+ });
expect(result).toHaveLength(0);
});
@@ -89,21 +122,33 @@ describe("filterActiveGroupBounties", () => {
const bounty = makeCandidate({
groups: [{ groupId: OTHER_GROUP_ID }, { groupId: GROUP_ID }],
});
- const result = filterActiveGroupBounties([bounty], { groupId: GROUP_ID, now: NOW });
+ const result = filterActiveGroupBounties([bounty], {
+ groupId: GROUP_ID,
+ now: NOW,
+ });
expect(result).toHaveLength(1);
});
it("filters multiple bounties correctly in a mixed set", () => {
const bounties = [
- makeCandidate({ id: "bnty_1", archivedAt: new Date("2025-01-01T00:00:00.000Z") }),
- makeCandidate({ id: "bnty_2", startsAt: new Date("2025-07-01T00:00:00.000Z") }),
+ makeCandidate({
+ id: "bnty_1",
+ archivedAt: new Date("2025-01-01T00:00:00.000Z"),
+ }),
+ makeCandidate({
+ id: "bnty_2",
+ startsAt: new Date("2025-07-01T00:00:00.000Z"),
+ }),
makeCandidate({ id: "bnty_3", endsAt: NOW }),
makeCandidate({ id: "bnty_4", groups: [] }),
makeCandidate({ id: "bnty_5", groups: [{ groupId: GROUP_ID }] }),
makeCandidate({ id: "bnty_6", groups: [{ groupId: OTHER_GROUP_ID }] }),
];
- const result = filterActiveGroupBounties(bounties, { groupId: GROUP_ID, now: NOW });
+ const result = filterActiveGroupBounties(bounties, {
+ groupId: GROUP_ID,
+ now: NOW,
+ });
expect(result.map((b) => b.id)).toEqual(["bnty_4", "bnty_5"]);
});
});
diff --git a/apps/web/ui/customers/customer-selector.tsx b/apps/web/ui/customers/customer-selector.tsx
index 9603204261..720a93c191 100644
--- a/apps/web/ui/customers/customer-selector.tsx
+++ b/apps/web/ui/customers/customer-selector.tsx
@@ -133,7 +133,9 @@ export function CustomerSelector({
caret={true}
placeholder={variant === "header" ? "" : "Select customer"}
searchPlaceholder={
- variant === "header" ? "Search customers..." : "Search or create customer..."
+ variant === "header"
+ ? "Search customers..."
+ : "Search or create customer..."
}
onSearchChange={setSearch}
{...(variant !== "header" && {
diff --git a/apps/web/ui/modals/application-settings-modal.tsx b/apps/web/ui/modals/application-settings-modal.tsx
index 99912ac2f4..c26d196d7d 100644
--- a/apps/web/ui/modals/application-settings-modal.tsx
+++ b/apps/web/ui/modals/application-settings-modal.tsx
@@ -3,10 +3,18 @@ import { updateApplicationSettingsAction } from "@/lib/actions/partners/update-a
import { mutatePrefix } from "@/lib/swr/mutate";
import useProgram from "@/lib/swr/use-program";
import useWorkspace from "@/lib/swr/use-workspace";
+import { ApplicationRequirementsDB } from "@/lib/types";
+import { DEFAULT_PARTNER_GROUP } from "@/lib/zod/schemas/groups";
+import {
+ EligibilityCondition,
+ EligibilityRequirements,
+ generateId,
+} from "@/ui/partners/eligibility-requirements";
import { Category } from "@dub/prisma/client";
-import { Button, Modal, useEnterSubmit } from "@dub/ui";
+import { Button, Modal, ToggleGroup, useEnterSubmit } from "@dub/ui";
import { cn } from "@dub/utils";
import { useAction } from "next-safe-action/hooks";
+import Link from "next/link";
import {
Dispatch,
SetStateAction,
@@ -21,6 +29,7 @@ import { ProgramCategorySelect } from "../partners/program-category-select";
type FormData = {
description: string;
categories: Category[];
+ eligibilityConditions: EligibilityCondition[];
};
function ApplicationSettingsModal({
@@ -31,7 +40,10 @@ function ApplicationSettingsModal({
setShowApplicationSettingsModal: Dispatch<SetStateAction<boolean>>;
}) {
const { program } = useProgram();
- const { id: workspaceId } = useWorkspace();
+ const { id: workspaceId, slug: workspaceSlug } = useWorkspace();
+ const [activeSection, setActiveSection] = useState<
+ "applications" | "marketplace"
+ >("applications");
const {
control,
@@ -43,6 +55,12 @@ function ApplicationSettingsModal({
defaultValues: {
description: program?.description ?? "",
categories: program?.categories ?? [],
+ eligibilityConditions: (
+ (program?.applicationRequirements as ApplicationRequirementsDB | null) ??
+ []
+ )
+ .filter((c) => c.key === "country")
+ .map((c) => ({ ...c, key: "country" as const, id: generateId() })),
},
});
@@ -65,6 +83,13 @@ function ApplicationSettingsModal({
const result = await executeAsync({
workspaceId: workspaceId!,
...data,
+ eligibilityConditions: data.eligibilityConditions
+ .filter((c) => c.key && c.operator && c.value && c.value.length > 0)
+ .map(({ id: _id, key, operator, value }) => ({
+ key: key!,
+ operator: operator!,
+ value: value!,
+ })),
});
if (result?.serverError || result?.validationErrors) {
@@ -82,64 +107,156 @@ function ApplicationSettingsModal({
<Modal
showModal={showApplicationSettingsModal}
setShowModal={setShowApplicationSettingsModal}
+ className="flex max-h-[calc(100dvh-64px)] flex-col sm:max-h-[min(90dvh,720px)]"
>
- <div className="space-y-2 border-b border-neutral-200 p-4 sm:p-6">
+ <div className="shrink-0 space-y-2 border-b border-neutral-200 p-4 sm:p-6">
<h3 className="text-lg font-medium leading-none">
Application settings
</h3>
</div>
- <form onSubmit={onSubmit}>
- <div className="space-y-6 bg-neutral-50 p-4 sm:p-6">
- <div>
- <label
- htmlFor="description"
- className="block text-sm font-medium text-neutral-800"
- >
- Product description
- </label>
- <div className="mt-1">
- <textarea
- id="description"
- {...register("description")}
- rows={4}
- placeholder="Describe your program for the marketplace..."
- onKeyDown={handleKeyDown}
- className={cn(
- "w-full rounded-md border border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",
- errors.description &&
- "border-red-600 focus:border-red-600 focus:ring-red-600",
- )}
+ <form onSubmit={onSubmit} className="flex min-h-0 flex-1 flex-col">
+ <div className="scrollbar-hide flex-1 overflow-y-auto">
+ <div
+ className={cn(
+ "space-y-6 bg-neutral-50 p-4 sm:p-6",
+ program?.addedToMarketplaceAt && "pt-2 sm:pt-4",
+ )}
+ >
+ {program?.addedToMarketplaceAt && (
+ <ToggleGroup
+ className="flex w-full items-center gap-1 rounded-md border border-neutral-200 bg-neutral-50 p-1"
+ optionClassName="h-8 flex items-center justify-center rounded-md flex-1 text-sm normal-case"
+ indicatorClassName="bg-white"
+ options={[
+ { value: "applications", label: "Applications" },
+ { value: "marketplace", label: "Marketplace" },
+ ]}
+ selected={activeSection}
+ selectAction={(value) =>
+ setActiveSection(value as "applications" | "marketplace")
+ }
/>
- <p className="mt-1 text-xs text-neutral-500">
- This description will be displayed in the program marketplace.
- </p>
- </div>
- </div>
+ )}
- <div>
- <label className="block text-sm font-medium text-neutral-800">
- Product categories
- </label>
- <div className="mt-1">
- <Controller
- control={control}
- name="categories"
- render={({ field }) => (
- <ProgramCategorySelect
- selected={field.value}
- onChange={field.onChange}
- buttonProps={{
- className: cn(errors.categories && "border-red-600"),
- }}
+ {(!program?.addedToMarketplaceAt ||
+ activeSection === "applications") && (
+ <div className="space-y-5">
+ <div className="space-y-2">
+ <div>
+ <label className="block text-sm font-medium text-neutral-900">
+ Eligibility requirements (optional)
+ </label>
+ <p className="text-sm text-neutral-500">
+ Only eligible partners can apply.{" "}
+ <Link
+ href="https://dub.co/help/article/partner-groups#eligibility-requirements"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-neutral-500 underline underline-offset-2"
+ >
+ Learn more
+ </Link>
+ </p>
+ </div>
+
+ <Controller
+ control={control}
+ name="eligibilityConditions"
+ render={({ field }) => (
+ <EligibilityRequirements
+ value={field.value}
+ onChange={field.onChange}
+ />
+ )}
/>
- )}
- />
- </div>
+ </div>
+
+ <div className="space-y-2">
+ <div>
+ <p className="block text-sm font-medium text-neutral-900">
+ Auto-approval settings
+ </p>
+ <p className="text-sm text-neutral-500">
+ The auto-approval setting is configurable at the group
+ level.
+ </p>
+ </div>
+
+ <a
+ href={`/${workspaceSlug}/program/groups/${DEFAULT_PARTNER_GROUP.slug}/settings`}
+ target="_blank"
+ className="block"
+ >
+ <Button
+ type="button"
+ variant="secondary"
+ text="View default group settings ↗"
+ className="h-8 w-full px-3"
+ />
+ </a>
+ </div>
+ </div>
+ )}
+
+ {program?.addedToMarketplaceAt &&
+ activeSection === "marketplace" && (
+ <div className="space-y-5">
+ <div>
+ <label
+ htmlFor="description"
+ className="block text-sm font-medium text-neutral-800"
+ >
+ Product description
+ </label>
+ <div className="mt-1">
+ <textarea
+ id="description"
+ {...register("description")}
+ rows={4}
+ placeholder="Describe your program for the marketplace..."
+ onKeyDown={handleKeyDown}
+ className={cn(
+ "w-full rounded-md border border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",
+ errors.description &&
+ "border-red-600 focus:border-red-600 focus:ring-red-600",
+ )}
+ />
+ <p className="mt-1 text-xs text-neutral-500">
+ This description will be displayed in the program
+ marketplace.
+ </p>
+ </div>
+ </div>
+
+ <div>
+ <label className="block text-sm font-medium text-neutral-800">
+ Product categories
+ </label>
+ <div className="mt-1">
+ <Controller
+ control={control}
+ name="categories"
+ render={({ field }) => (
+ <ProgramCategorySelect
+ selected={field.value}
+ onChange={field.onChange}
+ buttonProps={{
+ className: cn(
+ errors.categories && "border-red-600",
+ ),
+ }}
+ />
+ )}
+ />
+ </div>
+ </div>
+ </div>
+ )}
</div>
</div>
- <div className="flex items-center justify-end gap-2 border-t border-neutral-200 bg-neutral-50 px-4 py-5 sm:px-6">
+ <div className="flex shrink-0 items-center justify-end gap-2 border-t border-neutral-200 bg-neutral-50 px-4 py-5 sm:px-6">
<Button
onClick={() => setShowApplicationSettingsModal(false)}
variant="secondary"
diff --git a/apps/web/ui/partners/eligibility-requirements.tsx b/apps/web/ui/partners/eligibility-requirements.tsx
new file mode 100644
index 0000000000..56db249562
--- /dev/null
+++ b/apps/web/ui/partners/eligibility-requirements.tsx
@@ -0,0 +1,342 @@
+"use client";
+
+import { EligibilityConditionDB } from "@/lib/types";
+import {
+ InlineBadgePopover,
+ InlineBadgePopoverMenu,
+} from "@/ui/shared/inline-badge-popover";
+import { AnimatedSizeContainer } from "@dub/ui";
+import { CircleCheck, Users2, Xmark } from "@dub/ui/icons";
+import { COUNTRIES } from "@dub/utils";
+
+type ConditionKey = EligibilityConditionDB["key"];
+
+type EligibilityOperator = EligibilityConditionDB["operator"];
+
+export type EligibilityCondition = {
+ id: string;
+ key: EligibilityConditionDB["key"] | null;
+ operator: EligibilityConditionDB["operator"] | null;
+ value: EligibilityConditionDB["value"] | null;
+};
+
+const CONDITION_CONFIGS: Record<
+ ConditionKey,
+ {
+ label: string;
+ operators: EligibilityOperator[];
+ }
+> = {
+ country: {
+ label: "country",
+ operators: ["is", "is_not"],
+ },
+ emailDomain: {
+ label: "email domain",
+ operators: ["is", "is_not"],
+ },
+};
+
+const OPERATOR_LABELS: Record<EligibilityOperator, string> = {
+ is: "is",
+ is_not: "is not",
+};
+
+function isValueValid(value: string[] | null): boolean {
+ return Array.isArray(value) && value.length > 0 && value[0] !== "";
+}
+
+export function generateId(): string {
+ return Math.random().toString(36).slice(2, 10);
+}
+
+const COUNTRY_ITEMS = Object.entries(COUNTRIES).map(([code, name]) => ({
+ text: name,
+ value: code,
+ icon: (
+ <img
+ alt={`${code} flag`}
+ src={`https://hatscripts.github.io/circle-flags/flags/${code.toLowerCase()}.svg`}
+ className="size-3 shrink-0"
+ />
+ ),
+}));
+
+function CountryValueInput({
+ value,
+ onChange,
+}: {
+ value: string[];
+ onChange: (v: string[]) => void;
+}) {
+ return (
+ <InlineBadgePopoverMenu
+ search
+ selectedValue={value}
+ items={COUNTRY_ITEMS}
+ onSelect={(code) =>
+ onChange(
+ value.includes(code)
+ ? value.filter((v) => v !== code)
+ : [...value, code],
+ )
+ }
+ />
+ );
+}
+
+// EmailDomainInput — commented out, preserved for future use
+// function EmailDomainInput({
+// value,
+// onChange,
+// }: {
+// value: string[];
+// onChange: (v: string[]) => void;
+// }) {
+// const domains = value.length > 0 ? value : [""];
+// const inputRefs = useRef<(HTMLInputElement | null)[]>([]);
+//
+// const handleChange = (index: number, newVal: string) => {
+// const next = [...domains];
+// next[index] = newVal;
+// onChange(next);
+// };
+//
+// const handleRemove = (index: number) => {
+// const next = domains.filter((_, i) => i !== index);
+// onChange(next.length > 0 ? next : [""]);
+// const focusIndex = Math.max(0, index - 1);
+// requestAnimationFrame(() => inputRefs.current[focusIndex]?.focus());
+// };
+//
+// const handleAdd = () => {
+// onChange([...domains, ""]);
+// };
+//
+// const showRemove = domains.length > 1;
+//
+// const hasInvalidEntry = domains.some(
+// (d) => d.trim().length > 0 && !isValidDomainPattern(d),
+// );
+//
+// return (
+// <div className="flex w-52 flex-col gap-1">
+// {domains.map((domain, index) => {
+// const isInvalid =
+// domain.trim().length > 0 && !isValidDomainPattern(domain);
+// return (
+// <div key={index} className="flex flex-col gap-0.5">
+// <div className="relative flex items-center">
+// <input
+// ref={(el) => { inputRefs.current[index] = el; }}
+// type="text"
+// value={domain}
+// placeholder="@domain.com"
+// autoFocus={index === domains.length - 1 && index > 0}
+// className={cn(
+// "block h-8 w-full rounded-lg border py-1.5 text-sm text-neutral-800 placeholder-neutral-400",
+// "focus:outline-none focus:ring-1",
+// isInvalid
+// ? "border-red-400 focus:border-red-500 focus:ring-red-500"
+// : "border-neutral-300 focus:border-neutral-500 focus:ring-neutral-500",
+// showRemove ? "pl-2.5 pr-8" : "px-2.5",
+// )}
+// onChange={(e) => handleChange(index, e.target.value)}
+// onKeyDown={(e) => {
+// if (e.key === "Enter") {
+// e.preventDefault();
+// if (domain.trim() && !hasInvalidEntry) handleAdd();
+// }
+// if (e.key === "Backspace" && !domain && showRemove) {
+// e.preventDefault();
+// handleRemove(index);
+// }
+// }}
+// />
+// {showRemove && (
+// <button
+// type="button"
+// onClick={() => handleRemove(index)}
+// className="absolute right-1 flex h-6 w-6 items-center justify-center rounded-md bg-neutral-100 text-neutral-900 hover:bg-neutral-200"
+// aria-label="Remove domain"
+// >
+// <Xmark className="size-3" />
+// </button>
+// )}
+// </div>
+// {isInvalid && (
+// <p className="text-xs text-red-500">
+// Use format: @domain.com or @*.tld
+// </p>
+// )}
+// </div>
+// );
+// })}
+// <Button
+// type="button"
+// variant="secondary"
+// text="Add domain"
+// className="h-6 text-xs font-medium text-neutral-900"
+// onClick={handleAdd}
+// disabled={hasInvalidEntry}
+// />
+// </div>
+// );
+// }
+
+function ValueBadge({
+ value,
+ onChange,
+}: {
+ conditionKey: ConditionKey;
+ value: string[] | null;
+ onChange: (v: string[]) => void;
+}) {
+ const displayText = isValueValid(value) ? value!.join(", ") : "value";
+ const isInvalid = !isValueValid(value);
+
+ return (
+ <InlineBadgePopover text={displayText} invalid={isInvalid}>
+ <div className="p-1">
+ <CountryValueInput value={value ?? []} onChange={onChange} />
+ </div>
+ {/* emailDomain branch commented out — preserved for future use */}
+ {/* {config.valueType === "emailDomain" && (
+ <div className="p-1">
+ <EmailDomainInput value={value ?? []} onChange={onChange} />
+ </div>
+ )} */}
+ </InlineBadgePopover>
+ );
+}
+
+function ConditionRow({
+ condition,
+ onChange,
+ onRemove,
+}: {
+ condition: EligibilityCondition;
+ onChange: (updated: EligibilityCondition) => void;
+ onRemove: () => void;
+}) {
+ const keyConfig = CONDITION_CONFIGS["country"];
+
+ const handleOperatorChange = (operator: EligibilityOperator) => {
+ onChange({ ...condition, operator, value: null });
+ };
+
+ const handleValueChange = (value: string[]) => {
+ onChange({ ...condition, value });
+ };
+
+ return (
+ <div className="flex items-start gap-2 rounded-xl border border-neutral-200 bg-white p-2.5 shadow-sm">
+ <div className="flex size-7 shrink-0 items-center justify-center rounded-md bg-neutral-100">
+ <Users2 className="size-4 text-neutral-800" />
+ </div>
+
+ <span className="flex min-w-0 flex-1 flex-wrap items-center gap-x-1 gap-y-1 text-sm font-medium leading-relaxed text-neutral-800">
+ If partner {keyConfig.label}
+ <InlineBadgePopover
+ text={
+ condition.operator
+ ? OPERATOR_LABELS[condition.operator]
+ : "operator"
+ }
+ invalid={!condition.operator}
+ >
+ <InlineBadgePopoverMenu
+ selectedValue={condition.operator ?? undefined}
+ onSelect={(op) => handleOperatorChange(op as EligibilityOperator)}
+ items={keyConfig.operators.map((op) => ({
+ text: OPERATOR_LABELS[op],
+ value: op,
+ }))}
+ />
+ </InlineBadgePopover>
+ {condition.operator && (
+ <ValueBadge
+ conditionKey="country"
+ value={condition.value}
+ onChange={handleValueChange}
+ />
+ )}
+ </span>
+
+ <button
+ type="button"
+ onClick={onRemove}
+ className="shrink-0 rounded-md p-2 text-neutral-900 transition-colors hover:bg-neutral-100"
+ aria-label="Remove condition"
+ >
+ <Xmark className="size-3" />
+ </button>
+ </div>
+ );
+}
+
+export function EligibilityRequirements({
+ value: conditions,
+ onChange,
+}: {
+ value: EligibilityCondition[];
+ onChange: (conditions: EligibilityCondition[]) => void;
+}) {
+ const hasCondition = conditions.length > 0;
+
+ const handleAdd = () => {
+ if (hasCondition) return;
+ onChange([
+ { id: generateId(), key: "country", operator: null, value: null },
+ ]);
+ };
+
+ const handleChange = (updated: EligibilityCondition) => {
+ onChange([updated]);
+ };
+
+ const handleRemove = () => {
+ onChange([]);
+ };
+
+ return (
+ <AnimatedSizeContainer
+ height
+ className="rounded-[10px] border border-neutral-200 bg-neutral-100"
+ >
+ <div className="flex flex-col px-2.5 py-3">
+ {!hasCondition ? (
+ <button
+ type="button"
+ onClick={handleAdd}
+ className="flex w-full items-center justify-center gap-2 rounded-lg border border-neutral-200 bg-white px-2 py-2 text-sm font-medium text-neutral-900 transition-colors hover:bg-neutral-50"
+ >
+ <Users2 className="size-4" />
+ Add condition
+ </button>
+ ) : (
+ <div>
+ <div className="flex flex-col">
+ <ConditionRow
+ condition={conditions[0]}
+ onChange={handleChange}
+ onRemove={handleRemove}
+ />
+ </div>
+
+ <div className="ml-6 h-3 w-px bg-neutral-300" />
+
+ <div className="flex items-center gap-2.5 rounded-xl border border-neutral-200 bg-white p-2.5 shadow-sm">
+ <div className="flex size-7 shrink-0 items-center justify-center rounded-md bg-neutral-100">
+ <CircleCheck className="size-4 text-neutral-600" />
+ </div>
+ <span className="text-sm font-medium text-neutral-700">
+ Allow partner to apply
+ </span>
+ </div>
+ </div>
+ )}
+ </div>
+ </AnimatedSizeContainer>
+ );
+}
diff --git a/apps/web/ui/partners/program-eligibility-card.tsx b/apps/web/ui/partners/program-eligibility-card.tsx
new file mode 100644
index 0000000000..f05c7fc715
--- /dev/null
+++ b/apps/web/ui/partners/program-eligibility-card.tsx
@@ -0,0 +1,88 @@
+"use client";
+
+import { evaluateCondition } from "@/lib/partners/evaluate-application-requirements";
+import usePartnerProfile from "@/lib/swr/use-partner-profile";
+import useProgramEnrollment from "@/lib/swr/use-program-enrollment";
+import { EligibilityConditionDB } from "@/lib/types";
+import { Lock } from "@dub/ui/icons";
+import { COUNTRIES } from "@dub/utils";
+
+function oxfordJoin(items: string[]): string {
+ if (items.length === 0) return "";
+ if (items.length === 1) return items[0];
+ if (items.length === 2) return `${items[0]} or ${items[1]}`;
+ return `${items.slice(0, -1).join(", ")}, or ${items[items.length - 1]}`;
+}
+
+function formatConditionText(condition: EligibilityConditionDB): string {
+ if (condition.key === "country") {
+ const countryNames = condition.value.map((code) => COUNTRIES[code] ?? code);
+ const joined = oxfordJoin(countryNames);
+
+ if (condition.operator === "is") {
+ return `Your country is ${joined}`;
+ } else {
+ return `Your country is not ${joined}`;
+ }
+ }
+
+ // emailDomain — commented out, preserved for future use
+ // if (condition.key === "emailDomain") {
+ // const joined = oxfordJoin(condition.value);
+ // if (condition.operator === "is") {
+ // return `Your email domain is ${joined}`;
+ // } else {
+ // return `Your email domain is not ${joined}`;
+ // }
+ // }
+
+ return "";
+}
+
+export function ProgramEligibilityCard({
+ requirements: requirementsProp,
+}: {
+ requirements?: EligibilityConditionDB[] | null;
+} = {}) {
+ const { programEnrollment } = useProgramEnrollment();
+ const { partner, loading } = usePartnerProfile();
+
+ const requirements =
+ requirementsProp !== undefined
+ ? requirementsProp
+ : programEnrollment?.program?.applicationRequirements;
+
+ if (!requirements?.length || loading) return null;
+
+ const context = {
+ country: partner?.country,
+ email: partner?.email,
+ };
+
+ const unmet = requirements.filter(
+ (condition) =>
+ !evaluateCondition({
+ condition,
+ context,
+ }),
+ );
+
+ const unmetWithText = unmet.map(formatConditionText).filter(Boolean);
+
+ if (unmetWithText.length === 0) return null;
+
+ return (
+ <div className="mt-4 space-y-3 rounded-[10px] border border-blue-200 bg-blue-50 p-4">
+ <div className="flex items-center gap-2 font-semibold text-blue-900">
+ <Lock className="size-4 text-blue-500" />
+ Program eligibility
+ </div>
+
+ <ul className="list-disc space-y-1 pl-5 text-sm text-blue-800">
+ {unmetWithText.map((text, i) => (
+ <li key={i}>{text}</li>
+ ))}
+ </ul>
+ </div>
+ );
+}
diff --git a/packages/email/src/templates/partner-application-rejected.tsx b/packages/email/src/templates/partner-application-rejected.tsx
new file mode 100644
index 0000000000..56eed00933
--- /dev/null
+++ b/packages/email/src/templates/partner-application-rejected.tsx
@@ -0,0 +1,92 @@
+import { DUB_WORDMARK } from "@dub/utils";
+import {
+ Body,
+ Container,
+ Head,
+ Heading,
+ Html,
+ Img,
+ Link,
+ Preview,
+ Section,
+ Tailwind,
+ Text,
+} from "@react-email/components";
+import { Footer } from "../components/footer";
+
+export default function PartnerApplicationRejected({
+ partner = {
+ name: "John",
+ email: "[email protected]",
+ },
+ program = {
+ name: "Acme",
+ slug: "acme",
+ supportEmail: "[email protected]",
+ },
+}: {
+ partner: {
+ name: string;
+ email: string;
+ };
+ program: {
+ name: string;
+ slug: string;
+ supportEmail?: string | null;
+ };
+}) {
+ return (
+ <Html>
+ <Head />
+ <Preview>
+ {program.name} has rejected your application to join their partner
+ program
+ </Preview>
+ <Tailwind>
+ <Body className="mx-auto my-auto bg-white font-sans">
+ <Container className="mx-auto my-10 max-w-[600px] rounded border border-solid border-neutral-200 px-10 py-5">
+ <Section className="mb-8 mt-6">
+ <Img src={DUB_WORDMARK} width="61" height="32" alt="dub" />
+ </Section>
+
+ <Heading className="mx-0 p-0 text-lg font-medium text-neutral-600">
+ Hello {partner.name},
+ </Heading>
+
+ <Text className="text-sm leading-6 text-neutral-600">
+ Your application to join <strong>{program.name}'s</strong> partner
+ program has been rejected. You did not meet the program's
+ eligibility requirements.
+ </Text>
+
+ <Text className="text-sm leading-6 text-neutral-600">
+ You will be able to re-apply in 30 days.
+ </Text>
+
+ <Text className="text-sm leading-6 text-neutral-600">
+ {program.supportEmail ? (
+ <>
+ If you have any questions, please{" "}
+ <Link
+ href={`mailto:${program.supportEmail}`}
+ className="font-semibold text-neutral-700 underline underline-offset-2"
+ >
+ reach out to the {program.name} team ↗
+ </Link>
+ .
+ </>
+ ) : (
+ <>
+ If you have any questions, please contact the {program.name}{" "}
+ team directly.
+ </>
+ )}
+ </Text>
+
+ <Footer email={partner.email} />
+ </Container>
+ </Body>
+ </Tailwind>
+ </Html>
+ );
+}
diff --git a/packages/prisma/schema/program.prisma b/packages/prisma/schema/program.prisma
index 21be301b07..a380201ce6 100644
--- a/packages/prisma/schema/program.prisma
+++ b/packages/prisma/schema/program.prisma
@@ -39,10 +39,11 @@ 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
- referralFormData Json? @db.Json
+ inviteEmailData Json? @db.Json
+ embedData Json? @db.Json
+ resources Json? @db.Json
+ referralFormData Json? @db.Json
+ applicationRequirements Json? @db.Json
termsUrl String? @db.Text
helpUrl String? @db.Text
supportEmail String?
diff --git a/packages/ui/src/animated-size-container.tsx b/packages/ui/src/animated-size-container.tsx
index 6975d3fbf6..5ca58f4b49 100644
--- a/packages/ui/src/animated-size-container.tsx
+++ b/packages/ui/src/animated-size-container.tsx
@@ -10,6 +10,8 @@ import {
} from "react";
import { useResizeObserver } from "./hooks";
+const defaultTransition = { type: "spring" as const, duration: 0.3 };
+
type AnimatedSizeContainerProps = PropsWithChildren<{
width?: boolean;
height?: boolean;
@@ -35,20 +37,34 @@ const AnimatedSizeContainer: ForwardRefExoticComponent<
) => {
const containerRef = useRef<HTMLDivElement>(null);
const resizeObserverEntry = useResizeObserver(containerRef);
+ const hasMeasuredRef = useRef(false);
+
+ const measuredWidth = resizeObserverEntry?.contentRect?.width;
+ const measuredHeight = resizeObserverEntry?.contentRect?.height;
+ const isFirstMeasurement =
+ (width ? measuredWidth != null : true) &&
+ (height ? measuredHeight != null : true) &&
+ !hasMeasuredRef.current;
+
+ if (resizeObserverEntry) {
+ hasMeasuredRef.current = true;
+ }
+
+ const effectiveTransition =
+ transition ??
+ (isFirstMeasurement
+ ? { duration: 0 }
+ : defaultTransition);
return (
<motion.div
ref={forwardedRef}
className={cn("overflow-hidden", className)}
animate={{
- width: width
- ? resizeObserverEntry?.contentRect?.width ?? "auto"
- : "auto",
- height: height
- ? resizeObserverEntry?.contentRect?.height ?? "auto"
- : "auto",
+ width: width ? measuredWidth ?? "auto" : "auto",
+ height: height ? measuredHeight ?? "auto" : "auto",
}}
- transition={transition ?? { type: "spring", duration: 0.3 }}
+ transition={effectiveTransition}
{...rest}
>
<div