The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add cron route for sending bounty published emails
Kiran K407fb58f8c5a
diff --git a/apps/web/app/(ee)/api/bounties/route.ts b/apps/web/app/(ee)/api/bounties/route.tsindex dc880a0974..b8e85568d9 100644--- a/apps/web/app/(ee)/api/bounties/route.ts+++ b/apps/web/app/(ee)/api/bounties/route.ts@@ -3,6 +3,7 @@ import { createId } from "@/lib/api/create-id";import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";import { parseRequestBody } from "@/lib/api/utils";import { withWorkspace } from "@/lib/auth";+import { qstash } from "@/lib/cron";import { WorkflowAction } from "@/lib/types";import { sendWorkspaceWebhook } from "@/lib/webhook/publish";import {@@ -17,6 +18,7 @@ import {} from "@/lib/zod/schemas/workflows";import { prisma } from "@dub/prisma";import { Workflow } from "@dub/prisma/client";+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";import { waitUntil } from "@vercel/functions";import { NextResponse } from "next/server";import { z } from "zod";@@ -121,11 +123,21 @@ export const POST = withWorkspace(async ({ workspace, req }) => {});waitUntil(- sendWorkspaceWebhook({- workspace,- trigger: "bounty.created",- data: BountySchema.parse(bounty),- }),+ Promise.allSettled([+ sendWorkspaceWebhook({+ workspace,+ trigger: "bounty.created",+ data: BountySchema.parse(bounty),+ }),++ qstash.publishJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/bounties/published`,+ body: {+ bountyId: bounty.id,+ page: 1,+ },+ }),+ ]),);return NextResponse.json(BountySchema.parse(bounty));diff --git a/apps/web/app/(ee)/api/cron/bounties/published/route.ts b/apps/web/app/(ee)/api/cron/bounties/published/route.tsnew file mode 100644index 0000000000..8f0f4b180a--- /dev/null+++ b/apps/web/app/(ee)/api/cron/bounties/published/route.ts@@ -0,0 +1,126 @@+import { handleAndReturnErrorResponse } from "@/lib/api/errors";+import { qstash } from "@/lib/cron";+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";+import { resend } from "@dub/email/resend";+import { VARIANT_TO_FROM_MAP } from "@dub/email/resend/constants";+import BountyPublished from "@dub/email/templates/new-bounty-published";+import { prisma } from "@dub/prisma";+import { APP_DOMAIN_WITH_NGROK, log } from "@dub/utils";+import { z } from "zod";+import { logAndRespond } from "../../utils";++export const dynamic = "force-dynamic";++const schema = z.object({+ bountyId: z.string(),+ page: z.number().optional().default(1),+});++const PAGE_SIZE = 100;++// POST /api/cron/bounties/published+// Send emails to eligible partners about new bounty that is published+export async function POST(req: Request) {+ try {+ const rawBody = await req.text();++ await verifyQstashSignature({+ req,+ rawBody,+ });++ const { bountyId, page } = schema.parse(JSON.parse(rawBody));++ // Find bounty+ const bounty = await prisma.bounty.findUnique({+ where: {+ id: bountyId,+ },+ include: {+ groups: true,+ program: true,+ },+ });++ if (!bounty) {+ return logAndRespond(`Bounty ${bountyId} not found.`, {+ logLevel: "error",+ });+ }++ // Find groupIds+ const groupIds = bounty.groups.map(({ groupId }) => groupId);++ // Find programEnrollments+ const programEnrollments = await prisma.programEnrollment.findMany({+ where: {+ programId: bounty.programId,+ ...(groupIds.length > 0 && {+ groupId: {+ in: groupIds,+ },+ }),+ status: {+ in: ["approved", "invited"],+ },+ },+ include: {+ partner: true,+ },+ take: PAGE_SIZE,+ skip: (page - 1) * PAGE_SIZE,+ });++ if (programEnrollments.length === 0) {+ return logAndRespond(+ page === 1+ ? `No program enrollments found for bounty ${bountyId}.`+ : `No more program enrollments found for bounty ${bountyId}.`,+ );+ }++ await resend?.batch.send(+ programEnrollments+ .filter(({ partner }) => partner.email)+ .map(({ partner }) => ({+ from: VARIANT_TO_FROM_MAP.notifications,+ to: partner.email!,+ subject: "New bounty published",+ react: BountyPublished({+ email: partner.email!,+ bounty: {+ name: bounty.name!,+ type: bounty.type,+ endsAt: bounty.endsAt,+ description: bounty.description,+ },+ program: {+ slug: bounty.program.slug,+ },+ }),+ headers: {+ "Idempotency-Key": `${bountyId}-${partner.id}`,+ },+ })),+ );++ // Trigger next page+ const nextPage = page + 1;+ await qstash.publishJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/bounties/published`,+ body: {+ bountyId,+ page: nextPage,+ },+ });++ return logAndRespond(`Triggered cron for next page ${nextPage}.`);+ } catch (error) {+ await log({+ message: "New bounties published cron failed. Error: " + error.message,+ type: "errors",+ });++ return handleAndReturnErrorResponse(error);+ }+}diff --git a/apps/web/app/(ee)/api/cron/utils.ts b/apps/web/app/(ee)/api/cron/utils.tsnew file mode 100644index 0000000000..a3f24263c4--- /dev/null+++ b/apps/web/app/(ee)/api/cron/utils.ts@@ -0,0 +1,13 @@+export function logAndRespond(+ message: string,+ {+ status = 200,+ logLevel = "info",+ }: {+ status?: number;+ logLevel?: "error" | "warn" | "info";+ } = {},+) {+ console[logLevel](message);+ return new Response(message, { status });+}diff --git a/packages/email/src/components/bounty-thumbnail.tsx b/packages/email/src/components/bounty-thumbnail.tsxindex fe8bc09fbf..c94861b081 100644--- a/packages/email/src/components/bounty-thumbnail.tsx+++ b/packages/email/src/components/bounty-thumbnail.tsx@@ -20,7 +20,13 @@ export function BountyThumbnailImage({})}width={118}height={118}- className={cn("size-full object-contain", className)}+ className={cn("mx-auto my-auto object-contain", className)}+ style={{+ display: "block",+ margin: "0 auto",+ maxWidth: "118px",+ maxHeight: "118px",+ }}/>);}diff --git a/packages/email/src/templates/new-bounty-published.tsx b/packages/email/src/templates/new-bounty-published.tsxindex 69efa17cc4..9cd9923f1f 100644--- a/packages/email/src/templates/new-bounty-published.tsx+++ b/packages/email/src/templates/new-bounty-published.tsx@@ -17,7 +17,7 @@ import { Footer } from "../components/footer";export default function NewBountyPublished({bounty = {- name: "Promote Acme at your campus and earn $500 ",+ name: "Promote Acme at your campus and earn $500",type: "performance",endsAt: new Date(),description:@@ -55,7 +55,7 @@ export default function NewBountyPublished({</Heading><Section className="rounded-xl border border-solid border-neutral-200 bg-white">- <Section className="flex h-[140px] items-center justify-center rounded-none rounded-t-xl bg-neutral-100 py-1.5">+ <Section className="h-[140px] rounded-none rounded-t-xl bg-gray-50 py-1.5 text-center"><BountyThumbnailImage type={bounty.type} /></Section>@@ -81,10 +81,10 @@ export default function NewBountyPublished({</Section>)}- <Section className="px-6 pb-6">+ <Section className="px-6 pb-6 text-center"><Linkhref={`https://partners.dub.co/programs/${program.slug}/bounties`}- className="box-border block flex h-9 w-full items-center justify-center rounded-lg bg-black px-0 py-4 text-center text-sm leading-none text-white no-underline"+ className="box-border block w-full rounded-md bg-black px-2 py-4 text-center text-sm font-medium leading-none text-white no-underline">View bounty</Link>