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 partner notification settings

Tim Wilsonaee7d177fed5
diff --git a/apps/web/app/(ee)/api/partner-profile/notification-preferences/route.ts b/apps/web/app/(ee)/api/partner-profile/notification-preferences/route.ts
new file mode 100644
index 0000000000..6e76eef55c
--- /dev/null
+++ b/apps/web/app/(ee)/api/partner-profile/notification-preferences/route.ts
@@ -0,0 +1,23 @@
+import { withPartnerProfile } from "@/lib/auth/partner";
+import { prisma } from "@dub/prisma";
+import { NextResponse } from "next/server";
+
+// GET /api/partner-profile/notification-preferences – get notification preferences for the current partner+user
+export const GET = withPartnerProfile(async ({ partner, session }) => {
+ const response = await prisma.partnerNotificationPreferences.findFirstOrThrow(
+ {
+ select: {
+ sale: true,
+ applicationApproved: true,
+ },
+ where: {
+ partnerUser: {
+ partnerId: partner.id,
+ userId: session.user.id,
+ },
+ },
+ },
+ );
+
+ return NextResponse.json(response);
+});
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/settings/notifications/page-client.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/settings/notifications/page-client.tsx
new file mode 100644
index 0000000000..66f488b1c8
--- /dev/null
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/settings/notifications/page-client.tsx
@@ -0,0 +1,116 @@
+"use client";
+
+import { updatePartnerNotificationPreference } from "@/lib/actions/partners/update-partner-notification-preference";
+import { partnerNotificationTypes } from "@/lib/zod/schemas/partner-profile";
+import {
+ CircleCheck,
+ InvoiceDollar,
+ Switch,
+ useOptimisticUpdate,
+} from "@dub/ui";
+import { useAction } from "next-safe-action/hooks";
+import { z } from "zod";
+
+type PreferenceType = z.infer<typeof partnerNotificationTypes>;
+type Preferences = Record<PreferenceType, boolean>;
+
+const notifications = [
+ {
+ type: "sale",
+ icon: InvoiceDollar,
+ title: "New sale",
+ description: "Alert when a new sale is made.",
+ },
+ {
+ type: "applicationApproved",
+ icon: CircleCheck,
+ title: "Application approval",
+ description: "Alert when an application to a program is approved.",
+ },
+];
+
+export function PartnerSettingsNotificationsPageClient() {
+ const {
+ data: preferences,
+ isLoading,
+ update,
+ } = useOptimisticUpdate<Preferences>(
+ `/api/partner-profile/notification-preferences`,
+ {
+ loading: "Updating notification preference...",
+ success: "Notification preference updated.",
+ error: "Failed to update notification preference.",
+ },
+ );
+
+ const { executeAsync } = useAction(updatePartnerNotificationPreference);
+
+ const handleUpdate = async ({
+ type,
+ value,
+ currentPreferences,
+ }: {
+ type: string;
+ value: boolean;
+ currentPreferences: Preferences;
+ }) => {
+ await executeAsync({
+ type: type as PreferenceType,
+ value,
+ });
+
+ return {
+ ...currentPreferences,
+ [type]: value,
+ };
+ };
+
+ return (
+ <div className="mt-2 grid grid-cols-1 gap-3">
+ {notifications.map(({ type, icon: Icon, title, description }) => (
+ <div
+ key={type}
+ className="flex items-center justify-between gap-4 rounded-xl border border-neutral-200 bg-white p-5"
+ >
+ <div className="flex min-w-0 items-center gap-4">
+ <div className="hidden rounded-full border border-neutral-200 sm:block">
+ <div className="rounded-full border border-white bg-gradient-to-t from-neutral-100 p-1 md:p-3">
+ <Icon className="size-5" />
+ </div>
+ </div>
+ <div className="overflow-hidden">
+ <div className="flex items-center gap-1.5 sm:gap-2.5">
+ <div className="truncate text-sm font-medium">{title}</div>
+ </div>
+ <div className="mt-1 flex items-center gap-1 text-xs">
+ <span className="whitespace-pre-wrap text-neutral-500">
+ {description}
+ </span>
+ </div>
+ </div>
+ </div>
+ <Switch
+ checked={preferences?.[type] ?? false}
+ disabled={isLoading}
+ fn={(checked: boolean) => {
+ if (!preferences) return;
+
+ update(
+ () =>
+ handleUpdate({
+ type,
+ value: checked,
+ currentPreferences: preferences,
+ }),
+ {
+ ...preferences,
+ [type]: checked,
+ },
+ );
+ }}
+ />
+ </div>
+ ))}
+ </div>
+ );
+}
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/settings/notifications/page.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/settings/notifications/page.tsx
new file mode 100644
index 0000000000..accfaddb81
--- /dev/null
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/settings/notifications/page.tsx
@@ -0,0 +1,19 @@
+import { PageContent } from "@/ui/layout/page-content";
+import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
+import { PartnerSettingsNotificationsPageClient } from "./page-client";
+
+export default function PartnerSettingsNotificationsPage() {
+ return (
+ <PageContent
+ title="Notifications"
+ titleInfo={{
+ title:
+ "Adjust your personal notification preferences and choose which updates you want to receive. These settings will only be applied to your personal account.",
+ }}
+ >
+ <PageWidthWrapper>
+ <PartnerSettingsNotificationsPageClient />
+ </PageWidthWrapper>
+ </PageContent>
+ );
+}
diff --git a/apps/web/lib/actions/partners/bulk-approve-partners.ts b/apps/web/lib/actions/partners/bulk-approve-partners.ts
index d24273e88a..71a1042d29 100644
--- a/apps/web/lib/actions/partners/bulk-approve-partners.ts
+++ b/apps/web/lib/actions/partners/bulk-approve-partners.ts
@@ -33,7 +33,20 @@ export const bulkApprovePartnersAction = authActionClient
},
},
include: {
- partner: true,
+ partner: {
+ include: {
+ users: {
+ where: {
+ notificationPreference: {
+ applicationApproved: true,
+ },
+ },
+ include: {
+ user: true,
+ },
+ },
+ },
+ },
},
},
},
diff --git a/apps/web/lib/actions/partners/onboard-partner.ts b/apps/web/lib/actions/partners/onboard-partner.ts
index 91ed2e1f70..58c678604d 100644
--- a/apps/web/lib/actions/partners/onboard-partner.ts
+++ b/apps/web/lib/actions/partners/onboard-partner.ts
@@ -60,6 +60,7 @@ export const onboardPartnerAction = authUserActionClient
create: {
userId: user.id,
role: "owner",
+ notificationPreference: {},
},
},
},
diff --git a/apps/web/lib/actions/partners/update-partner-notification-preference.ts b/apps/web/lib/actions/partners/update-partner-notification-preference.ts
new file mode 100644
index 0000000000..e364d9f952
--- /dev/null
+++ b/apps/web/lib/actions/partners/update-partner-notification-preference.ts
@@ -0,0 +1,37 @@
+"use server";
+
+import { partnerNotificationTypes } from "@/lib/zod/schemas/partner-profile";
+import { prisma } from "@dub/prisma";
+import z from "../../zod";
+import { authPartnerActionClient } from "../safe-action";
+
+const schema = z.object({
+ type: partnerNotificationTypes,
+ value: z.boolean(),
+});
+
+// Update the notification preference for a partner+user
+export const updatePartnerNotificationPreference = authPartnerActionClient
+ .schema(schema)
+ .action(async ({ ctx, parsedInput }) => {
+ const { user, partner } = ctx;
+ const { type, value } = parsedInput;
+
+ await prisma.partnerUser.update({
+ where: {
+ userId_partnerId: {
+ userId: user.id,
+ partnerId: partner.id,
+ },
+ },
+ data: {
+ notificationPreference: {
+ update: {
+ [type]: value,
+ },
+ },
+ },
+ });
+
+ return { ok: true };
+ });
diff --git a/apps/web/lib/api/partners/notify-partner-sale.ts b/apps/web/lib/api/partners/notify-partner-sale.ts
index 5a76014193..6237cff3f2 100644
--- a/apps/web/lib/api/partners/notify-partner-sale.ts
+++ b/apps/web/lib/api/partners/notify-partner-sale.ts
@@ -47,6 +47,20 @@ export async function notifyPartnerSale({
select: {
name: true,
email: true,
+ users: {
+ where: {
+ notificationPreference: {
+ sale: true,
+ },
+ },
+ select: {
+ user: {
+ select: {
+ email: true,
+ },
+ },
+ },
+ },
},
}),
prisma.projectUsers.findMany({
@@ -95,19 +109,25 @@ export async function notifyPartnerSale({
},
};
+ const partnerEmailsToNotify = partner.users
+ .map(({ user }) => user.email)
+ .filter(Boolean) as string[];
+
await Promise.all([
- ...(partner.email
- ? [
- sendEmail({
- subject: "You just made a sale via Dub Partners!",
- email: partner.email!,
- react: NewSaleAlertPartner({
- email: partner.email!,
- ...data,
+ ...(partnerEmailsToNotify.length
+ ? partnerEmailsToNotify.map((email) =>
+ limiter.schedule(() =>
+ sendEmail({
+ subject: "You just made a sale via Dub Partners!",
+ email,
+ react: NewSaleAlertPartner({
+ email,
+ ...data,
+ }),
+ variant: "notifications",
}),
- variant: "notifications",
- }),
- ]
+ ),
+ )
: []),
...workspaceUsers.map(({ user }) =>
limiter.schedule(() =>
diff --git a/apps/web/lib/partners/approve-partner-enrollment.ts b/apps/web/lib/partners/approve-partner-enrollment.ts
index d63a84f2e7..deb6bef8f6 100644
--- a/apps/web/lib/partners/approve-partner-enrollment.ts
+++ b/apps/web/lib/partners/approve-partner-enrollment.ts
@@ -1,5 +1,6 @@
import { ProgramRewardDescription } from "@/ui/partners/program-reward-description";
-import { sendEmail } from "@dub/email";
+import { resend } from "@dub/email/resend";
+import { VARIANT_TO_FROM_MAP } from "@dub/email/resend/constants";
import PartnerApplicationApproved from "@dub/email/templates/partner-application-approved";
import { prisma } from "@dub/prisma";
import { waitUntil } from "@vercel/functions";
@@ -79,7 +80,20 @@ export async function approvePartnerEnrollment({
}),
},
include: {
- partner: true,
+ partner: {
+ include: {
+ users: {
+ where: {
+ notificationPreference: {
+ applicationApproved: true,
+ },
+ },
+ include: {
+ user: true,
+ },
+ },
+ },
+ },
},
}),
@@ -123,6 +137,10 @@ export async function approvePartnerEnrollment({
});
}
+ const partnerEmailsToNotify = partner.users
+ .map(({ user }) => user.email)
+ .filter(Boolean) as string[];
+
waitUntil(
(async () => {
const user = await prisma.user.findUniqueOrThrow({
@@ -145,26 +163,29 @@ export async function approvePartnerEnrollment({
await Promise.allSettled([
updatedLink ? recordLink(updatedLink) : Promise.resolve(null),
- sendEmail({
- subject: `Your application to join ${program.name} partner program has been approved!`,
- email: partner.email!,
- react: PartnerApplicationApproved({
- program: {
- name: program.name,
- logo: program.logo,
- slug: program.slug,
- supportEmail: program.supportEmail,
- },
- partner: {
- name: partner.name,
- email: partner.email!,
- payoutsEnabled: Boolean(partner.payoutsEnabledAt),
- },
- rewardDescription: ProgramRewardDescription({
- reward: rewards.find((r) => r.event === "sale"),
+ resend?.batch.send(
+ partnerEmailsToNotify.map((email) => ({
+ subject: `Your application to join ${program.name} partner program has been approved!`,
+ from: VARIANT_TO_FROM_MAP.notifications,
+ to: email,
+ react: PartnerApplicationApproved({
+ program: {
+ name: program.name,
+ logo: program.logo,
+ slug: program.slug,
+ supportEmail: program.supportEmail,
+ },
+ partner: {
+ name: partner.name,
+ email,
+ payoutsEnabled: Boolean(partner.payoutsEnabledAt),
+ },
+ rewardDescription: ProgramRewardDescription({
+ reward: rewards.find((r) => r.event === "sale"),
+ }),
}),
- }),
- }),
+ })),
+ ),
sendWorkspaceWebhook({
workspace,
diff --git a/apps/web/lib/partners/bulk-approve-partners.ts b/apps/web/lib/partners/bulk-approve-partners.ts
index 523188eeb8..606ae03def 100644
--- a/apps/web/lib/partners/bulk-approve-partners.ts
+++ b/apps/web/lib/partners/bulk-approve-partners.ts
@@ -30,7 +30,9 @@ export async function bulkApprovePartners({
}: {
workspace: Pick<WorkspaceProps, "id" | "plan" | "webhookEnabled">;
program: ProgramWithLanderDataProps;
- programEnrollments: (ProgramEnrollment & { partner: Partner })[];
+ programEnrollments: (ProgramEnrollment & {
+ partner: Partner & { users: { user: { email: string | null } }[] };
+ })[];
rewards: RewardProps[];
discount: DiscountProps | null;
user: Session["user"];
@@ -85,27 +87,33 @@ export async function bulkApprovePartners({
// Send approval emails
...programEnrollmentChunks.map((chunk) =>
resend?.batch.send(
- chunk.map(({ partner }) => ({
- subject: `Your application to join ${program.name} partner program has been approved!`,
- from: VARIANT_TO_FROM_MAP.notifications,
- to: partner.email!,
- react: PartnerApplicationApproved({
- program: {
- name: program.name,
- logo: program.logo,
- slug: program.slug,
- supportEmail: program.supportEmail,
- },
- partner: {
- name: partner.name,
- email: partner.email!,
- payoutsEnabled: Boolean(partner.payoutsEnabledAt),
- },
- rewardDescription: ProgramRewardDescription({
- reward: rewards?.find((r) => r.event === "sale"),
+ chunk.flatMap(({ partner }) => {
+ const partnerEmailsToNotify = partner.users
+ .map(({ user }) => user.email)
+ .filter(Boolean) as string[];
+
+ return partnerEmailsToNotify.map((email) => ({
+ subject: `Your application to join ${program.name} partner program has been approved!`,
+ from: VARIANT_TO_FROM_MAP.notifications,
+ to: email,
+ react: PartnerApplicationApproved({
+ program: {
+ name: program.name,
+ logo: program.logo,
+ slug: program.slug,
+ supportEmail: program.supportEmail,
+ },
+ partner: {
+ name: partner.name,
+ email,
+ payoutsEnabled: Boolean(partner.payoutsEnabledAt),
+ },
+ rewardDescription: ProgramRewardDescription({
+ reward: rewards?.find((r) => r.event === "sale"),
+ }),
}),
- }),
- })),
+ }));
+ }),
),
),
diff --git a/apps/web/lib/zod/schemas/partner-profile.ts b/apps/web/lib/zod/schemas/partner-profile.ts
index 1cf81a1276..04edbf8866 100644
--- a/apps/web/lib/zod/schemas/partner-profile.ts
+++ b/apps/web/lib/zod/schemas/partner-profile.ts
@@ -126,3 +126,5 @@ export const partnerProfileProgramsQuerySchema = z.object({
export const partnerProfileProgramsCountQuerySchema =
partnerProfileProgramsQuerySchema.pick({ status: true });
+
+export const partnerNotificationTypes = z.enum(["sale", "applicationApproved"]);
diff --git a/apps/web/ui/layout/page-content/index.tsx b/apps/web/ui/layout/page-content/index.tsx
index 0572842078..a476f92ea7 100644
--- a/apps/web/ui/layout/page-content/index.tsx
+++ b/apps/web/ui/layout/page-content/index.tsx
@@ -18,7 +18,7 @@ export function PageContent({
children,
}: PropsWithChildren<{
title?: ReactNode;
- titleInfo?: ReactNode | { title: string; href: string };
+ titleInfo?: ReactNode | { title: string; href?: string };
titleBackHref?: string;
controls?: ReactNode;
className?: string;
@@ -26,10 +26,7 @@ export function PageContent({
}>) {
// Generate titleInfo from object if provided
const finalTitleInfo =
- titleInfo &&
- typeof titleInfo === "object" &&
- "title" in titleInfo &&
- "href" in titleInfo ? (
+ titleInfo && typeof titleInfo === "object" && "title" in titleInfo ? (
<InfoTooltip
content={
<SimpleTooltipContent
diff --git a/apps/web/ui/layout/sidebar/partners-sidebar-nav.tsx b/apps/web/ui/layout/sidebar/partners-sidebar-nav.tsx
index dd3c32ae42..d391a85222 100644
--- a/apps/web/ui/layout/sidebar/partners-sidebar-nav.tsx
+++ b/apps/web/ui/layout/sidebar/partners-sidebar-nav.tsx
@@ -5,9 +5,11 @@ import useProgramEnrollmentsCount from "@/lib/swr/use-program-enrollments-count"
import { useRouterStuff } from "@dub/ui";
import {
CircleDollar,
+ CircleInfo,
CircleUser,
ColorPalette2,
Gauge6,
+ Gear,
Gear2,
Globe,
GridIcon,
@@ -59,6 +61,13 @@ const NAV_GROUPS: SidebarNavGroups<SidebarNavData> = ({ pathname }) => [
href: "/profile",
active: pathname.startsWith("/profile"),
},
+ {
+ name: "Settings",
+ description: "Manage preferences for your partner account.",
+ icon: Gear,
+ href: "/settings/notifications",
+ active: pathname.startsWith("/settings"),
+ },
];
const NAV_AREAS: SidebarNavAreas<SidebarNavData> = {
@@ -187,6 +196,24 @@ const NAV_AREAS: SidebarNavAreas<SidebarNavData> = {
],
}),
+ // Partner settings
+ partnerSettings: () => ({
+ title: "Settings",
+ direction: "left",
+ content: [
+ {
+ items: [
+ {
+ name: "Notifications",
+ icon: CircleInfo,
+ href: "/settings/notifications",
+ exact: true,
+ },
+ ],
+ },
+ ],
+ }),
+
// User settings
userSettings: () => ({
title: "Settings",
@@ -233,13 +260,15 @@ export function PartnersSidebarNav({
const currentArea = useMemo(() => {
return pathname.startsWith("/account/settings")
? "userSettings"
- : pathname.startsWith("/profile")
- ? "profile"
- : pathname.startsWith("/payouts")
- ? null
- : isEnrolledProgramPage
- ? "program"
- : "programs";
+ : pathname.startsWith("/settings")
+ ? "partnerSettings"
+ : pathname.startsWith("/profile")
+ ? "profile"
+ : pathname.startsWith("/payouts")
+ ? null
+ : isEnrolledProgramPage
+ ? "program"
+ : "programs";
}, [pathname, programSlug, isEnrolledProgramPage]);
const { count: invitationsCount } = useProgramEnrollmentsCount({
diff --git a/packages/email/src/templates/new-sale-alert-partner.tsx b/packages/email/src/templates/new-sale-alert-partner.tsx
index d8080a5ed6..2d65fbc25f 100644
--- a/packages/email/src/templates/new-sale-alert-partner.tsx
+++ b/packages/email/src/templates/new-sale-alert-partner.tsx
@@ -128,7 +128,10 @@ export default function NewSaleAlertPartner({
View earnings
</Link>
</Section>
- <Footer email={email} />
+ <Footer
+ email={email}
+ notificationSettingsUrl="https://partners.dub.co/settings/notifications"
+ />
</Container>
</Body>
</Tailwind>
diff --git a/packages/email/src/templates/partner-application-approved.tsx b/packages/email/src/templates/partner-application-approved.tsx
index 4e99973adc..d64dab3534 100644
--- a/packages/email/src/templates/partner-application-approved.tsx
+++ b/packages/email/src/templates/partner-application-approved.tsx
@@ -169,7 +169,10 @@ export default function PartnerApplicationApproved({
success!
</Text>
- <Footer email={partner.email} />
+ <Footer
+ email={partner.email}
+ notificationSettingsUrl="https://partners.dub.co/settings/notifications"
+ />
</Container>
</Body>
</Tailwind>
diff --git a/packages/prisma/schema/partner.prisma b/packages/prisma/schema/partner.prisma
index 90a2d97feb..7d19ca4106 100644
--- a/packages/prisma/schema/partner.prisma
+++ b/packages/prisma/schema/partner.prisma
@@ -68,10 +68,22 @@ model PartnerUser {
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
partner Partner @relation(fields: [partnerId], references: [id], onDelete: Cascade)
+ notificationPreference PartnerNotificationPreferences?
+
@@unique([userId, partnerId])
@@index([partnerId])
}
+model PartnerNotificationPreferences {
+ id String @id @default(cuid())
+ partnerUserId String @unique
+
+ sale Boolean @default(true)
+ applicationApproved Boolean @default(true)
+
+ partnerUser PartnerUser @relation(fields: [partnerUserId], references: [id], onDelete: Cascade)
+}
+
model PartnerInvite {
email String
expires DateTime