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 cron job

Kiran K407ba9d61f4a
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 ee360a740d..0098b6d577 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,8 +1,14 @@
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { qstash } from "@/lib/cron";
+import { limiter } from "@/lib/cron/limiter";
import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
import { verifyVercelSignature } from "@/lib/cron/verify-vercel";
+import { sendEmail } from "@dub/email";
+import { PartnerProgramSummary } from "@dub/email/templates/partner-program-summary";
import { prisma } from "@dub/prisma";
-import { log } from "@dub/utils";
+import { Prisma } from "@dub/prisma/client";
+import { APP_DOMAIN_WITH_NGROK, log } from "@dub/utils";
+import { endOfMonth, startOfMonth, subMonths } from "date-fns";
import { NextResponse } from "next/server";
/*
@@ -24,17 +30,158 @@ async function handler(req: Request) {
}
const programs = await prisma.program.findMany({
- take: 10,
+ take: 1, // TODO: Fix this
+ skip: 0, // TODO: Fix this
orderBy: {
createdAt: "asc",
},
+ select: {
+ id: true,
+ name: true,
+ logo: true,
+ slug: true,
+ },
});
if (programs.length === 0) {
- console.info("No programs found.");
- return;
+ console.log("No programs found.");
+ return NextResponse.json("No programs found.");
+ }
+
+ const program = programs[0];
+
+ const programEnrollments = await prisma.programEnrollment.findMany({
+ where: {
+ programId: program.id,
+ status: "approved",
+ },
+ select: {
+ partner: {
+ select: {
+ id: true,
+ email: true,
+ },
+ },
+ },
+ });
+
+ if (programEnrollments.length === 0) {
+ console.info(`No active partners found for program ${program.id}.`);
+ return NextResponse.json(
+ `No active partners found for program ${program.id}.`,
+ );
}
+ const partners = programEnrollments.map((enrollment) => enrollment.partner);
+
+ // TODO
+ // Find analytics
+
+ const previousMonth = subMonths(new Date(), 1);
+
+ const commissionWhere: Prisma.CommissionWhereInput = {
+ earnings: {
+ gt: 0,
+ },
+ programId: program.id,
+ partnerId: {
+ in: partners.map((partner) => partner.id),
+ },
+ status: {
+ in: ["pending", "processed", "paid"],
+ },
+ };
+
+ const [earningsPreviousMonth, earningsLifetime] = await Promise.all([
+ prisma.commission.groupBy({
+ by: ["partnerId"],
+ where: {
+ ...commissionWhere,
+ createdAt: {
+ gte: startOfMonth(previousMonth),
+ lte: endOfMonth(previousMonth),
+ },
+ },
+ _sum: {
+ earnings: true,
+ },
+ }),
+
+ prisma.commission.groupBy({
+ by: ["partnerId"],
+ where: {
+ ...commissionWhere,
+ },
+ _sum: {
+ earnings: true,
+ },
+ }),
+ ]);
+
+ if (earningsLifetime.length === 0) {
+ console.log(`No commissions found for program ${program.id}.`);
+ return NextResponse.json(
+ `No commissions found for program ${program.id}.`,
+ );
+ }
+
+ const stats = partners.map((partner) => {
+ const earningsMonthly = earningsPreviousMonth.find(
+ (commission) => commission.partnerId === partner.id,
+ );
+
+ const earningsTotal = earningsLifetime.find(
+ (commission) => commission.partnerId === partner.id,
+ );
+
+ return {
+ partner,
+ earningsPreviousMonth: earningsMonthly?._sum.earnings ?? 0,
+ earningsLifetime: earningsTotal?._sum.earnings ?? 0,
+ };
+ });
+
+ if (stats.length === 0) {
+ console.log(`No stats found for program ${program.id}.`);
+ return NextResponse.json(`No stats found for program ${program.id}.`);
+ }
+
+ console.log(stats);
+ return;
+
+ await Promise.allSettled(
+ stats.map(({ partner, earningsPreviousMonth, earningsLifetime }) => {
+ limiter.schedule(() =>
+ sendEmail({
+ subject: `${program.name} partner program summary`,
+ email: partner.email!,
+ react: PartnerProgramSummary({
+ program,
+ partner,
+ currentMonth: {
+ clicks: 0,
+ leads: 0,
+ sales: 0,
+ earnings: earningsPreviousMonth,
+ },
+ lifetime: {
+ clicks: 0,
+ leads: 0,
+ sales: 0,
+ earnings: earningsLifetime,
+ },
+ }),
+ }),
+ );
+ }),
+ );
+
+ await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/partner-program-summary`,
+ method: "POST",
+ body: {},
+ });
+
return NextResponse.json("Ok");
} catch (error) {
await log({
diff --git a/apps/web/vercel.json b/apps/web/vercel.json
index 8edbed602d..d534ee0edb 100644
--- a/apps/web/vercel.json
+++ b/apps/web/vercel.json
@@ -35,6 +35,10 @@
{
"path": "/api/cron/payouts/reminders",
"schedule": "0 14 * * *"
+ },
+ {
+ "path": "/api/cron/partner-program-summary",
+ "schedule": "0 1 1 * *"
}
],
"functions": {
diff --git a/packages/email/src/templates/partner-program-summary.tsx b/packages/email/src/templates/partner-program-summary.tsx
index d63c3637d9..73bb6c2b4c 100644
--- a/packages/email/src/templates/partner-program-summary.tsx
+++ b/packages/email/src/templates/partner-program-summary.tsx
@@ -33,13 +33,13 @@ export function PartnerProgramSummary({
partner = {
},
- monthlyPerformance = {
+ currentMonth: monthlyPerformance = {
clicks: 100,
leads: 100,
sales: 100,
earnings: 100,
},
- lifetimePerformance = {
+ lifetime: lifetimePerformance = {
clicks: 200,
leads: 200,
sales: 200,
@@ -48,19 +48,19 @@ export function PartnerProgramSummary({
}: {
program: {
name: string;
- logo: string;
+ logo: string | null;
slug: string;
};
partner: {
- email: string;
+ email: string | null;
};
- monthlyPerformance: {
+ currentMonth: {
clicks: number;
leads: number;
sales: number;
earnings: number;
};
- lifetimePerformance: {
+ lifetime: {
clicks: number;
leads: number;
sales: number;
@@ -105,26 +105,31 @@ export function PartnerProgramSummary({
},
];
+ const currentMonth = new Date().toLocaleString("en-US", {
+ month: "long",
+ });
+
return (
<Html>
<Head />
- <Preview>
- Your application to join {program.name}'s partner program has been
- approved!
- </Preview>
+ <Preview>{`Your ${currentMonth} performance report for ${program.name} program.`}</Preview>
<Tailwind>
<Body className="mx-auto my-auto bg-white font-sans">
<Container className="mx-auto my-10 max-w-[600px] space-y-10 rounded border border-solid border-neutral-200 px-10 py-5">
<Section className="mt-8">
- <Img src={program.logo} height="32" alt={program.name} />
+ <Img
+ src={program.logo || DUB_WORDMARK}
+ height="32"
+ alt={program.name}
+ />
</Section>
<Heading className="mx-0 mt-[40px] p-0 text-lg font-medium text-black">
- Partner program weekly report
+ {program.name} partner program monthly summary
</Heading>
<Text className="text-sm text-neutral-600">
- Here's a summary of your activity for the week of Apr 1-8, 2025.
+ Here's a summary of your activity for the month of {currentMonth}.
</Text>
<Section className="mb-8">
@@ -132,7 +137,7 @@ export function PartnerProgramSummary({
as="h4"
className="text-base font-semibold leading-6 text-neutral-800"
>
- Weekly Stats
+ Monthly Stats
</Heading>
<div className="grid grid-cols-2 gap-x-3 gap-y-8">
@@ -168,7 +173,7 @@ export function PartnerProgramSummary({
</Link>
</Section>
- <Footer email={partner.email} />
+ <Footer email={partner.email!} />
</Container>
</Body>
</Tailwind>