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.

Program applications summary email (#3333)

Kiran K444774b26a3e
diff --git a/apps/web/app/(ee)/api/cron/pending-applications-summary/route.ts b/apps/web/app/(ee)/api/cron/pending-applications-summary/route.ts
new file mode 100644
index 0000000000..ec22523003
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/pending-applications-summary/route.ts
@@ -0,0 +1,276 @@
+import { qstash } from "@/lib/cron";
+import { withCron } from "@/lib/cron/with-cron";
+import { sendBatchEmail } from "@dub/email";
+import { ResendBulkEmailOptions } from "@dub/email/resend/types";
+import PendingApplicationsSummary from "@dub/email/templates/pending-applications-summary";
+import { prisma } from "@dub/prisma";
+import { Prisma } from "@dub/prisma/client";
+import { APP_DOMAIN_WITH_NGROK, chunk } from "@dub/utils";
+import * as z from "zod/v4";
+import { logAndRespond } from "../utils";
+
+export const dynamic = "force-dynamic";
+
+const PROGRAMS_BATCH_SIZE = 50;
+
+const schema = z.object({
+ startingAfter: z.string().optional(),
+});
+
+// GET/POST /api/cron/pending-applications-summary
+// This route sends a daily summary of pending partner applications to program owners
+// Runs daily at 9:00 AM UTC
+export const GET = withCron(async ({ rawBody }) => {
+ let { startingAfter } = schema.parse(
+ rawBody ? JSON.parse(rawBody) : { startingAfter: undefined },
+ );
+
+ // Get batch of programs with pending applications
+ const programs = await prisma.program.findMany({
+ where: {
+ partners: {
+ some: {
+ status: "pending",
+ },
+ },
+ },
+ include: {
+ workspace: {
+ select: {
+ id: true,
+ slug: true,
+ },
+ },
+ },
+ take: PROGRAMS_BATCH_SIZE,
+ ...(startingAfter && {
+ skip: 1,
+ cursor: {
+ id: startingAfter,
+ },
+ }),
+ orderBy: {
+ id: "asc",
+ },
+ });
+
+ if (!programs.length) {
+ return logAndRespond(
+ "No more programs with pending applications found. Skipping...",
+ );
+ }
+
+ const programIds = programs.map((p) => p.id);
+
+ // Get top 3 pending enrollments per program using SQL window function
+ // This efficiently gets only the top 3 from each program directly from the database
+ const topEnrollments = await prisma.$queryRaw<
+ Array<{
+ programId: string;
+ partnerId: string;
+ partnerName: string | null;
+ partnerEmail: string | null;
+ partnerImage: string | null;
+ }>
+ >(Prisma.sql`
+ SELECT
+ pe.programId,
+ p.id as partnerId,
+ p.name as partnerName,
+ p.email as partnerEmail,
+ p.image as partnerImage
+ FROM (
+ SELECT
+ id,
+ programId,
+ partnerId,
+ ROW_NUMBER() OVER (PARTITION BY programId ORDER BY createdAt DESC) as rn
+ FROM ProgramEnrollment
+ WHERE programId IN (${Prisma.join(programIds)})
+ AND status = 'pending'
+ ) ranked
+ INNER JOIN ProgramEnrollment pe ON pe.id = ranked.id
+ INNER JOIN Partner p ON p.id = pe.partnerId
+ WHERE ranked.rn <= 3
+ ORDER BY pe.programId, pe.createdAt DESC
+ `);
+
+ // Group enrollments by programId
+ const enrollmentsByProgramMap = new Map<
+ string,
+ Array<{
+ id: string;
+ name: string | null;
+ email: string | null;
+ image: string | null;
+ }>
+ >();
+
+ for (const enrollment of topEnrollments) {
+ const existing = enrollmentsByProgramMap.get(enrollment.programId) || [];
+ enrollmentsByProgramMap.set(enrollment.programId, [
+ ...existing,
+ {
+ id: enrollment.partnerId,
+ name: enrollment.partnerName,
+ email: enrollment.partnerEmail,
+ image: enrollment.partnerImage,
+ },
+ ]);
+ }
+
+ // Get counts of pending enrollments per program
+ const pendingCounts = await prisma.programEnrollment.groupBy({
+ by: ["programId"],
+ where: {
+ programId: {
+ in: programIds,
+ },
+ status: "pending",
+ },
+ _count: true,
+ });
+
+ // Create a map of programId -> count
+ const pendingCountMap = new Map(
+ pendingCounts.map((pc) => [pc.programId, pc._count]),
+ );
+
+ const workspaceUsers = await prisma.projectUsers.findMany({
+ where: {
+ project: {
+ defaultProgramId: {
+ in: programIds,
+ },
+ },
+ notificationPreference: {
+ pendingApplicationsSummary: true,
+ },
+ user: {
+ email: {
+ not: null,
+ },
+ },
+ },
+ select: {
+ project: {
+ select: {
+ slug: true,
+ defaultProgramId: true,
+ },
+ },
+ user: {
+ select: {
+ email: true,
+ },
+ },
+ },
+ });
+
+ // create a map of programId -> workspace users
+ const programWorkspaceUsersMap = new Map<
+ string,
+ {
+ users: {
+ email: string;
+ }[];
+ workspace: {
+ slug: string;
+ };
+ }
+ >();
+
+ for (const workspaceUser of workspaceUsers) {
+ const programId = workspaceUser.project.defaultProgramId!; // coerce since we filtered above
+ const workspaceUserEmail = workspaceUser.user.email!; // coerce since we filtered above
+ const existingData = programWorkspaceUsersMap.get(programId);
+ if (existingData) {
+ existingData.users.push({
+ email: workspaceUserEmail,
+ });
+ } else {
+ programWorkspaceUsersMap.set(programId, {
+ users: [
+ {
+ email: workspaceUserEmail,
+ },
+ ],
+ workspace: {
+ slug: workspaceUser.project.slug,
+ },
+ });
+ }
+ }
+
+ // Process each program
+ const emailsToSend: ResendBulkEmailOptions = [];
+
+ for (const program of programs) {
+ const totalPendingApplications = pendingCountMap.get(program.id) || 0;
+
+ if (totalPendingApplications === 0) {
+ continue;
+ }
+
+ const pendingEnrollments = enrollmentsByProgramMap.get(program.id) || [];
+
+ const { users, workspace } = programWorkspaceUsersMap.get(program.id) || {};
+
+ if (!users || !workspace) {
+ continue;
+ }
+
+ // Create email for each owner
+ for (const user of users) {
+ emailsToSend.push({
+ variant: "notifications",
+ to: user.email,
+ subject: `You have ${totalPendingApplications} partner application${totalPendingApplications === 1 ? "" : "s"} pending review`,
+ react: PendingApplicationsSummary({
+ email: user.email,
+ partners: pendingEnrollments,
+ totalCount: totalPendingApplications,
+ date: new Date(),
+ workspace: {
+ slug: workspace.slug,
+ },
+ }),
+ });
+ }
+ }
+
+ if (!emailsToSend.length) {
+ return logAndRespond(
+ "No emails to send. All programs either have no pending applications or no owners with notification preference enabled.",
+ );
+ }
+
+ // Send email in batches
+ const emailChunks = chunk(emailsToSend, 100);
+ for (const emailChunk of emailChunks) {
+ await sendBatchEmail(emailChunk);
+ }
+
+ // Schedule the next batch if there are more programs to process
+ if (programs.length === PROGRAMS_BATCH_SIZE) {
+ startingAfter = programs[programs.length - 1].id;
+
+ const response = await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/pending-applications-summary`,
+ method: "POST",
+ body: {
+ startingAfter,
+ },
+ });
+
+ return logAndRespond(
+ `Sent ${emailsToSend.length} emails and scheduled next batch (startingAfter: ${startingAfter}, messageId: ${response.messageId}).`,
+ );
+ }
+
+ return logAndRespond(
+ `Successfully sent ${emailsToSend.length} pending applications summary email(s).`,
+ );
+});
+
+export const POST = GET;
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/notification-preferences/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/notification-preferences/route.ts
index 3426916c93..3dd9f57a9d 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/notification-preferences/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/notification-preferences/route.ts
@@ -10,6 +10,7 @@ export const GET = withWorkspace(async ({ workspace, session }) => {
linkUsageSummary: true,
newPartnerSale: true,
newPartnerApplication: true,
+ pendingApplicationsSummary: true,
newBountySubmitted: true,
newMessageFromPartner: true,
},
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/notifications/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/notifications/page-client.tsx
index 472fec7920..b789dd90ab 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/notifications/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/notifications/page-client.tsx
@@ -6,7 +6,7 @@ import { notificationTypes } from "@/lib/zod/schemas/workspaces";
import { Switch, useOptimisticUpdate } from "@dub/ui";
import { Globe, Hyperlink, Msgs, UserPlus } from "@dub/ui/icons";
import { isClickOnInteractiveChild } from "@dub/utils";
-import { DollarSign, Trophy } from "lucide-react";
+import { DollarSign, ListChecks, Trophy } from "lucide-react";
import { useAction } from "next-safe-action/hooks";
import React from "react";
import * as z from "zod/v4";
@@ -35,13 +35,6 @@ export default function NotificationsSettingsPageClient() {
];
const partnerProgramNotifications = [
- {
- type: "newPartnerApplication",
- icon: UserPlus,
- title: "New partner application",
- description:
- "Alert when a new partner application is made in your partner program.",
- },
{
type: "newPartnerSale",
icon: DollarSign,
@@ -62,6 +55,19 @@ export default function NotificationsSettingsPageClient() {
description:
"Alert when a new message is received from a partner in your partner program.",
},
+ {
+ type: "newPartnerApplication",
+ icon: UserPlus,
+ title: "New partner application",
+ description:
+ "Alert when a new partner application is made in your partner program.",
+ },
+ {
+ type: "pendingApplicationsSummary",
+ icon: ListChecks,
+ title: "Pending applications summary",
+ description: "Daily summary email of pending partner applications.",
+ },
// {
// type: "fraudEventsSummary",
// icon: ShieldAlert,
diff --git a/apps/web/lib/api/get-workspace-users.ts b/apps/web/lib/api/get-workspace-users.ts
index 60de88cf28..36c530ea07 100644
--- a/apps/web/lib/api/get-workspace-users.ts
+++ b/apps/web/lib/api/get-workspace-users.ts
@@ -7,13 +7,13 @@ type GetWorkspaceUsersParams =
| {
workspaceId: string;
programId?: never;
- role: WorkspaceRole;
+ role: WorkspaceRole | WorkspaceRole[];
notificationPreference?: z.infer<typeof notificationTypes>;
}
| {
programId: string;
workspaceId?: never;
- role: WorkspaceRole;
+ role: WorkspaceRole | WorkspaceRole[];
notificationPreference?: z.infer<typeof notificationTypes>;
};
@@ -50,7 +50,11 @@ export async function getWorkspaceUsers({
},
users: {
where: {
- role,
+ role: Array.isArray(role)
+ ? {
+ in: role,
+ }
+ : role,
...(notificationPreference && {
notificationPreference: {
[notificationPreference]: true,
diff --git a/apps/web/lib/zod/schemas/workspaces.ts b/apps/web/lib/zod/schemas/workspaces.ts
index 1765a26b64..ba17ba3854 100644
--- a/apps/web/lib/zod/schemas/workspaces.ts
+++ b/apps/web/lib/zod/schemas/workspaces.ts
@@ -166,6 +166,7 @@ export const notificationTypes = z.enum([
"domainConfigurationUpdates",
"newPartnerSale",
"newPartnerApplication",
+ "pendingApplicationsSummary",
"newBountySubmitted",
"newMessageFromPartner",
"fraudEventsSummary",
diff --git a/apps/web/vercel.json b/apps/web/vercel.json
index 3f1116fea5..aaf11ac447 100644
--- a/apps/web/vercel.json
+++ b/apps/web/vercel.json
@@ -47,6 +47,10 @@
{
"path": "/api/cron/payouts/reminders/program-owners",
"schedule": "0 13 25-31,1-5 * *"
+ },
+ {
+ "path": "/api/cron/pending-applications-summary",
+ "schedule": "0 9 * * *"
}
],
"functions": {
diff --git a/packages/email/src/templates/pending-applications-summary.tsx b/packages/email/src/templates/pending-applications-summary.tsx
new file mode 100644
index 0000000000..8c43bb90cb
--- /dev/null
+++ b/packages/email/src/templates/pending-applications-summary.tsx
@@ -0,0 +1,161 @@
+import { DUB_WORDMARK, OG_AVATAR_URL } from "@dub/utils";
+import { nFormatter } from "@dub/utils/src";
+import {
+ Body,
+ Column,
+ Container,
+ Heading,
+ Html,
+ Img,
+ Link,
+ Preview,
+ Row,
+ Section,
+ Tailwind,
+ Text,
+} from "@react-email/components";
+import { format } from "date-fns";
+import { Footer } from "../components/footer";
+
+export default function PendingApplicationsSummary({
+ email = "[email protected]",
+ workspace = {
+ slug: "acme",
+ },
+ partners = [
+ {
+ id: "pn_1JPBEGP7EXF76CXT1W99VERW5",
+ name: "Sarah Charpentier",
+ email: "[email protected]",
+ image: `${OG_AVATAR_URL}pn_1JPBEGP7EXF76CXT1W99VERW5`,
+ },
+ {
+ id: "pn_1JPBEGP7EXF76CXT1W99VERW6",
+ name: "Derek Forbes",
+ email: "[email protected]",
+ image: `${OG_AVATAR_URL}pn_1JPBEGP7EXF76CXT1W99VERW6`,
+ },
+ {
+ id: "pn_1JPBEGP7EXF76CXT1W99VERW7",
+ name: "Marvin Ta",
+ email: "[email protected]",
+ image: `${OG_AVATAR_URL}pn_1JPBEGP7EXF76CXT1W99VERW7`,
+ },
+ ],
+ totalCount = 1234,
+ date = new Date(),
+}: {
+ email: string;
+ workspace: {
+ slug: string;
+ };
+ partners: {
+ id: string;
+ name: string | null;
+ email: string | null;
+ image: string | null;
+ }[];
+ totalCount: number;
+ date: Date;
+}) {
+ const formattedDate = format(date, "MMM d, yyyy");
+ const applicationsUrl = `https://app.dub.co/${workspace.slug}/program/partners/applications`;
+
+ return (
+ <Html>
+ <Preview>
+ You have {nFormatter(totalCount, { full: true })} pending applications
+ to review on Dub for {formattedDate}
+ </Preview>
+ <Tailwind>
+ <Body className="mx-auto my-auto bg-white font-sans">
+ <Container className="mx-auto my-10 max-w-[600px] px-10 py-8">
+ <Section className="mt-8">
+ <Img src={DUB_WORDMARK} height="32" alt="Dub" />
+ </Section>
+
+ <Heading className="mx-0 mb-5 mt-10 p-0 text-lg font-medium text-black">
+ {nFormatter(totalCount, { full: true })} partner applications
+ pending review
+ </Heading>
+
+ <Text className="text-sm leading-6 text-gray-600">
+ You have <strong>{nFormatter(totalCount, { full: true })}</strong>{" "}
+ pending applications to{" "}
+ <Link
+ href={applicationsUrl}
+ className="text-gray-600 underline underline-offset-4"
+ >
+ review on Dub
+ </Link>
+ . Reviewing these on time will keep your program running smooth
+ and provide a better partner experience.
+ </Text>
+
+ <Section className="my-6">
+ {partners.map((partner, index) => {
+ return (
+ <Section
+ key={partner.id}
+ className={`rounded-lg border border-solid border-neutral-200 bg-neutral-50 p-4 ${index < partners.length - 1 ? "mb-3" : ""}`}
+ >
+ <Row>
+ <Column width="auto" className="pr-3" valign="middle">
+ <div className="flex items-center">
+ <Img
+ src={
+ partner.image || `${OG_AVATAR_URL}${partner.id}`
+ }
+ width="40"
+ height="40"
+ alt={partner.name || "partner avatar"}
+ className="rounded-full"
+ />
+ <div className="ml-3">
+ <Text className="m-0 p-0 text-sm font-semibold text-neutral-900">
+ {partner.name || ""}
+ </Text>
+ <Text className="m-0 p-0 text-sm font-medium text-neutral-500 no-underline">
+ {partner.email}
+ </Text>
+ </div>
+ </div>
+ </Column>
+ <Column
+ width="auto"
+ align="right"
+ valign="middle"
+ className="whitespace-nowrap"
+ >
+ <Link
+ href={`${applicationsUrl}?partnerId=${partner.id}`}
+ className="box-border inline-block rounded-md border border-solid border-neutral-200 bg-white px-4 py-2 text-center text-sm font-medium leading-none text-black no-underline"
+ >
+ Review
+ </Link>
+ </Column>
+ </Row>
+ </Section>
+ );
+ })}
+ </Section>
+
+ <Section className="mt-6 text-center">
+ <Link
+ href={applicationsUrl}
+ className="box-border block w-full rounded-md bg-black px-2 py-3 text-center text-sm font-medium leading-none text-white no-underline"
+ >
+ View all applications
+ </Link>
+ </Section>
+
+ <Footer
+ email={email}
+ notificationSettingsUrl={`https://app.dub.co/${workspace.slug}/settings/notifications`}
+ />
+ </Container>
+ </Body>
+ </Tailwind>
+ </Html>
+ );
+}
diff --git a/packages/email/src/templates/program-payout-reminder.tsx b/packages/email/src/templates/program-payout-reminder.tsx
index 19236242cf..85c43d1d58 100644
--- a/packages/email/src/templates/program-payout-reminder.tsx
+++ b/packages/email/src/templates/program-payout-reminder.tsx
@@ -63,9 +63,10 @@ export default function ProgramPayoutReminder({
</Heading>
<Text className="text-sm leading-6 text-neutral-600">
- You have some partners awaiting their payout for {program.name}.
- Completing these on time will keep your program running smooth and
- your partners happy.
+ You have <strong>{payout.partnersCount}</strong> partners awaiting
+ their payout for <strong>{program.name}</strong>. Completing these
+ on time will keep your program running smooth and your partners
+ happy.
</Text>
<Section className="rounded-lg border border-solid border-neutral-200 p-4">
diff --git a/packages/prisma/schema/notification.prisma b/packages/prisma/schema/notification.prisma
index 4e0eda561b..d3d81e37b2 100644
--- a/packages/prisma/schema/notification.prisma
+++ b/packages/prisma/schema/notification.prisma
@@ -51,6 +51,7 @@ model NotificationPreference {
domainConfigurationUpdates Boolean @default(true)
newPartnerSale Boolean @default(true)
newPartnerApplication Boolean @default(true)
+ pendingApplicationsSummary Boolean @default(true)
newBountySubmitted Boolean @default(true)
newMessageFromPartner Boolean @default(true)
fraudEventsSummary Boolean @default(true)