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.

Email campaign updates (#3062)

Tim Wilson3d4e4ea6d8e3
diff --git a/apps/web/app/(ee)/api/campaigns/[campaignId]/route.ts b/apps/web/app/(ee)/api/campaigns/[campaignId]/route.ts
index a375ecf503..0ed5676d51 100644
--- a/apps/web/app/(ee)/api/campaigns/[campaignId]/route.ts
+++ b/apps/web/app/(ee)/api/campaigns/[campaignId]/route.ts
@@ -64,6 +64,7 @@ export const PATCH = withWorkspace(
const {
name,
subject,
+ preview,
from,
status,
bodyJson,
@@ -121,6 +122,7 @@ export const PATCH = withWorkspace(
data: {
...(name && { name }),
...(subject && { subject }),
+ ...(preview !== undefined && { preview }),
...(from && { from }),
...(status && { status }),
...(bodyJson && { bodyJson }),
diff --git a/apps/web/app/(ee)/api/cron/campaigns/broadcast/route.ts b/apps/web/app/(ee)/api/cron/campaigns/broadcast/route.ts
index fe5db59303..3dcfea3f56 100644
--- a/apps/web/app/(ee)/api/cron/campaigns/broadcast/route.ts
+++ b/apps/web/app/(ee)/api/cron/campaigns/broadcast/route.ts
@@ -226,7 +226,7 @@ export async function POST(req: Request) {
},
campaign: {
type: campaign.type,
- subject: campaign.subject,
+ preview: campaign.preview,
body: renderCampaignEmailHTML({
content: campaign.bodyJson as unknown as TiptapNode,
variables: {
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 abdcefc317..75db9c2424 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
@@ -21,10 +21,17 @@ import {
TooltipContent,
useKeyboardShortcut,
} from "@dub/ui";
-import { capitalize } from "@dub/utils";
+import { capitalize, cn } from "@dub/utils";
+import { motion } from "motion/react";
import { useAction } from "next-safe-action/hooks";
import Link from "next/link";
-import { useCallback, useEffect, useRef } from "react";
+import {
+ PropsWithChildren,
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+} from "react";
import { Controller, FormProvider, useForm } from "react-hook-form";
import { toast } from "sonner";
import { useDebouncedCallback } from "use-debounce";
@@ -38,7 +45,7 @@ import { TransactionalCampaignLogic } from "./transactional-campaign-logic";
import { isValidTriggerCondition } from "./utils";
const inputClassName =
- "hover:border-border-subtle h-8 w-full rounded-md transition-colors duration-150 focus:border-black/75 border focus:ring-black/75 border-transparent px-1.5 py-0 text-sm text-content-default placeholder:text-content-muted hover:bg-neutral-100 hover:cursor-pointer";
+ "hover:border-border-subtle h-8 w-full rounded-md transition-colors duration-150 focus:border-black/75 border focus:ring-black/75 border-transparent px-1.5 py-0 sm:text-sm text-content-default placeholder:text-content-muted hover:bg-neutral-100 hover:cursor-pointer";
const labelClassName = "text-sm font-medium text-content-subtle";
@@ -95,6 +102,7 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
defaultValues: {
name: campaign.name,
subject: campaign.subject,
+ preview: campaign.preview,
from: campaign.from ?? undefined,
bodyJson: campaign.bodyJson,
groupIds: campaign.groups.map(({ id }) => id),
@@ -112,6 +120,26 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
formState: { dirtyFields },
} = form;
+ const previewInputRef = useRef<HTMLInputElement>(null);
+
+ const [showPreviewText, setShowPreviewText] = useState(
+ Boolean(campaign.preview),
+ );
+
+ // Show preview text when preview is set
+ useEffect(() => {
+ const { unsubscribe } = watch(({ preview }) => {
+ if (preview) setShowPreviewText(true);
+ });
+ return () => unsubscribe();
+ }, [watch]);
+
+ // Focus preview input when opened
+ useEffect(() => {
+ if (showPreviewText && !getValues("preview"))
+ previewInputRef.current?.focus();
+ }, [showPreviewText, getValues]);
+
const saveCampaign = useCallback(
async ({ isDraft = false }: { isDraft?: boolean }) => {
const allFormData = getValues();
@@ -215,6 +243,11 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
const statusBadge = CAMPAIGN_STATUS_BADGES[campaign.status];
const editorRef = useRef<{ setContent: (content: any) => void }>(null);
+ const previewInputProps = register("preview", {
+ onBlur: (e) => {
+ if (!e.target.value) setShowPreviewText(false);
+ },
+ });
return (
<FormProvider {...form}>
@@ -275,7 +308,7 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
contentWrapperClassName="flex flex-col"
>
<PageWidthWrapper className="mb-8 max-w-[600px]">
- <div className="grid grid-cols-[max-content_minmax(0,1fr)] items-center gap-x-6 gap-y-2">
+ <div className="grid grid-cols-[max-content_minmax(0,1fr)] items-center gap-x-6 [&>*:nth-child(n+2)]:mt-2">
<span className={labelClassName}>Name</span>
<DisabledInputWrapper
tooltip={isReadOnly ? statusMessages[campaign.status] : ""}
@@ -326,7 +359,7 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
<input
type="text"
placeholder="Address"
- className="text-content-default placeholder:text-content-muted min-w-0 flex-1 border-0 bg-transparent p-0 text-sm focus:outline-none focus:ring-0"
+ className="text-content-default placeholder:text-content-muted min-w-0 flex-1 border-0 bg-transparent p-0 focus:outline-none focus:ring-0 sm:text-sm"
disabled={isDisabled}
value={localPart}
onChange={(e) => {
@@ -402,14 +435,54 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
disabled={isReadOnly}
hideIcon={true}
>
+ <div className="relative">
+ <input
+ type="text"
+ placeholder="Enter a subject..."
+ className={cn(
+ inputClassName,
+ !isReadOnly && !showPreviewText && "pr-24",
+ )}
+ disabled={isReadOnly}
+ {...register("subject")}
+ />
+ {!isReadOnly && (
+ <div className="absolute right-0 top-1/2 -translate-y-1/2">
+ <button
+ type="button"
+ onClick={() => setShowPreviewText(true)}
+ className={cn(
+ "text-content-subtle hover:text-content-default px-2 py-1 text-sm font-medium",
+ "transition-[transform,opacity] duration-150 ease-out",
+ showPreviewText && "translate-y-1 opacity-0",
+ )}
+ inert={showPreviewText}
+ >
+ Preview text
+ </button>
+ </div>
+ )}
+ </div>
+ </DisabledInputWrapper>
+
+ <ConditionalColumn show={showPreviewText}>
+ <span className={cn(labelClassName, "flex h-8 items-center")}>
+ Preview
+ </span>
+ </ConditionalColumn>
+ <ConditionalColumn show={showPreviewText}>
<input
type="text"
- placeholder="Enter a subject..."
+ placeholder="Enter preview text..."
className={inputClassName}
disabled={isReadOnly}
- {...register("subject")}
+ {...previewInputProps}
+ ref={(e) => {
+ previewInputProps.ref(e);
+ previewInputRef.current = e;
+ }}
/>
- </DisabledInputWrapper>
+ </ConditionalColumn>
{campaign.type === "transactional" && (
<>
@@ -515,3 +588,23 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
</FormProvider>
);
}
+
+const ConditionalColumn = ({
+ show,
+ children,
+}: PropsWithChildren<{ show: boolean }>) => {
+ return (
+ <motion.div
+ initial={false}
+ animate={{ height: show ? "auto" : 0 }}
+ transition={{ duration: 0.15, ease: "easeOut" }}
+ className={cn(
+ "transition-[margin,opacity] duration-150",
+ !show && "!mt-0 opacity-0",
+ )}
+ inert={!show}
+ >
+ {children}
+ </motion.div>
+ );
+};
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/send-email-preview-modal.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/send-email-preview-modal.tsx
index e406e85f5e..474b17898b 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/send-email-preview-modal.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/send-email-preview-modal.tsx
@@ -27,9 +27,9 @@ function SendEmailPreviewModal({
const { control } = useCampaignFormContext();
const [emailAddresses, setEmailAddresses] = useState(user?.email ?? "");
- const [subject, bodyJson, from] = useWatch({
+ const [subject, preview, bodyJson, from] = useWatch({
control,
- name: ["subject", "bodyJson", "from"],
+ name: ["subject", "preview", "bodyJson", "from"],
});
const { executeAsync: sendEmailPreview, isPending } = useAction(
@@ -81,6 +81,7 @@ function SendEmailPreviewModal({
workspaceId,
campaignId,
subject,
+ preview,
bodyJson,
from,
emailAddresses: emails,
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 0d2533764d..0a3bb481cc 100644
--- a/apps/web/lib/actions/campaigns/send-campaign-preview-email.ts
+++ b/apps/web/lib/actions/campaigns/send-campaign-preview-email.ts
@@ -16,6 +16,7 @@ const sendPreviewEmailSchema = z
campaignId: z.string(),
workspaceId: z.string(),
subject: z.string().min(1, "Email subject is required."),
+ preview: z.string().nullish(),
from: z.string().email().optional(),
emailAddresses: z
.array(z.string().email())
@@ -32,7 +33,8 @@ export const sendCampaignPreviewEmail = authActionClient
.schema(sendPreviewEmailSchema)
.action(async ({ parsedInput, ctx }) => {
const { workspace } = ctx;
- const { campaignId, subject, from, bodyJson, emailAddresses } = parsedInput;
+ const { campaignId, subject, preview, from, bodyJson, emailAddresses } =
+ parsedInput;
const programId = getDefaultProgramIdOrThrow(workspace);
@@ -66,7 +68,7 @@ export const sendCampaignPreviewEmail = authActionClient
},
campaign: {
type: campaign.type,
- subject,
+ preview,
body: renderCampaignEmailHTML({
content: bodyJson as unknown as TiptapNode,
variables: {
diff --git a/apps/web/lib/api/campaigns/validate-campaign.ts b/apps/web/lib/api/campaigns/validate-campaign.ts
index 532b2f3878..b256757938 100644
--- a/apps/web/lib/api/campaigns/validate-campaign.ts
+++ b/apps/web/lib/api/campaigns/validate-campaign.ts
@@ -34,6 +34,7 @@ export async function validateCampaign({
if (
input.name ||
input.subject ||
+ input.preview ||
input.bodyJson ||
input.groupIds ||
input.triggerCondition ||
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 eae4816c60..01e8c9ac0d 100644
--- a/apps/web/lib/api/workflows/execute-send-campaign-workflow.ts
+++ b/apps/web/lib/api/workflows/execute-send-campaign-workflow.ts
@@ -192,7 +192,7 @@ export const executeSendCampaignWorkflow = async ({
},
campaign: {
type: campaign.type,
- subject: campaign.subject,
+ preview: campaign.preview,
body: renderCampaignEmailHTML({
content: campaign.bodyJson as unknown as TiptapNode,
variables: {
diff --git a/apps/web/lib/api/workflows/render-campaign-email-html.ts b/apps/web/lib/api/workflows/render-campaign-email-html.ts
index 335c905e82..cee5ebbe9f 100644
--- a/apps/web/lib/api/workflows/render-campaign-email-html.ts
+++ b/apps/web/lib/api/workflows/render-campaign-email-html.ts
@@ -20,7 +20,11 @@ export function renderCampaignEmailHTML({
levels: [1, 2],
},
}),
- Image,
+ Image.configure({
+ HTMLAttributes: {
+ style: "max-width: 100%; height: auto; margin: 12px auto;",
+ },
+ }),
Mention.extend({
renderHTML({ node }: { node: any }) {
return [
@@ -84,7 +88,7 @@ const sanitizeHtmlBody = (body: string) => {
],
allowedAttributes: {
a: ["href", "name", "target", "rel"],
- img: ["src", "alt", "title"],
+ img: ["src", "alt", "title", "style"],
ul: ["style"],
ol: ["style"],
li: ["style"],
diff --git a/apps/web/lib/zod/schemas/campaigns.ts b/apps/web/lib/zod/schemas/campaigns.ts
index ac780bf5cd..d2c0f86835 100644
--- a/apps/web/lib/zod/schemas/campaigns.ts
+++ b/apps/web/lib/zod/schemas/campaigns.ts
@@ -50,6 +50,7 @@ export const CampaignSchema = z.object({
id: z.string(),
name: z.string(),
subject: z.string(),
+ preview: z.string().nullable().default(null),
from: z.string().nullable(),
bodyJson: z.record(z.string(), z.any()),
type: z.nativeEnum(CampaignType),
@@ -84,6 +85,7 @@ export const updateCampaignSchema = z
.string()
.trim()
.max(100, "Subject must be less than 100 characters."),
+ preview: z.string().nullish(),
from: z.string().email().trim().toLowerCase(),
bodyJson: z.record(z.string(), z.any()),
triggerCondition: workflowConditionSchema.nullish(),
diff --git a/apps/web/scripts/perplexity/ban-partners.ts b/apps/web/scripts/perplexity/ban-partners.ts
index e18d6e6984..0a7672a9ac 100644
--- a/apps/web/scripts/perplexity/ban-partners.ts
+++ b/apps/web/scripts/perplexity/ban-partners.ts
@@ -1,4 +1,3 @@
-import { syncTotalCommissions } from "@/lib/api/partners/sync-total-commissions";
import { BAN_PARTNER_REASONS } from "@/lib/zod/schemas/partners";
import PartnerBanned from "@dub/email/templates/partner-banned";
import { prisma } from "@dub/prisma";
@@ -6,6 +5,7 @@ import "dotenv-flow/config";
import * as fs from "fs";
import * as Papa from "papaparse";
import { linkCache } from "../../lib/api/links/cache";
+import { syncTotalCommissions } from "../../lib/api/partners/sync-total-commissions";
import { queueBatchEmail } from "../../lib/email/queue-batch-email";
let partnersToBan: string[] = [];
@@ -38,12 +38,15 @@ async function main() {
partnerId: {
in: partnersToBan,
},
+ status: {
+ not: "banned",
+ },
},
include: {
links: true,
partner: true,
},
- take: 100,
+ take: 200,
});
if (programEnrollments.length === 0) {
@@ -127,6 +130,8 @@ async function main() {
),
);
+ console.log("commissionsRes", commissionsRes);
+
const qstashRes = await queueBatchEmail<typeof PartnerBanned>(
programEnrollments
.filter((p) => p.partner.email)
diff --git a/apps/web/tests/campaigns/index.test.ts b/apps/web/tests/campaigns/index.test.ts
index 226f068558..1a668d668c 100644
--- a/apps/web/tests/campaigns/index.test.ts
+++ b/apps/web/tests/campaigns/index.test.ts
@@ -33,6 +33,7 @@ const expectedCampaign: Partial<Campaign> = {
...campaign,
type: "transactional",
status: expect.any(String),
+ preview: null,
from: null,
scheduledAt: null,
groups: [{ id: E2E_PARTNER_GROUP.id }],
diff --git a/packages/email/src/templates/campaign-email.tsx b/packages/email/src/templates/campaign-email.tsx
index 0f669aa53e..5aa632b745 100644
--- a/packages/email/src/templates/campaign-email.tsx
+++ b/packages/email/src/templates/campaign-email.tsx
@@ -1,5 +1,3 @@
-import { DUB_WORDMARK } from "@dub/utils";
-
import {
Body,
Container,
@@ -24,8 +22,8 @@ export default function CampaignEmail({
},
campaign = {
type: "marketing",
- subject: "Test Subject",
- body: `<p xmlns="http://www.w3.org/1999/xhtml">Hi <span class="px-1 py-0.5 bg-blue-100 text-blue-700 rounded font-semibold" data-type="mention" data-id="PartnerName">{{PartnerName}}</span>,</p><p xmlns="http://www.w3.org/1999/xhtml">Thrilled to have you officially join the Acme Ambassador Program!</p><p xmlns="http://www.w3.org/1999/xhtml">As a Acme Ambassador, you're joining the front line of change. You're freeing people from broken healthcare and giving them back control of their health.</p><p xmlns="http://www.w3.org/1999/xhtml">Your 3 quick steps to get started:</p><ol xmlns="http://www.w3.org/1999/xhtml"><li><p>Activate your membership with your 50% off code: <strong>ACME50OFF</strong></p></li><li><p><a target="_blank" rel="noopener noreferrer nofollow" href="https://partners.dub.co/programs/acme">Open your dashboard</a> and copy your referral link</p></li><li><p>Share Acme with your loved ones! Use our <a target="_blank" rel="noopener noreferrer nofollow" href="http://acme.dub.sh">Ambassador Hub</a> for all the information you need like message templates, images, and information about Acme.</p></li></ol><p xmlns="http://www.w3.org/1999/xhtml">And a bonus: make your first referral within 7 days and you'll also receive a limited-edition Acme hoodie.</p><img xmlns="http://www.w3.org/1999/xhtml" src="https://dubassets.com/programs/prog_CYCu7IMAapjkRpTnr8F1azjN/lander/image_JjbkiaM" /><p xmlns="http://www.w3.org/1999/xhtml">We're here with you every step of the way.</p><p xmlns="http://www.w3.org/1999/xhtml">To your health,</p><p xmlns="http://www.w3.org/1999/xhtml">The Acme team</p>`,
+ preview: "Test Preview",
+ body: `<p xmlns="http://www.w3.org/1999/xhtml">Hi <span class="px-1 py-0.5 bg-blue-100 text-blue-700 rounded font-semibold" data-type="mention" data-id="PartnerName">{{PartnerName}}</span>,</p><p xmlns="http://www.w3.org/1999/xhtml">Thrilled to have you officially join the Acme Ambassador Program!</p><p xmlns="http://www.w3.org/1999/xhtml">As a Acme Ambassador, you're joining the front line of change. You're freeing people from broken healthcare and giving them back control of their health.</p><p xmlns="http://www.w3.org/1999/xhtml">Your 3 quick steps to get started:</p><ol xmlns="http://www.w3.org/1999/xhtml"><li><p>Activate your membership with your 50% off code: <strong>ACME50OFF</strong></p></li><li><p><a target="_blank" rel="noopener noreferrer nofollow" href="https://partners.dub.co/programs/acme">Open your dashboard</a> and copy your referral link</p></li><li><p>Share Acme with your loved ones! Use our <a target="_blank" rel="noopener noreferrer nofollow" href="http://acme.dub.sh">Ambassador Hub</a> for all the information you need like message templates, images, and information about Acme.</p></li></ol><p xmlns="http://www.w3.org/1999/xhtml">And a bonus: make your first referral within 7 days and you'll also receive a limited-edition Acme hoodie.</p><img xmlns="http://www.w3.org/1999/xhtml" src="https://dubassets.com/programs/prog_CYCu7IMAapjkRpTnr8F1azjN/lander/image_JjbkiaM" style="max-width: 100%; height: auto; margin: 12px auto;" /><p xmlns="http://www.w3.org/1999/xhtml">We're here with you every step of the way.</p><p xmlns="http://www.w3.org/1999/xhtml">To your health,</p><p xmlns="http://www.w3.org/1999/xhtml">The Acme team</p>`,
},
}: {
program?: {
@@ -36,20 +34,12 @@ export default function CampaignEmail({
};
campaign?: {
type: "transactional" | "marketing";
- subject: string;
+ preview?: string | null;
body: string;
};
}) {
- // Wrap the HTML with styles to prevent overflow from large images
const styledHtml = `
<div style="max-width: 100%; overflow: hidden;">
- <style>
- #campaign-email-body img {
- max-width: 100% !important;
- height: auto !important;
- margin: 12px auto !important;
- }
- </style>
${campaign.body}
</div>
`;
@@ -57,14 +47,10 @@ export default function CampaignEmail({
return (
<Html>
<Head />
- <Preview>{campaign.subject}</Preview>
+ {campaign.preview && <Preview>{campaign.preview}</Preview>}
<Tailwind>
<Body className="mx-auto my-auto bg-white font-sans">
<Container className="mx-auto my-10 max-w-[600px] px-10 py-5">
- <Section className="mt-8">
- <Img src={DUB_WORDMARK} height="32" alt="Dub" />
- </Section>
-
<Section className="my-8">
<div className="flex items-center">
<Img
@@ -89,10 +75,7 @@ export default function CampaignEmail({
</Section>
<Section>
- <div
- id="campaign-email-body"
- dangerouslySetInnerHTML={{ __html: styledHtml }}
- />
+ <div dangerouslySetInnerHTML={{ __html: styledHtml }} />
</Section>
{program?.messagingEnabledAt &&
diff --git a/packages/prisma/schema/campaign.prisma b/packages/prisma/schema/campaign.prisma
index d2d9933748..32e5ad7988 100644
--- a/packages/prisma/schema/campaign.prisma
+++ b/packages/prisma/schema/campaign.prisma
@@ -27,6 +27,7 @@ model Campaign {
status CampaignStatus @default(draft)
name String
subject String
+ preview String? @db.Text
from String?
bodyJson Json @db.Json
scheduledAt DateTime?