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.

Refactor email rendering to use a dedicated function for generating campaign HTML and update variable handling in templates

Kiran K4e4553bb9252
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor.tsx
index 5e97dc3fd9..ec51207010 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor.tsx
@@ -268,7 +268,7 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
editorClassName="-m-2 min-h-[200px] p-2"
initialValue={field.value}
onChange={(editor) => field.onChange(editor.getJSON())}
- variables={EMAIL_TEMPLATE_VARIABLES}
+ variables={[...EMAIL_TEMPLATE_VARIABLES]}
uploadImage={async (file) => {
try {
const result = await executeImageUpload({
diff --git a/apps/web/lib/actions/campaigns/send-campaign-preview-email.ts b/apps/web/lib/actions/campaigns/send-campaign-preview-email.ts
index 4900afbd9a..77f062e124 100644
--- a/apps/web/lib/actions/campaigns/send-campaign-preview-email.ts
+++ b/apps/web/lib/actions/campaigns/send-campaign-preview-email.ts
@@ -1,15 +1,11 @@
"use server";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
-import { renderEmailTemplate } from "@/lib/api/workflows/render-email-template";
+import { generateCampaignEmailHTML } from "@/lib/api/workflows/generate-campaign-email-html";
import { CampaignSchema } from "@/lib/zod/schemas/campaigns";
import { sendBatchEmail } from "@dub/email";
import CampaignEmail from "@dub/email/templates/campaign-email";
import { prisma } from "@dub/prisma";
-import Image from "@tiptap/extension-image";
-import Mention from "@tiptap/extension-mention";
-import { generateHTML } from "@tiptap/html/server";
-import StarterKit from "@tiptap/starter-kit";
import { z } from "zod";
import { authActionClient } from "../safe-action";
@@ -44,50 +40,15 @@ export const sendCampaignPreviewEmail = authActionClient
},
});
- const bodyHtml = renderEmailTemplate({
- template: generateHTML(bodyJson, [
- StarterKit.configure({
- heading: {
- levels: [1, 2],
- },
- }),
- Image,
- Mention.extend({
- renderHTML({ node }: { node: any }) {
- return [
- "span",
- {
- class:
- "px-1 py-0.5 bg-blue-100 text-blue-700 rounded font-semibold",
- "data-type": "mention",
- "data-id": node.attrs.id,
- },
- `{{${node.attrs.id}}}`,
- ];
- },
- renderText({ node }: { node: any }) {
- return `{{${node.attrs.id}}}`;
- },
- }).configure({
- suggestion: {
- items: ({ query }: { query: string }) => {
- const variables = ["PartnerName", "PartnerEmail"];
- return variables
- .filter((item) =>
- item.toLowerCase().startsWith(query.toLowerCase()),
- )
- .slice(0, 5);
- },
- },
- }),
- ]),
+ const bodyHtml = generateCampaignEmailHTML({
+ bodyJson,
variables: {
PartnerName: "Partner",
PartnerEmail: "[email protected]",
},
});
- const response = await sendBatchEmail(
+ await sendBatchEmail(
emailAddresses.map((email) => ({
variant: "notifications",
to: email,
@@ -100,6 +61,4 @@ export const sendCampaignPreviewEmail = authActionClient
}),
})),
);
-
- console.log(JSON.stringify(response, null, 2));
});
diff --git a/apps/web/lib/api/workflows/execute-send-campaign-workflow.ts b/apps/web/lib/api/workflows/execute-send-campaign-workflow.ts
index 6633e96e67..69a2933e73 100644
--- a/apps/web/lib/api/workflows/execute-send-campaign-workflow.ts
+++ b/apps/web/lib/api/workflows/execute-send-campaign-workflow.ts
@@ -3,14 +3,12 @@ import { WORKFLOW_ACTION_TYPES } from "@/lib/zod/schemas/workflows";
import { sendBatchEmail } from "@dub/email";
import NewMessageFromProgram from "@dub/email/templates/new-message-from-program";
import { prisma } from "@dub/prisma";
-import { richTextAreaExtensions } from "@dub/ui";
import { chunk } from "@dub/utils";
import { NotificationEmailType, Workflow } from "@prisma/client";
-import { generateHTML } from "@tiptap/html/server";
import { subDays } from "date-fns";
import { createId } from "../create-id";
+import { generateCampaignEmailHTML } from "./generate-campaign-email-html";
import { parseWorkflowConfig } from "./parse-workflow-config";
-import { renderEmailTemplate } from "./render-email-template";
export const executeSendCampaignWorkflow = async ({
workflow,
@@ -146,13 +144,11 @@ export const executeSendCampaignWorkflow = async ({
senderUserId: campaign.userId,
type: "campaign",
subject: campaign.subject,
- text: renderEmailTemplate({
- template: generateHTML(
- campaign.bodyJson as any,
- richTextAreaExtensions,
- ),
+ text: generateCampaignEmailHTML({
+ bodyJson: campaign.bodyJson as any,
variables: {
PartnerName: programEnrollment.partner.name,
+ PartnerEmail: programEnrollment.partner.email,
},
}),
})),
@@ -176,13 +172,11 @@ export const executeSendCampaignWorkflow = async ({
},
messages: [
{
- text: renderEmailTemplate({
- template: generateHTML(
- campaign.bodyJson as any,
- richTextAreaExtensions,
- ),
+ text: generateCampaignEmailHTML({
+ bodyJson: campaign.bodyJson as any,
variables: {
PartnerName: partnerUser.partner.name,
+ PartnerEmail: partnerUser.partner.email,
},
}),
createdAt: new Date(),
diff --git a/apps/web/lib/api/workflows/generate-campaign-email-html.ts b/apps/web/lib/api/workflows/generate-campaign-email-html.ts
new file mode 100644
index 0000000000..8d7fc0fb49
--- /dev/null
+++ b/apps/web/lib/api/workflows/generate-campaign-email-html.ts
@@ -0,0 +1,58 @@
+import { EmailTemplateVariables } from "@/lib/types";
+import Image from "@tiptap/extension-image";
+import Mention from "@tiptap/extension-mention";
+import { generateHTML } from "@tiptap/html/server";
+import StarterKit from "@tiptap/starter-kit";
+import { renderEmailTemplate } from "./render-email-template";
+
+// This function configures the proper TipTap extensions (StarterKit, Image, Mention)
+// and renders the campaign body with variable placeholders replaced.
+export function generateCampaignEmailHTML({
+ bodyJson,
+ variables,
+}: {
+ bodyJson: any;
+ variables: Partial<EmailTemplateVariables>;
+}): string {
+ const html = generateHTML(bodyJson, [
+ StarterKit.configure({
+ heading: {
+ levels: [1, 2],
+ },
+ }),
+ Image,
+ Mention.extend({
+ renderHTML({ node }: { node: any }) {
+ return [
+ "span",
+ {
+ class:
+ "px-1 py-0.5 bg-blue-100 text-blue-700 rounded font-semibold",
+ "data-type": "mention",
+ "data-id": node.attrs.id,
+ },
+ `{{${node.attrs.id}}}`,
+ ];
+ },
+ renderText({ node }: { node: any }) {
+ return `{{${node.attrs.id}}}`;
+ },
+ }).configure({
+ suggestion: {
+ items: ({ query }: { query: string }) => {
+ const campaignVariables = ["PartnerName", "PartnerEmail"];
+ return campaignVariables
+ .filter((item) =>
+ item.toLowerCase().startsWith(query.toLowerCase()),
+ )
+ .slice(0, 5);
+ },
+ },
+ }),
+ ]);
+
+ return renderEmailTemplate({
+ template: html,
+ variables,
+ });
+}
diff --git a/apps/web/lib/api/workflows/render-email-template.ts b/apps/web/lib/api/workflows/render-email-template.ts
index 8890471c1c..652f7f63a7 100644
--- a/apps/web/lib/api/workflows/render-email-template.ts
+++ b/apps/web/lib/api/workflows/render-email-template.ts
@@ -1,4 +1,4 @@
-import { EMAIL_TEMPLATE_VARIABLES } from "@/lib/zod/schemas/campaigns";
+import { EmailTemplateVariables } from "@/lib/types";
/**
* Renders an email template by replacing variable placeholders with actual values.
@@ -25,12 +25,7 @@ export function renderEmailTemplate({
variables,
}: {
template: string;
- variables: Partial<
- Record<
- (typeof EMAIL_TEMPLATE_VARIABLES)[number],
- string | number | null | undefined
- >
- >;
+ variables: Partial<EmailTemplateVariables>;
}): string {
return template.replace(
/{{\s*([\w.]+)(?:\|([^}]+))?\s*}}/g,
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index 8e8a03d701..011f4a8693 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -38,6 +38,7 @@ import {
CampaignListSchema,
CampaignSchema,
campaignSummarySchema,
+ EMAIL_TEMPLATE_VARIABLES,
updateCampaignSchema,
} from "./zod/schemas/campaigns";
import {
@@ -672,3 +673,8 @@ export type CampaignWorkflowAttribute =
export type CampaignSummary = z.infer<typeof campaignSummarySchema>;
export type StripeMode = "test" | "sandbox" | "live";
+
+export type EmailTemplateVariables = Record<
+ (typeof EMAIL_TEMPLATE_VARIABLES)[number],
+ string | null | undefined
+>;
diff --git a/apps/web/lib/zod/schemas/campaigns.ts b/apps/web/lib/zod/schemas/campaigns.ts
index 1299a8458f..77369cdf6f 100644
--- a/apps/web/lib/zod/schemas/campaigns.ts
+++ b/apps/web/lib/zod/schemas/campaigns.ts
@@ -8,7 +8,7 @@ import { workflowConditionSchema } from "./workflows";
export const ALLOWED_ATTRIBUTE_VALUES_IN_DAYS = [0, 1, 3, 7, 14, 30];
-export const EMAIL_TEMPLATE_VARIABLES = ["PartnerName", "PartnerEmail"];
+export const EMAIL_TEMPLATE_VARIABLES = ["PartnerName", "PartnerEmail"] as const;
export const CAMPAIGN_WORKFLOW_ATTRIBUTES = ["partnerEnrolledDays"] as const;
diff --git a/packages/email/package.json b/packages/email/package.json
index a1e7c5ba18..02406dbc46 100644
--- a/packages/email/package.json
+++ b/packages/email/package.json
@@ -11,16 +11,6 @@
"@dub/ui": "workspace:*",
"@dub/utils": "workspace:*",
"@react-email/components": "^0.0.22",
- "@tiptap/extension-file-handler": "^3.0.9",
- "@tiptap/extension-image": "^3.0.9",
- "@tiptap/extension-link": "^3.6.6",
- "@tiptap/extension-mention": "^3.0.9",
- "@tiptap/extensions": "^3.0.9",
- "@tiptap/html": "^3.6.5",
- "@tiptap/pm": "^3.0.9",
- "@tiptap/react": "^3.0.9",
- "@tiptap/starter-kit": "^3.0.9",
- "@tiptap/static-renderer": "^3.6.6",
"lucide-react": "^0.462.0",
"nodemailer": "^6.9.3",
"react-email": "^2.1.6",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 1f88194701..56bdc18775 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -528,36 +528,6 @@ importers:
'@react-email/components':
specifier: ^0.0.22
- '@tiptap/extension-file-handler':
- specifier: ^3.0.9
- version: 3.0.9(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected])))(@tiptap/[email protected])
- '@tiptap/extension-image':
- specifier: ^3.0.9
- version: 3.0.9(@tiptap/[email protected](@tiptap/[email protected]))
- '@tiptap/extension-link':
- specifier: ^3.6.6
- version: 3.6.6(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])
- '@tiptap/extension-mention':
- specifier: ^3.0.9
- version: 3.0.9(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))
- '@tiptap/extensions':
- specifier: ^3.0.9
- version: 3.0.9(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])
- '@tiptap/html':
- specifier: ^3.6.5
- version: 3.6.5(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])([email protected])
- '@tiptap/pm':
- specifier: ^3.0.9
- version: 3.0.9
- '@tiptap/react':
- specifier: ^3.0.9
- '@tiptap/starter-kit':
- specifier: ^3.0.9
- version: 3.0.9
- '@tiptap/static-renderer':
- specifier: ^3.6.6
lucide-react:
specifier: ^0.462.0
version: 0.462.0([email protected])
@@ -5656,14 +5626,6 @@ packages:
'@tiptap/[email protected]':
resolution: {integrity: sha512-CYg6tV5fYOvkP1gyATkJJj+nFYmwjDKLipQc/r0D/tHKypxefENrm4G7mf4B78zsB/izfk5mW3iujvyeod6EcQ==}
- '@tiptap/[email protected]':
- resolution: {integrity: sha512-m0A18LFuGnWxUdg5miDclouwvA7KyUtiSaGds6EWKGFSSErJZEcaRq1ZdSvuFJtT/rVXc1MhG0Wu2g6mGX6eTw==}
- peerDependencies:
- '@tiptap/core': ^3.6.6
- '@tiptap/pm': ^3.6.6
- react: ^17.0.0 || ^18.0.0 || ^19.0.0
- react-dom: ^17.0.0 || ^18.0.0 || ^19.0.0
-
'@tiptap/[email protected]':
resolution: {integrity: sha512-irthqfUybezo3IwR6AXvyyTOtkzwfvvst58VXZtTnR1nN6NEcrs3TQoY3bGKGbN83bdiquKh6aU2nLnZfAhoXg==}
peerDependencies:
@@ -19888,21 +19850,6 @@ snapshots:
prosemirror-transform: 1.10.4
prosemirror-view: 1.40.1
- dependencies:
- '@tiptap/core': 3.0.9(@tiptap/[email protected])
- '@tiptap/pm': 3.0.9
- '@types/use-sync-external-store': 0.0.6
- fast-deep-equal: 3.1.3
- react: 18.3.1
- react-dom: 18.3.1([email protected])
- use-sync-external-store: 1.5.0([email protected])
- optionalDependencies:
- '@tiptap/extension-bubble-menu': 3.0.9(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])
- '@tiptap/extension-floating-menu': 3.0.9(@floating-ui/[email protected])(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])
- transitivePeerDependencies:
- - '@floating-ui/dom'
-
dependencies:
'@tiptap/core': 3.0.9(@tiptap/[email protected])
@@ -19945,13 +19892,6 @@ snapshots:
'@tiptap/extensions': 3.0.9(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])
'@tiptap/pm': 3.0.9
- dependencies:
- '@tiptap/core': 3.0.9(@tiptap/[email protected])
- '@tiptap/pm': 3.0.9
- react: 18.3.1
- react-dom: 18.3.1([email protected])
-
dependencies:
'@tiptap/core': 3.0.9(@tiptap/[email protected])
@@ -29398,10 +29338,6 @@ snapshots:
dependencies:
react: 19.1.1
- dependencies:
- react: 18.3.1
-
dependencies:
react: 19.1.1