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 summary email updates (#4451)

Marcus Farrell122b1f5ad4b2
diff --git a/apps/web/app/(ee)/api/cron/partner-program-summary/process/route.ts b/apps/web/app/(ee)/api/cron/partner-program-summary/process/route.ts
deleted file mode 100644
index 2cb8e45ece..0000000000
--- a/apps/web/app/(ee)/api/cron/partner-program-summary/process/route.ts
+++ /dev/null
@@ -1,362 +0,0 @@
-import { getAnalytics } from "@/lib/analytics/get-analytics";
-import { qstash } from "@/lib/cron";
-import { withCron } from "@/lib/cron/with-cron";
-import { prisma } from "@/lib/prisma";
-import { sendBatchEmail } from "@dub/email";
-import PartnerProgramSummary from "@dub/email/templates/partner-program-summary";
-import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
-import { Prisma } from "@prisma/client";
-import { endOfMonth, format, startOfMonth, subMonths } from "date-fns";
-import * as z from "zod/v4";
-import { logAndRespond } from "../../utils";
-
-export const dynamic = "force-dynamic";
-
-const PARTNER_BATCH_SIZE = 100;
-
-const queue = qstash.queue({
- queueName: "send-partner-summary",
-});
-
-const schema = z.object({
- programId: z.string(),
- startingAfter: z.string().nullish(),
- batchNumber: z.number().nullish(),
-});
-
-interface AnalyticsResponse {
- partnerId: string;
- clicks: number;
- leads: number;
- sales: number;
- saleAmount: number;
-}
-
-type PartnerProgramSummaryMonthMetrics = {
- earnings: number;
- clicks: number;
- leads: number;
- sales: number;
-};
-
-function monthHasNoActivity(m: PartnerProgramSummaryMonthMetrics) {
- return m.earnings === 0 && m.clicks === 0 && m.leads === 0 && m.sales === 0;
-}
-
-// This route processes partner program summary emails for a specific program.
-// Called by the main route after enqueuing jobs for each program.
-// POST /api/cron/partner-program-summary/process
-export const POST = withCron(async ({ rawBody }) => {
- const result = schema.parse(JSON.parse(rawBody));
-
- let { programId, startingAfter, batchNumber } = result;
-
- const previousMonth = startOfMonth(subMonths(new Date(), 2));
- const currentMonth = startOfMonth(subMonths(new Date(), 1));
-
- const program = await prisma.program.findUnique({
- where: {
- id: programId,
- },
- select: {
- id: true,
- name: true,
- logo: true,
- slug: true,
- supportEmail: true,
- workspaceId: true,
- },
- });
-
- if (!program) {
- return logAndRespond(`Program ${programId} not found.`);
- }
-
- console.info(`Sending program summary for ${program.slug}`, {
- previousMonth,
- currentMonth,
- });
-
- // Find the clicks, leads, sales analytics
- const [previousMonthAnalytics, currentMonthAnalytics] = await Promise.all([
- // 2 months ago
- getAnalytics({
- event: "composite",
- groupBy: "top_partners",
- workspaceId: program.workspaceId,
- programId: program.id,
- start: previousMonth,
- end: endOfMonth(previousMonth),
- }),
-
- // 1 month ago
- getAnalytics({
- event: "composite",
- groupBy: "top_partners",
- workspaceId: program.workspaceId,
- programId: program.id,
- start: currentMonth,
- end: endOfMonth(currentMonth),
- }),
- ]);
-
- const programEnrollments = await prisma.programEnrollment.findMany({
- where: {
- programId: program.id,
- status: "approved",
- totalLeads: {
- gt: 0,
- },
- partner: {
- users: {
- some: {
- notificationPreferences: {
- monthlyProgramSummary: true,
- },
- },
- },
- },
- },
- select: {
- id: true,
- partner: {
- select: {
- id: true,
- email: true,
- createdAt: true,
- },
- },
- links: {
- select: {
- clicks: true,
- leads: true,
- sales: true,
- },
- },
- },
- ...(startingAfter && {
- skip: 1,
- cursor: {
- id: startingAfter,
- },
- }),
- orderBy: {
- id: "desc",
- },
- take: PARTNER_BATCH_SIZE,
- });
-
- console.info(
- `Found ${programEnrollments.length} active partners that have signed up for partners.dub.co and have links with at least 1 total lead.`,
- );
-
- if (programEnrollments.length === 0) {
- return logAndRespond(
- `No more active partners found for program ${program.id}.`,
- );
- }
-
- // Find the earnings
- const partners = programEnrollments.map(({ partner }) => partner);
-
- const commissionWhere: Prisma.CommissionWhereInput = {
- earnings: {
- gt: 0,
- },
- programId: program.id,
- partnerId: {
- in: partners.map((partner) => partner.id),
- },
- status: {
- in: ["pending", "processed", "paid"],
- },
- };
-
- const [previousMonthEarnings, currentMonthEarnings, lifetimeEarnings] =
- await Promise.all([
- // Earnings 2 months ago (to compare with previous month)
- prisma.commission.groupBy({
- by: ["partnerId"],
- where: {
- ...commissionWhere,
- createdAt: {
- gte: previousMonth,
- lte: endOfMonth(previousMonth),
- },
- },
- _sum: {
- earnings: true,
- },
- }),
-
- // Earnings 1 month ago,
- prisma.commission.groupBy({
- by: ["partnerId"],
- where: {
- ...commissionWhere,
- createdAt: {
- gte: currentMonth,
- lte: endOfMonth(currentMonth),
- },
- },
- _sum: {
- earnings: true,
- },
- }),
-
- // All-time earnings
- prisma.commission.groupBy({
- by: ["partnerId"],
- where: {
- ...commissionWhere,
- },
- _sum: {
- earnings: true,
- },
- }),
- ]);
-
- const previousEarningsMap = new Map(
- previousMonthEarnings.map((e) => [e.partnerId, e]),
- );
-
- const currentEarningsMap = new Map(
- currentMonthEarnings.map((e) => [e.partnerId, e]),
- );
-
- const lifetimeEarningsMap = new Map(
- lifetimeEarnings.map((e) => [e.partnerId, e]),
- );
-
- const previousAnalyticsMap: Map<string, AnalyticsResponse> = new Map(
- previousMonthAnalytics.map((a: AnalyticsResponse) => [a.partnerId, a]),
- );
-
- const currentAnalyticsMap: Map<string, AnalyticsResponse> = new Map(
- currentMonthAnalytics.map((a: AnalyticsResponse) => [a.partnerId, a]),
- );
-
- const summary = partners.map((partner) => {
- // Get previous and current month analytics from Tinybird
- const _previousMonthAnalytics = previousAnalyticsMap.get(partner.id);
- const _currentMonthAnalytics = currentAnalyticsMap.get(partner.id);
-
- // Get lifetime analytics from MySQL
- const _lifetimeAnalytics = programEnrollments
- .find((enrollment) => enrollment.partner.id === partner.id)
- ?.links.reduce(
- (acc, link) => ({
- clicks: acc.clicks + link.clicks,
- leads: acc.leads + link.leads,
- sales: acc.sales + link.sales,
- }),
- { clicks: 0, leads: 0, sales: 0 },
- );
-
- // Get earnings data from MySQL
- const _previousMonthEarnings = previousEarningsMap.get(partner.id);
- const _currentMonthEarnings = currentEarningsMap.get(partner.id);
- const _lifetimeEarnings = lifetimeEarningsMap.get(partner.id);
-
- return {
- partner,
- previousMonth: {
- earnings: _previousMonthEarnings?._sum.earnings ?? 0,
- clicks: _previousMonthAnalytics?.clicks ?? 0,
- leads: _previousMonthAnalytics?.leads ?? 0,
- sales: _previousMonthAnalytics?.sales ?? 0,
- },
- currentMonth: {
- earnings: _currentMonthEarnings?._sum.earnings ?? 0,
- clicks: _currentMonthAnalytics?.clicks ?? 0,
- leads: _currentMonthAnalytics?.leads ?? 0,
- sales: _currentMonthAnalytics?.sales ?? 0,
- },
- lifetime: {
- earnings: _lifetimeEarnings?._sum.earnings ?? 0,
- clicks: _lifetimeAnalytics?.clicks ?? 0,
- leads: _lifetimeAnalytics?.leads ?? 0,
- sales: _lifetimeAnalytics?.sales ?? 0,
- },
- };
- });
-
- console.table(
- summary.map((s) => ({
- partner: s.partner.email,
- program: program.name,
- currentEarnings: s.currentMonth.earnings,
- currentClicks: s.currentMonth.clicks,
- currentLeads: s.currentMonth.leads,
- currentSales: s.currentMonth.sales,
- lifetimeEarnings: s.lifetime.earnings,
- lifetimeClicks: s.lifetime.clicks,
- lifetimeLeads: s.lifetime.leads,
- lifetimeSales: s.lifetime.sales,
- })),
- );
-
- const reportingMonth = format(currentMonth, "MMM yyyy");
- batchNumber = batchNumber || 1;
-
- const summaryToSend = summary.filter(
- (s) =>
- !(
- monthHasNoActivity(s.previousMonth) &&
- monthHasNoActivity(s.currentMonth)
- ),
- );
-
- const skippedEmpty = summary.length - summaryToSend.length;
- if (skippedEmpty > 0) {
- console.info(
- `Skipped ${skippedEmpty} partner program summary email(s) with no activity in both reporting months.`,
- );
- }
-
- await sendBatchEmail(
- summaryToSend.map(({ partner, ...rest }) => ({
- variant: "notifications",
- subject: `Your ${reportingMonth} performance report for ${program.name} program`,
- to: partner.email!,
- replyTo: program.supportEmail || "noreply",
- react: PartnerProgramSummary({
- program,
- partner,
- ...rest,
- reportingPeriod: {
- month: reportingMonth,
- start: currentMonth.toISOString(),
- end: endOfMonth(currentMonth).toISOString(),
- },
- }),
- })),
- {
- idempotencyKey: `partner-program-summary-${reportingMonth}-${program.id}-${batchNumber}`,
- },
- );
-
- // Schedule the next batch if there are more partners to process
- if (programEnrollments.length === PARTNER_BATCH_SIZE) {
- startingAfter = programEnrollments[programEnrollments.length - 1].id;
- batchNumber++;
-
- const response = await queue.enqueueJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/partner-program-summary/process`,
- method: "POST",
- body: {
- ...result,
- startingAfter,
- batchNumber,
- },
- });
-
- return logAndRespond(
- `Enqueued partner program summary jobs for the next batch ${response.messageId}`,
- );
- }
-
- return logAndRespond(
- `Finished processing all partners for program ${program.id}.`,
- );
-});
diff --git a/apps/web/app/(ee)/api/cron/partner-program-summary/route.ts b/apps/web/app/(ee)/api/cron/partner-program-summary/route.ts
index 2bb9edf714..d1be1a2f13 100644
--- a/apps/web/app/(ee)/api/cron/partner-program-summary/route.ts
+++ b/apps/web/app/(ee)/api/cron/partner-program-summary/route.ts
@@ -1,55 +1,26 @@
-import { enqueueBatchJobs } from "@/lib/cron/enqueue-batch-jobs";
import { withCron } from "@/lib/cron/with-cron";
-import { prisma } from "@/lib/prisma";
-import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import { queuePartnerProgramSummaryJob } from "@/lib/jobs/handlers/queue-partner-program-summary-job";
import { format, startOfMonth, subMonths } from "date-fns";
import { logAndRespond } from "../utils";
export const dynamic = "force-dynamic";
-const PROGRAM_BATCH_SIZE = 50;
-
-// This route handles the monthly partner program summary emails for partners.
+// This route kicks off the monthly partner program summary emails.
// Scheduled to run at 1 PM UTC on the 1st day of every month to send the previous month's summary.
// GET /api/cron/partner-program-summary
export const GET = withCron(async () => {
- const currentMonth = startOfMonth(subMonths(new Date(), 1));
- const yearMonth = format(currentMonth, "yyyy-MM");
-
- let page = 0;
-
- while (true) {
- const programs = await prisma.program.findMany({
- where: { deactivatedAt: null },
- select: {
- id: true,
- },
- take: PROGRAM_BATCH_SIZE,
- skip: page * PROGRAM_BATCH_SIZE,
- orderBy: {
- id: "asc",
- },
- });
-
- if (programs.length === 0) {
- break;
- }
-
- await enqueueBatchJobs(
- programs.map((program) => ({
- queueName: "send-partner-summary",
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/partner-program-summary/process`,
- deduplicationId: `partner-program-summary-${yearMonth}-${program.id}`,
- body: {
- programId: program.id,
- },
- })),
- );
-
- page++;
- }
+ const yearMonth = format(startOfMonth(subMonths(new Date(), 1)), "yyyy-MM");
+
+ await queuePartnerProgramSummaryJob.dispatch(
+ {
+ yearMonth,
+ },
+ {
+ deduplicationId: `queue-program-summary-${yearMonth}`,
+ },
+ );
return logAndRespond(
- `Enqueued partner program summary jobs for ${yearMonth}.`,
+ `Enqueued partner program summary queue job for ${yearMonth}.`,
);
});
diff --git a/apps/web/lib/api/workflows/send-campaign/execute.ts b/apps/web/lib/api/workflows/send-campaign/execute.ts
index 8a4d0c4e6a..b168cf16c5 100644
--- a/apps/web/lib/api/workflows/send-campaign/execute.ts
+++ b/apps/web/lib/api/workflows/send-campaign/execute.ts
@@ -4,6 +4,7 @@ import { resolveCampaignFromAddress } from "@/lib/email/parse-campaign-from-addr
import { aggregatePartnerLinksStats } from "@/lib/partners/aggregate-partner-links-stats";
import { prisma } from "@/lib/prisma";
import { TiptapNode } from "@/lib/types";
+import { ACTIVE_ENROLLMENT_STATUSES } from "@/lib/zod/schemas/partners";
import { WORKFLOW_ACTION_TYPES } from "@/lib/zod/schemas/workflows";
import { sendBatchEmail } from "@dub/email";
import CampaignEmail from "@dub/email/templates/campaign-email";
@@ -12,7 +13,6 @@ import {
CommissionStatus,
NotificationEmailType,
Prisma,
- ProgramEnrollmentStatus,
Workflow,
} from "@prisma/client";
import { addHours, differenceInDays, subDays } from "date-fns";
@@ -326,7 +326,9 @@ function campaignAudienceWhere({
partnerTagIds: string[];
}) {
return {
- status: ProgramEnrollmentStatus.approved,
+ status: {
+ in: ACTIVE_ENROLLMENT_STATUSES,
+ },
...(groupIds.length > 0 && {
groupId: {
in: groupIds,
diff --git a/apps/web/lib/jobs/handlers/queue-partner-program-summary-job.ts b/apps/web/lib/jobs/handlers/queue-partner-program-summary-job.ts
new file mode 100644
index 0000000000..95449c9b94
--- /dev/null
+++ b/apps/web/lib/jobs/handlers/queue-partner-program-summary-job.ts
@@ -0,0 +1,118 @@
+import { prisma } from "@/lib/prisma";
+import { yearMonthSchema } from "@/lib/zod/schemas/misc";
+import { Prisma } from "@prisma/client";
+import * as z from "zod/v4";
+import { defineJob } from "../index";
+import { sendPartnerProgramSummaryJob } from "./send-partner-program-summary-job";
+
+const PARTNER_BATCH_SIZE = 100;
+const MAX_BATCHES_PER_RUN = 10;
+
+const inputSchema = z.object({
+ yearMonth: yearMonthSchema,
+ startingAfter: z.string().optional(),
+});
+
+// Pages distinct eligible partnerIds by partnerId cursor, keeps partners with
+// at least one user who has monthlyProgramSummary enabled, and dispatches one
+// send-partner-program-summary-job per partner. Self-continues with a partner
+// cursor.
+export const queuePartnerProgramSummaryJob = defineJob({
+ name: "queue-partner-program-summary-job",
+ schema: inputSchema,
+ async handle(input) {
+ const { yearMonth } = input;
+ let startingAfter = input.startingAfter;
+ let partnerCount = 0;
+ let hasMore = false;
+
+ for (let batch = 0; batch < MAX_BATCHES_PER_RUN; batch++) {
+ const cursorFragment = startingAfter
+ ? Prisma.sql`AND pe.partnerId > ${startingAfter}`
+ : Prisma.sql``;
+
+ const rows = await prisma.$queryRaw<{ partnerId: string }[]>(Prisma.sql`
+ SELECT DISTINCT pe.partnerId
+ FROM ProgramEnrollment pe
+ WHERE pe.status = 'approved'
+ AND pe.totalLeads > 0
+ ${cursorFragment}
+ ORDER BY pe.partnerId ASC
+ LIMIT ${PARTNER_BATCH_SIZE}
+ `);
+
+ if (rows.length === 0) {
+ if (partnerCount === 0 && !input.startingAfter) {
+ console.info(`No eligible partners found for ${yearMonth}.`);
+ return;
+ }
+
+ hasMore = false;
+ break;
+ }
+
+ // Advance cursor from the raw page so filtered-out partners are not re-read
+ startingAfter = rows[rows.length - 1].partnerId;
+ hasMore = rows.length === PARTNER_BATCH_SIZE;
+
+ const partners = await prisma.partner.findMany({
+ where: {
+ id: {
+ in: rows.map((r) => r.partnerId),
+ },
+ users: {
+ some: {
+ notificationPreferences: {
+ monthlyProgramSummary: true,
+ },
+ },
+ },
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ if (partners.length > 0) {
+ await sendPartnerProgramSummaryJob.dispatchBatch(
+ partners.map(({ id: partnerId }) => ({
+ partnerId,
+ yearMonth,
+ })),
+ ({ partnerId }) => ({
+ deduplicationId: `send-program-summary-${yearMonth}-${partnerId}`,
+ flowControl: {
+ key: "send-program-summary",
+ parallelism: 10,
+ },
+ }),
+ );
+
+ partnerCount += partners.length;
+ }
+
+ if (!hasMore) {
+ break;
+ }
+ }
+
+ if (hasMore && startingAfter) {
+ await queuePartnerProgramSummaryJob.dispatch(
+ {
+ yearMonth,
+ startingAfter,
+ },
+ {
+ delay: 2,
+ },
+ );
+
+ console.info(
+ `Dispatched ${partnerCount} send jobs for ${yearMonth}. Scheduled next batch (startingAfter: ${startingAfter}).`,
+ );
+ return;
+ }
+
+ console.info(`Dispatched ${partnerCount} send jobs for ${yearMonth}.`);
+ },
+});
diff --git a/apps/web/lib/jobs/handlers/send-partner-program-summary-job.ts b/apps/web/lib/jobs/handlers/send-partner-program-summary-job.ts
new file mode 100644
index 0000000000..6ccaa1bba5
--- /dev/null
+++ b/apps/web/lib/jobs/handlers/send-partner-program-summary-job.ts
@@ -0,0 +1,452 @@
+import { getAnalytics } from "@/lib/analytics/get-analytics";
+import { prisma } from "@/lib/prisma";
+import { redis } from "@/lib/upstash";
+import { yearMonthSchema } from "@/lib/zod/schemas/misc";
+import { ACTIVE_ENROLLMENT_STATUSES } from "@/lib/zod/schemas/partners";
+import { tz } from "@date-fns/tz";
+import { sendBatchEmail } from "@dub/email";
+import PartnerProgramSummary from "@dub/email/templates/partner-program-summary";
+import { chunk } from "@dub/utils";
+import { CommissionStatus, Prisma, Program } from "@prisma/client";
+import { endOfMonth, format, parse, subMonths } from "date-fns";
+import * as z from "zod/v4";
+import { defineJob } from "../index";
+
+const MAX_PROGRAMS_PER_SUMMARY = 10;
+const ANALYTICS_CACHE_TTL_SECONDS = 60 * 60; // 1 hour
+const ANALYTICS_REQUEST_BATCH_SIZE = 10;
+
+// earnings from MySQL, clicks, leads, sales from Tinybird
+type MonthMetrics = {
+ earnings: number;
+ clicks: number;
+ leads: number;
+ sales: number;
+};
+
+type PartnerAnalyticsMetrics = {
+ clicks: number;
+ leads: number;
+ sales: number;
+};
+
+const EMPTY_PARTNER_ANALYTICS: PartnerAnalyticsMetrics = {
+ clicks: 0,
+ leads: 0,
+ sales: 0,
+};
+
+type ProgramSummaryStats = {
+ previousMonth: MonthMetrics;
+ currentMonth: MonthMetrics;
+};
+
+function monthHasNoActivity(m: MonthMetrics) {
+ return m.earnings === 0 && m.clicks === 0 && m.leads === 0 && m.sales === 0;
+}
+
+function byCurrentMonthPerformance(
+ a: ProgramSummaryStats,
+ b: ProgramSummaryStats,
+) {
+ return (
+ b.currentMonth.earnings - a.currentMonth.earnings ||
+ b.currentMonth.sales - a.currentMonth.sales ||
+ b.currentMonth.leads - a.currentMonth.leads ||
+ b.currentMonth.clicks - a.currentMonth.clicks
+ );
+}
+
+export function getReportingPeriod(yearMonth: string) {
+ const utc = tz("UTC");
+ const currentMonthStart = parse(yearMonth, "yyyy-MM", new Date(), {
+ in: utc,
+ });
+ const previousMonthStart = subMonths(currentMonthStart, 1);
+ const currentMonthEnd = endOfMonth(currentMonthStart);
+ const previousMonthEnd = endOfMonth(previousMonthStart);
+
+ const currentMonth = new Date(currentMonthStart.getTime());
+ const previousMonth = new Date(previousMonthStart.getTime());
+ const end = new Date(currentMonthEnd.getTime());
+
+ return {
+ currentMonth,
+ previousMonth,
+ previousMonthEnd: new Date(previousMonthEnd.getTime()),
+ currentMonthEnd: end,
+ month: format(currentMonthStart, "MMMM yyyy", { in: utc }),
+ start: currentMonth.toISOString(),
+ end: end.toISOString(),
+ };
+}
+
+// Fetches composite top_partners for a program/month window once, caches the
+// partnerId -> metrics map in Redis so other send jobs for the same program reuse it.
+async function getTopPartnersAnalytics({
+ workspaceId,
+ programId,
+ yearMonth,
+ period,
+ start,
+ end,
+}: {
+ workspaceId: string;
+ programId: string;
+ yearMonth: string;
+ period: "previous" | "current";
+ start: Date;
+ end: Date;
+}): Promise<Record<string, PartnerAnalyticsMetrics>> {
+ const cacheKey = `topPartnersAnalytics:${programId}:${yearMonth}:${period}`;
+
+ const cached =
+ await redis.get<Record<string, PartnerAnalyticsMetrics>>(cacheKey);
+
+ if (cached) {
+ return cached;
+ }
+
+ const rows = await getAnalytics({
+ event: "composite",
+ groupBy: "top_partners",
+ workspaceId,
+ programId,
+ start,
+ end,
+ });
+
+ const byPartnerId: Record<string, PartnerAnalyticsMetrics> = {};
+
+ for (const row of rows) {
+ byPartnerId[row.partnerId] = {
+ clicks: row.clicks ?? 0,
+ leads: row.leads ?? 0,
+ sales: row.sales ?? 0,
+ };
+ }
+
+ console.info(
+ `[getProgramTopPartnersAnalytics] Cached ${Object.keys(byPartnerId).length} partners for ${programId} in ${yearMonth} ${period}`,
+ );
+
+ await redis.set(cacheKey, byPartnerId, {
+ ex: ANALYTICS_CACHE_TTL_SECONDS,
+ });
+
+ return byPartnerId;
+}
+
+async function getPartnerAnalytics({
+ enrollments,
+ partnerId,
+ yearMonth,
+ previousMonth,
+ previousMonthEnd,
+ currentMonth,
+ currentMonthEnd,
+}: {
+ enrollments: {
+ program: Pick<Program, "id" | "name" | "logo" | "slug" | "workspaceId">;
+ }[];
+ partnerId: string;
+ yearMonth: string;
+} & Pick<
+ ReturnType<typeof getReportingPeriod>,
+ "previousMonth" | "previousMonthEnd" | "currentMonth" | "currentMonthEnd"
+>) {
+ const analyticsRequests = enrollments.flatMap(({ program }) => [
+ {
+ program,
+ period: "previous" as const,
+ start: previousMonth,
+ end: previousMonthEnd,
+ },
+ {
+ program,
+ period: "current" as const,
+ start: currentMonth,
+ end: currentMonthEnd,
+ },
+ ]);
+
+ const analyticsByKey = new Map<
+ string,
+ Record<string, PartnerAnalyticsMetrics>
+ >();
+
+ for (const batch of chunk(analyticsRequests, ANALYTICS_REQUEST_BATCH_SIZE)) {
+ const batchResults = await Promise.all(
+ batch.map(async ({ program, period, start, end }) => {
+ const byPartner = await getTopPartnersAnalytics({
+ workspaceId: program.workspaceId,
+ programId: program.id,
+ yearMonth,
+ period,
+ start,
+ end,
+ });
+
+ return {
+ key: `${program.id}:${period}`,
+ byPartner,
+ };
+ }),
+ );
+
+ for (const { key, byPartner } of batchResults) {
+ analyticsByKey.set(key, byPartner);
+ }
+ }
+
+ return enrollments.map(({ program }) => ({
+ program,
+ previousMonthAnalytics:
+ analyticsByKey.get(`${program.id}:previous`)?.[partnerId] ??
+ EMPTY_PARTNER_ANALYTICS,
+ currentMonthAnalytics:
+ analyticsByKey.get(`${program.id}:current`)?.[partnerId] ??
+ EMPTY_PARTNER_ANALYTICS,
+ }));
+}
+
+const inputSchema = z.object({
+ partnerId: z.string(),
+ yearMonth: yearMonthSchema,
+});
+
+// Builds the monthly program summary for a partner (all programs combined)
+// and sends it to each partner user with monthlyProgramSummary enabled.
+// Skip if no users to notify or no program activity in the reporting window.
+export const sendPartnerProgramSummaryJob = defineJob({
+ name: "send-partner-program-summary-job",
+ schema: inputSchema,
+ async handle(input) {
+ const { partnerId, yearMonth } = input;
+
+ const partner = await prisma.partner.findUnique({
+ where: {
+ id: partnerId,
+ },
+ select: {
+ users: {
+ where: {
+ notificationPreferences: {
+ monthlyProgramSummary: true,
+ },
+ },
+ select: {
+ user: {
+ select: {
+ email: true,
+ },
+ },
+ },
+ },
+ },
+ });
+
+ const partnerUsersToNotify = (partner?.users ?? [])
+ .map(({ user }) => user)
+ .filter((user): user is { email: string } => Boolean(user?.email));
+
+ if (partnerUsersToNotify.length === 0) {
+ console.info(
+ `[sendPartnerProgramSummaryJob] No partner emails to notify for partner ${partnerId}. Skipping...`,
+ );
+ return;
+ }
+
+ const enrollments = await prisma.programEnrollment.findMany({
+ where: {
+ partnerId,
+ program: {
+ deactivatedAt: null,
+ },
+ status: {
+ in: ACTIVE_ENROLLMENT_STATUSES,
+ },
+ totalLeads: {
+ gt: 0,
+ },
+ },
+ select: {
+ program: {
+ select: {
+ id: true,
+ name: true,
+ logo: true,
+ slug: true,
+ workspaceId: true,
+ },
+ },
+ },
+ });
+
+ if (enrollments.length === 0) {
+ console.info(
+ `[sendPartnerProgramSummaryJob] Partner ${partnerId} has no eligible enrollments. Skipping...`,
+ );
+ return;
+ }
+
+ const {
+ previousMonth,
+ previousMonthEnd,
+ currentMonth,
+ currentMonthEnd,
+ month,
+ start,
+ end,
+ } = getReportingPeriod(yearMonth);
+
+ const programIds = enrollments.map((e) => e.program.id);
+
+ const commissionWhere: Prisma.CommissionWhereInput = {
+ partnerId,
+ programId: {
+ in: programIds,
+ },
+ earnings: {
+ gt: 0,
+ },
+ status: {
+ in: [
+ CommissionStatus.pending,
+ CommissionStatus.processed,
+ CommissionStatus.paid,
+ ],
+ },
+ };
+
+ const [previousMonthEarnings, currentMonthEarnings, analyticsByProgram] =
+ await Promise.all([
+ prisma.commission.groupBy({
+ by: ["programId"],
+ where: {
+ ...commissionWhere,
+ createdAt: {
+ gte: previousMonth,
+ lte: previousMonthEnd,
+ },
+ },
+ _sum: {
+ earnings: true,
+ },
+ }),
+
+ prisma.commission.groupBy({
+ by: ["programId"],
+ where: {
+ ...commissionWhere,
+ createdAt: {
+ gte: currentMonth,
+ lte: currentMonthEnd,
+ },
+ },
+ _sum: {
+ earnings: true,
+ },
+ }),
+
+ getPartnerAnalytics({
+ enrollments,
+ partnerId,
+ yearMonth,
+ previousMonth,
+ previousMonthEnd,
+ currentMonth,
+ currentMonthEnd,
+ }),
+ ]);
+
+ const previousEarningsMap = new Map(
+ previousMonthEarnings.map((e) => [e.programId, e._sum.earnings ?? 0]),
+ );
+
+ const currentEarningsMap = new Map(
+ currentMonthEarnings.map((e) => [e.programId, e._sum.earnings ?? 0]),
+ );
+
+ const programs = analyticsByProgram
+ .map(({ program, previousMonthAnalytics, currentMonthAnalytics }) => {
+ const stats: ProgramSummaryStats = {
+ previousMonth: {
+ earnings: previousEarningsMap.get(program.id) ?? 0,
+ clicks: previousMonthAnalytics.clicks ?? 0,
+ leads: previousMonthAnalytics.leads ?? 0,
+ sales: previousMonthAnalytics.sales ?? 0,
+ },
+ currentMonth: {
+ earnings: currentEarningsMap.get(program.id) ?? 0,
+ clicks: currentMonthAnalytics.clicks ?? 0,
+ leads: currentMonthAnalytics.leads ?? 0,
+ sales: currentMonthAnalytics.sales ?? 0,
+ },
+ };
+
+ return {
+ id: program.id,
+ name: program.name,
+ logo: program.logo,
+ slug: program.slug,
+ ...stats,
+ };
+ })
+ .filter(
+ (program) =>
+ !(
+ monthHasNoActivity(program.previousMonth) &&
+ monthHasNoActivity(program.currentMonth)
+ ),
+ )
+ .sort(byCurrentMonthPerformance)
+ .slice(0, MAX_PROGRAMS_PER_SUMMARY);
+
+ if (programs.length === 0) {
+ console.info(
+ `[sendPartnerProgramSummaryJob] Partner ${partnerId} has no program activity for ${yearMonth}. Skipping...`,
+ );
+ return;
+ }
+
+ console.table(
+ programs.map((p) => {
+ return {
+ name: p.name,
+ current: JSON.stringify(p.currentMonth),
+ previous: JSON.stringify(p.previousMonth),
+ };
+ }),
+ );
+
+ const { error } = await sendBatchEmail(
+ partnerUsersToNotify.map(({ email }) => ({
+ variant: "notifications",
+ subject: `Your ${month} partner program summary`,
+ to: email,
+ replyTo: "noreply",
+ react: PartnerProgramSummary({
+ email,
+ programs,
+ reportingPeriod: {
+ month,
+ start,
+ end,
+ },
+ }),
+ })),
+ {
+ idempotencyKey: `partner-program-summary-${yearMonth}-${partnerId}`,
+ },
+ );
+
+ if (error) {
+ throw new Error(error.message);
+ }
+
+ console.info(
+ `[sendPartnerProgramSummaryJob] Sent summary for partner ${partnerId} (${yearMonth}) to ${partnerUsersToNotify.length} users with ${programs.length} programs.`,
+ );
+ },
+});
diff --git a/apps/web/lib/jobs/registry.ts b/apps/web/lib/jobs/registry.ts
index 39b8d4e726..91313d0c46 100644
--- a/apps/web/lib/jobs/registry.ts
+++ b/apps/web/lib/jobs/registry.ts
@@ -55,6 +55,16 @@ const jobLoaders = {
import("./handlers/auto-reject-partner-job").then(
(m) => m.autoRejectPartnerJob,
),
+
+ "queue-partner-program-summary-job": () =>
+ import("./handlers/queue-partner-program-summary-job").then(
+ (m) => m.queuePartnerProgramSummaryJob,
+ ),
+
+ "send-partner-program-summary-job": () =>
+ import("./handlers/send-partner-program-summary-job").then(
+ (m) => m.sendPartnerProgramSummaryJob,
+ ),
} as const satisfies Record<string, () => Promise<JobDefinition>>;
const jobCache = new Map<string, JobDefinition>();
diff --git a/apps/web/lib/zod/schemas/misc.ts b/apps/web/lib/zod/schemas/misc.ts
index a6f583a2db..e7b8b8076e 100644
--- a/apps/web/lib/zod/schemas/misc.ts
+++ b/apps/web/lib/zod/schemas/misc.ts
@@ -16,6 +16,10 @@ export const maxDurationSchema = z.coerce
export const planSchema = z.enum(plans).describe("The plan of the workspace.");
+export const yearMonthSchema = z
+ .string()
+ .regex(/^\d{4}-(0[1-9]|1[0-2])$/, "Expected a month in the format yyyy-MM");
+
export const roleSchema = z
.enum(WorkspaceRole)
.describe("The role of the authenticated user in the workspace.");
diff --git a/apps/web/tests/partners/get-reporting-period.test.ts b/apps/web/tests/partners/get-reporting-period.test.ts
new file mode 100644
index 0000000000..576dc610b7
--- /dev/null
+++ b/apps/web/tests/partners/get-reporting-period.test.ts
@@ -0,0 +1,40 @@
+import { getReportingPeriod } from "@/lib/jobs/handlers/send-partner-program-summary-job";
+import { describe, expect, it } from "vitest";
+
+describe("getReportingPeriod", () => {
+ it("returns UTC month bounds for a mid-year month", () => {
+ const period = getReportingPeriod("2026-08");
+
+ expect(period.month).toBe("August 2026");
+ expect(period.currentMonth.toISOString()).toBe("2026-08-01T00:00:00.000Z");
+ expect(period.previousMonth.toISOString()).toBe("2026-07-01T00:00:00.000Z");
+ expect(period.start).toBe("2026-08-01T00:00:00.000Z");
+ expect(period.end).toBe("2026-08-31T23:59:59.999Z");
+ });
+
+ it("rolls the previous month into the prior year for January", () => {
+ const period = getReportingPeriod("2026-01");
+
+ expect(period.month).toBe("January 2026");
+ expect(period.currentMonth.toISOString()).toBe("2026-01-01T00:00:00.000Z");
+ expect(period.previousMonth.toISOString()).toBe("2025-12-01T00:00:00.000Z");
+ expect(period.start).toBe("2026-01-01T00:00:00.000Z");
+ expect(period.end).toBe("2026-01-31T23:59:59.999Z");
+ });
+
+ it("uses the last day of February for a non-leap year", () => {
+ const period = getReportingPeriod("2025-02");
+
+ expect(period.month).toBe("February 2025");
+ expect(period.start).toBe("2025-02-01T00:00:00.000Z");
+ expect(period.end).toBe("2025-02-28T23:59:59.999Z");
+ });
+
+ it("uses the last day of February for a leap year", () => {
+ const period = getReportingPeriod("2024-02");
+
+ expect(period.month).toBe("February 2024");
+ expect(period.start).toBe("2024-02-01T00:00:00.000Z");
+ expect(period.end).toBe("2024-02-29T23:59:59.999Z");
+ });
+});
diff --git a/packages/email/src/templates/partner-program-summary.tsx b/packages/email/src/templates/partner-program-summary.tsx
index 3bb55f07a0..c0d701088a 100644
--- a/packages/email/src/templates/partner-program-summary.tsx
+++ b/packages/email/src/templates/partner-program-summary.tsx
@@ -2,7 +2,6 @@ import {
currencyFormatter,
DUB_LOGO,
DUB_WORDMARK,
- formatDate,
nFormatter,
} from "@dub/utils";
import {
@@ -11,7 +10,6 @@ import {
Container,
Head,
Heading,
- Hr,
Html,
Img,
Link,
@@ -23,15 +21,18 @@ import {
} from "@react-email/components";
import { Footer } from "../components/footer";
+const PARTNERS_URL = "https://partners.dub.co";
+
+// The top programs get a card with full stats, the rest are listed in a compact table
+const MAX_PROGRAM_CARDS = 3;
+
const ICONS = {
+ earnings: "https://assets.dub.co/misc/icons/nucleo/money-bills.png",
clicks: "https://assets.dub.co/misc/icons/nucleo/cursor-rays.png",
leads: "https://assets.dub.co/misc/icons/nucleo/user-plus.png",
sales: "https://assets.dub.co/misc/icons/nucleo/invoice-dollar.png",
- earnings: "https://assets.dub.co/misc/icons/nucleo/money-bills.png",
} as const;
-type Icon = keyof typeof ICONS;
-
const percentStateMap = {
positive: {
color: "bg-green-50 text-green-700",
@@ -42,11 +43,33 @@ const percentStateMap = {
sign: "-",
},
neutral: {
- color: "bg-neutral-50 text-neutral-700",
+ color: "bg-neutral-100 text-neutral-700",
sign: "",
},
};
+type MonthMetrics = {
+ earnings: number;
+ clicks: number;
+ leads: number;
+ sales: number;
+};
+
+type ProgramSummary = {
+ id: string;
+ name: string;
+ logo: string | null;
+ slug: string;
+ previousMonth: MonthMetrics;
+ currentMonth: MonthMetrics;
+};
+
+type ReportingPeriod = {
+ month: string;
+ start: string;
+ end: string;
+};
+
function getPercentChange(current: number, previous: number) {
if (previous === 0) {
return current === 0 ? 0 : 100;
@@ -55,11 +78,7 @@ function getPercentChange(current: number, previous: number) {
return Math.round(((current - previous) / Math.abs(previous)) * 100);
}
-function getPercentState(percent?: number) {
- if (typeof percent !== "number") {
- return percentStateMap.neutral;
- }
-
+function getPercentState(percent: number) {
if (percent > 0) {
return percentStateMap.positive;
}
@@ -71,192 +90,122 @@ function getPercentState(percent?: number) {
return percentStateMap.neutral;
}
-export default function PartnerProgramSummary({
- program = {
- name: "Acme",
- logo: DUB_LOGO,
- slug: "acme",
- },
- partner = {
- email: "[email protected]",
- createdAt: new Date(),
- },
- previousMonth = {
- earnings: 12500,
- clicks: 200,
- leads: 50,
- sales: 25,
+function getProgramLogo(program: Pick<ProgramSummary, "logo">) {
+ return program.logo || DUB_LOGO;
+}
+
+function getProgramUrl(
+ program: Pick<ProgramSummary, "slug">,
+ reportingPeriod: ReportingPeriod,
+) {
+ return `${PARTNERS_URL}/programs/${program.slug}?start=${reportingPeriod.start}&end=${reportingPeriod.end}`;
+}
+
+const SAMPLE_METRICS = {
+ previousMonth: {
+ earnings: 100000,
+ clicks: 364,
+ leads: 182,
+ sales: 102,
},
- currentMonth = {
- earnings: 12850,
- clicks: 210,
- leads: 45,
- sales: 25,
+ currentMonth: {
+ earnings: 100000,
+ clicks: 400,
+ leads: 200,
+ sales: 100,
},
- lifetime = {
- earnings: 11241050,
- clicks: 398585,
- leads: 23409,
- sales: 1492,
+};
+
+const SAMPLE_PROGRAMS: ProgramSummary[] = [
+ "Framer",
+ "Acme",
+ "Guideless",
+ "Granola",
+ "Fillout",
+ "Firecrawl",
+ "Wispr Flow",
+ "Superhuman",
+ "Dub",
+ "Tella",
+].map((name, index) => ({
+ id: `prog_${index + 1}`,
+ name,
+ logo: null,
+ slug: name.toLowerCase().replace(/\s+/g, "-"),
+ previousMonth: SAMPLE_METRICS.previousMonth,
+ currentMonth: {
+ ...SAMPLE_METRICS.currentMonth,
+ earnings: Math.max(0, 100000 - index * 20000),
},
+}));
+
+export default function PartnerProgramSummary({
+ email = "[email protected]",
reportingPeriod = {
- month: "May 2025",
- start: "2025-05-01T00:00:00.000Z",
- end: "2025-05-31T23:59:59.999Z",
+ month: "August 2026",
+ start: "2026-08-01T00:00:00.000Z",
+ end: "2026-08-31T23:59:59.999Z",
},
+ programs = SAMPLE_PROGRAMS,
}: {
- program: {
- name: string;
- logo: string | null;
- slug: string;
- };
- partner: {
- email: string | null;
- createdAt: Date;
- };
- previousMonth: {
- earnings: number;
- clicks: number;
- leads: number;
- sales: number;
- };
- currentMonth: {
- earnings: number;
- clicks: number;
- leads: number;
- sales: number;
- };
- lifetime: {
- earnings: number;
- clicks: number;
- leads: number;
- sales: number;
- };
- reportingPeriod: {
- month: string;
- start: string;
- end: string;
- };
+ email: string;
+ reportingPeriod: ReportingPeriod;
+ programs: ProgramSummary[];
}) {
- const monthlyStats = [
- {
- title: "Earnings",
- value: currencyFormatter(currentMonth.earnings),
- percent: getPercentChange(currentMonth.earnings, previousMonth.earnings),
- },
- {
- title: "Clicks",
- value: nFormatter(currentMonth.clicks),
- percent: getPercentChange(currentMonth.clicks, previousMonth.clicks),
- },
- {
- title: "Leads",
- value: nFormatter(currentMonth.leads),
- percent: getPercentChange(currentMonth.leads, previousMonth.leads),
- },
- {
- title: "Sales",
- value: nFormatter(currentMonth.sales),
- percent: getPercentChange(currentMonth.sales, previousMonth.sales),
- },
- ];
-
- const lifetimeStats = [
- {
- title: "Earnings",
- value: currencyFormatter(lifetime.earnings),
- },
- {
- title: "Clicks",
- value: nFormatter(lifetime.clicks),
- },
- {
- title: "Leads",
- value: nFormatter(lifetime.leads),
- },
- {
- title: "Sales",
- value: nFormatter(lifetime.sales),
- },
- ];
-
- const previewText = monthlyStats
- .map(
- ({ title, value, percent }) =>
- `${title.toUpperCase()} ${value} (${getPercentState(percent).sign}${Math.abs(percent)}%)`,
- )
- .join(" | ");
+ const programCards = programs.slice(0, MAX_PROGRAM_CARDS);
+ const programRows = programs.slice(MAX_PROGRAM_CARDS);
return (
<Html>
<Head />
- <Preview>{previewText}</Preview>
+ <Preview>
+ See how you performed across your top Dub programs in{" "}
+ {reportingPeriod.month}, compared with the previous month.
+ </Preview>
<Tailwind>
<Body className="mx-auto my-auto bg-white font-sans">
- <Container className="mx-auto my-10 max-w-[600px] space-y-10 px-3 py-5">
+ <Container className="mx-auto my-10 max-w-[600px] px-10 py-5">
<Section className="mt-8">
- <Img src={DUB_WORDMARK} height="32" alt={program.name} />
+ <Img src={DUB_WORDMARK} height="32" alt="Dub" />
</Section>
- <Heading className="mx-0 mt-[40px] p-0 text-lg font-medium text-black">
- {program.name} partner program monthly summary (
- {reportingPeriod.month})
+ <Heading className="mx-0 mb-1 mt-10 p-0 text-lg font-semibold leading-7 text-neutral-800">
+ {reportingPeriod.month} program summary
</Heading>
- <Section className="mt-6 rounded-xl border border-solid border-neutral-200 bg-neutral-50">
- <Section className="rounded-t-xl px-6 py-5">
- <div className="flex items-center">
- <Img
- src={program.logo || DUB_WORDMARK}
- alt={program.name}
- height="32"
- width="32"
- className="mr-4 rounded-md"
- />
-
- <div>
- <div className="text-base font-semibold leading-tight text-neutral-800">
- {program.name}
- </div>
- <div className="text-xs font-medium text-neutral-500">
- Partner since{" "}
- {formatDate(partner.createdAt, { month: "short" })}
- </div>
- </div>
- </div>
- </Section>
-
- <Section className="space-y-6 rounded-xl border-t border-solid border-neutral-200 bg-white p-6">
- <Section>
- <Heading className="mb-4 mt-0 text-base font-semibold leading-6 text-neutral-800">
- Stats for {reportingPeriod.month} (vs previous month)
- </Heading>
-
- <StatsGrid stats={monthlyStats} />
- </Section>
-
- <Hr className="mx-0 my-8 w-full border border-neutral-200" />
-
- <Section>
- <Heading className="mb-4 mt-0 text-base font-semibold leading-6 text-neutral-800">
- All-time Performance
- </Heading>
-
- <StatsGrid stats={lifetimeStats} />
- </Section>
-
- <Section className="mt-8 text-center">
- <Link
- href={`https://partners.dub.co/programs/${program.slug}?start=${reportingPeriod.start}&end=${reportingPeriod.end}`}
- className="box-border block w-full rounded-lg bg-black px-0 py-4 text-center text-sm font-semibold leading-none text-white no-underline"
- >
- View dashboard
- </Link>
- </Section>
- </Section>
+ <Text className="m-0 text-sm leading-5 text-neutral-600">
+ See how you performed across your top Dub programs, compared with
+ the previous month.
+ </Text>
+
+ {programCards.map((program) => (
+ <ProgramCard
+ key={program.id}
+ program={program}
+ reportingPeriod={reportingPeriod}
+ />
+ ))}
+
+ {programRows.length > 0 && (
+ <ProgramTable
+ programs={programRows}
+ reportingPeriod={reportingPeriod}
+ />
+ )}
+
+ <Section className="mt-5">
+ <Link
+ href={`${PARTNERS_URL}/programs`}
+ className="box-border inline-block rounded-lg bg-neutral-900 px-3.5 py-2 text-sm font-medium leading-5 text-white no-underline"
+ >
+ View all programs
+ </Link>
</Section>
- <Footer email={partner.email!} />
+ <Footer
+ email={email}
+ notificationSettingsUrl={`${PARTNERS_URL}/profile/notifications`}
+ />
</Container>
</Body>
</Tailwind>
@@ -264,73 +213,227 @@ export default function PartnerProgramSummary({
);
}
-const StatsGrid = ({
- stats,
+const ProgramCard = ({
+ program,
+ reportingPeriod,
}: {
- stats: {
- title: string;
- value: number | string;
- percent?: number;
- }[];
+ program: ProgramSummary;
+ reportingPeriod: ReportingPeriod;
}) => {
+ const { previousMonth, currentMonth } = program;
+
+ const stats = [
+ {
+ title: "Earnings",
+ icon: ICONS.earnings,
+ value: currencyFormatter(currentMonth.earnings),
+ percent: getPercentChange(currentMonth.earnings, previousMonth.earnings),
+ },
+ {
+ title: "Clicks",
+ icon: ICONS.clicks,
+ value: nFormatter(currentMonth.clicks),
+ percent: getPercentChange(currentMonth.clicks, previousMonth.clicks),
+ },
+ {
+ title: "Leads",
+ icon: ICONS.leads,
+ value: nFormatter(currentMonth.leads),
+ percent: getPercentChange(currentMonth.leads, previousMonth.leads),
+ },
+ {
+ title: "Sales",
+ icon: ICONS.sales,
+ value: nFormatter(currentMonth.sales),
+ percent: getPercentChange(currentMonth.sales, previousMonth.sales),
+ },
+ ];
+
return (
- <>
- {[0, 2].map((startIndex) => (
- <Row
- key={startIndex}
- style={{
- width: "100%",
- ...(startIndex === 2 && { marginTop: "32px" }),
- }}
- >
- <Column width="50%">
- <Stats {...stats[startIndex]} />
+ <Section className="mt-5 rounded-xl border border-solid border-neutral-200 bg-neutral-50">
+ <Section className="rounded-t-xl px-3 py-2.5">
+ <Row>
+ <Column width={28} valign="middle">
+ <Img
+ src={getProgramLogo(program)}
+ width="20"
+ height="20"
+ alt={program.name}
+ className="rounded-full"
+ />
+ </Column>
+ <Column
+ valign="middle"
+ className="text-sm font-semibold leading-5 text-neutral-800"
+ >
+ {program.name}
</Column>
- <Column width="50%">
- <Stats {...stats[startIndex + 1]} />
+ <Column align="right" valign="middle">
+ <Link
+ href={getProgramUrl(program, reportingPeriod)}
+ className="box-border inline-block rounded-lg bg-neutral-900 px-2.5 py-1 text-sm font-medium leading-5 text-white no-underline"
+ style={{ whiteSpace: "nowrap" }}
+ >
+ View dashboard
+ </Link>
</Column>
</Row>
- ))}
- </>
+ </Section>
+
+ <Section className="rounded-xl border-t border-solid border-neutral-200 bg-white p-4">
+ {[0, 2].map((startIndex) => (
+ <Row
+ key={startIndex}
+ style={{
+ width: "100%",
+ ...(startIndex === 2 && { marginTop: "20px" }),
+ }}
+ >
+ <Column width="50%" style={{ paddingRight: "12px" }}>
+ <Stat {...stats[startIndex]} />
+ </Column>
+ <Column width="50%" style={{ paddingLeft: "12px" }}>
+ <Stat {...stats[startIndex + 1]} />
+ </Column>
+ </Row>
+ ))}
+ </Section>
+ </Section>
);
};
-const Stats = ({
+const Stat = ({
title,
+ icon,
value,
percent,
}: {
title: string;
- value: number | string;
- percent?: number;
+ icon: string;
+ value: string;
+ percent: number;
+}) => {
+ return (
+ <Row>
+ <Column width={48} valign="middle">
+ <div className="box-border h-9 w-9 rounded-md border border-solid border-neutral-200 text-center leading-9">
+ <Img
+ src={icon}
+ alt={title}
+ width="18"
+ height="18"
+ className="inline-block align-middle"
+ />
+ </div>
+ </Column>
+ <Column valign="middle">
+ <Text className="m-0 text-xs font-medium leading-4 text-neutral-500">
+ {title}
+ </Text>
+ <Text className="m-0 text-sm font-medium leading-5 text-neutral-800">
+ {value}
+ <PercentBadge percent={percent} className="ml-1.5" />
+ </Text>
+ </Column>
+ </Row>
+ );
+};
+
+const PercentBadge = ({
+ percent,
+ className,
+}: {
+ percent: number;
+ className?: string;
}) => {
- const icon = ICONS[title.toLowerCase() as Icon];
const { color, sign } = getPercentState(percent);
return (
- <div className="flex flex-row items-center bg-white p-0">
- <div className="flex rounded-md bg-neutral-100 p-3">
- <Img src={icon} alt={title} className="h-4 w-4" draggable={false} />
- </div>
- <div className="ml-3">
- <p className="mb-0 mt-0 text-left text-xs font-medium text-neutral-500">
- {title}
- </p>
- <div className="flex items-center">
- <p className="m-0 text-left text-lg font-medium text-neutral-800">
- {value}
- </p>
-
- {typeof percent === "number" && (
- <Text
- className={`m-0 ml-2 rounded text-xs font-medium ${color} m-auto px-1.5 py-0.5`}
- >
- {sign}
- {Math.abs(percent)}%
- </Text>
- )}
- </div>
- </div>
- </div>
+ <span
+ className={`rounded px-1 py-0.5 text-xs font-medium leading-4 ${color} ${className ?? ""}`}
+ >
+ {/* "–" means no change compared to the previous month */}
+ {percent === 0 ? "–" : `${sign}${Math.abs(percent)}%`}
+ </span>
+ );
+};
+
+const ProgramTable = ({
+ programs,
+ reportingPeriod,
+}: {
+ programs: ProgramSummary[];
+ reportingPeriod: ReportingPeriod;
+}) => {
+ return (
+ <Section className="mt-5">
+ <Row>
+ <Column className="pb-2.5 text-xs font-medium leading-4 text-neutral-500">
+ Program
+ </Column>
+ <Column
+ align="right"
+ className="pb-2.5 text-xs font-medium leading-4 text-neutral-500"
+ >
+ Earnings
+ </Column>
+ <Column
+ width={48}
+ className="pb-2.5 pl-5 text-xs font-medium leading-4 text-neutral-500"
+ >
+ Change
+ </Column>
+ </Row>
+
+ {programs.map((program) => {
+ const programUrl = getProgramUrl(program, reportingPeriod);
+
+ return (
+ <Row key={program.id}>
+ <Column className="py-2.5">
+ <Row>
+ <Column width={28} valign="middle">
+ <Link href={programUrl}>
+ <Img
+ src={getProgramLogo(program)}
+ width="20"
+ height="20"
+ alt={program.name}
+ className="rounded-full"
+ />
+ </Link>
+ </Column>
+ <Column valign="middle">
+ <Link
+ href={programUrl}
+ className="text-sm font-semibold leading-5 text-neutral-800 no-underline"
+ >
+ {program.name}
+ </Link>
+ </Column>
+ </Row>
+ </Column>
+ <Column align="right" valign="middle" className="py-2.5">
+ <Link
+ href={programUrl}
+ className="text-sm leading-5 text-neutral-800 no-underline"
+ >
+ {currencyFormatter(program.currentMonth.earnings)}
+ </Link>
+ </Column>
+ <Column width={48} valign="middle" className="py-2.5 pl-5">
+ <Link href={programUrl} className="no-underline">
+ <PercentBadge
+ percent={getPercentChange(
+ program.currentMonth.earnings,
+ program.previousMonth.earnings,
+ )}
+ />
+ </Link>
+ </Column>
+ </Row>
+ );
+ })}
+ </Section>
);
};