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.

Improve reward sync cron job (#3944)

Kiran K0c408286a871
diff --git a/apps/web/app/(ee)/api/cron/cleanup/orphaned-rewards/route.ts b/apps/web/app/(ee)/api/cron/cleanup/orphaned-rewards/route.ts
new file mode 100644
index 0000000000..14918a3c01
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/cleanup/orphaned-rewards/route.ts
@@ -0,0 +1,84 @@
+import { withCron } from "@/lib/cron/with-cron";
+import { REWARD_EVENT_COLUMN_MAPPING } from "@/lib/zod/schemas/rewards";
+import { prisma } from "@dub/prisma";
+import { subMinutes } from "date-fns";
+import { logAndRespond } from "../../utils";
+
+export const dynamic = "force-dynamic";
+
+// The rewards/process cron normally hard-deletes once enrollments are cleared, but a newer
+// reward change for the same group + event type can bump the version and skip stale jobs
+// (e.g. delete then create), leaving the old row behind. This job is a safety net for those orphans.
+
+const REWARD_BATCH_SIZE = 10;
+
+// GET /api/cron/cleanup/orphaned-rewards
+export const GET = withCron(async () => {
+ const rewards = await prisma.reward.findMany({
+ where: {
+ programId: null,
+ updatedAt: {
+ lt: subMinutes(new Date(), 30), // 30 minutes ago
+ },
+ },
+ select: {
+ id: true,
+ event: true,
+ },
+ orderBy: {
+ updatedAt: "asc",
+ },
+ take: REWARD_BATCH_SIZE,
+ });
+
+ if (rewards.length === 0) {
+ return logAndRespond("No orphaned rewards found.");
+ }
+
+ for (const reward of rewards) {
+ const rewardIdColumn = REWARD_EVENT_COLUMN_MAPPING[reward.event];
+
+ const [partnerGroupCount, programEnrollmentCount] = await Promise.all([
+ prisma.partnerGroup.count({
+ where: {
+ [rewardIdColumn]: reward.id,
+ },
+ }),
+
+ prisma.programEnrollment.count({
+ where: {
+ [rewardIdColumn]: reward.id,
+ },
+ }),
+ ]);
+
+ // Ideally this should never happen, but just in case
+ if (partnerGroupCount > 0) {
+ console.log(
+ `Reward ${reward.id} is referenced by ${partnerGroupCount} partner groups. Skipping...`,
+ );
+ continue;
+ }
+
+ if (programEnrollmentCount > 0) {
+ console.log(
+ `Reward ${reward.id} is referenced by ${programEnrollmentCount} program enrollments. Skipping...`,
+ );
+ continue;
+ }
+
+ try {
+ await prisma.reward.delete({
+ where: {
+ id: reward.id,
+ },
+ });
+
+ console.log(`Deleted reward ${reward.id}.`);
+ } catch (error) {
+ console.error(`Error deleting reward ${reward.id}`, error);
+ }
+ }
+
+ return logAndRespond("Finished deleting orphaned rewards.");
+});
diff --git a/apps/web/app/(ee)/api/cron/rewards/process/route.ts b/apps/web/app/(ee)/api/cron/rewards/process/route.ts
new file mode 100644
index 0000000000..658ca928dc
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/rewards/process/route.ts
@@ -0,0 +1,213 @@
+import { notifyPartnerRewardChange } from "@/lib/api/partners/notify-partner-reward-change";
+import {
+ queueRewardProcessing,
+ rewardJobSchema,
+} from "@/lib/api/rewards/queue-reward-processing";
+import { isStaleRewardVersion } from "@/lib/api/rewards/reward-version";
+import { withCron } from "@/lib/cron/with-cron";
+import { INACTIVE_ENROLLMENT_STATUSES } from "@/lib/zod/schemas/partners";
+import { REWARD_EVENT_COLUMN_MAPPING } from "@/lib/zod/schemas/rewards";
+import { prisma } from "@dub/prisma";
+import { Prisma } from "@dub/prisma/client";
+import { logAndRespond } from "../../utils";
+
+export const dynamic = "force-dynamic";
+
+// POST /api/cron/rewards/process
+export const POST = withCron(async ({ rawBody }) => {
+ const input = rewardJobSchema.parse(JSON.parse(rawBody));
+
+ const {
+ event,
+ groupId,
+ version,
+ occurredAt,
+ batchNumber,
+ rewardSnapshot,
+ startAfterProgramEnrollmentId,
+ } = input;
+
+ const { id: rewardId } = rewardSnapshot;
+
+ const reward = await prisma.reward.findUnique({
+ where: {
+ id: rewardId,
+ },
+ select: {
+ id: true,
+ event: true,
+ },
+ });
+
+ if (!reward) {
+ return logAndRespond(`Reward ${rewardId} not found. Skipping...`);
+ }
+
+ const group = await prisma.partnerGroup.findUnique({
+ where: {
+ id: groupId,
+ },
+ select: {
+ id: true,
+ program: {
+ select: {
+ id: true,
+ name: true,
+ slug: true,
+ logo: true,
+ supportEmail: true,
+ },
+ },
+ },
+ });
+
+ if (!group) {
+ return logAndRespond(`Group ${groupId} not found. Skipping...`);
+ }
+
+ const isStaleVersion = await isStaleRewardVersion({
+ version,
+ groupId,
+ event: rewardSnapshot.event,
+ });
+
+ if (isStaleVersion) {
+ return logAndRespond(
+ "Reward changed while processing. Skipping stale reward evaluation.",
+ );
+ }
+
+ const rewardIdColumn = REWARD_EVENT_COLUMN_MAPPING[reward.event];
+
+ let startingAfter = startAfterProgramEnrollmentId;
+ let where: Prisma.ProgramEnrollmentWhereInput | undefined = undefined;
+ let data: Prisma.ProgramEnrollmentUpdateManyArgs["data"] | undefined =
+ undefined;
+
+ switch (event) {
+ case "reward-created":
+ data = { [rewardIdColumn]: reward.id };
+ break;
+
+ case "reward-updated":
+ where = { [rewardIdColumn]: reward.id };
+ break;
+
+ case "reward-deleted":
+ data = { [rewardIdColumn]: null };
+ break;
+ }
+
+ const programEnrollments = await prisma.programEnrollment.findMany({
+ where: {
+ groupId: group.id,
+ status: {
+ notIn: INACTIVE_ENROLLMENT_STATUSES,
+ },
+ ...(startAfterProgramEnrollmentId && {
+ id: {
+ gt: startAfterProgramEnrollmentId,
+ },
+ }),
+ ...where,
+ },
+ select: {
+ id: true,
+ partner: {
+ select: {
+ users: {
+ where: {
+ user: {
+ email: {
+ not: null,
+ },
+ },
+ },
+ select: {
+ user: {
+ select: {
+ name: true,
+ email: true,
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ orderBy: {
+ id: "asc",
+ },
+ take: 300,
+ });
+
+ if (programEnrollments.length > 0) {
+ let shouldNotify = !data;
+
+ // Only when event is "reward-created" or "reward-deleted"
+ if (data) {
+ const { count } = await prisma.programEnrollment.updateMany({
+ where: {
+ id: {
+ in: programEnrollments.map(({ id }) => id),
+ },
+ },
+ data: {
+ ...data,
+ },
+ });
+
+ shouldNotify = count > 0;
+ }
+
+ if (shouldNotify) {
+ const users = programEnrollments.flatMap(({ partner }) =>
+ partner.users.map(({ user }) => user),
+ );
+
+ await notifyPartnerRewardChange({
+ action: event,
+ program: group.program,
+ reward,
+ rewardSnapshot,
+ effectiveAt: occurredAt,
+ users,
+ idempotencyKey: `partner-reward-change-${rewardId}-${batchNumber}-${version}`,
+ });
+ }
+
+ startingAfter = programEnrollments[programEnrollments.length - 1].id;
+
+ await queueRewardProcessing({
+ ...input,
+ startAfterProgramEnrollmentId: startingAfter,
+ batchNumber: batchNumber + 1,
+ });
+
+ return logAndRespond(
+ `Enqueued next batch (${batchNumber + 1}) for reward ${rewardId} for the group ${groupId}.`,
+ );
+ }
+
+ // No more program enrollments found, hard delete the reward
+ if (event === "reward-deleted") {
+ try {
+ await prisma.reward.delete({
+ where: {
+ id: reward.id,
+ },
+ });
+ } catch (error) {
+ // Treat already-deleted reward as success so retries can resend the notification
+ if (!(error.code === "P2025")) {
+ throw new Error(
+ `Failed to hard delete reward ${reward.id}: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+ }
+ }
+
+ return logAndRespond(
+ `Finished processing reward ${rewardId} for the group ${groupId}.`,
+ );
+});
diff --git a/apps/web/app/(ee)/api/cron/rewards/sync-enrollments/route.ts b/apps/web/app/(ee)/api/cron/rewards/sync-enrollments/route.ts
deleted file mode 100644
index 77a2574fd4..0000000000
--- a/apps/web/app/(ee)/api/cron/rewards/sync-enrollments/route.ts
+++ /dev/null
@@ -1,202 +0,0 @@
-import { handleAndReturnErrorResponse } from "@/lib/api/errors";
-import { notifyPartnersRewardChanged } from "@/lib/api/partners/notify-partners-reward-changed";
-import { serializeReward } from "@/lib/api/partners/serialize-reward";
-import {
- queueRewardEnrollmentSync,
- RewardSnapshot,
-} from "@/lib/api/rewards/queue-reward-enrollment-sync";
-import { CRON_BATCH_SIZE } from "@/lib/cron";
-import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
-import { REWARD_EVENT_COLUMN_MAPPING } from "@/lib/zod/schemas/rewards";
-import { prisma } from "@dub/prisma";
-import { EventType, Prisma } from "@dub/prisma/client";
-import { log } from "@dub/utils";
-import * as z from "zod/v4";
-import { logAndRespond } from "../../utils";
-
-export const dynamic = "force-dynamic";
-
-const schema = z.object({
- action: z.enum(["create", "delete"]),
- rewardId: z.string(),
- groupId: z.string(),
- programId: z.string(),
- event: z.enum(EventType),
- startAfterProgramEnrollmentId: z.string().optional(),
- rewardSnapshot: z
- .object({
- title: z.string(),
- description: z.string(),
- icon: z.string(),
- })
- .optional(),
-});
-
-// POST /api/cron/rewards/sync-enrollments
-export async function POST(req: Request) {
- try {
- const rawBody = await req.text();
- await verifyQstashSignature({ req, rawBody });
-
- const {
- action,
- rewardId,
- groupId,
- programId,
- event,
- startAfterProgramEnrollmentId,
- rewardSnapshot,
- } = schema.parse(JSON.parse(rawBody));
-
- const rewardIdColumn = REWARD_EVENT_COLUMN_MAPPING[event];
-
- const enrollmentWhere: Prisma.ProgramEnrollmentWhereInput =
- action === "create"
- ? {
- groupId,
- [rewardIdColumn]: null,
- }
- : {
- [rewardIdColumn]: rewardId,
- };
-
- const programEnrollments = await prisma.programEnrollment.findMany({
- where: {
- ...enrollmentWhere,
- ...(startAfterProgramEnrollmentId && {
- id: {
- gt: startAfterProgramEnrollmentId,
- },
- }),
- },
- select: {
- id: true,
- },
- take: CRON_BATCH_SIZE,
- orderBy: {
- id: "asc",
- },
- });
-
- console.log(
- `Found ${programEnrollments.length} enrollments to ${action} ${event} reward ${rewardId}.`,
- );
-
- if (programEnrollments.length > 0) {
- const updatedEnrollments = await prisma.programEnrollment.updateMany({
- where: {
- id: {
- in: programEnrollments.map(({ id }) => id),
- },
- },
- data: {
- [rewardIdColumn]: action === "create" ? rewardId : null,
- },
- });
-
- console.log(
- `Updated ${updatedEnrollments.count} enrollments to ${action} ${event} reward ${rewardId}.`,
- );
- }
-
- const remainingEnrollments = await prisma.programEnrollment.count({
- where: enrollmentWhere,
- });
-
- if (remainingEnrollments > 0) {
- if (programEnrollments.length === 0) {
- return logAndRespond(
- `Found ${remainingEnrollments} remaining enrollments for reward ${rewardId}, but no enrollments were processed. Skipping...`,
- { logLevel: "error" },
- );
- }
-
- await queueRewardEnrollmentSync({
- action,
- rewardId,
- groupId,
- programId,
- event,
- startAfterProgramEnrollmentId:
- programEnrollments[programEnrollments.length - 1].id,
- rewardSnapshot: rewardSnapshot as RewardSnapshot | undefined,
- });
-
- return logAndRespond(
- `Updated ${programEnrollments.length} enrollments for reward ${rewardId}, ${remainingEnrollments} remaining. Starting next batch...`,
- );
- }
-
- const effectiveAt = new Date();
-
- if (action === "delete") {
- try {
- await prisma.reward.delete({
- where: {
- id: rewardId,
- },
- });
- } catch (error) {
- // treat already-deleted reward as success so retries can resend the notification
- if (error.code !== "P2025") {
- await log({
- message: `Failed to hard delete reward ${rewardId}: ${error.message}`,
- type: "errors",
- });
-
- return logAndRespond(
- `Finished syncing enrollments for reward ${rewardId}, but hard delete failed.`,
- {
- logLevel: "error",
- },
- );
- }
- }
-
- await notifyPartnersRewardChanged({
- programId,
- groupId,
- action: "removed",
- effectiveAt,
- rewardSnapshot,
- idempotencyKey: `reward-sync-${rewardId}-removed`,
- });
-
- return logAndRespond(
- `Finished syncing enrollments and deleted reward ${rewardId}.`,
- );
- }
-
- const reward = await prisma.reward.findUnique({
- where: {
- id: rewardId,
- },
- });
-
- if (!reward) {
- return logAndRespond(`Reward ${rewardId} not found. Skipping email...`, {
- logLevel: "error",
- });
- }
-
- await notifyPartnersRewardChanged({
- programId,
- groupId,
- action: "added",
- effectiveAt,
- reward: serializeReward(reward),
- idempotencyKey: `reward-sync-${rewardId}-added`,
- });
-
- return logAndRespond(
- `Finished syncing enrollments for created reward ${rewardId}.`,
- );
- } catch (error) {
- await log({
- message: `Error syncing reward enrollments: ${error.message}.`,
- type: "errors",
- });
-
- return handleAndReturnErrorResponse(error);
- }
-}
diff --git a/apps/web/lib/actions/partners/create-reward.ts b/apps/web/lib/actions/partners/create-reward.ts
index 298c675e0a..f529253b7e 100644
--- a/apps/web/lib/actions/partners/create-reward.ts
+++ b/apps/web/lib/actions/partners/create-reward.ts
@@ -6,13 +6,14 @@ import { createId } from "@/lib/api/create-id";
import { getGroupOrThrow } from "@/lib/api/groups/get-group-or-throw";
import { serializeReward } from "@/lib/api/partners/serialize-reward";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
-import { queueRewardEnrollmentSync } from "@/lib/api/rewards/queue-reward-enrollment-sync";
+import { queueRewardProcessing } from "@/lib/api/rewards/queue-reward-processing";
import { validateReward } from "@/lib/api/rewards/validate-reward";
import { getPlanCapabilities } from "@/lib/plan-capabilities";
import {
createRewardSchema,
REWARD_EVENT_COLUMN_MAPPING,
} from "@/lib/zod/schemas/rewards";
+import { formatRewardDescription } from "@/ui/partners/format-reward-description";
import { prisma } from "@dub/prisma";
import { Prisma } from "@dub/prisma/client";
import { waitUntil } from "@vercel/functions";
@@ -108,12 +109,17 @@ export const createRewardAction = authActionClient
return reward;
});
- await queueRewardEnrollmentSync({
- action: "create",
- rewardId: reward.id,
+ await queueRewardProcessing({
+ event: "reward-created",
groupId,
- programId,
- event,
+ occurredAt: new Date().toISOString(),
+ rewardSnapshot: {
+ id: reward.id,
+ event: reward.event,
+ description: formatRewardDescription(serializeReward(reward), {
+ includeEarnPrefix: false,
+ }),
+ },
});
waitUntil(
diff --git a/apps/web/lib/actions/partners/delete-reward.ts b/apps/web/lib/actions/partners/delete-reward.ts
index 39f5ed42d1..9a5634350d 100644
--- a/apps/web/lib/actions/partners/delete-reward.ts
+++ b/apps/web/lib/actions/partners/delete-reward.ts
@@ -3,10 +3,11 @@
import { trackRewardActivityLog } from "@/lib/api/activity-log/track-reward-activity-log";
import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
import { getRewardOrThrow } from "@/lib/api/partners/get-reward-or-throw";
-import { getRewardEmailSnapshot } from "@/lib/api/partners/notify-partners-reward-changed";
+import { serializeReward } from "@/lib/api/partners/serialize-reward";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
-import { queueRewardEnrollmentSync } from "@/lib/api/rewards/queue-reward-enrollment-sync";
+import { queueRewardProcessing } from "@/lib/api/rewards/queue-reward-processing";
import { REWARD_EVENT_COLUMN_MAPPING } from "@/lib/zod/schemas/rewards";
+import { formatRewardDescription } from "@/ui/partners/format-reward-description";
import { prisma } from "@dub/prisma";
import { waitUntil } from "@vercel/functions";
import * as z from "zod/v4";
@@ -37,39 +38,47 @@ export const deleteRewardAction = authActionClient
});
const rewardIdColumn = REWARD_EVENT_COLUMN_MAPPING[reward.event];
- const rewardSnapshot = getRewardEmailSnapshot(reward);
- const partnerGroup = await prisma.$transaction(async (tx) => {
- const group = await tx.partnerGroup.update({
- // @ts-ignore
- where: {
- [rewardIdColumn]: reward.id,
- },
- data: {
- [rewardIdColumn]: null,
- },
- });
+ const { partnerGroup, deletedReward } = await prisma.$transaction(
+ async (tx) => {
+ const partnerGroup = await tx.partnerGroup.update({
+ // @ts-ignore
+ where: {
+ [rewardIdColumn]: reward.id,
+ },
+ data: {
+ [rewardIdColumn]: null,
+ },
+ });
- // soft delete reward, we will hard delete it in the cron job
- await tx.reward.update({
- where: {
- id: reward.id,
- },
- data: {
- programId: null,
- },
- });
+ // soft delete reward, we will hard delete it in the cron job
+ const deletedReward = await tx.reward.update({
+ where: {
+ id: reward.id,
+ },
+ data: {
+ programId: null,
+ },
+ });
- return group;
- });
+ return {
+ partnerGroup,
+ deletedReward,
+ };
+ },
+ );
- await queueRewardEnrollmentSync({
- action: "delete",
- rewardId: reward.id,
+ await queueRewardProcessing({
+ event: "reward-deleted",
groupId: partnerGroup.id,
- programId,
- event: reward.event,
- rewardSnapshot,
+ occurredAt: new Date().toISOString(),
+ rewardSnapshot: {
+ id: deletedReward.id,
+ event: deletedReward.event,
+ description: formatRewardDescription(serializeReward(deletedReward), {
+ includeEarnPrefix: false,
+ }),
+ },
});
waitUntil(
@@ -95,7 +104,7 @@ export const deleteRewardAction = authActionClient
userId: user.id,
resourceId: reward.id,
parentResourceType: "group",
- parentResourceId: partnerGroup?.id,
+ parentResourceId: partnerGroup.id,
old: reward,
new: null,
}),
diff --git a/apps/web/lib/actions/partners/update-reward.ts b/apps/web/lib/actions/partners/update-reward.ts
index db62e7ea6d..47c9411f57 100644
--- a/apps/web/lib/actions/partners/update-reward.ts
+++ b/apps/web/lib/actions/partners/update-reward.ts
@@ -3,12 +3,13 @@
import { trackRewardActivityLog } from "@/lib/api/activity-log/track-reward-activity-log";
import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
import { getRewardOrThrow } from "@/lib/api/partners/get-reward-or-throw";
-import { notifyPartnersRewardChanged } from "@/lib/api/partners/notify-partners-reward-changed";
import { serializeReward } from "@/lib/api/partners/serialize-reward";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { queueRewardProcessing } from "@/lib/api/rewards/queue-reward-processing";
import { validateReward } from "@/lib/api/rewards/validate-reward";
import { getPlanCapabilities } from "@/lib/plan-capabilities";
import { updateRewardSchema } from "@/lib/zod/schemas/rewards";
+import { formatRewardDescription } from "@/ui/partners/format-reward-description";
import { prisma } from "@dub/prisma";
import { Prisma } from "@dub/prisma/client";
import { waitUntil } from "@vercel/functions";
@@ -117,6 +118,23 @@ export const updateRewardAction = authActionClient
salePartnerGroup ||
referralPartnerGroup;
+ if (!partnerGroup) {
+ throw new Error("Partner group not found.");
+ }
+
+ await queueRewardProcessing({
+ event: "reward-updated",
+ groupId: partnerGroup.id,
+ occurredAt: new Date().toISOString(),
+ rewardSnapshot: {
+ id: reward.id,
+ event: reward.event,
+ description: formatRewardDescription(serializeReward(updatedReward), {
+ includeEarnPrefix: false,
+ }),
+ },
+ });
+
waitUntil(
Promise.allSettled([
recordAuditLog({
@@ -140,7 +158,7 @@ export const updateRewardAction = authActionClient
userId: user.id,
resourceId: rewardMetadata.id,
parentResourceType: "group",
- parentResourceId: partnerGroup?.id,
+ parentResourceId: partnerGroup.id,
old: reward,
new: updatedReward,
}),
@@ -156,16 +174,6 @@ export const updateRewardAction = authActionClient
),
]
: []),
-
- partnerGroup &&
- notifyPartnersRewardChanged({
- programId,
- groupId: partnerGroup.id,
- action: "updated",
- effectiveAt: updatedReward.updatedAt,
- reward: serializeReward(rewardMetadata),
- idempotencyKey: `reward-sync-${rewardId}-updated-${updatedReward.updatedAt.getTime()}`,
- }),
]),
);
});
diff --git a/apps/web/lib/api/partners/notify-partner-reward-change.ts b/apps/web/lib/api/partners/notify-partner-reward-change.ts
new file mode 100644
index 0000000000..d7b0caa257
--- /dev/null
+++ b/apps/web/lib/api/partners/notify-partner-reward-change.ts
@@ -0,0 +1,71 @@
+import type { RewardJob } from "@/lib/api/rewards/queue-reward-processing";
+import { queueBatchEmail } from "@/lib/email/queue-batch-email";
+import { RewardProps } from "@/lib/types";
+import type PartnerRewardUpdated from "@dub/email/templates/partner-reward-updated";
+import { Program, Reward, User } from "@dub/prisma/client";
+
+const REWARD_ICONS: Record<RewardProps["event"], string> = {
+ click: "https://assets.dub.co/email-assets/icons/cursor-rays.png",
+ lead: "https://assets.dub.co/email-assets/icons/user-plus.png",
+ sale: "https://assets.dub.co/email-assets/icons/invoice-dollar.png",
+ referral: "https://assets.dub.co/email-assets/icons/nodes-4.png",
+};
+
+interface NotifyPartnerRewardChangeParams {
+ action: RewardJob["event"];
+ program: Pick<Program, "id" | "name" | "logo" | "slug" | "supportEmail">;
+ reward: Pick<Reward, "id" | "event">;
+ rewardSnapshot: { description: string };
+ effectiveAt: Date | string;
+ users: Pick<User, "name" | "email">[];
+ idempotencyKey: string;
+}
+
+export async function notifyPartnerRewardChange({
+ action,
+ program,
+ reward,
+ rewardSnapshot,
+ effectiveAt,
+ users,
+ idempotencyKey,
+}: NotifyPartnerRewardChangeParams) {
+ const usersWithEmail = users.filter(
+ (user): user is Pick<User, "name"> & { email: string } =>
+ user.email !== null,
+ );
+
+ if (usersWithEmail.length === 0) {
+ return;
+ }
+
+ await queueBatchEmail<typeof PartnerRewardUpdated>(
+ usersWithEmail.map((user) => ({
+ to: user.email,
+ subject: `Your rewards for ${program.name} have been updated`,
+ variant: "notifications",
+ templateName: "PartnerRewardUpdated",
+ templateProps: {
+ program: {
+ name: program.name,
+ logo: program.logo,
+ slug: program.slug,
+ supportEmail: program.supportEmail,
+ },
+ partner: {
+ name: user.name ?? "",
+ email: user.email,
+ },
+ rewardSnapshot: {
+ description: rewardSnapshot.description,
+ icon: REWARD_ICONS[reward.event],
+ },
+ effectiveAt,
+ action,
+ },
+ })),
+ {
+ idempotencyKey,
+ },
+ );
+}
diff --git a/apps/web/lib/api/partners/notify-partners-reward-changed.ts b/apps/web/lib/api/partners/notify-partners-reward-changed.ts
deleted file mode 100644
index 321f3e9a10..0000000000
--- a/apps/web/lib/api/partners/notify-partners-reward-changed.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-import type { RewardSnapshot } from "@/lib/api/rewards/queue-reward-enrollment-sync";
-import { queueBatchEmail } from "@/lib/email/queue-batch-email";
-import { RewardProps } from "@/lib/types";
-import { formatRewardDescription } from "@/ui/partners/format-reward-description";
-import { REWARD_EVENT_DESCRIPTIONS } from "@/ui/partners/rewards/reward-event-descriptions";
-import type PartnerRewardsUpdated from "@dub/email/templates/partner-rewards-updated";
-import { prisma } from "@dub/prisma";
-
-const REWARD_ICONS: Record<RewardProps["event"], string> = {
- click: "https://assets.dub.co/email-assets/icons/cursor-rays.png",
- lead: "https://assets.dub.co/email-assets/icons/user-plus.png",
- sale: "https://assets.dub.co/email-assets/icons/invoice-dollar.png",
- referral: "https://assets.dub.co/email-assets/icons/nodes-4.png",
-};
-
-type RewardChangeAction = "added" | "updated" | "removed";
-
-interface NotifyPartnersRewardChangedParams {
- programId: string;
- groupId: string;
- action: RewardChangeAction;
- effectiveAt: Date;
- reward?: RewardProps;
- rewardSnapshot?: RewardSnapshot;
- idempotencyKey?: string;
-}
-
-export function getRewardEmailSnapshot(reward: RewardProps): RewardSnapshot {
- return {
- title: REWARD_EVENT_DESCRIPTIONS[reward.event].title,
- description: formatRewardDescription(reward, {
- includeEarnPrefix: false,
- }),
- icon: REWARD_ICONS[reward.event],
- };
-}
-
-export async function notifyPartnersRewardChanged({
- programId,
- groupId,
- action,
- effectiveAt,
- reward,
- rewardSnapshot,
- idempotencyKey,
-}: NotifyPartnersRewardChangedParams) {
- const snapshot =
- rewardSnapshot ?? (reward ? getRewardEmailSnapshot(reward) : null);
-
- if (!snapshot) {
- console.log(`No snapshot found for reward ${reward?.id}.`);
- return;
- }
-
- const program = await prisma.program.findUnique({
- where: {
- id: programId,
- },
- include: {
- partners: {
- where: {
- groupId,
- partner: {
- email: {
- not: null,
- },
- },
- },
- include: {
- partner: true,
- },
- },
- },
- });
- if (!program) {
- console.log(
- `No program with partners found for program ${programId} and group ${groupId}.`,
- );
- return;
- }
-
- const partnersToNotify = program.partners.map(({ partner }) => partner);
-
- await queueBatchEmail<typeof PartnerRewardsUpdated>(
- partnersToNotify.map((partner) => ({
- to: partner.email!,
- subject: `Your rewards for ${program.name} have been updated`,
- variant: "notifications",
- templateName: "PartnerRewardsUpdated",
- templateProps: {
- program: {
- name: program.name,
- logo: program.logo,
- slug: program.slug,
- supportEmail: program.supportEmail,
- },
- partner: {
- name: partner.name,
- email: partner.email!,
- },
- effectiveAt,
- changes: [
- {
- action,
- title: snapshot.title,
- description: snapshot.description,
- icon: snapshot.icon,
- },
- ],
- },
- })),
- idempotencyKey ? { idempotencyKey } : undefined,
- );
-}
diff --git a/apps/web/lib/api/rewards/queue-reward-enrollment-sync.ts b/apps/web/lib/api/rewards/queue-reward-enrollment-sync.ts
deleted file mode 100644
index c79d263ded..0000000000
--- a/apps/web/lib/api/rewards/queue-reward-enrollment-sync.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { qstash } from "@/lib/cron";
-import { EventType } from "@dub/prisma/client";
-import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
-
-export interface RewardSnapshot {
- title: string;
- description: string;
- icon: string;
-}
-
-export interface QueueRewardEnrollmentSyncProps {
- action: "create" | "delete";
- rewardId: string;
- groupId: string;
- programId: string;
- event: EventType;
- startAfterProgramEnrollmentId?: string;
- rewardSnapshot?: RewardSnapshot;
-}
-
-export async function queueRewardEnrollmentSync({
- action,
- rewardId,
- groupId,
- programId,
- event,
- startAfterProgramEnrollmentId,
- rewardSnapshot,
-}: QueueRewardEnrollmentSyncProps) {
- return await qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/rewards/sync-enrollments`,
- method: "POST",
- // set a flow control key to ensure that only one job is running for a given group at a time
- flowControl: {
- key: groupId,
- rate: 1,
- },
- body: {
- action,
- rewardId,
- groupId,
- programId,
- event,
- ...(startAfterProgramEnrollmentId && { startAfterProgramEnrollmentId }),
- ...(rewardSnapshot && { rewardSnapshot }),
- },
- });
-}
diff --git a/apps/web/lib/api/rewards/queue-reward-processing.ts b/apps/web/lib/api/rewards/queue-reward-processing.ts
new file mode 100644
index 0000000000..55627be9da
--- /dev/null
+++ b/apps/web/lib/api/rewards/queue-reward-processing.ts
@@ -0,0 +1,81 @@
+import { logger } from "@/lib/axiom/server";
+import { qstash } from "@/lib/cron";
+import { EventType } from "@dub/prisma/client";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import * as z from "zod/v4";
+import { incrementRewardVersion } from "./reward-version";
+
+export const rewardJobSchema = z.object({
+ event: z.enum(["reward-created", "reward-updated", "reward-deleted"]),
+ groupId: z.string(),
+ occurredAt: z.string(),
+ version: z
+ .number()
+ .optional()
+ .default(1)
+ .describe(
+ "Incremented by 1 for each new reward change (create/update/delete) for same reward type in a group.",
+ ),
+ batchNumber: z
+ .number()
+ .optional()
+ .default(1)
+ .describe("Used as a idempotency key for Resend."),
+ startAfterProgramEnrollmentId: z.string().nullish(),
+ rewardSnapshot: z.object({
+ id: z.string(),
+ event: z.enum(EventType),
+ description: z.string(),
+ }),
+});
+
+export type RewardJob = z.input<typeof rewardJobSchema>;
+
+export async function queueRewardProcessing(params: RewardJob) {
+ try {
+ // If version is provided (recursive cron job), use it, otherwise increment the version
+ const version =
+ params.version !== undefined
+ ? params.version
+ : await incrementRewardVersion({
+ groupId: params.groupId,
+ event: params.rewardSnapshot.event,
+ });
+
+ const response = await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/rewards/process`,
+ method: "POST",
+ body: {
+ ...params,
+ version,
+ },
+ });
+
+ if (!response?.messageId) {
+ throw new Error(
+ "We couldn't start reward processing right now. Please try again in a few moments.",
+ );
+ }
+
+ return response;
+ } catch (error) {
+ logger.error("publishJSON.failed", {
+ service: "qstash",
+ event: "publishJSON.failed",
+ url: `/api/cron/rewards/process`,
+ errorName: error instanceof Error ? error.name : undefined,
+ errorStack: error instanceof Error ? error.stack : undefined,
+ correlation: {
+ event: params.event,
+ groupId: params.groupId,
+ rewardId: params.rewardSnapshot.id,
+ },
+ });
+
+ await logger.flush();
+
+ throw new Error(
+ "We couldn't start reward processing right now. Please try again in a few moments.",
+ );
+ }
+}
diff --git a/apps/web/lib/api/rewards/reward-version.ts b/apps/web/lib/api/rewards/reward-version.ts
new file mode 100644
index 0000000000..b566f1949a
--- /dev/null
+++ b/apps/web/lib/api/rewards/reward-version.ts
@@ -0,0 +1,50 @@
+import { redis } from "@/lib/upstash";
+import { EventType } from "@dub/prisma/client";
+
+const REWARD_VERSION_TTL_SECONDS = 24 * 60 * 60; // 24 hours
+
+export function getRewardVersionKey({
+ groupId,
+ event,
+}: {
+ groupId: string;
+ event: EventType; // Reward type
+}) {
+ return `reward-version:${groupId}:${event}`;
+}
+
+export async function incrementRewardVersion({
+ groupId,
+ event,
+}: {
+ groupId: string;
+ event: EventType;
+}) {
+ const key = getRewardVersionKey({
+ groupId,
+ event,
+ });
+
+ const version = await redis.incr(key);
+ await redis.expire(key, REWARD_VERSION_TTL_SECONDS);
+ return version;
+}
+
+export async function isStaleRewardVersion({
+ version,
+ groupId,
+ event,
+}: {
+ version: number;
+ groupId: string;
+ event: EventType;
+}) {
+ const key = getRewardVersionKey({
+ groupId,
+ event,
+ });
+
+ const currentVersion = await redis.get(key);
+
+ return currentVersion != null && version < Number(currentVersion);
+}
diff --git a/apps/web/lib/email/email-templates-map.ts b/apps/web/lib/email/email-templates-map.ts
index a2994f7064..41951306cf 100644
--- a/apps/web/lib/email/email-templates-map.ts
+++ b/apps/web/lib/email/email-templates-map.ts
@@ -8,7 +8,7 @@ import PartnerDeactivated from "@dub/email/templates/partner-deactivated";
import PartnerGroupChanged from "@dub/email/templates/partner-group-changed";
import PartnerPayoutConfirmed from "@dub/email/templates/partner-payout-confirmed";
import PartnerPayoutProcessed from "@dub/email/templates/partner-payout-processed";
-import PartnerRewardsUpdated from "@dub/email/templates/partner-rewards-updated";
+import PartnerRewardUpdated from "@dub/email/templates/partner-reward-updated";
import ProgramPayoutThankYou from "@dub/email/templates/program-payout-thank-you";
import UnresolvedFraudEventsSummary from "@dub/email/templates/unresolved-fraud-events-summary";
@@ -23,7 +23,7 @@ export const EMAIL_TEMPLATES_MAP = {
ProgramPayoutThankYou,
UnresolvedFraudEventsSummary,
PartnerGroupChanged,
- PartnerRewardsUpdated,
+ PartnerRewardUpdated,
// special broadcast emails
// DubPartnerRewind,
diff --git a/packages/email/src/templates/partner-rewards-updated.tsx b/packages/email/src/templates/partner-reward-updated.tsx
similarity index 63%
rename from packages/email/src/templates/partner-rewards-updated.tsx
rename to packages/email/src/templates/partner-reward-updated.tsx
index 371beebea1..8b195c3f3d 100644
--- a/packages/email/src/templates/partner-rewards-updated.tsx
+++ b/packages/email/src/templates/partner-reward-updated.tsx
@@ -1,4 +1,4 @@
-import { DUB_WORDMARK, formatDateTime } from "@dub/utils";
+import { capitalize, DUB_WORDMARK, formatDateTime } from "@dub/utils";
import {
Body,
Column,
@@ -17,17 +17,13 @@ import {
} from "@react-email/components";
import { Footer } from "../components/footer";
-type RewardChangeAction = "added" | "updated" | "removed";
-
-const ACTION_LABELS: Record<RewardChangeAction, string> = {
- added: "Added",
- updated: "Updated",
- removed: "Removed",
+const REWARD_EVENT_TO_EMAIL_ACTION = {
+ "reward-created": "added",
+ "reward-updated": "updated",
+ "reward-deleted": "removed",
};
-const ACTION_ORDER: RewardChangeAction[] = ["added", "updated", "removed"];
-
-export default function PartnerRewardsUpdated({
+export default function PartnerRewardUpdated({
program = {
name: "Acme",
logo: DUB_WORDMARK,
@@ -38,15 +34,12 @@ export default function PartnerRewardsUpdated({
name: "John Doe",
},
+ rewardSnapshot = {
+ description: "30% per sale for the customers lifetime",
+ icon: "https://assets.dub.co/email-assets/icons/invoice-dollar.png",
+ },
effectiveAt = new Date("2026-01-02T20:32:00.000Z"),
- changes = [
- {
- action: "added" as RewardChangeAction,
- title: "Sale reward",
- description: "30% per sale for the customers lifetime",
- icon: "https://assets.dub.co/email-assets/icons/invoice-dollar.png",
- },
- ],
+ action = "reward-created",
}: {
program: {
name: string;
@@ -58,23 +51,17 @@ export default function PartnerRewardsUpdated({
name: string;
email: string;
};
- effectiveAt: Date | string;
- changes: {
- action: RewardChangeAction;
- title: string;
+ rewardSnapshot: {
description: string;
icon: string;
- }[];
+ };
+ effectiveAt: Date | string;
+ action: "reward-created" | "reward-updated" | "reward-deleted";
}) {
const formattedEffectiveAt = formatDateTime(effectiveAt, {
timeZoneName: "short",
});
- const changesByAction = ACTION_ORDER.map((action) => ({
- action,
- items: changes.filter((change) => change.action === action),
- })).filter(({ items }) => items.length > 0);
-
return (
<Html>
<Head />
@@ -102,34 +89,24 @@ export default function PartnerRewardsUpdated({
program:
</Text>
- {Boolean(changes.length) && (
- <Section className="my-4 rounded-xl border border-solid border-neutral-200 bg-neutral-50 px-5 py-4">
- {changesByAction.map(({ action, items }, index) => (
- <Section key={action}>
- <Text
- className={`mb-0 text-base font-semibold text-black ${index > 0 ? "mt-5" : "mt-0"}`}
- >
- {ACTION_LABELS[action]}
+ <Section className="my-4 rounded-xl border border-solid border-neutral-200 bg-neutral-50 px-5 py-4">
+ <Section>
+ <Text className="mb-0 mt-0 text-base font-semibold text-black">
+ {capitalize(REWARD_EVENT_TO_EMAIL_ACTION[action])}
+ </Text>
+
+ <Row className="mb-0 mt-2">
+ <Column className="align-center">
+ <Img src={rewardSnapshot.icon} height="16" alt="" />
+ </Column>
+ <Column className="w-full pl-2">
+ <Text className="my-0 text-sm font-medium text-neutral-600">
+ {rewardSnapshot.description}
</Text>
- {items.map((change) => (
- <Row
- key={`${change.action}-${change.title}`}
- className="mb-0 mt-2"
- >
- <Column className="align-center">
- <Img src={change.icon} height="16" alt="" />
- </Column>
- <Column className="w-full pl-2">
- <Text className="my-0 text-sm font-medium text-neutral-600">
- {change.description}
- </Text>
- </Column>
- </Row>
- ))}
- </Section>
- ))}
+ </Column>
+ </Row>
</Section>
- )}
+ </Section>
<Text className="text-sm leading-6 text-neutral-600">
This update is in effect as of{" "}