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.

add application screening and a Jev hold on auto-approve

Pedro Ladeirae24787b6be0c
diff --git a/apps/web/.env.example b/apps/web/.env.example
index c8b378c39e..eaca01dd11 100644
--- a/apps/web/.env.example
+++ b/apps/web/.env.example
@@ -130,6 +130,7 @@ NEXT_PUBLIC_NGROK_URL=
# For AI features
ANTHROPIC_API_KEY=
+AI_GATEWAY_API_KEY=
# Axiom – used for logging and monitoring
# Get your Axiom token here: https://axiom.co/docs/rest-api/authentication
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/applications/application-auto-approve-settings.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/applications/application-auto-approve-settings.tsx
new file mode 100644
index 0000000000..ee57bea885
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/applications/application-auto-approve-settings.tsx
@@ -0,0 +1,304 @@
+"use client";
+
+import useWorkspace from "@/lib/swr/use-workspace";
+import { GroupProps } from "@/lib/types";
+import { DEFAULT_PARTNER_GROUP } from "@/lib/zod/schemas/groups";
+import { GroupColorCircle } from "@/ui/partners/groups/group-color-circle";
+import { AnimatedSizeContainer, StatusBadge, Switch } from "@dub/ui";
+import Link from "next/link";
+import { useCallback, useMemo, useState } from "react";
+
+export type AutoApproveGroup = Pick<
+ GroupProps,
+ "id" | "name" | "slug" | "color" | "autoApprovePartnersEnabledAt"
+>;
+
+export type AutoApproveUpdate = {
+ groupId: string;
+ autoApprovePartners: boolean;
+ applyToAllGroups?: boolean;
+};
+
+type AllGroupsState = { enabled: boolean };
+
+const FADE_SCROLL_DISTANCE = 40;
+
+export function useApplicationAutoApproveSettings(
+ groups: AutoApproveGroup[] | undefined,
+) {
+ const [overrides, setOverrides] = useState<Record<string, boolean>>({});
+ const [allGroups, setAllGroups] = useState<AllGroupsState | null>(null);
+
+ const sortedGroups = useMemo(() => {
+ if (!groups) return [];
+
+ const defaultGroup = groups.find(
+ (group) => group.slug === DEFAULT_PARTNER_GROUP.slug,
+ );
+
+ return defaultGroup
+ ? [defaultGroup, ...groups.filter((group) => group !== defaultGroup)]
+ : groups;
+ }, [groups]);
+
+ const defaultGroup = sortedGroups[0];
+
+ const isGroupEnabled = useCallback(
+ (group: AutoApproveGroup) =>
+ overrides[group.id] ?? Boolean(group.autoApprovePartnersEnabledAt),
+ [overrides],
+ );
+
+ const setGroupEnabled = useCallback(
+ (group: AutoApproveGroup, enabled: boolean) =>
+ setOverrides((prev) => {
+ const next = { ...prev };
+ const saved = Boolean(group.autoApprovePartnersEnabledAt);
+
+ if (enabled === saved) {
+ delete next[group.id];
+ } else {
+ next[group.id] = enabled;
+ }
+
+ return next;
+ }),
+ [],
+ );
+
+ const savedAllEnabled =
+ sortedGroups.length > 0 &&
+ sortedGroups.every((group) => Boolean(group.autoApprovePartnersEnabledAt));
+
+ const allGroupsEnabled = allGroups ? allGroups.enabled : savedAllEnabled;
+
+ const setAllGroupsEnabled = useCallback((enabled: boolean) => {
+ setAllGroups({ enabled });
+ }, []);
+
+ const pendingUpdates = useMemo<AutoApproveUpdate[]>(() => {
+ if (allGroupsEnabled) {
+ const needsUpdate = sortedGroups.some(
+ (group) => !group.autoApprovePartnersEnabledAt,
+ );
+
+ return needsUpdate && defaultGroup
+ ? [
+ {
+ groupId: defaultGroup.id,
+ autoApprovePartners: true,
+ applyToAllGroups: true,
+ },
+ ]
+ : [];
+ }
+
+ return sortedGroups.flatMap((group) => {
+ const enabled = overrides[group.id];
+
+ return enabled !== undefined &&
+ enabled !== Boolean(group.autoApprovePartnersEnabledAt)
+ ? [{ groupId: group.id, autoApprovePartners: enabled }]
+ : [];
+ });
+ }, [allGroupsEnabled, defaultGroup, sortedGroups, overrides]);
+
+ return {
+ sortedGroups,
+ isGroupEnabled,
+ setGroupEnabled,
+ allGroupsEnabled,
+ setAllGroupsEnabled,
+ pendingUpdates,
+ };
+}
+
+export type ApplicationAutoApproveSettings = ReturnType<
+ typeof useApplicationAutoApproveSettings
+>;
+
+export function ApplicationAutoApproveSettings({
+ loading,
+ autoApprove,
+}: {
+ loading: boolean;
+ autoApprove: ApplicationAutoApproveSettings;
+}) {
+ const {
+ sortedGroups,
+ isGroupEnabled,
+ setGroupEnabled,
+ allGroupsEnabled,
+ setAllGroupsEnabled,
+ } = autoApprove;
+
+ return (
+ <div className="space-y-3">
+ <div>
+ <h4 className="text-content-emphasis text-sm font-medium leading-5 tracking-[-0.02em]">
+ Auto-approval settings
+ </h4>
+ <p className="text-xs font-normal leading-4 tracking-[-0.02em] text-neutral-500">
+ The auto-approval setting is configurable at the group level.
+ </p>
+ </div>
+
+ <label className="flex w-fit cursor-pointer select-none items-center gap-3 py-1">
+ <Switch
+ checked={allGroupsEnabled}
+ fn={setAllGroupsEnabled}
+ disabled={loading}
+ />
+ <span className="text-sm font-medium leading-5 tracking-[-0.02em] text-neutral-800">
+ Enable auto-approve for all groups
+ </span>
+ </label>
+
+ <AnimatedSizeContainer height>
+ {allGroupsEnabled ? (
+ <div className="flex h-11 items-center justify-between gap-4 rounded-lg border border-neutral-200 bg-white px-4">
+ <div className="flex min-w-0 items-center gap-2">
+ <div className="flex -space-x-1">
+ {sortedGroups.slice(0, 3).map((group) => (
+ <div
+ key={group.id}
+ className="rounded-full ring-2 ring-white"
+ >
+ <GroupColorCircle group={group} />
+ </div>
+ ))}
+ </div>
+ <span className="text-sm font-medium text-neutral-700">
+ All groups
+ </span>
+ <span className="rounded-md bg-neutral-100 px-1.5 py-0.5 text-xs font-semibold text-neutral-700">
+ {sortedGroups.length}
+ </span>
+ </div>
+
+ <StatusBadge
+ variant="success"
+ icon={null}
+ className="px-1.5 py-0.5"
+ >
+ Auto-approve enabled
+ </StatusBadge>
+ </div>
+ ) : (
+ <AutoApproveGroupsTable
+ groups={sortedGroups}
+ loading={loading}
+ isGroupEnabled={isGroupEnabled}
+ onGroupEnabledChange={setGroupEnabled}
+ />
+ )}
+ </AnimatedSizeContainer>
+ </div>
+ );
+}
+
+function AutoApproveGroupsTable({
+ groups,
+ loading,
+ isGroupEnabled,
+ onGroupEnabledChange,
+}: {
+ groups: AutoApproveGroup[];
+ loading: boolean;
+ isGroupEnabled: (group: AutoApproveGroup) => boolean;
+ onGroupEnabledChange: (group: AutoApproveGroup, enabled: boolean) => void;
+}) {
+ const { slug: workspaceSlug } = useWorkspace();
+ const [fades, setFades] = useState({ top: 0, bottom: 0 });
+
+ const updateFades = useCallback((el: HTMLElement) => {
+ const maxScrollTop = el.scrollHeight - el.clientHeight;
+ const top = Math.min(el.scrollTop / FADE_SCROLL_DISTANCE, 1);
+ const bottom =
+ maxScrollTop <= 0
+ ? 0
+ : Math.min((maxScrollTop - el.scrollTop) / FADE_SCROLL_DISTANCE, 1);
+
+ setFades((prev) =>
+ prev.top === top && prev.bottom === bottom ? prev : { top, bottom },
+ );
+ }, []);
+
+ const scrollRef = useCallback(
+ (el: HTMLDivElement | null) => {
+ if (!el) return;
+
+ const observer = new ResizeObserver(() => updateFades(el));
+ observer.observe(el);
+ if (el.firstElementChild) observer.observe(el.firstElementChild);
+
+ return () => observer.disconnect();
+ },
+ [updateFades],
+ );
+
+ return (
+ <div className="relative overflow-hidden rounded-lg border border-neutral-200 bg-white">
+ <div
+ ref={scrollRef}
+ onScroll={(e) => updateFades(e.currentTarget)}
+ className="scrollbar-hide max-h-[268px] overflow-y-auto [clip-path:inset(0)]"
+ >
+ <div className="divide-y divide-neutral-200">
+ {loading
+ ? [...Array(3)].map((_, idx) => (
+ <div
+ key={idx}
+ className="flex h-11 items-center justify-between px-4"
+ >
+ <div className="h-4 w-32 animate-pulse rounded-md bg-neutral-200" />
+ <div className="h-4 w-8 animate-pulse rounded-md bg-neutral-200" />
+ </div>
+ ))
+ : groups.map((group) => (
+ <div
+ key={group.id}
+ className="flex h-11 items-center justify-between gap-4 px-4"
+ >
+ <div className="flex min-w-0 items-center gap-2">
+ <Link
+ href={`/${workspaceSlug}/program/groups/${group.slug}/settings`}
+ target="_blank"
+ className="flex min-w-0 items-center gap-2 rounded-md text-sm font-medium text-neutral-700 transition-colors hover:text-neutral-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-500"
+ >
+ <GroupColorCircle group={group} />
+ <span className="truncate">{group.name}</span>
+ </Link>
+ {group.slug === DEFAULT_PARTNER_GROUP.slug && (
+ <StatusBadge
+ variant="new"
+ icon={null}
+ className="px-1.5 py-0.5"
+ >
+ Default
+ </StatusBadge>
+ )}
+ </div>
+
+ <Switch
+ checked={isGroupEnabled(group)}
+ fn={(checked) => onGroupEnabledChange(group, checked)}
+ />
+ </div>
+ ))}
+ </div>
+ </div>
+
+ <div
+ aria-hidden
+ className="pointer-events-none absolute inset-x-0 top-0 h-8 bg-gradient-to-b from-white to-transparent"
+ style={{ opacity: fades.top }}
+ />
+ <div
+ aria-hidden
+ className="pointer-events-none absolute inset-x-0 bottom-0 h-20 bg-gradient-to-t from-white to-transparent"
+ style={{ opacity: fades.bottom }}
+ />
+ </div>
+ );
+}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/applications/application-settings-sheet.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/applications/application-settings-sheet.tsx
new file mode 100644
index 0000000000..19f7ff0b45
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/applications/application-settings-sheet.tsx
@@ -0,0 +1,413 @@
+"use client";
+
+import { parseActionError } from "@/lib/actions/parse-action-errors";
+import { updateApplicationSettingsAction } from "@/lib/actions/partners/update-application-settings";
+import { mutatePrefix } from "@/lib/swr/mutate";
+import useGroups from "@/lib/swr/use-groups";
+import useProgram from "@/lib/swr/use-program";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { ApplicationRequirementsDB, ProgramProps } from "@/lib/types";
+import {
+ EligibilityCondition,
+ EligibilityRequirements,
+ generateId,
+} from "@/ui/partners/eligibility-requirements";
+import { ProgramCategorySelect } from "@/ui/partners/program-category-select";
+import { X } from "@/ui/shared/icons";
+import {
+ Button,
+ Sheet,
+ Sparkle3,
+ Switch,
+ ToggleGroup,
+ useEnterSubmit,
+} from "@dub/ui";
+import { cn } from "@dub/utils";
+import { Category } from "@prisma/client";
+import { useAction } from "next-safe-action/hooks";
+import Link from "next/link";
+import { Dispatch, SetStateAction, useEffect, useState } from "react";
+import { Controller, useForm } from "react-hook-form";
+import { toast } from "sonner";
+import {
+ ApplicationAutoApproveSettings,
+ AutoApproveUpdate,
+ useApplicationAutoApproveSettings,
+} from "./application-auto-approve-settings";
+
+type ApplicationSettingsSheetProps = {
+ setIsOpen: Dispatch<SetStateAction<boolean>>;
+};
+
+type FormData = {
+ description: string;
+ categories: Category[];
+ eligibilityConditions: EligibilityCondition[];
+ applicationScreeningCriteria: string;
+ aiAutoApproveEnabled: boolean;
+};
+
+function ApplicationSettingsSheetContent({
+ setIsOpen,
+}: ApplicationSettingsSheetProps) {
+ // Screening/AI config is workspace-scoped, so it is not part of ProgramProps
+ const { program } = useProgram<
+ ProgramProps & {
+ applicationScreeningCriteria: string | null;
+ aiAutoApproveEnabledAt: Date | null;
+ }
+ >();
+ const { id: workspaceId, defaultProgramId } = useWorkspace();
+ const { groups, loading: groupsLoading } = useGroups({
+ query: { sortBy: "createdAt", sortOrder: "asc" },
+ });
+ const [activeSection, setActiveSection] = useState<
+ "applications" | "marketplace"
+ >("applications");
+
+ const {
+ control,
+ handleSubmit,
+ register,
+ reset,
+ formState: { errors, isSubmitting, isDirty },
+ } = useForm<FormData>({
+ defaultValues: {
+ description: "",
+ categories: [],
+ eligibilityConditions: [],
+ applicationScreeningCriteria: "",
+ aiAutoApproveEnabled: false,
+ },
+ });
+
+ useEffect(() => {
+ if (!program) {
+ return;
+ }
+
+ reset({
+ 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() })),
+ applicationScreeningCriteria: program.applicationScreeningCriteria ?? "",
+ aiAutoApproveEnabled: Boolean(program.aiAutoApproveEnabledAt),
+ });
+ }, [program?.id, reset]);
+
+ const { handleKeyDown } = useEnterSubmit();
+ const autoApprove = useApplicationAutoApproveSettings(groups);
+ const { executeAsync } = useAction(updateApplicationSettingsAction);
+
+ const onSubmit = async (data: FormData) => {
+ if (!workspaceId || !program) {
+ return;
+ }
+
+ const requests: Promise<void>[] = [
+ executeAsync({
+ workspaceId,
+ description: data.description,
+ categories: data.categories,
+ 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!,
+ })),
+ applicationScreeningCriteria: data.applicationScreeningCriteria,
+ aiAutoApproveEnabled: data.aiAutoApproveEnabled,
+ }).then((result) => {
+ if (result?.serverError || result?.validationErrors) {
+ throw new Error(
+ parseActionError(result, "Failed to update application settings."),
+ );
+ }
+ }),
+ ...autoApprove.pendingUpdates.map((update) =>
+ updateGroupAutoApprove({ workspaceId, ...update }),
+ ),
+ ];
+
+ const results = await Promise.allSettled(requests);
+
+ await mutatePrefix([`/api/programs/${defaultProgramId}`, "/api/groups"]);
+
+ const failure = results.find(
+ (result): result is PromiseRejectedResult => result.status === "rejected",
+ );
+
+ if (failure) {
+ toast.error(
+ failure.reason instanceof Error
+ ? failure.reason.message
+ : "Failed to update application settings.",
+ );
+ return;
+ }
+
+ toast.success("Application settings updated");
+ setIsOpen(false);
+ };
+
+ const hasChanges = isDirty || autoApprove.pendingUpdates.length > 0;
+
+ return (
+ <form onSubmit={handleSubmit(onSubmit)} className="flex h-full flex-col">
+ <div className="sticky top-0 z-10 border-b border-neutral-200 bg-white">
+ <div className="flex h-16 items-center justify-between px-6 py-4">
+ <Sheet.Title className="text-lg font-semibold">
+ Application settings
+ </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="flex min-h-0 flex-1 flex-col gap-6 overflow-y-auto bg-neutral-50 p-4 sm:p-6">
+ {program?.addedToMarketplaceAt && (
+ <ToggleGroup
+ className="flex h-10 w-full items-center gap-1.5 rounded-lg border border-neutral-200 bg-neutral-100 p-0.5"
+ optionClassName="flex h-9 flex-1 items-center justify-center rounded-md px-4 text-sm font-medium normal-case"
+ indicatorClassName="rounded-md border border-neutral-100 bg-white shadow-[0px_2px_2px_0px_#00000008]"
+ options={[
+ { value: "applications", label: "Applications" },
+ { value: "marketplace", label: "Marketplace" },
+ ]}
+ selected={activeSection}
+ selectAction={(value) =>
+ setActiveSection(value as "applications" | "marketplace")
+ }
+ />
+ )}
+
+ {(!program?.addedToMarketplaceAt ||
+ activeSection === "applications") && (
+ <>
+ <div className="space-y-3">
+ <div>
+ <h4 className="text-content-emphasis text-sm font-medium leading-5 tracking-[-0.02em]">
+ Eligibility requirements (optional)
+ </h4>
+ <p className="text-xs font-normal leading-4 tracking-[-0.02em] text-neutral-500">
+ Only eligible partners can apply.{" "}
+ <Link
+ href="https://dub.co/help/article/program-applications#eligibility-requirements"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="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 className="space-y-3">
+ <div>
+ <h4 className="text-content-emphasis flex items-center gap-1 text-sm font-medium leading-5 tracking-[-0.02em]">
+ <Sparkle3 variant="fill" className="size-4 shrink-0" />
+ Application screening (optional)
+ </h4>
+ <p className="text-xs font-normal leading-4 tracking-[-0.02em] text-neutral-500">
+ Automatically reject applications that match criteria you
+ describe.
+ </p>
+ </div>
+
+ <textarea
+ {...register("applicationScreeningCriteria")}
+ rows={4}
+ placeholder="Partners that offer SEO, backlinking, paid advertising, or affiliate marketing services."
+ onKeyDown={handleKeyDown}
+ className={cn(
+ "w-full rounded-lg 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.applicationScreeningCriteria &&
+ "border-red-600 focus:border-red-600 focus:ring-red-600",
+ )}
+ />
+ </div>
+
+ <div className="space-y-6">
+ <ApplicationAutoApproveSettings
+ loading={groupsLoading}
+ autoApprove={autoApprove}
+ />
+
+ <label className="flex cursor-pointer select-none items-start gap-3">
+ <Controller
+ control={control}
+ name="aiAutoApproveEnabled"
+ render={({ field }) => (
+ <span className="mt-0.5 inline-flex">
+ <Switch
+ checked={field.value}
+ fn={field.onChange}
+ disabled={groupsLoading}
+ />
+ </span>
+ )}
+ />
+ <span>
+ <span className="flex items-center gap-1 text-sm font-medium leading-5 tracking-[-0.02em] text-neutral-800">
+ <Sparkle3 variant="fill" className="size-4 shrink-0" />
+ Hold spam applications for review
+ </span>
+ <span className="mt-0.5 block text-xs font-normal leading-4 tracking-[-0.02em] text-neutral-500">
+ When auto-approving, high-confidence spam or clearly
+ irrelevant applications stay pending.
+ </span>
+ </span>
+ </label>
+ </div>
+ </>
+ )}
+
+ {program?.addedToMarketplaceAt && activeSection === "marketplace" && (
+ <div className="space-y-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",
+ )}
+ />
+ <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 className="sticky bottom-0 z-10 border-t border-neutral-200 bg-white">
+ <div className="flex items-center justify-end gap-2 p-5">
+ <Button
+ variant="secondary"
+ text="Cancel"
+ disabled={isSubmitting}
+ className="h-8 w-fit px-3"
+ type="button"
+ onClick={() => setIsOpen(false)}
+ />
+ <Button
+ text="Save"
+ className="h-8 w-fit px-3"
+ loading={isSubmitting}
+ disabled={!hasChanges}
+ type="submit"
+ />
+ </div>
+ </div>
+ </form>
+ );
+}
+
+async function updateGroupAutoApprove({
+ workspaceId,
+ groupId,
+ autoApprovePartners,
+ applyToAllGroups,
+}: AutoApproveUpdate & { workspaceId: string }) {
+ const response = await fetch(
+ `/api/groups/${groupId}?workspaceId=${workspaceId}`,
+ {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ autoApprovePartners,
+ ...(applyToAllGroups && {
+ updateAutoApprovePartnersForAllGroups: true,
+ }),
+ }),
+ },
+ );
+
+ if (!response.ok) {
+ const { error } = await response.json();
+ throw new Error(
+ error?.message || "Failed to update auto-approve settings.",
+ );
+ }
+}
+
+export function ApplicationSettingsSheet({
+ isOpen,
+ ...rest
+}: ApplicationSettingsSheetProps & {
+ isOpen: boolean;
+}) {
+ return (
+ <Sheet open={isOpen} onOpenChange={rest.setIsOpen}>
+ <ApplicationSettingsSheetContent {...rest} />
+ </Sheet>
+ );
+}
+
+export function useApplicationSettingsSheet() {
+ const [isOpen, setIsOpen] = useState(false);
+
+ return {
+ applicationSettingsSheet: (
+ <ApplicationSettingsSheet setIsOpen={setIsOpen} isOpen={isOpen} />
+ ),
+ setIsOpen,
+ };
+}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/applications/applications-menu-popover.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/applications/applications-menu-popover.tsx
index cf2fce9873..5841288d6b 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/applications/applications-menu-popover.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/applications/applications-menu-popover.tsx
@@ -2,7 +2,6 @@
import useProgram from "@/lib/swr/use-program";
import useWorkspace from "@/lib/swr/use-workspace";
-import { useApplicationSettingsModal } from "@/ui/modals/application-settings-modal";
import { useExportApplicationsModal } from "@/ui/modals/export-applications-modal";
import { ThreeDots } from "@/ui/shared/icons";
import {
@@ -15,6 +14,7 @@ import {
} from "@dub/ui";
import Link from "next/link";
import { useState } from "react";
+import { useApplicationSettingsSheet } from "./application-settings-sheet";
export function ApplicationsMenuPopover() {
const { slug: workspaceSlug } = useWorkspace();
@@ -25,19 +25,20 @@ export function ApplicationsMenuPopover() {
const { setShowExportApplicationsModal, ExportApplicationsModal } =
useExportApplicationsModal();
- const { setShowApplicationSettingsModal, ApplicationSettingsModal } =
- useApplicationSettingsModal();
+ const { applicationSettingsSheet, setIsOpen } = useApplicationSettingsSheet();
const { isMobile } = useMediaQuery();
return (
<>
- <ApplicationSettingsModal />
+ {applicationSettingsSheet}
<ExportApplicationsModal />
<Button
+ type="button"
text={isMobile ? "Settings" : "Application settings"}
- onClick={() => setShowApplicationSettingsModal(true)}
+ onClick={() => setIsOpen(true)}
variant="secondary"
+ className="h-9 px-3"
/>
<Popover
openPopover={openPopover}
diff --git a/apps/web/lib/actions/partners/create-program-application.ts b/apps/web/lib/actions/partners/create-program-application.ts
index 4543b86b02..61f03fc381 100644
--- a/apps/web/lib/actions/partners/create-program-application.ts
+++ b/apps/web/lib/actions/partners/create-program-application.ts
@@ -10,9 +10,9 @@ import { markApplicationEventSubmitted } from "@/lib/application-events/update-a
import { getApplicationEventCookieName } from "@/lib/application-events/utils";
import { getSession } from "@/lib/auth";
import { qstash } from "@/lib/cron";
-import { autoApprovePartnerJob } from "@/lib/jobs/handlers/auto-approve-partner-job";
import { autoRejectPartnerJob } from "@/lib/jobs/handlers/auto-reject-partner-job";
import { getNetworkProfileChecklistProgress } from "@/lib/network/get-network-profile-checklist-progress";
+import { dispatchPartnerApplicationReview } from "@/lib/partners/dispatch-partner-application-review";
import { evaluateApplicationRequirements } from "@/lib/partners/evaluate-application-requirements";
import {
formatApplicationFormData,
@@ -338,18 +338,12 @@ async function createApplicationAndEnrollment({
application,
}),
- // Auto-approve the partner if the group has auto-approval enabled
- group.autoApprovePartnersEnabledAt
- ? autoApprovePartnerJob.dispatch(
- {
- programId: program.id,
- partnerId: partner.id,
- },
- {
- label: partner.id,
- },
- )
- : Promise.resolve(null),
+ dispatchPartnerApplicationReview({
+ programId: program.id,
+ partnerId: partner.id,
+ autoApprovePartnersEnabledAt: group.autoApprovePartnersEnabledAt,
+ applicationScreeningCriteria: program.applicationScreeningCriteria,
+ }),
// Send "partner.application_submitted" webhook
sendWorkspaceWebhook({
diff --git a/apps/web/lib/actions/partners/update-application-settings.ts b/apps/web/lib/actions/partners/update-application-settings.ts
index 544aaac3d5..17bc80a51f 100644
--- a/apps/web/lib/actions/partners/update-application-settings.ts
+++ b/apps/web/lib/actions/partners/update-application-settings.ts
@@ -13,13 +13,21 @@ const schema = z.object({
description: z.string().optional(),
categories: z.array(z.enum(Category)).optional(),
eligibilityConditions: applicationRequirementsSchema.optional(),
+ applicationScreeningCriteria: z.string().max(2000).optional(),
+ aiAutoApproveEnabled: z.boolean().optional(),
});
export const updateApplicationSettingsAction = authActionClient
.inputSchema(schema)
.action(async ({ parsedInput, ctx }) => {
const { workspace } = ctx;
- const { description, categories, eligibilityConditions } = parsedInput;
+ const {
+ description,
+ categories,
+ eligibilityConditions,
+ applicationScreeningCriteria,
+ aiAutoApproveEnabled,
+ } = parsedInput;
throwIfNoPermission({
role: workspace.role,
@@ -43,6 +51,13 @@ export const updateApplicationSettingsAction = authActionClient
...(eligibilityConditions !== undefined && {
applicationRequirements: eligibilityConditions,
}),
+ ...(applicationScreeningCriteria !== undefined && {
+ applicationScreeningCriteria:
+ applicationScreeningCriteria.trim() || null,
+ }),
+ ...(aiAutoApproveEnabled !== undefined && {
+ aiAutoApproveEnabledAt: aiAutoApproveEnabled ? new Date() : null,
+ }),
},
});
diff --git a/apps/web/lib/ai/evaluate-partner-application.ts b/apps/web/lib/ai/evaluate-partner-application.ts
new file mode 100644
index 0000000000..bd8fcc8fab
--- /dev/null
+++ b/apps/web/lib/ai/evaluate-partner-application.ts
@@ -0,0 +1,301 @@
+import {
+ formatApplicationFormData,
+ formatWebsiteAndSocialsFields,
+} from "@/lib/partners/format-application-form-data";
+import { programLanderSchema } from "@/lib/zod/schemas/program-lander";
+import { ProgramApplication } from "@prisma/client";
+import * as z from "zod/v4";
+
+export const JEV_MATCH_THRESHOLD = 0.85;
+
+const MAX_TEXT_LENGTH = 500;
+const JEV_EVALUATE_TIMEOUT_MS = 2_000;
+const JEV_MODEL_ID = "typesafe-ai/jev";
+const JEV_EVALUATE_URL = "https://ai-gateway.vercel.sh/v4/ai/evaluation-model";
+
+export type EvaluatePartnerApplicationInput = {
+ program: {
+ name: string;
+ description: string | null;
+ };
+ partner: {
+ name: string;
+ country: string | null;
+ description: string | null;
+ platforms: {
+ type: string;
+ identifier: string;
+ subscribers: bigint | number;
+ verifiedAt: Date | null;
+ }[];
+ };
+ application: ProgramApplication | null;
+ landerData: unknown;
+};
+
+/**
+ * `skipped` (nothing to evaluate) and `failed` (Jev errored) both fail open –
+ * only `matched` is a high-confidence yes.
+ */
+export type JevEvaluation = {
+ status: "matched" | "unmatched" | "skipped" | "failed";
+ probability?: number;
+ error?: string;
+ usage?: {
+ inputTokens?: number;
+ outputTokens?: number;
+ };
+};
+
+const jevEvaluateResponseSchema = z.object({
+ answers: z.record(
+ z.string(),
+ z.object({
+ type: z.literal("boolean"),
+ probability: z.number().finite(),
+ }),
+ ),
+ usage: z
+ .object({
+ inputTokens: z.number().optional(),
+ outputTokens: z.number().optional(),
+ })
+ .optional(),
+});
+
+export function isConfidentMatch(probability: number | null | undefined) {
+ return (
+ probability != null &&
+ Number.isFinite(probability) &&
+ probability >= JEV_MATCH_THRESHOLD
+ );
+}
+
+export async function evaluatePartnerApplication(
+ input: EvaluatePartnerApplicationInput,
+): Promise<JevEvaluation> {
+ const state = buildPartnerApplicationState(input);
+
+ if (!state) {
+ return { status: "skipped" };
+ }
+
+ return await evaluateBooleanQuestion({
+ state,
+ questionKey: "poorFit",
+ instructions:
+ "Is this application spam, empty, or clearly irrelevant to this program?",
+ criteria: {
+ true: "Spam, empty, or clearly irrelevant to the program",
+ false: "Plausible fit, or not enough signal to reject",
+ },
+ tag: "jev-partner-auto-approve",
+ });
+}
+
+export async function evaluateApplicationScreening({
+ screeningCriteria,
+ ...input
+}: EvaluatePartnerApplicationInput & {
+ screeningCriteria: string;
+}): Promise<JevEvaluation> {
+ const state = buildPartnerApplicationState(input);
+
+ if (!state) {
+ return { status: "skipped" };
+ }
+
+ return await evaluateBooleanQuestion({
+ state: {
+ ...state,
+ screeningCriteria: truncate(screeningCriteria, 1000),
+ },
+ questionKey: "matchesScreeningCriteria",
+ instructions:
+ "Does this application match the program's rejection criteria in screeningCriteria?",
+ criteria: {
+ true: "The application clearly matches the program's rejection criteria",
+ false:
+ "The application does not match, or there is not enough signal to reject",
+ },
+ tag: "jev-partner-application-screening",
+ });
+}
+
+// Returns null when the application has no text worth evaluating
+function buildPartnerApplicationState({
+ program,
+ partner,
+ application,
+ landerData,
+}: EvaluatePartnerApplicationInput) {
+ const applicationAnswers = (
+ application ? formatApplicationFormData(application) : []
+ )
+ .filter((field) => field.value.trim().length > 0)
+ .map((field) => ({
+ title: field.title,
+ value: truncate(field.value),
+ }));
+
+ const formSocials = application
+ ? formatWebsiteAndSocialsFields(application)
+ : {};
+
+ const socials = application
+ ? compactRecord({
+ website: formSocials.website ?? application.website,
+ youtube: formSocials.youtube ?? application.youtube,
+ twitter: formSocials.twitter ?? application.twitter,
+ linkedin: formSocials.linkedin ?? application.linkedin,
+ instagram: formSocials.instagram ?? application.instagram,
+ tiktok: formSocials.tiktok ?? application.tiktok,
+ })
+ : {};
+
+ const platforms = partner.platforms
+ .filter((platform) => platform.identifier.trim().length > 0)
+ .map((platform) => ({
+ type: platform.type,
+ identifier: platform.identifier,
+ subscribers: Number(platform.subscribers),
+ verified: Boolean(platform.verifiedAt),
+ }));
+
+ const hasEvaluableText =
+ applicationAnswers.length > 0 ||
+ Boolean(truncate(partner.description)) ||
+ Object.keys(socials).length > 0 ||
+ platforms.length > 0;
+
+ if (!hasEvaluableText) {
+ return null;
+ }
+
+ const parsedLander = programLanderSchema.safeParse(landerData);
+ const lander = parsedLander.success
+ ? compactRecord({
+ title: truncate(parsedLander.data.title),
+ description: truncate(parsedLander.data.description),
+ })
+ : undefined;
+
+ return {
+ program: compactRecord({
+ name: program.name,
+ description: truncate(program.description),
+ }),
+ ...(lander && Object.keys(lander).length > 0 ? { lander } : {}),
+ partner: compactRecord({
+ name: partner.name,
+ country: partner.country ?? undefined,
+ description: truncate(partner.description),
+ ...socials,
+ ...(platforms.length > 0 ? { platforms } : {}),
+ }),
+ ...(applicationAnswers.length > 0 ? { applicationAnswers } : {}),
+ };
+}
+
+async function evaluateBooleanQuestion({
+ state,
+ questionKey,
+ instructions,
+ criteria,
+ tag,
+}: {
+ state: Record<string, unknown>;
+ questionKey: string;
+ instructions: string;
+ criteria: {
+ true: string;
+ false: string;
+ };
+ tag: string;
+}): Promise<JevEvaluation> {
+ const apiKey = process.env.AI_GATEWAY_API_KEY;
+
+ if (!apiKey) {
+ return { status: "skipped" };
+ }
+
+ const abortController = new AbortController();
+ const timeout = setTimeout(
+ () => abortController.abort(),
+ JEV_EVALUATE_TIMEOUT_MS,
+ );
+
+ try {
+ const response = await fetch(JEV_EVALUATE_URL, {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${apiKey}`,
+ "Content-Type": "application/json",
+ "ai-gateway-protocol-version": "0.0.1",
+ "ai-gateway-auth-method": "api-key",
+ "ai-evaluation-model-specification-version": "4",
+ "ai-model-id": JEV_MODEL_ID,
+ },
+ body: JSON.stringify({
+ state,
+ questions: {
+ [questionKey]: {
+ type: "boolean",
+ instructions,
+ criteria,
+ },
+ },
+ providerOptions: {
+ gateway: {
+ zeroDataRetention: true,
+ disallowPromptTraining: true,
+ tags: [tag],
+ },
+ },
+ }),
+ signal: abortController.signal,
+ });
+
+ if (!response.ok) {
+ throw new Error(`Jev evaluate failed with status ${response.status}.`);
+ }
+
+ const parsed = jevEvaluateResponseSchema.safeParse(await response.json());
+ const answer = parsed.success
+ ? parsed.data.answers[questionKey]
+ : undefined;
+
+ if (!parsed.success || !answer) {
+ throw new Error("Jev evaluate returned an invalid response.");
+ }
+
+ return {
+ status: isConfidentMatch(answer.probability) ? "matched" : "unmatched",
+ probability: answer.probability,
+ usage: parsed.data.usage,
+ };
+ } catch (error) {
+ return {
+ status: "failed",
+ error: error instanceof Error ? error.message : String(error),
+ };
+ } finally {
+ clearTimeout(timeout);
+ }
+}
+
+function truncate(value: string | null | undefined, max = MAX_TEXT_LENGTH) {
+ if (!value?.trim()) {
+ return undefined;
+ }
+
+ const trimmed = value.trim();
+
+ return trimmed.length > max ? `${trimmed.slice(0, max)}…` : trimmed;
+}
+
+function compactRecord<T extends Record<string, unknown>>(record: T) {
+ return Object.fromEntries(
+ Object.entries(record).filter(([, value]) => value != null && value !== ""),
+ ) as Partial<T>;
+}
diff --git a/apps/web/lib/api/partners/applications/reject-pending-enrollment.ts b/apps/web/lib/api/partners/applications/reject-pending-enrollment.ts
new file mode 100644
index 0000000000..7ae3bfd7ab
--- /dev/null
+++ b/apps/web/lib/api/partners/applications/reject-pending-enrollment.ts
@@ -0,0 +1,141 @@
+import { trackApplicationEvents } from "@/lib/application-events/update-application-event";
+import { prisma } from "@/lib/prisma";
+import { sendEmail } from "@dub/email";
+import PartnerApplicationRejected from "@dub/email/templates/partner-application-rejected";
+import {
+ ProgramApplicationRejectionReason,
+ ProgramEnrollmentStatus,
+} from "@prisma/client";
+import { resolveFraudGroups } from "../../fraud/resolve-fraud-groups";
+import { queuePartnerSearchSync } from "../queue-partner-search-sync";
+
+export async function rejectPendingEnrollment({
+ programId,
+ partnerId,
+ rejectionReason,
+}: {
+ programId: string;
+ partnerId: string;
+ rejectionReason: ProgramApplicationRejectionReason;
+}): Promise<boolean> {
+ const programEnrollment = await prisma.programEnrollment.findUnique({
+ where: {
+ partnerId_programId: {
+ partnerId,
+ programId,
+ },
+ },
+ include: {
+ partner: {
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ },
+ },
+ program: {
+ select: {
+ id: true,
+ name: true,
+ slug: true,
+ supportEmail: true,
+ },
+ },
+ },
+ });
+
+ if (!programEnrollment) {
+ return false;
+ }
+
+ if (programEnrollment.status !== ProgramEnrollmentStatus.pending) {
+ return false;
+ }
+
+ const { skipped } = await prisma.$transaction(async (tx) => {
+ const { count } = await tx.programEnrollment.updateMany({
+ where: {
+ id: programEnrollment.id,
+ status: ProgramEnrollmentStatus.pending,
+ },
+ data: {
+ status: ProgramEnrollmentStatus.rejected,
+ clickRewardId: null,
+ leadRewardId: null,
+ saleRewardId: null,
+ referralRewardId: null,
+ customRewardId: null,
+ discountId: null,
+ },
+ });
+
+ if (count === 0) {
+ return {
+ skipped: true,
+ };
+ }
+
+ if (programEnrollment.applicationId) {
+ await tx.programApplication.update({
+ where: {
+ id: programEnrollment.applicationId,
+ },
+ data: {
+ reviewedAt: new Date(),
+ rejectionReason,
+ rejectionNote: null,
+ },
+ });
+ }
+
+ return {
+ skipped: false,
+ };
+ });
+
+ if (skipped) {
+ return false;
+ }
+
+ const { partner, program } = programEnrollment;
+
+ await Promise.allSettled([
+ resolveFraudGroups({
+ where: {
+ programId,
+ partnerId,
+ },
+ resolutionReason:
+ "Resolved automatically because the partner application was automatically rejected.",
+ }),
+
+ trackApplicationEvents({
+ event: "rejected",
+ programId,
+ partnerIds: [partnerId],
+ }),
+
+ queuePartnerSearchSync({ enrollmentIds: [programEnrollment.id] }),
+
+ partner.email &&
+ 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 true;
+}
diff --git a/apps/web/lib/api/partners/applications/screen-partner-application.ts b/apps/web/lib/api/partners/applications/screen-partner-application.ts
new file mode 100644
index 0000000000..4003e25a6c
--- /dev/null
+++ b/apps/web/lib/api/partners/applications/screen-partner-application.ts
@@ -0,0 +1,52 @@
+import {
+ EvaluatePartnerApplicationInput,
+ evaluateApplicationScreening,
+} from "@/lib/ai/evaluate-partner-application";
+import { logger } from "@/lib/axiom/server";
+import { ProgramApplicationRejectionReason } from "@prisma/client";
+import { rejectPendingEnrollment } from "./reject-pending-enrollment";
+
+/**
+ * Rejects a pending application when Jev is confident it matches the program's
+ * written screening criteria. Fails open, so an unavailable Jev never rejects.
+ * Returns true when the criteria matched, i.e. the application must not be approved.
+ */
+export async function screenPartnerApplication({
+ programId,
+ partnerId,
+ ...input
+}: EvaluatePartnerApplicationInput & {
+ programId: string;
+ partnerId: string;
+ screeningCriteria: string;
+}) {
+ const evaluation = await evaluateApplicationScreening(input);
+
+ logger.info("jev.partner.application-screening", {
+ programId,
+ partnerId,
+ status: evaluation.status,
+ probability: evaluation.probability,
+ error: evaluation.error,
+ usage: evaluation.usage,
+ });
+ await logger.flush();
+
+ if (evaluation.status !== "matched") {
+ return false;
+ }
+
+ const rejected = await rejectPendingEnrollment({
+ programId,
+ partnerId,
+ rejectionReason: ProgramApplicationRejectionReason.notTheRightFit,
+ });
+
+ console.info(
+ rejected
+ ? `Successfully rejected partner ${partnerId} in program ${programId} (application screening).`
+ : `Partner ${partnerId} is no longer pending in program ${programId}.`,
+ );
+
+ return true;
+}
diff --git a/apps/web/lib/jobs/handlers/auto-approve-partner-job.ts b/apps/web/lib/jobs/handlers/auto-approve-partner-job.ts
index e4abdefc99..a3547e6257 100644
--- a/apps/web/lib/jobs/handlers/auto-approve-partner-job.ts
+++ b/apps/web/lib/jobs/handlers/auto-approve-partner-job.ts
@@ -1,5 +1,8 @@
+import { evaluatePartnerApplication } from "@/lib/ai/evaluate-partner-application";
import { getPartnerApplicationRisks } from "@/lib/api/fraud/get-partner-application-risks";
import { approvePartner } from "@/lib/api/partners/applications/approve-partner";
+import { screenPartnerApplication } from "@/lib/api/partners/applications/screen-partner-application";
+import { logger } from "@/lib/axiom/server";
import { evaluateApplicationRequirements } from "@/lib/partners/evaluate-application-requirements";
import { getPlanCapabilities } from "@/lib/plan-capabilities";
import { prisma } from "@/lib/prisma";
@@ -28,6 +31,7 @@ export const autoApprovePartnerJob = defineJob({
},
include: {
partnerGroup: true,
+ application: true,
partner: {
include: {
platforms: true,
@@ -60,15 +64,17 @@ export const autoApprovePartnerJob = defineJob({
return;
}
- // Check if the workspace plan has fraud event management capabilities
- // If enabled, we'll evaluate risk signals before auto-approving
const program = await prisma.program.findUniqueOrThrow({
where: {
id: programId,
},
select: {
id: true,
+ name: true,
+ description: true,
applicationRequirements: true,
+ applicationScreeningCriteria: true,
+ aiAutoApproveEnabledAt: true,
workspace: {
select: {
plan: true,
@@ -133,6 +139,56 @@ export const autoApprovePartnerJob = defineJob({
return;
}
+ const screeningCriteria = program.applicationScreeningCriteria?.trim();
+
+ if (screeningCriteria) {
+ const matchedScreeningCriteria = await screenPartnerApplication({
+ programId,
+ partnerId,
+ program: {
+ name: program.name,
+ description: program.description,
+ },
+ partner: programEnrollment.partner,
+ application: programEnrollment.application,
+ landerData: group.landerData,
+ screeningCriteria,
+ });
+
+ if (matchedScreeningCriteria) {
+ return;
+ }
+ }
+
+ if (program.aiAutoApproveEnabledAt) {
+ const evaluation = await evaluatePartnerApplication({
+ program: {
+ name: program.name,
+ description: program.description,
+ },
+ partner: programEnrollment.partner,
+ application: programEnrollment.application,
+ landerData: group.landerData,
+ });
+
+ logger.info("jev.partner.auto-approve", {
+ programId,
+ partnerId,
+ status: evaluation.status,
+ probability: evaluation.probability,
+ error: evaluation.error,
+ usage: evaluation.usage,
+ });
+ await logger.flush();
+
+ if (evaluation.status === "matched") {
+ console.warn(
+ `Partner ${partnerId} held from auto-approve (Jev poorFit=${evaluation.probability}).`,
+ );
+ return;
+ }
+ }
+
await approvePartner({
programId,
partnerId,
diff --git a/apps/web/lib/jobs/handlers/auto-reject-partner-job.ts b/apps/web/lib/jobs/handlers/auto-reject-partner-job.ts
index 635990362c..c9971c394a 100644
--- a/apps/web/lib/jobs/handlers/auto-reject-partner-job.ts
+++ b/apps/web/lib/jobs/handlers/auto-reject-partner-job.ts
@@ -1,10 +1,6 @@
-import { resolveFraudGroups } from "@/lib/api/fraud/resolve-fraud-groups";
-import { queuePartnerSearchSync } from "@/lib/api/partners/queue-partner-search-sync";
-import { trackApplicationEvents } from "@/lib/application-events/update-application-event";
+import { rejectPendingEnrollment } from "@/lib/api/partners/applications/reject-pending-enrollment";
import { evaluateApplicationRequirements } from "@/lib/partners/evaluate-application-requirements";
import { prisma } from "@/lib/prisma";
-import { sendEmail } from "@dub/email";
-import PartnerApplicationRejected from "@dub/email/templates/partner-application-rejected";
import {
ProgramApplicationRejectionReason,
ProgramEnrollmentStatus,
@@ -34,18 +30,12 @@ export const autoRejectPartnerJob = defineJob({
include: {
partner: {
select: {
- id: true,
- name: true,
- email: true,
country: true,
+ email: true,
},
},
program: {
select: {
- id: true,
- name: true,
- slug: true,
- supportEmail: true,
applicationRequirements: true,
},
},
@@ -78,96 +68,20 @@ export const autoRejectPartnerJob = defineJob({
return;
}
- const { skipped } = await prisma.$transaction(async (tx) => {
- const { count } = await tx.programEnrollment.updateMany({
- where: {
- id: programEnrollment.id,
- status: ProgramEnrollmentStatus.pending,
- },
- data: {
- status: ProgramEnrollmentStatus.rejected,
- clickRewardId: null,
- leadRewardId: null,
- saleRewardId: null,
- referralRewardId: null,
- customRewardId: null,
- discountId: null,
- },
- });
-
- if (count === 0) {
- return {
- skipped: true,
- };
- }
-
- if (programEnrollment.applicationId) {
- await tx.programApplication.update({
- where: {
- id: programEnrollment.applicationId,
- },
- data: {
- reviewedAt: new Date(),
- rejectionReason:
- ProgramApplicationRejectionReason.doesNotMeetRequirements,
- rejectionNote: null,
- },
- });
- }
-
- return {
- skipped: false,
- };
+ const rejected = await rejectPendingEnrollment({
+ programId,
+ partnerId,
+ rejectionReason:
+ ProgramApplicationRejectionReason.doesNotMeetRequirements,
});
- if (skipped) {
+ if (!rejected) {
console.warn(
`Partner ${partnerId} is no longer pending in program ${programId}.`,
);
return;
}
- const { partner, program } = programEnrollment;
-
- await Promise.allSettled([
- resolveFraudGroups({
- where: {
- programId,
- partnerId,
- },
- resolutionReason:
- "Resolved automatically because the partner application was automatically rejected.",
- }),
-
- trackApplicationEvents({
- event: "rejected",
- programId,
- partnerIds: [partnerId],
- }),
-
- // Queue an index update because the enrollment status moved to rejected.
- queuePartnerSearchSync({ enrollmentIds: [programEnrollment.id] }),
-
- partner.email &&
- 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,
- },
- }),
- }),
- ]);
-
console.info(
`Successfully auto-rejected partner ${partnerId} in program ${programId}.`,
);
diff --git a/apps/web/lib/jobs/handlers/screen-partner-application-job.ts b/apps/web/lib/jobs/handlers/screen-partner-application-job.ts
new file mode 100644
index 0000000000..fab7a227d9
--- /dev/null
+++ b/apps/web/lib/jobs/handlers/screen-partner-application-job.ts
@@ -0,0 +1,78 @@
+import { screenPartnerApplication } from "@/lib/api/partners/applications/screen-partner-application";
+import { prisma } from "@/lib/prisma";
+import { ProgramEnrollmentStatus } from "@prisma/client";
+import * as z from "zod/v4";
+import { defineJob } from "../index";
+
+const inputSchema = z.object({
+ programId: z.string(),
+ partnerId: z.string(),
+});
+
+// This job screens a pending application against the program's written criteria.
+// Groups with auto-approval enabled are screened inside auto-approve-partner-job instead.
+export const screenPartnerApplicationJob = defineJob({
+ name: "screen-partner-application-job",
+ schema: inputSchema,
+ async handle(input) {
+ const { programId, partnerId } = input;
+
+ const programEnrollment = await prisma.programEnrollment.findUnique({
+ where: {
+ partnerId_programId: {
+ partnerId,
+ programId,
+ },
+ },
+ include: {
+ partnerGroup: true,
+ application: true,
+ partner: {
+ include: {
+ platforms: true,
+ },
+ },
+ program: {
+ select: {
+ name: true,
+ description: true,
+ applicationScreeningCriteria: true,
+ },
+ },
+ },
+ });
+
+ if (!programEnrollment) {
+ console.warn(`Partner ${partnerId} not found in program ${programId}.`);
+ return;
+ }
+
+ if (programEnrollment.status !== ProgramEnrollmentStatus.pending) {
+ console.warn(`${partnerId} is in ${programEnrollment.status} status.`);
+ return;
+ }
+
+ const { program } = programEnrollment;
+ const screeningCriteria = program.applicationScreeningCriteria?.trim();
+
+ if (!screeningCriteria) {
+ console.warn(
+ `Program ${programId} does not have application screening criteria.`,
+ );
+ return;
+ }
+
+ await screenPartnerApplication({
+ programId,
+ partnerId,
+ program: {
+ name: program.name,
+ description: program.description,
+ },
+ partner: programEnrollment.partner,
+ application: programEnrollment.application,
+ landerData: programEnrollment.partnerGroup?.landerData,
+ screeningCriteria,
+ });
+ },
+});
diff --git a/apps/web/lib/jobs/registry.ts b/apps/web/lib/jobs/registry.ts
index 4364cf3371..bd031f0062 100644
--- a/apps/web/lib/jobs/registry.ts
+++ b/apps/web/lib/jobs/registry.ts
@@ -56,6 +56,11 @@ const jobLoaders = {
(m) => m.autoRejectPartnerJob,
),
+ "screen-partner-application-job": () =>
+ import("./handlers/screen-partner-application-job").then(
+ (m) => m.screenPartnerApplicationJob,
+ ),
+
"queue-partner-program-summary-job": () =>
import("./handlers/queue-partner-program-summary-job").then(
(m) => m.queuePartnerProgramSummaryJob,
diff --git a/apps/web/lib/partners/complete-program-applications.ts b/apps/web/lib/partners/complete-program-applications.ts
index 5e91493af9..85e22f90a7 100644
--- a/apps/web/lib/partners/complete-program-applications.ts
+++ b/apps/web/lib/partners/complete-program-applications.ts
@@ -5,11 +5,11 @@ import { detectAndRecordFraudApplication } from "../api/fraud/detect-record-frau
import { notifyPartnerApplication } from "../api/partners/notify-partner-application";
import { queuePartnerSearchSync } from "../api/partners/queue-partner-search-sync";
import { markApplicationEventSubmitted } from "../application-events/update-application-event";
-import { autoApprovePartnerJob } from "../jobs/handlers/auto-approve-partner-job";
import { autoRejectPartnerJob } from "../jobs/handlers/auto-reject-partner-job";
import { buildSocialPlatformLookup } from "../social-utils";
import { sendWorkspaceWebhook } from "../webhook/publish";
import { partnerApplicationWebhookSchema } from "../zod/schemas/program-application";
+import { dispatchPartnerApplicationReview } from "./dispatch-partner-application-review";
import { evaluateApplicationRequirements } from "./evaluate-application-requirements";
import {
formatApplicationFormData,
@@ -205,18 +205,14 @@ export async function completeProgramApplications(userEmail: string) {
application,
}),
- // Auto-approve the partner if the group has auto-approval enabled
- group?.autoApprovePartnersEnabledAt
- ? autoApprovePartnerJob.dispatch(
- {
- programId: program.id,
- partnerId: partner.id,
- },
- {
- label: partner.id,
- },
- )
- : Promise.resolve(null),
+ dispatchPartnerApplicationReview({
+ programId: program.id,
+ partnerId: partner.id,
+ autoApprovePartnersEnabledAt:
+ group?.autoApprovePartnersEnabledAt,
+ applicationScreeningCriteria:
+ program.applicationScreeningCriteria,
+ }),
// Send "partner.application_submitted" webhook
workspacesByProgramId.has(program.id) &&
diff --git a/apps/web/lib/partners/dispatch-partner-application-review.ts b/apps/web/lib/partners/dispatch-partner-application-review.ts
new file mode 100644
index 0000000000..5b6bdc4fc0
--- /dev/null
+++ b/apps/web/lib/partners/dispatch-partner-application-review.ts
@@ -0,0 +1,42 @@
+import { autoApprovePartnerJob } from "@/lib/jobs/handlers/auto-approve-partner-job";
+import { screenPartnerApplicationJob } from "@/lib/jobs/handlers/screen-partner-application-job";
+
+// Auto-approving groups are screened inside autoApprovePartnerJob, so the two
+// jobs never review the same enrollment concurrently.
+export function dispatchPartnerApplicationReview({
+ programId,
+ partnerId,
+ autoApprovePartnersEnabledAt,
+ applicationScreeningCriteria,
+}: {
+ programId: string;
+ partnerId: string;
+ autoApprovePartnersEnabledAt: Date | null | undefined;
+ applicationScreeningCriteria: string | null | undefined;
+}) {
+ if (autoApprovePartnersEnabledAt) {
+ return autoApprovePartnerJob.dispatch(
+ {
+ programId,
+ partnerId,
+ },
+ {
+ label: partnerId,
+ },
+ );
+ }
+
+ if (applicationScreeningCriteria?.trim()) {
+ return screenPartnerApplicationJob.dispatch(
+ {
+ programId,
+ partnerId,
+ },
+ {
+ label: partnerId,
+ },
+ );
+ }
+
+ return Promise.resolve(null);
+}
diff --git a/apps/web/lib/zod/schemas/programs.ts b/apps/web/lib/zod/schemas/programs.ts
index dc12588ff4..3d5a6cae05 100644
--- a/apps/web/lib/zod/schemas/programs.ts
+++ b/apps/web/lib/zod/schemas/programs.ts
@@ -83,8 +83,12 @@ export const ProgramSchema = z.object({
});
// TODO: move to group-level soon
+// Workspace-scoped only – ProgramSchema itself is embedded in partner-facing
+// payloads (e.g. ProgramEnrollmentSchema), so program config must not live there
export const ProgramSchemaWithInviteEmailData = ProgramSchema.extend({
inviteEmailData: programInviteEmailDataSchema,
+ applicationScreeningCriteria: z.string().nullish(),
+ aiAutoApproveEnabledAt: z.date().nullish(),
});
export const updateProgramSchema = z.object({
diff --git a/apps/web/prisma/schema/program.prisma b/apps/web/prisma/schema/program.prisma
index cf91a85609..ee4bf86b80 100644
--- a/apps/web/prisma/schema/program.prisma
+++ b/apps/web/prisma/schema/program.prisma
@@ -39,18 +39,20 @@ 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
- applicationRequirements Json? @db.Json
- termsUrl String? @db.Text
- helpUrl String? @db.Text
- supportEmail String?
- tremendousCampaignId String?
+ inviteEmailData Json? @db.Json
+ embedData Json? @db.Json
+ resources Json? @db.Json
+ referralFormData Json? @db.Json
+ applicationRequirements Json? @db.Json
+ applicationScreeningCriteria String? @db.Text
+ termsUrl String? @db.Text
+ helpUrl String? @db.Text
+ supportEmail String?
+ tremendousCampaignId String?
messagingEnabledAt DateTime?
partnerNetworkEnabledAt DateTime?
+ aiAutoApproveEnabledAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
startedAt DateTime?
diff --git a/apps/web/tests/partners/evaluate-partner-application.test.ts b/apps/web/tests/partners/evaluate-partner-application.test.ts
new file mode 100644
index 0000000000..33db9eb27e
--- /dev/null
+++ b/apps/web/tests/partners/evaluate-partner-application.test.ts
@@ -0,0 +1,27 @@
+import {
+ JEV_MATCH_THRESHOLD,
+ isConfidentMatch,
+} from "@/lib/ai/evaluate-partner-application";
+import { describe, expect, it } from "vitest";
+
+describe("isConfidentMatch", () => {
+ it("matches at and above the threshold", () => {
+ expect(isConfidentMatch(JEV_MATCH_THRESHOLD)).toBe(true);
+ expect(isConfidentMatch(0.99)).toBe(true);
+ });
+
+ it("does not match below the threshold", () => {
+ expect(isConfidentMatch(0.84)).toBe(false);
+ expect(isConfidentMatch(0)).toBe(false);
+ });
+
+ it("does not match when the probability is missing", () => {
+ expect(isConfidentMatch(null)).toBe(false);
+ expect(isConfidentMatch(undefined)).toBe(false);
+ });
+
+ it("does not match when the probability is not finite", () => {
+ expect(isConfidentMatch(Number.NaN)).toBe(false);
+ expect(isConfidentMatch(Number.POSITIVE_INFINITY)).toBe(false);
+ });
+});
diff --git a/apps/web/tests/partners/program-config-exposure.test.ts b/apps/web/tests/partners/program-config-exposure.test.ts
new file mode 100644
index 0000000000..d52a7fa9db
--- /dev/null
+++ b/apps/web/tests/partners/program-config-exposure.test.ts
@@ -0,0 +1,66 @@
+import {
+ ProgramEnrollmentSchema,
+ ProgramSchema,
+ ProgramSchemaWithInviteEmailData,
+} from "@/lib/zod/schemas/programs";
+import { describe, expect, it } from "vitest";
+
+const programRow = {
+ id: "prog_1",
+ name: "Acme",
+ slug: "acme",
+ logo: null,
+ domain: null,
+ url: null,
+ description: null,
+ primaryRewardEvent: "sale" as const,
+ minPayoutAmount: 0,
+ payoutMode: "internal" as const,
+ defaultFolderId: "fold_1",
+ defaultGroupId: "grp_1",
+ applicationScreeningCriteria: "reject anyone doing SEO or backlinking",
+ aiAutoApproveEnabledAt: new Date(),
+ createdAt: new Date(),
+ updatedAt: new Date(),
+};
+
+describe("program config exposure", () => {
+ it("is stripped from the partner-facing enrollment payload", () => {
+ const parsed = ProgramEnrollmentSchema.parse({
+ programId: "prog_1",
+ groupId: null,
+ partnerId: "pn_1",
+ tenantId: null,
+ program: programRow,
+ createdAt: new Date(),
+ status: "pending" as const,
+ links: null,
+ totalCommissions: 0,
+ customerDataSharingEnabledAt: null,
+ groupMoveDisabledAt: null,
+ riskMonitoringDisabledAt: null,
+ });
+
+ expect(parsed.program).not.toHaveProperty("applicationScreeningCriteria");
+ expect(parsed.program).not.toHaveProperty("aiAutoApproveEnabledAt");
+ });
+
+ it("is stripped from the bare ProgramSchema", () => {
+ const parsed = ProgramSchema.parse(programRow);
+
+ expect(parsed).not.toHaveProperty("applicationScreeningCriteria");
+ expect(parsed).not.toHaveProperty("aiAutoApproveEnabledAt");
+ });
+
+ it("is kept on the workspace-scoped program payload", () => {
+ const parsed = ProgramSchemaWithInviteEmailData.parse({
+ ...programRow,
+ inviteEmailData: null,
+ });
+
+ expect(parsed.applicationScreeningCriteria).toBe(
+ "reject anyone doing SEO or backlinking",
+ );
+ expect(parsed.aiAutoApproveEnabledAt).toBeInstanceOf(Date);
+ });
+});
diff --git a/apps/web/ui/modals/application-settings-modal.tsx b/apps/web/ui/modals/application-settings-modal.tsx
deleted file mode 100644
index e3986d0023..0000000000
--- a/apps/web/ui/modals/application-settings-modal.tsx
+++ /dev/null
@@ -1,303 +0,0 @@
-import { parseActionError } from "@/lib/actions/parse-action-errors";
-import { updateApplicationSettingsAction } from "@/lib/actions/partners/update-application-settings";
-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 { Button, Modal, ToggleGroup, useEnterSubmit } from "@dub/ui";
-import { cn } from "@dub/utils";
-import { Category } from "@prisma/client";
-import { useAction } from "next-safe-action/hooks";
-import Link from "next/link";
-import {
- Dispatch,
- SetStateAction,
- useCallback,
- useMemo,
- useState,
-} from "react";
-import { Controller, useForm } from "react-hook-form";
-import { toast } from "sonner";
-import { ProgramCategorySelect } from "../partners/program-category-select";
-
-type FormData = {
- description: string;
- categories: Category[];
- eligibilityConditions: EligibilityCondition[];
-};
-
-function ApplicationSettingsModal({
- showApplicationSettingsModal,
- setShowApplicationSettingsModal,
-}: {
- showApplicationSettingsModal: boolean;
- setShowApplicationSettingsModal: Dispatch<SetStateAction<boolean>>;
-}) {
- const { program } = useProgram();
- const { id: workspaceId, slug: workspaceSlug } = useWorkspace();
- const [activeSection, setActiveSection] = useState<
- "applications" | "marketplace"
- >("applications");
-
- const {
- control,
- handleSubmit,
- setError,
- register,
- formState: { errors, isSubmitting, isDirty },
- } = useForm<FormData>({
- 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() })),
- },
- });
-
- const { handleKeyDown } = useEnterSubmit();
-
- const { executeAsync } = useAction(updateApplicationSettingsAction, {
- onError: ({ error }) => {
- toast.error(error.serverError);
- },
- onSuccess: () => {
- toast.success("Application settings updated");
- mutatePrefix(["/api/partners", "/api/programs"]);
- setShowApplicationSettingsModal(false);
- },
- });
-
- const onSubmit = handleSubmit(async (data) => {
- if (!workspaceId) return;
-
- 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) {
- setError("root.serverError", {
- message: "Failed to update application settings",
- });
- toast.error(
- parseActionError(result, "Failed to update application settings"),
- );
- return;
- }
- });
-
- return (
- <Modal
- showModal={showApplicationSettingsModal}
- setShowModal={setShowApplicationSettingsModal}
- className="flex max-h-[calc(100dvh-64px)] flex-col overflow-hidden sm:max-h-[min(90dvh,720px)]"
- >
- <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}
- className="flex min-h-0 flex-col overflow-hidden"
- >
- <div className="scrollbar-hide min-h-0 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")
- }
- />
- )}
-
- {(!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/program-applications#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 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 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"
- text="Cancel"
- className="h-8 w-fit px-3"
- type="button"
- />
- <Button
- type="submit"
- loading={isSubmitting}
- disabled={!isDirty}
- text="Save"
- className="h-8 w-fit px-3"
- />
- </div>
- </form>
- </Modal>
- );
-}
-
-export function useApplicationSettingsModal() {
- const [showApplicationSettingsModal, setShowApplicationSettingsModal] =
- useState(false);
-
- const ApplicationSettingsModalCallback = useCallback(() => {
- return (
- <ApplicationSettingsModal
- showApplicationSettingsModal={showApplicationSettingsModal}
- setShowApplicationSettingsModal={setShowApplicationSettingsModal}
- />
- );
- }, [showApplicationSettingsModal, setShowApplicationSettingsModal]);
-
- return useMemo(
- () => ({
- setShowApplicationSettingsModal,
- ApplicationSettingsModal: ApplicationSettingsModalCallback,
- }),
- [setShowApplicationSettingsModal, ApplicationSettingsModalCallback],
- );
-}