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.

Move reward enrollment sync to cron (#3923)

Pedro Ladeira1c41db21e1ef
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
new file mode 100644
index 0000000000..77a2574fd4
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/rewards/sync-enrollments/route.ts
@@ -0,0 +1,202 @@
+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 6cecfa9873..298c675e0a 100644
--- a/apps/web/lib/actions/partners/create-reward.ts
+++ b/apps/web/lib/actions/partners/create-reward.ts
@@ -6,6 +6,7 @@ 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 { validateReward } from "@/lib/api/rewards/validate-reward";
import { getPlanCapabilities } from "@/lib/plan-capabilities";
import {
@@ -104,18 +105,17 @@ export const createRewardAction = authActionClient
},
});
- await tx.programEnrollment.updateMany({
- where: {
- groupId,
- },
- data: {
- [rewardIdColumn]: reward.id,
- },
- });
-
return reward;
});
+ await queueRewardEnrollmentSync({
+ action: "create",
+ rewardId: reward.id,
+ groupId,
+ programId,
+ event,
+ });
+
waitUntil(
Promise.allSettled([
recordAuditLog({
diff --git a/apps/web/lib/actions/partners/delete-reward.ts b/apps/web/lib/actions/partners/delete-reward.ts
index a9e4db8375..60a6d3f93d 100644
--- a/apps/web/lib/actions/partners/delete-reward.ts
+++ b/apps/web/lib/actions/partners/delete-reward.ts
@@ -3,7 +3,9 @@
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 { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { queueRewardEnrollmentSync } from "@/lib/api/rewards/queue-reward-enrollment-sync";
import { REWARD_EVENT_COLUMN_MAPPING } from "@/lib/zod/schemas/rewards";
import { prisma } from "@dub/prisma";
import { waitUntil } from "@vercel/functions";
@@ -35,6 +37,7 @@ 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({
@@ -47,24 +50,27 @@ export const deleteRewardAction = authActionClient
},
});
- await tx.programEnrollment.updateMany({
+ await tx.reward.update({
where: {
- [rewardIdColumn]: reward.id,
+ id: reward.id,
},
data: {
- [rewardIdColumn]: null,
- },
- });
-
- await tx.reward.delete({
- where: {
- id: reward.id,
+ programId: null,
},
});
return group;
});
+ await queueRewardEnrollmentSync({
+ action: "delete",
+ rewardId: reward.id,
+ groupId: partnerGroup.id,
+ programId,
+ event: reward.event,
+ rewardSnapshot,
+ });
+
waitUntil(
Promise.allSettled([
recordAuditLog({
diff --git a/apps/web/lib/actions/partners/update-reward.ts b/apps/web/lib/actions/partners/update-reward.ts
index 28fdbea2e1..db62e7ea6d 100644
--- a/apps/web/lib/actions/partners/update-reward.ts
+++ b/apps/web/lib/actions/partners/update-reward.ts
@@ -3,6 +3,7 @@
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 { validateReward } from "@/lib/api/rewards/validate-reward";
@@ -145,7 +146,7 @@ export const updateRewardAction = authActionClient
}),
// we only cache default group pages for now so we need to invalidate them
- ...(isDefaultGroup
+ ...(isDefaultGroup && program
? [
revalidatePath(`/partners.dub.co/${program.slug}`),
revalidatePath(`/partners.dub.co/${program.slug}/apply`),
@@ -155,6 +156,16 @@ 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-partners-reward-changed.ts b/apps/web/lib/api/partners/notify-partners-reward-changed.ts
new file mode 100644
index 0000000000..321f3e9a10
--- /dev/null
+++ b/apps/web/lib/api/partners/notify-partners-reward-changed.ts
@@ -0,0 +1,114 @@
+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
new file mode 100644
index 0000000000..c79d263ded
--- /dev/null
+++ b/apps/web/lib/api/rewards/queue-reward-enrollment-sync.ts
@@ -0,0 +1,48 @@
+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/email/email-templates-map.ts b/apps/web/lib/email/email-templates-map.ts
index 888165fc20..0c0e561b63 100644
--- a/apps/web/lib/email/email-templates-map.ts
+++ b/apps/web/lib/email/email-templates-map.ts
@@ -8,6 +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 ProgramPayoutThankYou from "@dub/email/templates/program-payout-thank-you";
import UnresolvedFraudEventsSummary from "@dub/email/templates/unresolved-fraud-events-summary";
@@ -22,6 +23,7 @@ export const EMAIL_TEMPLATES_MAP = {
ProgramPayoutThankYou,
UnresolvedFraudEventsSummary,
PartnerGroupChanged,
+ PartnerRewardsUpdated,
// special broadcast emails
// DubPartnerRewind,
diff --git a/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx b/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
index 37d1f7eae4..d706c72aee 100644
--- a/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
+++ b/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
@@ -233,33 +233,35 @@ function RewardSheetContent({
: undefined,
description: defaultValuesSource?.description ?? null,
tooltipDescription: defaultValuesSource?.tooltipDescription ?? null,
- modifiers: defaultValuesSource?.modifiers?.map((m) => {
- const maxDuration =
- m.maxDuration === undefined
- ? defaultValuesSource?.maxDuration
- : m.maxDuration;
-
- return {
- ...m,
- conditions: m.conditions.map((c) => ({
- ...c,
- value:
- REWARD_CONDITION_ATTRIBUTES.find((a) => a.id === c.attribute)
- ?.type === "currency" &&
- c.value !== "" &&
- c.value != null &&
- !Number.isNaN(Number(c.value))
- ? Number(c.value) / 100
- : c.value,
- })),
- amountInCents:
- m.amountInCents !== undefined && m.amountInCents !== null
- ? m.amountInCents / 100
- : undefined,
- amountInPercentage: m.amountInPercentage ?? undefined,
- maxDuration: m.maxDuration === null ? Infinity : maxDuration,
- };
- }),
+ modifiers: Array.isArray(defaultValuesSource?.modifiers)
+ ? defaultValuesSource.modifiers.map((m) => {
+ const maxDuration =
+ m.maxDuration === undefined
+ ? defaultValuesSource?.maxDuration
+ : m.maxDuration;
+
+ return {
+ ...m,
+ conditions: m.conditions.map((c) => ({
+ ...c,
+ value:
+ REWARD_CONDITION_ATTRIBUTES.find((a) => a.id === c.attribute)
+ ?.type === "currency" &&
+ c.value !== "" &&
+ c.value != null &&
+ !Number.isNaN(Number(c.value))
+ ? Number(c.value) / 100
+ : c.value,
+ })),
+ amountInCents:
+ m.amountInCents !== undefined && m.amountInCents !== null
+ ? m.amountInCents / 100
+ : undefined,
+ amountInPercentage: m.amountInPercentage ?? undefined,
+ maxDuration: m.maxDuration === null ? Infinity : maxDuration,
+ };
+ })
+ : undefined,
},
});
diff --git a/packages/email/src/templates/partner-rewards-updated.tsx b/packages/email/src/templates/partner-rewards-updated.tsx
new file mode 100644
index 0000000000..371beebea1
--- /dev/null
+++ b/packages/email/src/templates/partner-rewards-updated.tsx
@@ -0,0 +1,184 @@
+import { DUB_WORDMARK, formatDateTime } from "@dub/utils";
+import {
+ Body,
+ Column,
+ Container,
+ Head,
+ Heading,
+ Hr,
+ Html,
+ Img,
+ Link,
+ Preview,
+ Row,
+ Section,
+ Tailwind,
+ Text,
+} 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 ACTION_ORDER: RewardChangeAction[] = ["added", "updated", "removed"];
+
+export default function PartnerRewardsUpdated({
+ program = {
+ name: "Acme",
+ logo: DUB_WORDMARK,
+ slug: "acme",
+ supportEmail: "[email protected]",
+ },
+ partner = {
+ name: "John Doe",
+ email: "[email protected]",
+ },
+ 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",
+ },
+ ],
+}: {
+ program: {
+ name: string;
+ logo: string | null;
+ slug: string;
+ supportEmail?: string | null;
+ };
+ partner: {
+ name: string;
+ email: string;
+ };
+ effectiveAt: Date | string;
+ changes: {
+ action: RewardChangeAction;
+ title: string;
+ description: string;
+ icon: string;
+ }[];
+}) {
+ 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 />
+ <Preview>
+ This update is in effect as of {formattedEffectiveAt} and will apply to
+ all future activity.
+ </Preview>
+ <Tailwind>
+ <Body className="mx-auto my-auto bg-white font-sans">
+ <Container className="mx-auto my-10 max-w-[600px] rounded border border-solid border-neutral-200 px-10 py-5">
+ <Section className="mt-8">
+ <Img
+ src={program.logo || "https://assets.dub.co/wordmark.png"}
+ height="32"
+ alt={program.name}
+ />
+ </Section>
+
+ <Heading className="mx-0 my-7 p-0 text-lg font-medium text-black">
+ Hi {partner.name}!
+ </Heading>
+
+ <Text className="text-sm leading-6 text-neutral-600">
+ <strong>{program.name}</strong> has updated your rewards for their
+ 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]}
+ </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>
+ ))}
+ </Section>
+ )}
+
+ <Text className="text-sm leading-6 text-neutral-600">
+ This update is in effect as of{" "}
+ <strong>{formattedEffectiveAt}</strong> and will apply to all
+ future activity.
+ </Text>
+
+ <Hr className="border-neutral-200" />
+
+ <Section className="mb-8 mt-8">
+ <Link
+ className="rounded-lg bg-neutral-900 px-6 py-3 text-[13px] font-semibold text-white no-underline"
+ href={`https://partners.dub.co/programs/${program.slug}`}
+ >
+ Go to your dashboard
+ </Link>
+ </Section>
+
+ <Text className="text-sm leading-6 text-neutral-600">
+ If you have any questions about these changes, please{" "}
+ {program.supportEmail ? (
+ <>
+ reach out to the <strong>{program.name}</strong> team (
+ <Link
+ href={`mailto:${program.supportEmail}`}
+ className="font-semibold text-neutral-700 underline underline-offset-2"
+ >
+ {program.supportEmail}
+ </Link>
+ )
+ </>
+ ) : (
+ <Link
+ href={`https://partners.dub.co/messages/${program.slug}`}
+ className="font-semibold text-neutral-700 underline underline-offset-2"
+ >
+ reach out to the {program.name} team ↗
+ </Link>
+ )}
+ .
+ </Text>
+
+ <Footer
+ email={partner.email}
+ notificationSettingsUrl="https://partners.dub.co/profile/notifications"
+ />
+ </Container>
+ </Body>
+ </Tailwind>
+ </Html>
+ );
+}
diff --git a/packages/prisma/schema/reward.prisma b/packages/prisma/schema/reward.prisma
index 3b41ed1946..543ec2ad52 100644
--- a/packages/prisma/schema/reward.prisma
+++ b/packages/prisma/schema/reward.prisma
@@ -12,7 +12,7 @@ enum RewardStructure {
model Reward {
id String @id @default(cuid())
- programId String
+ programId String?
description String?
tooltipDescription String? @db.Text
event EventType
@@ -25,7 +25,7 @@ model Reward {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
- program Program @relation(fields: [programId], references: [id])
+ program Program? @relation(fields: [programId], references: [id])
clickEnrollments ProgramEnrollment[] @relation("ClickRewardEnrollments")
leadEnrollments ProgramEnrollment[] @relation("LeadRewardEnrollments")
saleEnrollments ProgramEnrollment[] @relation("SaleRewardEnrollments")