The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
finalize bounties/notify-partners cron
Steven Tey51f10f5cbc09
diff --git a/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts b/apps/web/app/(ee)/api/bounties/[bountyId]/route.tsindex 8cb2286f9a..87e440ccdc 100644--- a/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts+++ b/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts@@ -149,11 +149,11 @@ export const PATCH = withWorkspace(updatedBounty.startsAt &&updatedBounty.startsAt !== bounty.startsAt &&qstash.publishJSON({- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/bounties/published`,+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/bounties/notify-partners`,body: {bountyId: updatedBounty.id,},- notBefore: updatedBounty.startsAt.getTime(),+ notBefore: Math.floor(updatedBounty.startsAt.getTime() / 1000),}),]),);diff --git a/apps/web/app/(ee)/api/bounties/route.ts b/apps/web/app/(ee)/api/bounties/route.tsindex 3a60b318ea..d0dae5b40f 100644--- a/apps/web/app/(ee)/api/bounties/route.ts+++ b/apps/web/app/(ee)/api/bounties/route.ts@@ -159,12 +159,11 @@ export const POST = withWorkspace(}),qstash.publishJSON({- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/bounties/published`,+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/bounties/notify-partners`,body: {bountyId: bounty.id,},- // unix timestamp in milliseconds- notBefore: bounty.startsAt.getTime(),+ notBefore: Math.floor(bounty.startsAt.getTime() / 1000),}),]),);diff --git a/apps/web/app/(ee)/api/cron/bounties/notify-partners/route.ts b/apps/web/app/(ee)/api/cron/bounties/notify-partners/route.tsnew file mode 100644index 0000000000..fa5f0f0948--- /dev/null+++ b/apps/web/app/(ee)/api/cron/bounties/notify-partners/route.ts@@ -0,0 +1,135 @@+import { handleAndReturnErrorResponse } from "@/lib/api/errors";+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";+import { resend } from "@dub/email/resend";+import { VARIANT_TO_FROM_MAP } from "@dub/email/resend/constants";+import NewBountyAvailable from "@dub/email/templates/new-bounty-available";+import { prisma } from "@dub/prisma";+import { chunk, log } from "@dub/utils";+import { differenceInMinutes } from "date-fns";+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(0),+});++// POST /api/cron/bounties/notify-partners+// 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",+ });+ }++ let diffMinutes = differenceInMinutes(bounty.startsAt, new Date());++ if (diffMinutes >= 10) {+ return logAndRespond(+ `Bounty ${bountyId} not started yet, it will start at ${bounty.startsAt.toISOString()}`,+ );+ }++ // Find groupIds+ const groupIds = bounty.groups.map(({ groupId }) => groupId);++ let totalProgramEnrollments = 0;+ while (true) {+ // 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,+ },+ skip: totalProgramEnrollments,+ take: 5000,+ });++ if (programEnrollments.length === 0) {+ break;+ }++ totalProgramEnrollments += programEnrollments.length;++ const programEnrollmentChunks = chunk(programEnrollments, 100);++ for (const programEnrollmentChunk of programEnrollmentChunks) {+ console.log(+ `Sending emails to ${programEnrollmentChunk.length} partners: ${programEnrollmentChunk.map(({ partner }) => partner.email).join(", ")}`,+ );+ await resend?.batch.send(+ programEnrollmentChunk+ .filter(({ partner }) => partner.email)+ .map(({ partner }) => ({+ from: VARIANT_TO_FROM_MAP.notifications,+ to: partner.email!,+ subject: `New bounty available for ${bounty.program.name}`,+ react: NewBountyAvailable({+ email: partner.email!,+ bounty: {+ name: bounty.name!,+ type: bounty.type,+ endsAt: bounty.endsAt,+ description: bounty.description,+ },+ program: {+ name: bounty.program.name,+ slug: bounty.program.slug,+ },+ }),+ headers: {+ "Idempotency-Key": `${bountyId}-${partner.id}`,+ },+ })),+ );++ await new Promise((resolve) => setTimeout(resolve, 500));+ }+ }++ return logAndRespond(+ `Successfully sent bounty notification emails to ${totalProgramEnrollments} partners.`,+ );+ } 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/bounties/published/route.ts b/apps/web/app/(ee)/api/cron/bounties/published/route.tsdeleted file mode 100644index e0879e19b7..0000000000--- a/apps/web/app/(ee)/api/cron/bounties/published/route.ts+++ /dev/null@@ -1,139 +0,0 @@-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 NewBountyAvailable from "@dub/email/templates/new-bounty-available";-import { prisma } from "@dub/prisma";-import { APP_DOMAIN_WITH_NGROK, log } from "@dub/utils";-import { differenceInMinutes } from "date-fns";-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(0),-});--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",- });- }-- let diffMinutes = differenceInMinutes(bounty.startsAt, new Date());-- if (diffMinutes >= 10) {- return logAndRespond(- `Bounty ${bountyId} not started yet, it will start at ${bounty.startsAt.toISOString()}`,- );- }-- // 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}.`,- );- }-- console.log(- `Sending emails to ${programEnrollments.length} partners: ${programEnrollments.map(({ partner }) => partner.email).join(", ")}`,- );- await resend?.batch.send(- programEnrollments- .filter(({ partner }) => partner.email)- .map(({ partner }) => ({- from: VARIANT_TO_FROM_MAP.notifications,- to: partner.email!,- subject: `New bounty available for ${bounty.program.name}`,- react: NewBountyAvailable({- email: partner.email!,- bounty: {- name: bounty.name!,- type: bounty.type,- endsAt: bounty.endsAt,- description: bounty.description,- },- program: {- name: bounty.program.name,- 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/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty-sheet.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty-sheet.tsxindex cc28e8623b..d2c0f37268 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty-sheet.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty-sheet.tsx@@ -9,6 +9,7 @@ import {} from "@/lib/types";import { createBountySchema } from "@/lib/zod/schemas/bounties";import { workflowConditionSchema } from "@/lib/zod/schemas/workflows";+import { useConfirmModal } from "@/ui/modals/confirm-modal";import {BountyLogic,generateBountyName,@@ -129,6 +130,7 @@ function BountySheetContent({ setIsOpen, bounty }: BountySheetProps) {name,description,performanceCondition,+ groupIds,] = watch(["startsAt","endsAt",@@ -137,6 +139,7 @@ function BountySheetContent({ setIsOpen, bounty }: BountySheetProps) {"name","description","performanceCondition",+ "groupIds",]);// Make sure endsAt is null if hasEndDate is false@@ -165,6 +168,17 @@ function BountySheetContent({ setIsOpen, bounty }: BountySheetProps) {}}, [requireImage, requireUrl, setValue]);+ // Confirmation modal for bounty creation only+ const { setShowConfirmModal, confirmModal } = useConfirmModal({+ title: "Confirm bounty creation",+ description:+ "This will create the bounty and notify all partners in the selected partner groups. Are you sure you want to continue?",+ confirmText: "Confirm",+ onConfirm: async () => {+ await performSubmit();+ },+ });+// Decide if the submit button should be disabledconst shouldDisableSubmit = useMemo(() => {if (!startsAt || !rewardAmount) {@@ -200,8 +214,9 @@ function BountySheetContent({ setIsOpen, bounty }: BountySheetProps) {performanceCondition?.value,]);- // Handle form submission- const onSubmit = async (data: FormData) => {+ // Handle actual form submission (called after confirmation)+ const performSubmit = async () => {+ const data = form.getValues();if (!workspaceId) return;data.rewardAmount = data.rewardAmount * 100;@@ -249,8 +264,19 @@ function BountySheetContent({ setIsOpen, bounty }: BountySheetProps) {});};+ // Handle form submission (shows confirmation modal for creation only)+ const onSubmit = handleSubmit(async (data: FormData) => {+ if (bounty) {+ // For updates, submit directly without confirmation+ await performSubmit();+ } else {+ // For creation, show confirmation modal+ setShowConfirmModal(true);+ }+ });+return (- <form onSubmit={handleSubmit(onSubmit)} className="flex h-full flex-col">+ <form onSubmit={onSubmit} className="flex h-full flex-col"><div className="sticky top-0 z-10 border-b border-neutral-200 bg-white"><div className="flex h-16 items-center justify-between px-6 py-4"><Sheet.Title className="text-lg font-semibold">@@ -582,6 +608,7 @@ function BountySheetContent({ setIsOpen, bounty }: BountySheetProps) {</div></div></FormProvider>+ {!bounty && confirmModal}</form>);}