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 domains & Marketing campaigns (#2964)

Kiran K7bf5e730410e
diff --git a/apps/web/app/(ee)/api/campaigns/[campaignId]/duplicate/route.ts b/apps/web/app/(ee)/api/campaigns/[campaignId]/duplicate/route.ts
index 7f105c55fe..8b055dc81e 100644
--- a/apps/web/app/(ee)/api/campaigns/[campaignId]/duplicate/route.ts
+++ b/apps/web/app/(ee)/api/campaigns/[campaignId]/duplicate/route.ts
@@ -58,6 +58,7 @@ export const POST = withWorkspace(
workflowId,
userId: session.user.id,
status: CampaignStatus.draft,
+ from: campaign.from,
name: `${campaign.name} (copy)`,
subject: campaign.subject,
bodyJson: campaign.bodyJson ?? DEFAULT_CAMPAIGN_BODY,
diff --git a/apps/web/app/(ee)/api/campaigns/[campaignId]/route.ts b/apps/web/app/(ee)/api/campaigns/[campaignId]/route.ts
index 57558e36f0..a375ecf503 100644
--- a/apps/web/app/(ee)/api/campaigns/[campaignId]/route.ts
+++ b/apps/web/app/(ee)/api/campaigns/[campaignId]/route.ts
@@ -1,21 +1,22 @@
import { getCampaignOrThrow } from "@/lib/api/campaigns/get-campaign-or-throw";
+import {
+ scheduleMarketingCampaign,
+ scheduleTransactionalCampaign,
+} from "@/lib/api/campaigns/schedule-campaigns";
+import { validateCampaign } from "@/lib/api/campaigns/validate-campaign";
import { throwIfInvalidGroupIds } from "@/lib/api/groups/throw-if-invalid-group-ids";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { parseRequestBody } from "@/lib/api/utils";
import { parseWorkflowConfig } from "@/lib/api/workflows/parse-workflow-config";
-import { isScheduledWorkflow } from "@/lib/api/workflows/utils";
import { withWorkspace } from "@/lib/auth";
import { qstash } from "@/lib/cron";
import {
CampaignSchema,
updateCampaignSchema,
} from "@/lib/zod/schemas/campaigns";
-import {
- WORKFLOW_ATTRIBUTE_TRIGGER,
- WORKFLOW_SCHEDULES,
-} from "@/lib/zod/schemas/workflows";
+import { WORKFLOW_ATTRIBUTE_TRIGGER } from "@/lib/zod/schemas/workflows";
import { prisma } from "@dub/prisma";
-import { APP_DOMAIN_WITH_NGROK, arrayEqual } from "@dub/utils";
+import { arrayEqual } from "@dub/utils";
import { PartnerGroup } from "@prisma/client";
import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
@@ -53,9 +54,6 @@ export const PATCH = withWorkspace(
const { campaignId } = params;
const programId = getDefaultProgramIdOrThrow(workspace);
- const { name, subject, status, bodyJson, groupIds, triggerCondition } =
- updateCampaignSchema.parse(await parseRequestBody(req));
-
const campaign = await getCampaignOrThrow({
programId,
campaignId,
@@ -63,6 +61,20 @@ export const PATCH = withWorkspace(
includeGroups: true,
});
+ const {
+ name,
+ subject,
+ from,
+ status,
+ bodyJson,
+ groupIds,
+ triggerCondition,
+ scheduledAt,
+ } = await validateCampaign({
+ input: updateCampaignSchema.parse(await parseRequestBody(req)),
+ campaign,
+ });
+
// if groupIds is provided and is different from the current groupIds, update the groups
let updatedPartnerGroups: PartnerGroup[] | undefined = undefined;
let shouldUpdateGroups = false;
@@ -109,8 +121,10 @@ export const PATCH = withWorkspace(
data: {
...(name && { name }),
...(subject && { subject }),
+ ...(from && { from }),
...(status && { status }),
...(bodyJson && { bodyJson }),
+ ...(scheduledAt !== undefined && { scheduledAt }),
...(shouldUpdateGroups && {
groups: {
deleteMany: {},
@@ -132,38 +146,16 @@ export const PATCH = withWorkspace(
waitUntil(
(async () => {
- if (
- !updatedCampaign.workflow ||
- !isScheduledWorkflow(updatedCampaign.workflow)
- ) {
- return;
- }
-
- // Decide whether to schedule the workflow or delete the schedule
- const shouldSchedule =
- (campaign.status === "draft" || campaign.status === "paused") &&
- updatedCampaign.status === "active";
-
- const shouldDeleteSchedule =
- campaign.status === "active" && updatedCampaign.status === "paused";
-
- const cronSchedule =
- WORKFLOW_SCHEDULES[updatedCampaign.workflow.trigger];
-
- if (!cronSchedule) {
- throw new Error(
- `Cron schedule not found for trigger ${updatedCampaign.workflow.trigger}`,
- );
- }
-
- if (shouldSchedule) {
- await qstash.schedules.create({
- destination: `${APP_DOMAIN_WITH_NGROK}/api/cron/workflows/${updatedCampaign.workflow.id}`,
- cron: cronSchedule,
- scheduleId: updatedCampaign.workflow.id,
+ if (updatedCampaign.type === "marketing") {
+ await scheduleMarketingCampaign({
+ campaign,
+ updatedCampaign,
+ });
+ } else if (updatedCampaign.type === "transactional") {
+ await scheduleTransactionalCampaign({
+ campaign,
+ updatedCampaign,
});
- } else if (shouldDeleteSchedule) {
- await qstash.schedules.delete(updatedCampaign.workflow.id);
}
})(),
);
@@ -212,17 +204,17 @@ export const DELETE = withWorkspace(
waitUntil(
(async () => {
- if (!campaign.workflow) {
- return;
- }
+ if (campaign.type === "marketing" && campaign.qstashMessageId) {
+ await qstash.messages.delete(campaign.qstashMessageId);
+ } else if (campaign.type === "transactional" && campaign.workflow) {
+ const { condition } = parseWorkflowConfig(campaign.workflow);
- const { condition } = parseWorkflowConfig(campaign.workflow);
+ if (condition.attribute === "partnerJoined") {
+ return;
+ }
- if (condition.attribute === "partnerJoined") {
- return;
+ await qstash.schedules.delete(campaign.workflow.id);
}
-
- await qstash.schedules.delete(campaign.workflow.id);
})(),
);
diff --git a/apps/web/app/(ee)/api/campaigns/route.ts b/apps/web/app/(ee)/api/campaigns/route.ts
index 4416d5042f..a339e9f7b8 100644
--- a/apps/web/app/(ee)/api/campaigns/route.ts
+++ b/apps/web/app/(ee)/api/campaigns/route.ts
@@ -1,11 +1,11 @@
import { DEFAULT_CAMPAIGN_BODY } from "@/lib/api/campaigns/constants";
-import { getCampaigns } from "@/lib/api/campaigns/get-campaigns";
import { createId } from "@/lib/api/create-id";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { WorkflowAction, WorkflowCondition } from "@/lib/types";
import {
+ CampaignSchema,
createCampaignSchema,
getCampaignsQuerySchema,
} from "@/lib/zod/schemas/campaigns";
@@ -22,12 +22,41 @@ export const GET = withWorkspace(
async ({ workspace, searchParams }) => {
const programId = getDefaultProgramIdOrThrow(workspace);
- const campaigns = await getCampaigns({
- ...getCampaignsQuerySchema.parse(searchParams),
- programId,
+ const { type, status, search, page, pageSize } =
+ getCampaignsQuerySchema.parse(searchParams);
+
+ const campaigns = await prisma.campaign.findMany({
+ where: {
+ programId,
+ type,
+ status,
+ ...(search && {
+ OR: [
+ { name: { contains: search } },
+ { subject: { contains: search } },
+ ],
+ }),
+ },
+ include: {
+ groups: true,
+ workflow: true,
+ },
+ orderBy: {
+ createdAt: "desc",
+ },
+ skip: (page - 1) * pageSize,
+ take: pageSize,
});
- return NextResponse.json(campaigns);
+ return NextResponse.json(
+ campaigns.map((campaign) =>
+ CampaignSchema.parse({
+ ...campaign,
+ groups: campaign.groups.map(({ groupId }) => ({ id: groupId })),
+ triggerCondition: campaign.workflow?.triggerConditions?.[0],
+ }),
+ ),
+ );
},
{
requiredPlan: ["advanced", "enterprise"],
@@ -91,9 +120,12 @@ export const POST = withWorkspace(
return campaign;
});
- return NextResponse.json({
- id: campaign.id,
- });
+ return NextResponse.json(
+ {
+ id: campaign.id,
+ },
+ { status: 201 },
+ );
},
{
requiredPlan: ["advanced", "enterprise"],
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.ts
index afacbf54c7..166ab07481 100644
--- a/apps/web/app/(ee)/api/cron/bounties/notify-partners/route.ts
+++ b/apps/web/app/(ee)/api/cron/bounties/notify-partners/route.ts
@@ -50,7 +50,7 @@ export async function POST(req: Request) {
});
}
- let diffMinutes = differenceInMinutes(bounty.startsAt, new Date());
+ const diffMinutes = differenceInMinutes(bounty.startsAt, new Date());
if (diffMinutes >= 10) {
return logAndRespond(
diff --git a/apps/web/app/(ee)/api/cron/campaigns/broadcast/route.ts b/apps/web/app/(ee)/api/cron/campaigns/broadcast/route.ts
new file mode 100644
index 0000000000..fe5db59303
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/campaigns/broadcast/route.ts
@@ -0,0 +1,317 @@
+import { validateCampaignFromAddress } from "@/lib/api/campaigns/validate-campaign";
+import { createId } from "@/lib/api/create-id";
+import { handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { renderCampaignEmailHTML } from "@/lib/api/workflows/render-campaign-email-html";
+import { qstash } from "@/lib/cron";
+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
+import { TiptapNode } from "@/lib/types";
+import { sendBatchEmail } from "@dub/email";
+import CampaignEmail from "@dub/email/templates/campaign-email";
+import { prisma } from "@dub/prisma";
+import { NotificationEmailType } from "@dub/prisma/client";
+import { APP_DOMAIN_WITH_NGROK, log } from "@dub/utils";
+import { differenceInMinutes } from "date-fns";
+import { headers } from "next/headers";
+import { z } from "zod";
+import { logAndRespond } from "../../utils";
+
+export const dynamic = "force-dynamic";
+
+const schema = z.object({
+ campaignId: z.string(),
+ startingAfter: z.string().optional(),
+ batchNumber: z
+ .number()
+ .optional()
+ .default(1)
+ .describe("Keep track of the batches sent."),
+});
+
+const EMAIL_BATCH_SIZE = 100; // Batch size
+const BATCH_DELAY_SECONDS = 2; // Delay between batches
+const EXTENDED_DELAY_SECONDS = 30; // Extended delay after 25 batches
+const EXTENDED_DELAY_INTERVAL = 25; // Number of batches after which to extend the delay
+
+// POST /api/cron/campaigns/broadcast
+// Send marketing campaigns to partners in batches
+export async function POST(req: Request) {
+ try {
+ const rawBody = await req.text();
+
+ await verifyQstashSignature({
+ req,
+ rawBody,
+ });
+
+ let { campaignId, startingAfter, batchNumber } = schema.parse(
+ JSON.parse(rawBody),
+ );
+
+ const campaign = await prisma.campaign.findUnique({
+ where: {
+ id: campaignId,
+ },
+ include: {
+ groups: true,
+ program: {
+ include: {
+ emailDomains: {
+ where: {
+ status: "verified",
+ },
+ },
+ },
+ },
+ },
+ });
+
+ if (!campaign) {
+ return logAndRespond(`Campaign ${campaignId} not found.`);
+ }
+
+ if (campaign.type !== "marketing") {
+ return logAndRespond(
+ `Campaign ${campaignId} is not a marketing campaign.`,
+ );
+ }
+
+ if (!["scheduled", "sending"].includes(campaign.status)) {
+ return logAndRespond(
+ `Campaign ${campaignId} must be in "sending" or "scheduled" status to broadcast.`,
+ );
+ }
+
+ // This is a safety check to ensure the campaign is not scheduled to broadcast too far in the future
+ // Ideally this should not happen but just in case
+ if (campaign.scheduledAt) {
+ const diffMinutes = differenceInMinutes(campaign.scheduledAt, new Date());
+
+ if (diffMinutes >= 5) {
+ await log({
+ message: `Campaign ${campaignId} broadcast was skipped because it is scheduled to broadcast in the future. This might be an error in the campaign scheduling.`,
+ type: "errors",
+ });
+
+ return logAndRespond(
+ `Campaign ${campaignId} is not scheduled to broadcast yet.`,
+ );
+ }
+ }
+
+ // This is a safety check to ensure the campaign broadcast is not "initiated" multiple times
+ const headersList = await headers();
+ const upstashMessageId = headersList.get("Upstash-Message-Id");
+
+ if (
+ !startingAfter && // First run
+ campaign.qstashMessageId &&
+ upstashMessageId !== campaign.qstashMessageId
+ ) {
+ return logAndRespond(
+ `Campaign ${campaignId} broadcast was skipped because it is not the current message being processed.`,
+ );
+ }
+
+ const program = campaign.program;
+
+ // TODO: We should make the from address required. There are existing campaign without from address
+ if (campaign.from) {
+ validateCampaignFromAddress({
+ campaign,
+ emailDomains: program.emailDomains,
+ });
+ }
+
+ // Mark the campaign as sending
+ try {
+ await prisma.campaign.update({
+ where: {
+ id: campaignId,
+ status: "scheduled",
+ },
+ data: {
+ status: "sending",
+ },
+ });
+ } catch (error) {
+ //
+ }
+
+ const campaignGroupIds = campaign.groups.map(({ groupId }) => groupId);
+
+ const programEnrollments = await prisma.programEnrollment.findMany({
+ where: {
+ programId: campaign.programId,
+ status: "approved",
+ ...(campaignGroupIds.length > 0 && {
+ groupId: {
+ in: campaignGroupIds,
+ },
+ }),
+ },
+ select: {
+ id: true,
+ partner: {
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ users: {
+ where: {
+ notificationPreferences: {
+ marketingCampaign: true,
+ },
+ },
+ select: {
+ user: {
+ select: {
+ id: true,
+ email: true,
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ take: EMAIL_BATCH_SIZE,
+ skip: startingAfter ? 1 : 0,
+ ...(startingAfter && {
+ cursor: {
+ id: startingAfter,
+ },
+ }),
+ orderBy: {
+ id: "asc",
+ },
+ });
+
+ const partnerUsers = programEnrollments.flatMap((enrollment) =>
+ enrollment.partner.users
+ .filter(({ user }) => user.email)
+ .map(({ user }) => ({
+ ...user,
+ partner: {
+ ...enrollment.partner,
+ users: undefined,
+ },
+ enrollment: {
+ ...enrollment,
+ partner: undefined,
+ },
+ })),
+ );
+
+ console.table(
+ partnerUsers.map((partnerUser) => ({
+ id: partnerUser.partner.id,
+ name: partnerUser.partner.name,
+ email: partnerUser.email,
+ })),
+ );
+
+ if (partnerUsers.length > 0) {
+ const { data, error } = await sendBatchEmail(
+ partnerUsers.map((partnerUser) => ({
+ variant: "marketing",
+ from: `${program.name} <${campaign.from}>`,
+ to: partnerUser.email!,
+ subject: campaign.subject,
+ ...(program.supportEmail ? { replyTo: program.supportEmail } : {}),
+ react: CampaignEmail({
+ program: {
+ name: program.name,
+ slug: program.slug,
+ logo: program.logo,
+ },
+ campaign: {
+ type: campaign.type,
+ subject: campaign.subject,
+ body: renderCampaignEmailHTML({
+ content: campaign.bodyJson as unknown as TiptapNode,
+ variables: {
+ PartnerName: partnerUser.partner.name,
+ PartnerEmail: partnerUser.partner.email,
+ },
+ }),
+ },
+ }),
+ tags: [{ name: "type", value: "notification-email" }],
+ headers: {
+ "Idempotency-Key": `${campaign.id}-${startingAfter}`,
+ },
+ })),
+ );
+
+ if (error) {
+ console.error(error);
+ }
+
+ if (data) {
+ await prisma.notificationEmail.createMany({
+ data: partnerUsers.map((partnerUser, idx) => ({
+ id: createId({ prefix: "em_" }),
+ type: NotificationEmailType.Campaign,
+ emailId: data.data[idx].id,
+ campaignId: campaign.id,
+ programId: campaign.programId,
+ partnerId: partnerUser.partner.id,
+ recipientUserId: partnerUser.id,
+ })),
+ skipDuplicates: true,
+ });
+ }
+ }
+
+ if (programEnrollments.length === EMAIL_BATCH_SIZE) {
+ startingAfter = programEnrollments[programEnrollments.length - 1].id;
+
+ // Add BATCH_DELAY_SECONDS pause between each batch, and a longer EXTENDED_DELAY_SECONDS cooldown after every EXTENDED_DELAY_INTERVAL batches.
+ let delay = 0;
+ if (batchNumber > 0 && batchNumber % EXTENDED_DELAY_INTERVAL === 0) {
+ delay = EXTENDED_DELAY_SECONDS;
+ } else {
+ delay = BATCH_DELAY_SECONDS;
+ }
+
+ await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/campaigns/broadcast`,
+ method: "POST",
+ delay,
+ body: {
+ campaignId,
+ startingAfter,
+ batchNumber: batchNumber + 1,
+ },
+ });
+
+ return logAndRespond(
+ `Enqueued next page (${startingAfter}) for campaign ${campaignId} to run after ${delay} seconds.`,
+ );
+ }
+
+ // Mark the campaign as sent
+ try {
+ await prisma.campaign.update({
+ where: {
+ id: campaignId,
+ status: "sending",
+ },
+ data: {
+ status: "sent",
+ },
+ });
+ } catch (error) {
+ //
+ }
+
+ return logAndRespond(`Finished broadcasting campaign ${campaignId}.`);
+ } catch (error) {
+ await log({
+ message: "Campaign broadcast cron failed. Error: " + error.message,
+ type: "errors",
+ });
+
+ return handleAndReturnErrorResponse(error);
+ }
+}
diff --git a/apps/web/app/(ee)/api/cron/cleanup/e2e-tests/route.ts b/apps/web/app/(ee)/api/cron/cleanup/e2e-tests/route.ts
index 10361ba18f..cbd05cc261 100644
--- a/apps/web/app/(ee)/api/cron/cleanup/e2e-tests/route.ts
+++ b/apps/web/app/(ee)/api/cron/cleanup/e2e-tests/route.ts
@@ -21,7 +21,7 @@ export async function GET(req: Request) {
try {
await verifyVercelSignature(req);
- const oneHourAgo = new Date(Date.now() - 1000 * 60 * 60);
+ const oneDayAgo = new Date(Date.now() - 1000 * 60 * 60 * 24);
const [links, domains, tags, partners, users] = await Promise.all([
prisma.link.findMany({
@@ -29,7 +29,7 @@ export async function GET(req: Request) {
userId: E2E_USER_ID,
projectId: E2E_WORKSPACE_ID,
createdAt: {
- lt: oneHourAgo,
+ lt: oneDayAgo,
},
},
include: {
@@ -49,7 +49,7 @@ export async function GET(req: Request) {
endsWith: ".dub-internal-test.com",
},
createdAt: {
- lt: oneHourAgo,
+ lt: oneDayAgo,
},
},
select: {
@@ -64,7 +64,7 @@ export async function GET(req: Request) {
startsWith: "e2e-",
},
createdAt: {
- lt: oneHourAgo,
+ lt: oneDayAgo,
},
},
}),
@@ -75,7 +75,7 @@ export async function GET(req: Request) {
endsWith: "@dub-internal-test.com",
},
createdAt: {
- lt: oneHourAgo,
+ lt: oneDayAgo,
},
},
select: {
@@ -89,7 +89,7 @@ export async function GET(req: Request) {
endsWith: "@dub-internal-test.com",
},
createdAt: {
- lt: oneHourAgo,
+ lt: oneDayAgo,
},
},
}),
diff --git a/apps/web/app/(ee)/api/cron/email-domains/verify/route.ts b/apps/web/app/(ee)/api/cron/email-domains/verify/route.ts
new file mode 100644
index 0000000000..9949fa2808
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/email-domains/verify/route.ts
@@ -0,0 +1,99 @@
+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { verifyVercelSignature } from "@/lib/cron/verify-vercel";
+import { resend } from "@dub/email/resend/client";
+import { prisma } from "@dub/prisma";
+import { log } from "@dub/utils";
+import { EmailDomain } from "@prisma/client";
+import { NextResponse } from "next/server";
+import { logAndRespond } from "../../utils";
+
+export const dynamic = "force-dynamic";
+
+// GET /api/cron/email-domains/verify
+// Runs every hour (0 * * * *)
+export async function GET(req: Request) {
+ try {
+ await verifyVercelSignature(req);
+
+ if (!resend) {
+ throw new DubApiError({
+ code: "internal_server_error",
+ message: "Resend is not configured.",
+ });
+ }
+
+ const domains = await prisma.emailDomain.findMany({
+ where: {
+ resendDomainId: {
+ not: null,
+ },
+ },
+ orderBy: {
+ lastChecked: "asc",
+ },
+ take: 10,
+ });
+
+ if (domains.length === 0) {
+ return logAndRespond(
+ "No email domains to check the verification status.",
+ );
+ }
+
+ const results = await Promise.allSettled(
+ domains.map((domain) => verifyEmailDomain(domain)),
+ );
+
+ return NextResponse.json(results);
+ } catch (error) {
+ console.error(error);
+
+ await log({
+ message:
+ "Email domains verification cron failed. Error: " + error.message,
+ type: "errors",
+ });
+
+ return handleAndReturnErrorResponse(error);
+ }
+}
+
+async function verifyEmailDomain(domain: EmailDomain) {
+ if (!domain.resendDomainId) {
+ return null;
+ }
+
+ const { data: resendDomain, error } = await resend!.domains.get(
+ domain.resendDomainId,
+ );
+
+ if (error) {
+ return null;
+ }
+
+ await prisma.emailDomain.update({
+ where: {
+ id: domain.id,
+ },
+ data: {
+ status: resendDomain.status,
+ lastChecked: new Date(),
+ },
+ });
+
+ const statusChanged = resendDomain.status !== domain.status;
+
+ if (statusChanged) {
+ await log({
+ message: `Email domain *${domain.slug}* status changed to *${resendDomain.status}*`,
+ type: "cron",
+ });
+ }
+
+ // TODO:
+ // Send email notification
+
+ return {
+ domain,
+ };
+}
diff --git a/apps/web/app/(ee)/api/cron/program-application-reminder/route.ts b/apps/web/app/(ee)/api/cron/program-application-reminder/route.ts
index 25e42b5d35..44208bb063 100644
--- a/apps/web/app/(ee)/api/cron/program-application-reminder/route.ts
+++ b/apps/web/app/(ee)/api/cron/program-application-reminder/route.ts
@@ -88,7 +88,7 @@ export async function POST(req: Request) {
await qstash.publishJSON({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/program-application-reminder`,
- // repeat every 24 hours, but it'll be cancelled if the application is more than 3 days old or is associated with a partner
+ // repeat every 24 hours, but it'll be canceled if the application is more than 3 days old or is associated with a partner
delay: 24 * 60 * 60,
body: {
applicationId: application.id,
diff --git a/apps/web/app/(ee)/api/email-domains/[domain]/route.ts b/apps/web/app/(ee)/api/email-domains/[domain]/route.ts
new file mode 100644
index 0000000000..9510ba6baf
--- /dev/null
+++ b/apps/web/app/(ee)/api/email-domains/[domain]/route.ts
@@ -0,0 +1,155 @@
+import { getEmailDomainOrThrow } from "@/lib/api/domains/get-email-domain-or-throw";
+import { DubApiError } from "@/lib/api/errors";
+import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { parseRequestBody } from "@/lib/api/utils";
+import { withWorkspace } from "@/lib/auth";
+import {
+ EmailDomainSchema,
+ updateEmailDomainBodySchema,
+} from "@/lib/zod/schemas/email-domains";
+import { resend } from "@dub/email/resend";
+import { prisma } from "@dub/prisma";
+import { Prisma } from "@prisma/client";
+import { waitUntil } from "@vercel/functions";
+import { NextResponse } from "next/server";
+
+// PATCH /api/email-domains/[domain] - update an email domain
+export const PATCH = withWorkspace(
+ async ({ workspace, params, req }) => {
+ const { domain } = params;
+ const programId = getDefaultProgramIdOrThrow(workspace);
+
+ const { slug } = updateEmailDomainBodySchema.parse(
+ await parseRequestBody(req),
+ );
+
+ const emailDomain = await getEmailDomainOrThrow({
+ programId,
+ domain,
+ });
+
+ const domainChanged = slug && slug !== emailDomain.slug;
+
+ if (domainChanged) {
+ if (!resend) {
+ throw new DubApiError({
+ code: "internal_server_error",
+ message: "Resend is not configured.",
+ });
+ }
+
+ if (emailDomain.resendDomainId) {
+ await resend.domains.remove(emailDomain.resendDomainId);
+ }
+
+ const { data: resendDomain, error } = await resend.domains.create({
+ name: slug,
+ });
+
+ if (error) {
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: error.message,
+ });
+ }
+
+ waitUntil(
+ Promise.allSettled([
+ prisma.emailDomain.update({
+ where: {
+ id: emailDomain.id,
+ },
+ data: {
+ resendDomainId: resendDomain.id,
+ status: "pending",
+ },
+ }),
+
+ resend.domains.verify(resendDomain.id),
+ ]),
+ );
+ }
+
+ try {
+ await prisma.emailDomain.update({
+ where: {
+ id: emailDomain.id,
+ },
+ data: {
+ slug,
+ },
+ });
+
+ return NextResponse.json(EmailDomainSchema.parse(emailDomain));
+ } catch (error) {
+ console.error(error);
+
+ if (error instanceof Prisma.PrismaClientKnownRequestError) {
+ if (error.code === "P2002") {
+ throw new DubApiError({
+ code: "conflict",
+ message: `This ${slug} domain has been registered already by another program.`,
+ });
+ }
+ }
+
+ throw new DubApiError({
+ code: "internal_server_error",
+ message: error.message,
+ });
+ }
+ },
+ {
+ requiredPlan: ["advanced", "enterprise"],
+ requiredPermissions: ["domains.write"],
+ },
+);
+
+// DELETE /api/email-domains/[domain] - delete an email domain
+export const DELETE = withWorkspace(
+ async ({ workspace, params }) => {
+ const { domain } = params;
+ const programId = getDefaultProgramIdOrThrow(workspace);
+
+ const emailDomain = await getEmailDomainOrThrow({
+ programId,
+ domain,
+ });
+
+ // Check if any active campaigns use this domain
+ const activeCampaignsCount = await prisma.campaign.count({
+ where: {
+ programId,
+ status: {
+ in: ["active", "scheduled", "sending"],
+ },
+ from: {
+ endsWith: `@${emailDomain.slug}`,
+ },
+ },
+ });
+
+ if (activeCampaignsCount > 0) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: `There are active campaigns using this email domain. You can not delete it until all campaigns are completed or paused.`,
+ });
+ }
+
+ await prisma.emailDomain.delete({
+ where: {
+ id: emailDomain.id,
+ },
+ });
+
+ if (emailDomain.resendDomainId && resend) {
+ await resend.domains.remove(emailDomain.resendDomainId);
+ }
+
+ return NextResponse.json({ id: emailDomain.id });
+ },
+ {
+ requiredPlan: ["advanced", "enterprise"],
+ requiredPermissions: ["domains.write"],
+ },
+);
diff --git a/apps/web/app/(ee)/api/email-domains/[domain]/verify/route.ts b/apps/web/app/(ee)/api/email-domains/[domain]/verify/route.ts
new file mode 100644
index 0000000000..b12c9607d4
--- /dev/null
+++ b/apps/web/app/(ee)/api/email-domains/[domain]/verify/route.ts
@@ -0,0 +1,67 @@
+import { getEmailDomainOrThrow } from "@/lib/api/domains/get-email-domain-or-throw";
+import { DubApiError } from "@/lib/api/errors";
+import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { withWorkspace } from "@/lib/auth";
+import { resend } from "@dub/email/resend";
+import { prisma } from "@dub/prisma";
+import { NextResponse } from "next/server";
+
+// GET /api/email-domains/[domain]/verify - verify an email domain
+export const GET = withWorkspace(
+ async ({ workspace, params }) => {
+ const { domain } = params;
+ const programId = getDefaultProgramIdOrThrow(workspace);
+
+ const emailDomain = await getEmailDomainOrThrow({
+ programId,
+ domain,
+ });
+
+ if (!resend) {
+ throw new DubApiError({
+ code: "internal_server_error",
+ message: "Resend is not configured.",
+ });
+ }
+
+ if (!emailDomain.resendDomainId) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "Resend domain ID is not found for this domain.",
+ });
+ }
+
+ const [verificationResponse, domainResponse] = await Promise.all([
+ resend.domains.verify(emailDomain.resendDomainId),
+ resend.domains.get(emailDomain.resendDomainId),
+ ]);
+
+ if (verificationResponse.error || domainResponse.error) {
+ throw new DubApiError({
+ code: "internal_server_error",
+ message:
+ verificationResponse.error?.message ||
+ domainResponse.error?.message ||
+ "Failed to verify email domain. Please try again later.",
+ });
+ }
+
+ if (emailDomain.status !== domainResponse.data.status) {
+ await prisma.emailDomain.update({
+ where: {
+ id: emailDomain.id,
+ },
+ data: {
+ status: domainResponse.data.status,
+ lastChecked: new Date(),
+ },
+ });
+ }
+
+ return NextResponse.json(domainResponse.data);
+ },
+ {
+ requiredPlan: ["advanced", "enterprise"],
+ requiredPermissions: ["domains.read"],
+ },
+);
diff --git a/apps/web/app/(ee)/api/email-domains/route.ts b/apps/web/app/(ee)/api/email-domains/route.ts
new file mode 100644
index 0000000000..8fbcae85ef
--- /dev/null
+++ b/apps/web/app/(ee)/api/email-domains/route.ts
@@ -0,0 +1,129 @@
+import { createId } from "@/lib/api/create-id";
+import { DubApiError } from "@/lib/api/errors";
+import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { parseRequestBody } from "@/lib/api/utils";
+import { withWorkspace } from "@/lib/auth";
+import {
+ createEmailDomainBodySchema,
+ EmailDomainSchema,
+} from "@/lib/zod/schemas/email-domains";
+import { resend } from "@dub/email/resend";
+import { prisma } from "@dub/prisma";
+import { Prisma } from "@prisma/client";
+import { waitUntil } from "@vercel/functions";
+import { NextResponse } from "next/server";
+import { z } from "zod";
+
+// GET /api/email-domains - get all email domains for a program
+export const GET = withWorkspace(
+ async ({ workspace }) => {
+ const programId = getDefaultProgramIdOrThrow(workspace);
+
+ const emailDomains = await prisma.emailDomain.findMany({
+ where: {
+ programId,
+ },
+ });
+
+ return NextResponse.json(z.array(EmailDomainSchema).parse(emailDomains));
+ },
+ {
+ requiredPlan: ["advanced", "enterprise"],
+ requiredPermissions: ["domains.read"],
+ },
+);
+
+// POST /api/email-domains - create an email domain
+export const POST = withWorkspace(
+ async ({ workspace, req }) => {
+ const programId = getDefaultProgramIdOrThrow(workspace);
+
+ const { slug } = createEmailDomainBodySchema.parse(
+ await parseRequestBody(req),
+ );
+
+ const existingEmailDomain = await prisma.emailDomain.findFirst({
+ where: {
+ programId,
+ },
+ });
+
+ if (existingEmailDomain) {
+ throw new DubApiError({
+ code: "conflict",
+ message:
+ "An email domain has already been configured for this program. Each program can only have one email domain.",
+ });
+ }
+
+ if (!resend) {
+ throw new DubApiError({
+ code: "internal_server_error",
+ message: "Resend is not configured.",
+ });
+ }
+
+ const { data: resendDomain, error: resendError } =
+ await resend.domains.create({
+ name: slug,
+ });
+
+ if (resendError) {
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: resendError.message,
+ });
+ }
+
+ try {
+ const emailDomain = await prisma.emailDomain.create({
+ data: {
+ id: createId({ prefix: "dom_" }),
+ workspaceId: workspace.id,
+ programId,
+ slug,
+ resendDomainId: resendDomain.id,
+ },
+ });
+
+ waitUntil(
+ (async () => {
+ const { error: resendError } = await resend.domains.verify(
+ resendDomain.id,
+ );
+
+ if (resendError) {
+ console.error(
+ `Resend domain verify failed - ${resendError.message}`,
+ );
+ }
+ })(),
+ );
+
+ return NextResponse.json(EmailDomainSchema.parse(emailDomain), {
+ status: 201,
+ });
+ } catch (error) {
+ // Cleanup to avoid orphaned Resend domains
+ waitUntil(resend.domains.remove(resendDomain.id));
+
+ if (error instanceof Prisma.PrismaClientKnownRequestError) {
+ if (error.code === "P2002") {
+ throw new DubApiError({
+ code: "conflict",
+ message: `This ${slug} domain has been registered already by another program.`,
+ });
+ }
+ }
+
+ throw new DubApiError({
+ code: "internal_server_error",
+ message: error.message,
+ });
+ }
+ },
+ {
+ requiredPlan: ["advanced", "enterprise"],
+ requiredPermissions: ["domains.write"],
+ },
+);
diff --git a/apps/web/app/(ee)/api/partner-profile/notification-preferences/route.ts b/apps/web/app/(ee)/api/partner-profile/notification-preferences/route.ts
index 6d966adbdb..8b3fd79463 100644
--- a/apps/web/app/(ee)/api/partner-profile/notification-preferences/route.ts
+++ b/apps/web/app/(ee)/api/partner-profile/notification-preferences/route.ts
@@ -16,6 +16,7 @@ export const GET = withPartnerProfile(async ({ partner, session }) => {
commissionCreated: true,
applicationApproved: true,
newMessageFromProgram: true,
+ marketingCampaign: true,
},
},
);
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/notifications/page-client.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/notifications/page-client.tsx
index 7d83dd54f3..84ce87200a 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/notifications/page-client.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/notifications/page-client.tsx
@@ -4,6 +4,7 @@ import { updatePartnerNotificationPreference } from "@/lib/actions/partners/upda
import { partnerNotificationTypes } from "@/lib/zod/schemas/partner-profile";
import {
CircleCheck,
+ Flag6,
InvoiceDollar,
Msgs,
Switch,
@@ -34,6 +35,12 @@ const notifications = [
title: "New message from program",
description: "Alert when a new message is received from a program.",
},
+ {
+ type: "marketingCampaign",
+ icon: Flag6,
+ title: "Marketing campaigns",
+ description: "Receive marketing emails from your programs.",
+ },
] as const;
export function PartnerSettingsNotificationsPageClient() {
diff --git a/apps/web/app/api/resend/webhook/email-bounced.ts b/apps/web/app/api/resend/webhook/email-bounced.ts
index 09384e1709..549084b84c 100644
--- a/apps/web/app/api/resend/webhook/email-bounced.ts
+++ b/apps/web/app/api/resend/webhook/email-bounced.ts
@@ -2,11 +2,9 @@ import { prisma } from "@dub/prisma";
export async function emailBounced({
email_id: emailId,
- subject,
tags,
}: {
email_id: string;
- subject?: string;
tags?: Record<string, string>;
}) {
if (tags?.type !== "notification-email") {
diff --git a/apps/web/app/api/resend/webhook/email-delivered.ts b/apps/web/app/api/resend/webhook/email-delivered.ts
index 78eb63f0af..4faeaa551f 100644
--- a/apps/web/app/api/resend/webhook/email-delivered.ts
+++ b/apps/web/app/api/resend/webhook/email-delivered.ts
@@ -2,11 +2,9 @@ import { prisma } from "@dub/prisma";
export async function emailDelivered({
email_id: emailId,
- subject,
tags,
}: {
email_id: string;
- subject?: string;
tags?: Record<string, string>;
}) {
if (tags?.type !== "notification-email") {
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-info.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-info.tsx
index 2dc82ec50c..4ef7e23520 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-info.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-info.tsx
@@ -6,7 +6,7 @@ import {
SubmissionsCountByStatus,
useBountySubmissionsCount,
} from "@/lib/swr/use-bounty-submissions-count";
-import { usePartnersCountBounty } from "@/lib/swr/use-partners-count-bounty";
+import { usePartnersCountByGroupIds } from "@/lib/swr/use-partners-count-by-groupids";
import { BountyThumbnailImage } from "@/ui/partners/bounties/bounty-thumbnail-image";
import { formatDate, nFormatter, pluralize } from "@dub/utils";
import { CalendarDays, Gift, Users } from "lucide-react";
@@ -32,8 +32,10 @@ export function BountyInfo() {
return submissionsCount?.find((s) => s.status === "submitted")?.count ?? 0;
}, [submissionsCount]);
- const { totalPartnersForBounty, loading: totalPartnersForBountyLoading } =
- usePartnersCountBounty({ bounty });
+ const { totalPartners, loading: totalPartnersForBountyLoading } =
+ usePartnersCountByGroupIds({
+ groupIds: bounty?.groups.map((group) => group.id),
+ });
if (loading) {
return <BountyInfoSkeleton />;
@@ -75,7 +77,7 @@ export function BountyInfo() {
<div className="flex items-center space-x-2">
<Users className="size-4 shrink-0" />
<div className="text-sm text-neutral-500">
- {totalSubmissions === totalPartnersForBounty ? (
+ {totalSubmissions === totalPartners ? (
<>All</>
) : (
<>
@@ -92,11 +94,11 @@ export function BountyInfo() {
) : (
<>
<span className="font-medium text-neutral-700">
- {nFormatter(totalPartnersForBounty, { full: true })}
+ {nFormatter(totalPartners, { full: true })}
</span>
</>
)}{" "}
- {pluralize("partner", totalSubmissions ?? totalPartnersForBounty)}{" "}
+ {pluralize("partner", totalSubmissions ?? totalPartners)}{" "}
{bounty.type === "performance" ? "completed" : "submitted"}
{readyForReviewSubmissions > 0 && (
<>
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-card.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-card.tsx
index 931506c9a8..005012c046 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-card.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-card.tsx
@@ -1,5 +1,5 @@
import { getBountyRewardDescription } from "@/lib/partners/get-bounty-reward-description";
-import { usePartnersCountBounty } from "@/lib/swr/use-partners-count-bounty";
+import { usePartnersCountByGroupIds } from "@/lib/swr/use-partners-count-by-groupids";
import useWorkspace from "@/lib/swr/use-workspace";
import { BountyListProps } from "@/lib/types";
import { BountyThumbnailImage } from "@/ui/partners/bounties/bounty-thumbnail-image";
@@ -10,8 +10,8 @@ import Link from "next/link";
export function BountyCard({ bounty }: { bounty: BountyListProps }) {
const { slug: workspaceSlug } = useWorkspace();
- const { totalPartnersForBounty, loading } = usePartnersCountBounty({
- bounty,
+ const { totalPartners, loading } = usePartnersCountByGroupIds({
+ groupIds: bounty.groups.map((group) => group.id),
});
return (
@@ -66,7 +66,7 @@ export function BountyCard({ bounty }: { bounty: BountyListProps }) {
<div className="text-content-subtle flex items-center gap-2 text-sm font-medium">
<Users className="size-3.5" />
<div className="h-5">
- {bounty.submissionsCountData?.total === totalPartnersForBounty ? (
+ {bounty.submissionsCountData?.total === totalPartners ? (
<>All</>
) : (
<>
@@ -83,13 +83,13 @@ export function BountyCard({ bounty }: { bounty: BountyListProps }) {
) : (
<>
<span className="text-content-default">
- {nFormatter(totalPartnersForBounty, { full: true })}
+ {nFormatter(totalPartners, { full: true })}
</span>{" "}
</>
)}{" "}
{pluralize(
"partner",
- bounty.submissionsCountData?.total || totalPartnersForBounty,
+ bounty.submissionsCountData?.total || totalPartners,
)}{" "}
{bounty.type === "performance" ? "completed" : "submitted"}
</div>
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/confirm-create-bounty-modal.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/confirm-create-bounty-modal.tsx
index b08e18eade..4c57160720 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/confirm-create-bounty-modal.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/confirm-create-bounty-modal.tsx
@@ -1,6 +1,6 @@
import { getBountyRewardDescription } from "@/lib/partners/get-bounty-reward-description";
import { getPlanCapabilities } from "@/lib/plan-capabilities";
-import { usePartnersCountBounty } from "@/lib/swr/use-partners-count-bounty";
+import { usePartnersCountByGroupIds } from "@/lib/swr/use-partners-count-by-groupids";
import useWorkspace from "@/lib/swr/use-workspace";
import { BountyProps } from "@/lib/types";
import { BountyThumbnailImage } from "@/ui/partners/bounties/bounty-thumbnail-image";
@@ -48,8 +48,8 @@ function ConfirmCreateBountyModal({
canSendEmailCampaigns,
);
- const { totalPartnersForBounty, loading } = usePartnersCountBounty({
- bounty,
+ const { totalPartners, loading } = usePartnersCountByGroupIds({
+ groupIds: bounty?.groups.map((group) => group.id),
});
const handleConfirm = async () => {
@@ -149,9 +149,9 @@ function ConfirmCreateBountyModal({
{loading ? (
<span className="inline-block h-4 w-6 animate-pulse rounded bg-neutral-200 align-text-bottom" />
) : (
- nFormatter(totalPartnersForBounty, { full: true })
+ nFormatter(totalPartners, { full: true })
)}{" "}
- selected {pluralize("partner", totalPartnersForBounty)}
+ selected {pluralize("partner", totalPartners)}
</strong>
</span>
</label>
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-action-bar.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-action-bar.tsx
index 1f271cc343..7cb92cf6fd 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-action-bar.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-action-bar.tsx
@@ -1,3 +1,4 @@
+import { CAMPAIGN_EDITABLE_STATUSES } from "@/lib/api/campaigns/constants";
import { Campaign } from "@/lib/types";
import { Button } from "@dub/ui";
import { cn } from "@dub/utils";
@@ -26,7 +27,9 @@ export function CampaignActionBar({
// Only show action bar for non-draft campaigns when there are changes
const showActionBar =
- campaignStatus !== "draft" && (isDirty || isSubmitting || isSaving);
+ CAMPAIGN_EDITABLE_STATUSES.includes(campaignStatus) &&
+ campaignStatus !== "draft" &&
+ (isDirty || isSubmitting || isSaving);
return (
<div
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-controls.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-controls.tsx
index 6651ec3888..55d8a5117b 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-controls.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-controls.tsx
@@ -1,12 +1,12 @@
import { mutatePrefix } from "@/lib/swr/mutate";
import { useApiMutation } from "@/lib/swr/use-api-mutation";
import useWorkspace from "@/lib/swr/use-workspace";
-import { Campaign, UpdateCampaignFormData } from "@/lib/types";
-import { useConfirmModal } from "@/ui/modals/confirm-modal";
+import { Campaign } from "@/lib/types";
import { ThreeDots } from "@/ui/shared/icons";
import { CampaignStatus } from "@dub/prisma/client";
import {
Button,
+ CircleXmark,
Duplicate,
Flask,
LoadingCircle,
@@ -19,27 +19,25 @@ import {
useMediaQuery,
} from "@dub/ui";
import { Command } from "cmdk";
+import { isFuture } from "date-fns";
import { useRouter } from "next/navigation";
import { useCallback, useState } from "react";
import { useWatch } from "react-hook-form";
-import { toast } from "sonner";
import { useDeleteCampaignModal } from "../delete-campaign-modal";
import { useCampaignFormContext } from "./campaign-form-context";
import { useSendEmailPreviewModal } from "./send-email-preview-modal";
+import { useCampaignConfirmationModals } from "./use-campaign-confirmation-modals";
interface CampaignControlsProps {
campaign: Pick<Campaign, "id" | "name" | "type" | "status">;
}
export function CampaignControls({ campaign }: CampaignControlsProps) {
- const { isMobile } = useMediaQuery();
const router = useRouter();
+ const { isMobile } = useMediaQuery();
const { slug: workspaceSlug } = useWorkspace();
const [openPopover, setOpenPopover] = useState(false);
- const { control, getValues } = useCampaignFormContext();
-
- const { makeRequest, isSubmitting: isUpdatingCampaign } =
- useApiMutation<Campaign>();
+ const { control } = useCampaignFormContext();
const {
makeRequest: duplicateCampaign,
@@ -54,75 +52,25 @@ export function CampaignControls({ campaign }: CampaignControlsProps) {
const { DeleteCampaignModal, setShowDeleteCampaignModal } =
useDeleteCampaignModal(campaign);
- // Confirmation modals
- const {
- confirmModal: publishConfirmModal,
- setShowConfirmModal: setShowPublishModal,
- } = useConfirmModal({
- title: "Publish Campaign",
- description:
- "Are you sure you want to publish this email campaign? It will be sent to all selected partner groups.",
- onConfirm: async () => {
- await updateCampaign(
- {
- ...getValues(),
- status: CampaignStatus.active,
- },
- () => {
- toast.success("Email campaign published!");
- router.push(`/${workspaceSlug}/program/campaigns`);
- },
- );
- },
- confirmText: "Publish",
- confirmShortcut: "Enter",
- });
-
- const {
- confirmModal: pauseConfirmModal,
- setShowConfirmModal: setShowPauseModal,
- } = useConfirmModal({
- title: "Pause Campaign",
- description:
- "Are you sure you want to pause this email campaign? It will stop sending emails to new recipients.",
- onConfirm: async () => {
- await updateCampaign(
- {
- status: CampaignStatus.paused,
- },
- () => {
- toast.success("Email campaign paused!");
- },
- );
- },
- confirmText: "Pause",
- confirmShortcut: "Enter",
- });
-
- const {
- confirmModal: resumeConfirmModal,
- setShowConfirmModal: setShowResumeModal,
- } = useConfirmModal({
- title: "Resume Campaign",
- description:
- "Are you sure you want to resume this email campaign? It will continue sending emails to remaining recipients.",
- onConfirm: async () => {
- await updateCampaign(
- {
- status: CampaignStatus.active,
- },
- () => {
- toast.success("Email campaign resumed!");
- },
- );
- },
- confirmText: "Resume",
- confirmShortcut: "Enter",
- });
-
- const [name, subject, groupIds, bodyJson, triggerCondition] = useWatch({
+ const [
+ name,
+ subject,
+ groupIds,
+ bodyJson,
+ triggerCondition,
+ from,
+ scheduledAt,
+ ] = useWatch({
control,
- name: ["name", "subject", "groupIds", "bodyJson", "triggerCondition"],
+ name: [
+ "name",
+ "subject",
+ "groupIds",
+ "bodyJson",
+ "triggerCondition",
+ "from",
+ "scheduledAt",
+ ],
});
// Form validation
@@ -140,7 +88,15 @@ export function CampaignControls({ campaign }: CampaignControlsProps) {
return "Please select the groups you want to send this campaign to.";
}
- if (!sendPreview && !triggerCondition) {
+ if (!from && !sendPreview) {
+ return "Please select a sender email address.";
+ }
+
+ if (
+ !sendPreview &&
+ campaign.type === "transactional" &&
+ !triggerCondition
+ ) {
return "Please select a trigger condition.";
}
@@ -148,27 +104,25 @@ export function CampaignControls({ campaign }: CampaignControlsProps) {
return "Please write the message you want to send to the partners.";
}
},
- [name, subject, groupIds, triggerCondition, bodyJson],
+ [name, subject, groupIds, triggerCondition, bodyJson, from],
);
- const updateCampaign = useCallback(
- async (
- data: Partial<UpdateCampaignFormData>,
- onSuccess: (data: Campaign) => void,
- ) => {
- await makeRequest(`/api/campaigns/${campaign.id}`, {
- method: "PATCH",
- body: {
- ...data,
- },
- onSuccess: async (data) => {
- await mutatePrefix(`/api/campaigns/${campaign.id}`);
- onSuccess(data);
- },
- });
- },
- [makeRequest, campaign.id],
- );
+ // Confirmation modals
+ const {
+ isUpdatingCampaign,
+ publishConfirmModal,
+ setShowPublishModal,
+ scheduleConfirmModal,
+ setShowScheduleModal,
+ pauseConfirmModal,
+ setShowPauseModal,
+ resumeConfirmModal,
+ setShowResumeModal,
+ cancelConfirmModal,
+ setShowCancelModal,
+ } = useCampaignConfirmationModals({
+ campaign,
+ });
const handleCampaignDuplication = async () => {
await duplicateCampaign(`/api/campaigns/${campaign.id}/duplicate`, {
@@ -181,37 +135,78 @@ export function CampaignControls({ campaign }: CampaignControlsProps) {
};
const actionButton = (() => {
- switch (campaign.status) {
- case CampaignStatus.draft:
- return {
- text: "Publish",
- icon: PaperPlane,
- onClick: () => {
- setShowPublishModal(true);
- },
- loading: isUpdatingCampaign,
- };
- case CampaignStatus.active:
- return {
- text: "Pause",
- icon: MediaPause,
- onClick: () => {
- setShowPauseModal(true);
- },
- loading: isUpdatingCampaign,
- };
- case CampaignStatus.paused:
- return {
- text: "Resume",
- icon: MediaPlay,
- onClick: () => {
- setShowResumeModal(true);
- },
- loading: isUpdatingCampaign,
- };
- default:
- return null;
+ const marketingActionButtonMap = {
+ [CampaignStatus.draft]: {
+ text:
+ scheduledAt && isFuture(new Date(scheduledAt)) ? "Schedule" : "Send",
+ icon: PaperPlane,
+ loading: isUpdatingCampaign,
+ variant: "primary",
+ onClick: () => {
+ setShowScheduleModal(true);
+ },
+ },
+
+ [CampaignStatus.scheduled]: {
+ text: "Cancel",
+ icon: CircleXmark,
+ loading: isUpdatingCampaign,
+ onClick: () => {
+ setShowCancelModal(true);
+ },
+ },
+
+ [CampaignStatus.sending]: {
+ text: "Cancel",
+ icon: CircleXmark,
+ loading: isUpdatingCampaign,
+ onClick: () => {
+ setShowCancelModal(true);
+ },
+ },
+
+ [CampaignStatus.sent]: null, // No action once sent
+ [CampaignStatus.canceled]: null, // No action once canceled
+ };
+
+ const transactionalActionButtonMap = {
+ [CampaignStatus.draft]: {
+ text: "Publish",
+ icon: PaperPlane,
+ loading: isUpdatingCampaign,
+ onClick: () => {
+ setShowPublishModal(true);
+ },
+ },
+
+ [CampaignStatus.active]: {
+ text: "Pause",
+ icon: MediaPause,
+ loading: isUpdatingCampaign,
+ onClick: () => {
+ setShowPauseModal(true);
+ },
+ },
+
+ [CampaignStatus.paused]: {
+ text: "Resume",
+ icon: MediaPlay,
+ loading: isUpdatingCampaign,
+ onClick: () => {
+ setShowResumeModal(true);
+ },
+ },
+ };
+
+ if (campaign.type === "transactional") {
+ return transactionalActionButtonMap[campaign.status];
+ }
+
+ if (campaign.type === "marketing") {
+ return marketingActionButtonMap[campaign.status];
}
+
+ return null;
})();
return (
@@ -226,7 +221,7 @@ export function CampaignControls({ campaign }: CampaignControlsProps) {
onClick={actionButton.onClick}
loading={actionButton.loading}
className="hidden h-9 px-4 sm:flex"
- variant="secondary"
+ variant={actionButton.variant || "secondary"}
/>
)}
@@ -307,10 +302,11 @@ export function CampaignControls({ campaign }: CampaignControlsProps) {
<SendEmailPreviewModal />
<DeleteCampaignModal />
- {/* Confirmation Modals */}
{publishConfirmModal}
+ {scheduleConfirmModal}
{pauseConfirmModal}
{resumeConfirmModal}
+ {cancelConfirmModal}
</>
);
}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor-skeleton.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor-skeleton.tsx
index ae47c54973..7bd1cc2bfe 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor-skeleton.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor-skeleton.tsx
@@ -29,9 +29,15 @@ export function CampaignEditorSkeleton() {
<span className={labelClassName}>Name</span>
<div className="h-8 w-full animate-pulse rounded-md bg-neutral-100" />
+ <span className={labelClassName}>From</span>
+ <div className="h-8 w-full animate-pulse rounded-md bg-neutral-100" />
+
<span className={labelClassName}>To</span>
<div className="h-8 w-full animate-pulse rounded-md bg-neutral-100" />
+ <span className={labelClassName}>When</span>
+ <div className="h-8 w-full animate-pulse rounded-md bg-neutral-100" />
+
<span className={labelClassName}>Subject</span>
<div className="h-8 w-full animate-pulse rounded-md bg-neutral-100" />
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 9fa77c0c13..abdcefc317 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
@@ -1,5 +1,7 @@
import { uploadEmailImageAction } from "@/lib/actions/partners/upload-email-image";
+import { CAMPAIGN_READONLY_STATUSES } from "@/lib/api/campaigns/constants";
import { useApiMutation } from "@/lib/swr/use-api-mutation";
+import { useEmailDomains } from "@/lib/swr/use-email-domains";
import useProgram from "@/lib/swr/use-program";
import useWorkspace from "@/lib/swr/use-workspace";
import { Campaign, UpdateCampaignFormData } from "@/lib/types";
@@ -13,10 +15,13 @@ import {
Lock,
PaperPlane,
RichTextArea,
+ SmartDateTimePicker,
StatusBadge,
Tooltip,
+ TooltipContent,
useKeyboardShortcut,
} from "@dub/ui";
+import { capitalize } from "@dub/utils";
import { useAction } from "next-safe-action/hooks";
import Link from "next/link";
import { useCallback, useEffect, useRef } from "react";
@@ -66,11 +71,22 @@ const DisabledInputWrapper = ({
);
};
+const statusMessages = {
+ sending: "Edits aren't allowed while sending.",
+ sent: "Edits aren't allowed after sending.",
+ canceled: "Edits aren't allowed after cancellation.",
+};
+
export function CampaignEditor({ campaign }: { campaign: Campaign }) {
const { program } = useProgram();
const { id: workspaceId, slug: workspaceSlug } = useWorkspace();
+ const { emailDomains } = useEmailDomains();
+ const firstVerifiedEmailDomain = emailDomains?.find(
+ (domain) => domain.status === "verified",
+ );
const isActive = campaign.status === CampaignStatus.active;
+ const isReadOnly = CAMPAIGN_READONLY_STATUSES.includes(campaign.status);
const { makeRequest, isSubmitting: isSavingCampaign } =
useApiMutation<Campaign>();
@@ -79,9 +95,11 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
defaultValues: {
name: campaign.name,
subject: campaign.subject,
+ from: campaign.from ?? undefined,
bodyJson: campaign.bodyJson,
groupIds: campaign.groups.map(({ id }) => id),
triggerCondition: campaign.triggerCondition,
+ scheduledAt: campaign.scheduledAt,
},
});
@@ -137,10 +155,8 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
toast.success("Campaign saved successfully!");
}
},
- onError: () => {
- toast.error(
- `Failed to save the ${isDraft ? "draft " : ""}campaign.`,
- );
+ onError: (error) => {
+ toast.error(error);
},
});
}
@@ -219,13 +235,14 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
<span className="min-w-0 truncate text-lg font-semibold leading-7 text-neutral-900">
{campaign.status === CampaignStatus.draft ? (
<>
- New <span className="hidden sm:inline">transactional</span>{" "}
+ New{" "}
+ <span className="hidden sm:inline">{campaign.type}</span>{" "}
email
</>
) : (
<>
<span className="hidden sm:inline">
- Transactional email
+ {capitalize(campaign.type)} email
</span>
<span className="inline sm:hidden">Email</span>
</>
@@ -239,7 +256,7 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
}
controls={<CampaignControls campaign={campaign} />}
sidePanel={
- campaign.status !== CampaignStatus.draft
+ !["draft", "scheduled"].includes(campaign.status)
? {
title: "Metrics",
content: (
@@ -248,23 +265,87 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
<CampaignEvents />
</div>
),
- defaultOpen: campaign.status === CampaignStatus.active,
+ defaultOpen: ["active", "sending", "sent"].includes(
+ campaign.status,
+ ),
}
: undefined
}
individualScrolling
contentWrapperClassName="flex flex-col"
>
- <PageWidthWrapper className="mb-8 mt-6 max-w-[600px]">
+ <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">
- <label className="contents">
- <span className={labelClassName}>Name</span>
+ <span className={labelClassName}>Name</span>
+ <DisabledInputWrapper
+ tooltip={isReadOnly ? statusMessages[campaign.status] : ""}
+ disabled={isReadOnly}
+ hideIcon={true}
+ >
<input
type="text"
placeholder="Enter a name..."
className={inputClassName}
+ disabled={isReadOnly}
{...register("name")}
/>
+ </DisabledInputWrapper>
+
+ <label className="contents">
+ <span className={labelClassName}>From</span>
+ <Controller
+ control={control}
+ name="from"
+ render={({ field }) => {
+ const localPart = field.value?.split("@")[0] || "";
+ const domainSuffix = firstVerifiedEmailDomain?.slug
+ ? `@${firstVerifiedEmailDomain.slug}`
+ : "";
+ const isDisabled = isReadOnly || !firstVerifiedEmailDomain;
+
+ return (
+ <DisabledInputWrapper
+ tooltip={
+ isReadOnly ? (
+ statusMessages[campaign.status]
+ ) : !firstVerifiedEmailDomain ? (
+ <TooltipContent
+ title="You haven't configured an email domain yet. Please configure an email domain to enable campaign sending."
+ cta="Configure email domain"
+ href={`/${workspaceSlug}/settings/domains/email`}
+ target="_blank"
+ />
+ ) : undefined
+ }
+ disabled={isDisabled}
+ hideIcon={true}
+ >
+ <div
+ className={`flex items-center gap-1 ${inputClassName} ${isDisabled ? "cursor-not-allowed opacity-80" : ""}`}
+ >
+ <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"
+ disabled={isDisabled}
+ value={localPart}
+ onChange={(e) => {
+ const newLocalPart = e.target.value;
+ if (firstVerifiedEmailDomain?.slug) {
+ field.onChange(
+ `${newLocalPart}@${firstVerifiedEmailDomain.slug}`,
+ );
+ }
+ }}
+ />
+ <span className="text-content-muted shrink-0 text-sm">
+ {domainSuffix}
+ </span>
+ </div>
+ </DisabledInputWrapper>
+ );
+ }}
+ />
</label>
<span className={labelClassName}>To</span>
@@ -273,8 +354,13 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
name="groupIds"
render={({ field }) => (
<DisabledInputWrapper
- tooltip="Cannot change recipients while campaign is active. Pause the campaign to make changes."
- disabled={isActive}
+ tooltip={
+ isReadOnly
+ ? statusMessages[campaign.status]
+ : "Cannot change recipients while campaign is active. Pause the campaign to make changes."
+ }
+ disabled={isActive || isReadOnly}
+ hideIcon={isReadOnly}
>
<CampaignGroupsSelector
selectedGroupIds={field.value ?? null}
@@ -284,22 +370,57 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
)}
/>
- <label className="contents">
- <span className={labelClassName}>Subject</span>
+ {campaign.type === "marketing" && (
+ <>
+ <span className={labelClassName}>When</span>
+ <Controller
+ control={control}
+ name="scheduledAt"
+ render={({ field }) => (
+ <DisabledInputWrapper
+ tooltip={
+ isReadOnly ? statusMessages[campaign.status] : undefined
+ }
+ disabled={isReadOnly}
+ hideIcon={true}
+ >
+ <SmartDateTimePicker
+ value={field.value}
+ onChange={field.onChange}
+ placeholder='E.g. "tomorrow at 5pm" or "in 2 hours"'
+ className="[&>div]:hover:border-border-subtle [&>div]:mt-0 [&>div]:h-8 [&>div]:min-h-8 [&>div]:border-transparent [&>div]:shadow-none [&>div]:focus-within:border-black/75 [&>div]:focus-within:ring-black/75 [&>div]:hover:cursor-pointer [&>div]:hover:bg-neutral-100"
+ />
+ </DisabledInputWrapper>
+ )}
+ />
+ </>
+ )}
+
+ <span className={labelClassName}>Subject</span>
+ <DisabledInputWrapper
+ tooltip={isReadOnly ? statusMessages[campaign.status] : ""}
+ disabled={isReadOnly}
+ hideIcon={true}
+ >
<input
type="text"
placeholder="Enter a subject..."
className={inputClassName}
+ disabled={isReadOnly}
{...register("subject")}
/>
- </label>
+ </DisabledInputWrapper>
{campaign.type === "transactional" && (
<>
<span className={labelClassName}>Logic</span>
<DisabledInputWrapper
- tooltip="Cannot change trigger logic while campaign is active. Pause the campaign to make changes."
- disabled={isActive}
+ tooltip={
+ isReadOnly
+ ? statusMessages[campaign.status]
+ : "Cannot change trigger logic while campaign is active. Pause the campaign to make changes."
+ }
+ disabled={isActive || isReadOnly}
>
<TransactionalCampaignLogic />
</DisabledInputWrapper>
@@ -318,6 +439,9 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
initialValue={field.value}
onChange={(editor) => field.onChange(editor.getJSON())}
variables={[...EMAIL_TEMPLATE_VARIABLES]}
+ editable={
+ campaign.type === "marketing" ? !isReadOnly : !isActive
+ }
uploadImage={async (file) => {
try {
const result = await executeImageUpload({
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 3a4936624c..e406e85f5e 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] = useWatch({
+ const [subject, bodyJson, from] = useWatch({
control,
- name: ["subject", "bodyJson"],
+ name: ["subject", "bodyJson", "from"],
});
const { executeAsync: sendEmailPreview, isPending } = useAction(
@@ -82,6 +82,7 @@ function SendEmailPreviewModal({
campaignId,
subject,
bodyJson,
+ from,
emailAddresses: emails,
});
};
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/use-campaign-confirmation-modals.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/use-campaign-confirmation-modals.tsx
new file mode 100644
index 0000000000..1de8356018
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/use-campaign-confirmation-modals.tsx
@@ -0,0 +1,212 @@
+import { mutatePrefix } from "@/lib/swr/mutate";
+import { useApiMutation } from "@/lib/swr/use-api-mutation";
+import { usePartnersCountByGroupIds } from "@/lib/swr/use-partners-count-by-groupids";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { Campaign, UpdateCampaignFormData } from "@/lib/types";
+import { useConfirmModal } from "@/ui/modals/confirm-modal";
+import { CampaignStatus } from "@dub/prisma/client";
+import { pluralize } from "@dub/utils";
+import { isFuture } from "date-fns";
+import { useRouter } from "next/navigation";
+import { useCallback } from "react";
+import { toast } from "sonner";
+import { useCampaignFormContext } from "./campaign-form-context";
+
+interface UseCampaignConfirmationModalsProps {
+ campaign: Pick<Campaign, "id" | "type">;
+}
+
+export function useCampaignConfirmationModals({
+ campaign,
+}: UseCampaignConfirmationModalsProps) {
+ const router = useRouter();
+ const { slug: workspaceSlug } = useWorkspace();
+ const { watch, getValues } = useCampaignFormContext();
+
+ const { makeRequest, isSubmitting: isUpdatingCampaign } =
+ useApiMutation<Campaign>();
+
+ const scheduledAt = watch("scheduledAt");
+ const isScheduled = scheduledAt && isFuture(new Date(scheduledAt));
+
+ const updateCampaign = useCallback(
+ async (
+ data: Partial<UpdateCampaignFormData>,
+ onSuccess: (data: Campaign) => void,
+ ) => {
+ await makeRequest(`/api/campaigns/${campaign.id}`, {
+ method: "PATCH",
+ body: {
+ ...data,
+ },
+ onSuccess: async (data) => {
+ await mutatePrefix(`/api/campaigns/${campaign.id}`);
+ onSuccess(data);
+ },
+ });
+ },
+ [makeRequest, campaign.id],
+ );
+
+ const {
+ confirmModal: publishConfirmModal,
+ setShowConfirmModal: setShowPublishModal,
+ } = useConfirmModal({
+ title: "Publish Campaign",
+ description:
+ "Are you sure you want to publish this campaign? Once your campaign rules are met, it will be sent to the partners in the selected groups.",
+ onConfirm: async () => {
+ await updateCampaign(
+ {
+ ...getValues(),
+ status: CampaignStatus.active,
+ },
+ () => {
+ toast.success("Email campaign published!");
+ router.push(`/${workspaceSlug}/program/campaigns`);
+ },
+ );
+ },
+ confirmText: "Publish",
+ confirmShortcut: "Enter",
+ });
+
+ const { totalPartners } = usePartnersCountByGroupIds({
+ groupIds: campaign.type === "marketing" ? watch("groupIds") : undefined,
+ });
+
+ const {
+ confirmModal: scheduleConfirmModal,
+ setShowConfirmModal: setShowScheduleModal,
+ } = useConfirmModal({
+ title: isScheduled ? "Schedule Campaign" : "Send Campaign",
+ description: (
+ <>
+ Are you sure you want to {isScheduled ? "schedule" : "send"} this email
+ campaign? It will{" "}
+ {isScheduled ? "be automatically sent" : "start sending immediately"} to{" "}
+ <strong className="text-neutral-900">
+ {totalPartners} {pluralize("partner", totalPartners)}
+ </strong>
+ {isScheduled
+ ? " at the scheduled date and time you've set."
+ : " once published."}
+ </>
+ ),
+ onConfirm: async () => {
+ await updateCampaign(
+ {
+ ...getValues(),
+ status: CampaignStatus.scheduled,
+ },
+ () => {
+ toast.success("Email campaign scheduled!");
+ router.push(`/${workspaceSlug}/program/campaigns`);
+ },
+ );
+ },
+ confirmText: `${isScheduled ? "Schedule" : "Send"} to ${totalPartners} ${pluralize("partner", totalPartners)}`,
+ confirmShortcut: "Enter",
+ });
+
+ const {
+ confirmModal: pauseConfirmModal,
+ setShowConfirmModal: setShowPauseModal,
+ } = useConfirmModal({
+ title: "Pause Campaign",
+ description:
+ "Are you sure you want to pause this email campaign? It will stop sending emails to new recipients.",
+ onConfirm: async () => {
+ await updateCampaign(
+ {
+ status: CampaignStatus.paused,
+ },
+ () => {
+ toast.success("Email campaign paused!");
+ },
+ );
+ },
+ confirmText: "Pause",
+ confirmShortcut: "Enter",
+ });
+
+ const {
+ confirmModal: resumeConfirmModal,
+ setShowConfirmModal: setShowResumeModal,
+ } = useConfirmModal({
+ title: "Resume Campaign",
+ description:
+ "Are you sure you want to resume this email campaign? It will continue sending emails to remaining recipients.",
+ onConfirm: async () => {
+ await updateCampaign(
+ {
+ status: CampaignStatus.active,
+ },
+ () => {
+ toast.success("Email campaign resumed!");
+ },
+ );
+ },
+ confirmText: "Resume",
+ confirmShortcut: "Enter",
+ });
+
+ const {
+ confirmModal: cancelConfirmModal,
+ setShowConfirmModal: setShowCancelModal,
+ } = useConfirmModal({
+ title: "Cancel Campaign",
+ description: isScheduled ? (
+ <div className="space-y-2">
+ <p>
+ Are you sure you want to cancel this scheduled email campaign? The
+ campaign will not be sent at the scheduled time.
+ </p>
+
+ <p className="font-semibold">This action cannot be undone.</p>
+ </div>
+ ) : (
+ <div className="space-y-2">
+ <p>
+ Are you sure you want to cancel this email campaign? If you choose to
+ stop delivery, we'll begin cancelling the campaign immediately.
+ </p>
+
+ <p>
+ However, because sending happens in batches, some additional emails
+ may still go out before the process completes.
+ </p>
+
+ <p className="font-semibold">This action cannot be undone.</p>
+ </div>
+ ),
+ onConfirm: async () => {
+ await updateCampaign(
+ {
+ status: CampaignStatus.canceled,
+ scheduledAt: null,
+ },
+ () => {
+ toast.success("Email campaign canceled!");
+ },
+ );
+ },
+ confirmText: "Cancel Campaign",
+ confirmShortcut: "Enter",
+ });
+
+ return {
+ updateCampaign,
+ isUpdatingCampaign,
+ publishConfirmModal,
+ setShowPublishModal,
+ scheduleConfirmModal,
+ setShowScheduleModal,
+ pauseConfirmModal,
+ setShowPauseModal,
+ resumeConfirmModal,
+ setShowResumeModal,
+ cancelConfirmModal,
+ setShowCancelModal,
+ };
+}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/campaign-stats.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/campaign-stats.tsx
index 41aa6681e5..62c88051f7 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/campaign-stats.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/campaign-stats.tsx
@@ -1,20 +1,21 @@
"use client";
import { useRouterStuff } from "@dub/ui";
-import { Icon, Users } from "@dub/ui/icons";
+import { Users } from "@dub/ui/icons";
import { cn, nFormatter } from "@dub/utils";
import { CampaignType } from "@prisma/client";
import Link from "next/link";
import { useParams } from "next/navigation";
import { useMemo } from "react";
import { CAMPAIGN_TYPE_BADGES } from "./campaign-type-badges";
+import { CampaignTypeIcon } from "./campaign-type-icon";
import useCampaignsCount from "./use-campaigns-count";
interface StatsFilterProps {
label: string;
href: string;
count?: number;
- icon: Icon;
+ icon: React.ReactNode;
iconClassName?: string;
error: boolean;
active: boolean;
@@ -61,13 +62,13 @@ export function CampaignStats() {
label="All"
href={`/${slug}/program/campaigns`}
count={totalCount}
- icon={Users}
+ icon={<Users className="size-3.5" />}
iconClassName="text-neutral-600 bg-neutral-100"
error={!!error}
active={searchParamsObj.type == undefined}
/>
<StatsFilter
- {...CAMPAIGN_TYPE_BADGES.marketing}
+ label={CAMPAIGN_TYPE_BADGES.marketing.label}
href={
queryParams({
set: { type: "marketing" },
@@ -75,11 +76,12 @@ export function CampaignStats() {
}) as string
}
count={marketingCount}
+ icon={<CampaignTypeIcon type="marketing" />}
error={!!error}
active={searchParamsObj.type === "marketing"}
/>
<StatsFilter
- {...CAMPAIGN_TYPE_BADGES.transactional}
+ label={CAMPAIGN_TYPE_BADGES.transactional.label}
href={
queryParams({
set: { type: "transactional" },
@@ -87,6 +89,7 @@ export function CampaignStats() {
}) as string
}
count={transactionalCount}
+ icon={<CampaignTypeIcon type="transactional" />}
error={!!error}
active={searchParamsObj.type === "transactional"}
/>
@@ -99,7 +102,7 @@ function StatsFilter({
href,
count,
error,
- icon: Icon,
+ icon,
iconClassName,
active,
}: StatsFilterProps) {
@@ -112,14 +115,18 @@ function StatsFilter({
)}
>
<div className="flex items-center gap-2">
- <div
- className={cn(
- "flex size-6 items-center justify-center rounded-md",
- iconClassName,
- )}
- >
- <Icon className="size-3.5" />
- </div>
+ {iconClassName ? (
+ <div
+ className={cn(
+ "flex size-6 items-center justify-center rounded-md",
+ iconClassName,
+ )}
+ >
+ {icon}
+ </div>
+ ) : (
+ icon
+ )}
<div className="text-xs font-medium text-neutral-500">{label}</div>
</div>
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/campaign-status-badges.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/campaign-status-badges.tsx
index f5cbdd6350..1205dbacb3 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/campaign-status-badges.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/campaign-status-badges.tsx
@@ -1,4 +1,10 @@
-import { CircleHalfDottedClock, CirclePlay, PaperPlane, Pen2 } from "@dub/ui";
+import {
+ CircleHalfDottedClock,
+ CirclePlay,
+ CircleXmark,
+ PaperPlane,
+ Pen2,
+} from "@dub/ui";
export const CAMPAIGN_STATUS_BADGES = {
draft: {
@@ -19,16 +25,28 @@ export const CAMPAIGN_STATUS_BADGES = {
icon: CircleHalfDottedClock,
iconClassName: "text-yellow-600",
},
+ scheduled: {
+ label: "Scheduled",
+ variant: "warning",
+ icon: CircleHalfDottedClock,
+ iconClassName: "text-neutral-600",
+ },
sent: {
label: "Sent",
- variant: "neutral",
+ variant: "success",
icon: PaperPlane,
iconClassName: "text-neutral-600",
},
- scheduled: {
- label: "Scheduled",
- variant: "neutral",
+ sending: {
+ label: "Sending",
+ variant: "new",
icon: CircleHalfDottedClock,
iconClassName: "text-neutral-600",
},
+ canceled: {
+ label: "Canceled",
+ variant: "error",
+ icon: CircleXmark,
+ iconClassName: "text-neutral-600",
+ },
} as const;
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/campaign-type-badges.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/campaign-type-badges.tsx
index f16ed277ef..f8b87af94b 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/campaign-type-badges.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/campaign-type-badges.tsx
@@ -5,10 +5,12 @@ export const CAMPAIGN_TYPE_BADGES = {
label: "Marketing",
icon: Megaphone,
iconClassName: "text-green-600 bg-green-100",
+ value: "marketing",
},
transactional: {
label: "Transactional",
icon: Workflow,
iconClassName: "text-blue-600 bg-blue-100",
+ value: "transactional",
},
} as const;
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/campaign-type-icon.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/campaign-type-icon.tsx
new file mode 100644
index 0000000000..ee5bd52b92
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/campaign-type-icon.tsx
@@ -0,0 +1,25 @@
+import { cn } from "@dub/utils";
+import { CAMPAIGN_TYPE_BADGES } from "./campaign-type-badges";
+
+export function CampaignTypeIcon({
+ type,
+ className,
+}: {
+ type: keyof typeof CAMPAIGN_TYPE_BADGES;
+ className?: string;
+}) {
+ const { icon: Icon, iconClassName } = CAMPAIGN_TYPE_BADGES[type];
+
+ return (
+ <div
+ className={cn(
+ "flex size-6 shrink-0 items-center justify-center rounded-md",
+ iconClassName,
+ className,
+ )}
+ >
+ <Icon className="size-3.5" />
+ </div>
+ );
+}
+
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/campaigns-table.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/campaigns-table.tsx
index 1faccec1be..90a18eb971 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/campaigns-table.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/campaigns-table.tsx
@@ -2,7 +2,6 @@
import { mutatePrefix } from "@/lib/swr/mutate";
import { useApiMutation } from "@/lib/swr/use-api-mutation";
-import usePartnersCount from "@/lib/swr/use-partners-count";
import useWorkspace from "@/lib/swr/use-workspace";
import { Campaign, CampaignList } from "@/lib/types";
import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
@@ -11,20 +10,18 @@ import { CampaignStatus } from "@dub/prisma/client";
import {
AnimatedSizeContainer,
Button,
- EditColumnsButton,
Filter,
MenuItem,
Popover,
StatusBadge,
Table,
TimestampTooltip,
- Tooltip,
usePagination,
useRouterStuff,
useTable,
} from "@dub/ui";
import { Dots, Duplicate, LoadingCircle, Trash } from "@dub/ui/icons";
-import { cn, fetcher, formatDateTimeSmart, nFormatter } from "@dub/utils";
+import { fetcher, formatDateTimeSmart } from "@dub/utils";
import { Row } from "@tanstack/react-table";
import { Command } from "cmdk";
import { Mail, Pause, Play } from "lucide-react";
@@ -33,7 +30,7 @@ import { useState } from "react";
import { toast } from "sonner";
import useSWR from "swr";
import { CAMPAIGN_STATUS_BADGES } from "./campaign-status-badges";
-import { CAMPAIGN_TYPE_BADGES } from "./campaign-type-badges";
+import { CampaignTypeIcon } from "./campaign-type-icon";
import { CreateCampaignButton } from "./create-campaign-button";
import { useDeleteCampaignModal } from "./delete-campaign-modal";
import { useCampaignsFilters } from "./use-campaigns-filters";
@@ -47,13 +44,7 @@ export function CampaignsTable() {
const router = useRouter();
const { id: workspaceId, slug } = useWorkspace();
const { pagination, setPagination } = usePagination();
- const { queryParams, searchParams, getQueryString } = useRouterStuff();
-
- const { partnersCount: groupCount } = usePartnersCount<
- PartnersCountByGroup[] | undefined
- >({
- groupBy: "groupId",
- });
+ const { getQueryString } = useRouterStuff();
const {
filters,
@@ -64,9 +55,6 @@ export function CampaignsTable() {
isFiltered,
} = useCampaignsFilters();
- const sortBy = searchParams.get("sortBy") || "updatedAt";
- const sortOrder = searchParams.get("sortOrder") === "asc" ? "asc" : "desc";
-
const {
data: campaigns,
isLoading: campaignsLoading,
@@ -88,42 +76,13 @@ export function CampaignsTable() {
{
id: "email",
header: "Email",
- enableHiding: false,
- minSize: 200,
- cell: ({ row }) => {
- const { icon: Icon, iconClassName } =
- CAMPAIGN_TYPE_BADGES[row.original.type];
-
- return (
- <div className="flex items-center gap-2">
- <div
- className={cn(
- "flex size-6 shrink-0 items-center justify-center rounded-md",
- iconClassName,
- )}
- >
- <Icon className="size-3.5" />
- </div>
- <span className="text-content-emphasis truncate text-sm font-medium">
- {row.original.name}
- </span>
- </div>
- );
- },
- },
- {
- id: "createdAt",
- header: "Created",
- accessorFn: (d) => d.createdAt,
cell: ({ row }) => (
- <TimestampTooltip
- timestamp={row.original.createdAt}
- side="right"
- rows={["local"]}
- delayDuration={150}
- >
- <span>{formatDateTimeSmart(row.original.createdAt)}</span>
- </TimestampTooltip>
+ <div className="flex items-center gap-2">
+ <CampaignTypeIcon type={row.original.type} />
+ <span className="text-content-emphasis truncate text-sm font-medium">
+ {row.original.name}
+ </span>
+ </div>
),
},
{
@@ -142,76 +101,25 @@ export function CampaignsTable() {
},
},
{
- id: "partners",
- header: "Partners",
- cell: ({ row }) => {
- const groupIds = row.original.groups.map((g) => g.id);
-
- const partnersCount =
- groupCount
- ?.filter(
- (g) => groupIds.length === 0 || groupIds.includes(g.groupId),
- )
- .reduce((acc, curr) => acc + curr._count, 0) || 0;
-
- return nFormatter(partnersCount, { full: true });
- },
- },
- {
- id: "delivered",
- header: "Delivered",
- accessorFn: (d) => d.delivered,
- cell: ({ row }) => {
- const { sent, delivered } = row.original;
-
- return (
- <Tooltip content={`${nFormatter(delivered)} delivered`} side="top">
- <span className="cursor-help">
- {calculatePercentage(delivered, sent)}%
- </span>
- </Tooltip>
- );
- },
- },
- {
- id: "bounced",
- header: "Bounced",
- accessorFn: (d) => d.bounced,
- cell: ({ row }) => {
- const { sent, bounced } = row.original;
-
- return (
- <Tooltip content={`${nFormatter(bounced)} bounced`} side="top">
- <span className="cursor-help">
- {calculatePercentage(bounced, sent)}%
- </span>
- </Tooltip>
- );
- },
- },
- {
- id: "opened",
- header: "Opened",
- accessorFn: (d) => d.opened,
- cell: ({ row }) => {
- const { delivered, opened } = row.original;
-
- return (
- <Tooltip content={`${nFormatter(opened)} opened`} side="top">
- <span className="cursor-help">
- {calculatePercentage(opened, delivered)}%
- </span>
- </Tooltip>
- );
- },
+ id: "createdAt",
+ header: "Created",
+ accessorFn: (d) => d.createdAt,
+ cell: ({ row }) => (
+ <TimestampTooltip
+ timestamp={row.original.createdAt}
+ side="right"
+ rows={["local"]}
+ delayDuration={150}
+ >
+ <span>{formatDateTimeSmart(row.original.createdAt)}</span>
+ </TimestampTooltip>
+ ),
},
{
id: "menu",
- enableHiding: false,
- minSize: 43,
- size: 43,
- maxSize: 43,
- header: () => <EditColumnsButton table={table} />,
+ minSize: 20,
+ size: 20,
+ maxSize: 20,
cell: ({ row }) => <RowMenuButton row={row} />,
},
],
@@ -230,18 +138,7 @@ export function CampaignsTable() {
},
pagination,
onPaginationChange: setPagination,
- sortableColumns: ["createdAt", "status", "delivered", "bounced", "opened"],
- sortBy,
- sortOrder,
- onSortChange: ({ sortBy, sortOrder }) =>
- queryParams({
- set: {
- ...(sortBy && { sortBy }),
- ...(sortOrder && { sortOrder }),
- },
- del: "page",
- scroll: false,
- }),
+ columnPinning: { right: ["createdAt", "menu"] },
thClassName: "border-l-0",
tdClassName: "border-l-0",
resourceName: (p) => `campaign${p ? "s" : ""}`,
@@ -375,7 +272,7 @@ function RowMenuButton({
Duplicate
</MenuItem>
- {!isDraft && (
+ {!isDraft && campaign.type === "transactional" && (
<MenuItem
icon={
isUpdatingCampaign ? LoadingCircle : isPaused ? Play : Pause
@@ -419,5 +316,5 @@ const calculatePercentage = (value: number, total: number) => {
return 0;
}
- return Math.round((value / total) * 100);
+ return Number(((value / total) * 100).toFixed(2));
};
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/create-campaign-button.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/create-campaign-button.tsx
index 4f0410956c..0cd36562ff 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/create-campaign-button.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/create-campaign-button.tsx
@@ -4,19 +4,33 @@ import { mutatePrefix } from "@/lib/swr/mutate";
import { useApiMutation } from "@/lib/swr/use-api-mutation";
import useWorkspace from "@/lib/swr/use-workspace";
import { Campaign } from "@/lib/types";
-import { Button, useKeyboardShortcut } from "@dub/ui";
+import { Button, MenuItem, Popover, useKeyboardShortcut } from "@dub/ui";
+import { Command } from "cmdk";
+import { ChevronDown } from "lucide-react";
import { useRouter } from "next/navigation";
+import { useState } from "react";
+import { CAMPAIGN_TYPE_BADGES } from "./campaign-type-badges";
+import { CampaignTypeIcon } from "./campaign-type-icon";
+
+const campaignTypes = Object.values(CAMPAIGN_TYPE_BADGES).map(
+ ({ label, value }) => ({
+ label,
+ value,
+ shortcut: value === "marketing" ? "M" : "T",
+ }),
+);
export function CreateCampaignButton() {
const router = useRouter();
const { slug } = useWorkspace();
const { makeRequest, isSubmitting } = useApiMutation<Campaign>();
+ const [isOpen, setIsOpen] = useState(false);
- const createDraftCampaign = async () => {
+ const createDraftCampaign = async (type: "marketing" | "transactional") => {
await makeRequest(`/api/campaigns`, {
method: "POST",
body: {
- type: "transactional",
+ type,
},
onSuccess: (campaign) => {
router.push(`/${slug}/program/campaigns/${campaign.id}`);
@@ -25,16 +39,54 @@ export function CreateCampaignButton() {
});
};
- useKeyboardShortcut("c", () => createDraftCampaign());
+ useKeyboardShortcut("m", () => createDraftCampaign("marketing"), {
+ enabled: isOpen && !isSubmitting,
+ });
+
+ useKeyboardShortcut("t", () => createDraftCampaign("transactional"), {
+ enabled: isOpen && !isSubmitting,
+ });
return (
- <Button
- type="button"
- text="Create campaign"
- className="h-8 px-3 sm:h-9"
- loading={isSubmitting}
- shortcut="C"
- onClick={createDraftCampaign}
- />
+ <Popover
+ openPopover={isOpen}
+ setOpenPopover={setIsOpen}
+ content={
+ <Command tabIndex={0} loop className="focus:outline-none">
+ <Command.List className="flex w-screen flex-col gap-1 p-1.5 text-sm sm:w-auto sm:min-w-[200px]">
+ {campaignTypes.map(({ label, value, shortcut }) => (
+ <MenuItem
+ key={value}
+ icon={<CampaignTypeIcon type={value} />}
+ label={label}
+ shortcut={shortcut}
+ disabled={isSubmitting}
+ onClick={() => {
+ setIsOpen(false);
+ createDraftCampaign(value);
+ }}
+ >
+ {label}
+ </MenuItem>
+ ))}
+ </Command.List>
+ </Command>
+ }
+ align="end"
+ >
+ <Button
+ type="button"
+ variant="primary"
+ className="h-9 w-fit rounded-lg px-3"
+ loading={isSubmitting}
+ text={
+ <div className="flex items-center gap-2">
+ Create campaign{" "}
+ <ChevronDown className="size-4 transition-transform duration-75 group-data-[state=open]:rotate-180" />
+ </div>
+ }
+ onClick={() => setIsOpen(!isOpen)}
+ />
+ </Popover>
);
}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/delete-campaign-modal.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/delete-campaign-modal.tsx
index 61223469ba..767c8a3ab7 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/delete-campaign-modal.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/delete-campaign-modal.tsx
@@ -6,6 +6,7 @@ import { Button, Modal } from "@dub/ui";
import { cn } from "@dub/utils";
import { useRouter } from "next/navigation";
import { useCallback, useMemo, useState } from "react";
+import { useForm } from "react-hook-form";
import { toast } from "sonner";
import { CAMPAIGN_TYPE_BADGES } from "./campaign-type-badges";
@@ -24,6 +25,19 @@ const DeleteCampaignModal = ({
const { slug } = useWorkspace();
const { makeRequest: deleteCampaign, isSubmitting } = useApiMutation();
+ const {
+ register,
+ handleSubmit,
+ watch,
+ formState: { errors },
+ } = useForm<{ confirm: string }>({
+ defaultValues: {
+ confirm: "",
+ },
+ });
+
+ const confirm = watch("confirm");
+
const handleCampaignDeletion = async () => {
await deleteCampaign(`/api/campaigns/${campaign.id}`, {
method: "DELETE",
@@ -38,49 +52,76 @@ const DeleteCampaignModal = ({
const { icon: Icon, iconClassName } = CAMPAIGN_TYPE_BADGES[campaign.type];
+ const isDisabled = useMemo(() => {
+ return confirm !== "confirm delete campaign";
+ }, [confirm]);
+
return (
<Modal showModal={showModal} setShowModal={setShowModal}>
- <div className="space-y-6 p-6">
- <div>
- <h3 className="text-content-emphasis text-lg font-semibold">
- Confirm delete
- </h3>
- <p className="text-content-subtle mt-1 text-sm">
- Are you sure you want to delete this campaign?
+ <div className="border-b border-neutral-200 p-4 sm:p-6">
+ <h3 className="text-lg font-medium leading-none">Delete campaign</h3>
+ </div>
+
+ <form onSubmit={handleSubmit(handleCampaignDeletion)}>
+ <div className="flex flex-col gap-6 bg-neutral-50 p-4 sm:p-6">
+ <div className="flex items-center gap-4 rounded-lg border border-neutral-200 bg-white p-4">
+ <div
+ className={cn(
+ "flex size-6 shrink-0 items-center justify-center rounded-md",
+ iconClassName,
+ )}
+ >
+ <Icon className="size-3.5" />
+ </div>
+ <span className="text-content-emphasis truncate text-sm font-medium">
+ {campaign.name}
+ </span>
+ </div>
+
+ <p className="text-sm text-neutral-600">
+ This will permanently delete this campaign and all associated data.
+ This action is not reversible.
</p>
- </div>
- <div className="flex items-center gap-4 rounded-lg border border-neutral-200 bg-white p-4">
- <div
- className={cn(
- "flex size-6 shrink-0 items-center justify-center rounded-md",
- iconClassName,
- )}
- >
- <Icon className="size-3.5" />
+ <div>
+ <label className="block text-sm font-medium text-neutral-900">
+ To verify, type <strong>confirm delete campaign</strong> below
+ </label>
+ <div className="relative mt-1.5 rounded-md shadow-sm">
+ <input
+ className={cn(
+ "block w-full rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",
+ errors.confirm && "border-red-600",
+ )}
+ placeholder="confirm delete campaign"
+ type="text"
+ autoComplete="off"
+ {...register("confirm", {
+ required: true,
+ })}
+ />
+ </div>
</div>
- <span className="text-content-emphasis truncate text-sm font-medium">
- {campaign.name}
- </span>
</div>
- <div className="flex items-center justify-end gap-2">
+ <div className="flex items-center justify-end gap-2 bg-neutral-50 px-4 pb-5 sm:px-6">
<Button
variant="secondary"
- className="h-9 w-fit px-3"
+ className="h-8 w-fit px-3"
text="Cancel"
onClick={() => setShowModal(false)}
disabled={isSubmitting}
/>
<Button
+ type="submit"
variant="danger"
- className="h-9 w-fit px-3"
- text="Delete"
+ className="h-8 w-fit px-3"
+ text="Delete campaign"
+ disabled={isDisabled}
loading={isSubmitting}
- onClick={handleCampaignDeletion}
/>
</div>
- </div>
+ </form>
</Modal>
);
};
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/page.tsx
index 5c6672644d..0b36af1416 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/page.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/page.tsx
@@ -1,5 +1,6 @@
import { PageContent } from "@/ui/layout/page-content";
import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
+import { CampaignStats } from "./campaign-stats";
import { CampaignsTable } from "./campaigns-table";
import { CreateCampaignButton } from "./create-campaign-button";
@@ -7,8 +8,8 @@ export default function ProgramCampaignsPage() {
return (
<PageContent title="Email campaigns" controls={<CreateCampaignButton />}>
<PageWidthWrapper>
- {/* <CampaignStats /> */}
- <div>
+ <div className="space-y-4">
+ <CampaignStats />
<CampaignsTable />
</div>
</PageWidthWrapper>
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/use-campaigns-filters.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/use-campaigns-filters.tsx
index 4ca60507a6..4ec6ce0550 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/use-campaigns-filters.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/use-campaigns-filters.tsx
@@ -1,11 +1,12 @@
import useWorkspace from "@/lib/swr/use-workspace";
import { CampaignStatus, CampaignType } from "@dub/prisma/client";
import { useRouterStuff } from "@dub/ui";
-import { CircleDotted } from "@dub/ui/icons";
+import { CircleDotted, Sliders } from "@dub/ui/icons";
import { nFormatter } from "@dub/utils";
import { cn } from "@dub/utils/src";
import { useMemo } from "react";
import { CAMPAIGN_STATUS_BADGES } from "./campaign-status-badges";
+import { CAMPAIGN_TYPE_BADGES } from "./campaign-type-badges";
import useCampaignsCount from "./use-campaigns-count";
interface CampaignsCountByType {
@@ -58,28 +59,28 @@ export function useCampaignsFilters() {
};
}) ?? [],
},
- // {
- // key: "type",
- // icon: Sliders,
- // label: "Type",
- // options:
- // countByType?.map(({ type, _count }) => {
- // const {
- // label,
- // icon: Icon,
- // iconClassName,
- // } = CAMPAIGN_TYPE_BADGES[type];
-
- // return {
- // label,
- // value: type,
- // icon: (
- // <Icon className={cn(iconClassName, "size-4 bg-transparent")} />
- // ),
- // right: nFormatter(_count || 0, { full: true }),
- // };
- // }) ?? [],
- // },
+ {
+ key: "type",
+ icon: Sliders,
+ label: "Type",
+ options:
+ countByType?.map(({ type, _count }) => {
+ const {
+ label,
+ icon: Icon,
+ iconClassName,
+ } = CAMPAIGN_TYPE_BADGES[type];
+
+ return {
+ label,
+ value: type,
+ icon: (
+ <Icon className={cn(iconClassName, "size-4 bg-transparent")} />
+ ),
+ right: nFormatter(_count || 0, { full: true }),
+ };
+ }) ?? [],
+ },
],
[countByType, countByStatus],
);
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/domains/email/constants.ts b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/domains/email/constants.ts
new file mode 100644
index 0000000000..b89b1f2fc0
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/domains/email/constants.ts
@@ -0,0 +1,10 @@
+import { EmailDomainStatus } from "@dub/prisma/client";
+
+export const EMAIL_DOMAIN_STATUS_TO_VARIANT: Record<EmailDomainStatus, string> =
+ {
+ verified: "success",
+ failed: "error",
+ pending: "pending",
+ temporary_failure: "warning",
+ not_started: "neutral",
+ } as const;
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/domains/email/email-domain-card.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/domains/email/email-domain-card.tsx
new file mode 100644
index 0000000000..b7e162a0dc
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/domains/email/email-domain-card.tsx
@@ -0,0 +1,169 @@
+import useWorkspace from "@/lib/swr/use-workspace";
+import { EmailDomainProps } from "@/lib/types";
+import { DomainCardTitleColumn } from "@/ui/domains/domain-card-title-column";
+import { useAddEditEmailDomainModal } from "@/ui/modals/add-edit-email-domain-modal";
+import { useDeleteEmailDomainModal } from "@/ui/modals/delete-email-domain-modal";
+import { Delete, ThreeDots } from "@/ui/shared/icons";
+import { GetDomainResponseSuccess } from "@dub/email/resend/types";
+import {
+ Button,
+ Envelope,
+ PenWriting,
+ Plug2,
+ Popover,
+ Refresh2,
+ StatusBadge,
+ Tooltip,
+ useInViewport,
+} from "@dub/ui";
+import { capitalize, cn, fetcher, formatDate } from "@dub/utils";
+import { motion } from "motion/react";
+import { useEffect, useRef, useState } from "react";
+import useSWRImmutable from "swr/immutable";
+import { EMAIL_DOMAIN_STATUS_TO_VARIANT } from "./constants";
+import { EmailDomainDnsRecords } from "./email-domain-dns-records";
+
+interface EmailDomainCardProps {
+ domain: EmailDomainProps;
+}
+
+export function EmailDomainCard({ domain }: EmailDomainCardProps) {
+ const { id: workspaceId } = useWorkspace();
+ const [showDetails, setShowDetails] = useState(false);
+ const [openPopover, setOpenPopover] = useState(false);
+ const domainRef = useRef<HTMLDivElement>(null);
+ const isVisible = useInViewport(domainRef, { defaultValue: true });
+
+ const { isValidating, mutate, data } =
+ useSWRImmutable<GetDomainResponseSuccess>(
+ workspaceId &&
+ isVisible &&
+ `/api/email-domains/${domain.slug}/verify?workspaceId=${workspaceId}`,
+ fetcher,
+ );
+
+ const { addEditEmailDomainModal, setIsOpen: setShowEditModal } =
+ useAddEditEmailDomainModal({
+ emailDomain: {
+ id: domain.id,
+ slug: domain.slug,
+ },
+ });
+
+ const { DeleteEmailDomainModal, setShowDeleteEmailDomainModal } =
+ useDeleteEmailDomainModal({
+ id: domain.id,
+ slug: domain.slug,
+ });
+
+ // Automatically open DNS records section if status is not verified
+ useEffect(() => {
+ if (data?.status && data.status !== "verified") {
+ setShowDetails(true);
+ }
+ }, [data?.status]);
+
+ return (
+ <>
+ {addEditEmailDomainModal}
+ <DeleteEmailDomainModal />
+ <div
+ ref={domainRef}
+ className="hover:drop-shadow-card-hover group rounded-xl border border-neutral-200 bg-white transition-[filter]"
+ >
+ <div className="p-4 sm:p-5">
+ <div className="flex w-full items-center justify-between gap-2">
+ <DomainCardTitleColumn
+ domain={domain.slug}
+ icon={Envelope}
+ description={`Added on ${formatDate(domain.createdAt)}`}
+ />
+
+ <div className="flex items-center gap-2.5">
+ {!isValidating && data?.status ? (
+ <StatusBadge
+ variant={EMAIL_DOMAIN_STATUS_TO_VARIANT[data.status]}
+ className="h-8 rounded-lg"
+ >
+ {capitalize(data.status.replace(/_/g, " "))}
+ </StatusBadge>
+ ) : (
+ <div className="h-8 min-w-20 animate-pulse rounded-lg bg-neutral-200" />
+ )}
+
+ <Button
+ variant="secondary"
+ className="border-border-subtle h-8 rounded-lg p-2"
+ icon={<Plug2 className="size-3.5 shrink-0" />}
+ onClick={() => setShowDetails((s) => !s)}
+ />
+
+ <Tooltip content="Refresh">
+ <Button
+ icon={
+ <Refresh2
+ className={cn(
+ "size-3.5 shrink-0 -scale-100 transition-colors [animation-duration:0.25s]",
+ isValidating && "animate-spin text-neutral-500",
+ )}
+ />
+ }
+ variant="secondary"
+ className="h-8 rounded-lg p-2 text-neutral-600"
+ onClick={() => mutate()}
+ />
+ </Tooltip>
+
+ <Popover
+ content={
+ <div className="w-full sm:w-48">
+ <div className="grid gap-px p-2">
+ <Button
+ text="Edit"
+ variant="outline"
+ onClick={() => {
+ setOpenPopover(false);
+ setShowEditModal(true);
+ }}
+ icon={<PenWriting className="h-4 w-4" />}
+ className="h-9 justify-start px-2 font-medium"
+ />
+ <Button
+ text="Delete"
+ variant="danger-outline"
+ onClick={() => {
+ setOpenPopover(false);
+ setShowDeleteEmailDomainModal(true);
+ }}
+ icon={<Delete className="h-4 w-4" />}
+ className="h-9 justify-start px-2 font-medium"
+ />
+ </div>
+ </div>
+ }
+ align="end"
+ openPopover={openPopover}
+ setOpenPopover={setOpenPopover}
+ >
+ <Button
+ variant="outline"
+ className="h-8 rounded-lg px-2"
+ icon={<ThreeDots className="size-3.5 shrink-0" />}
+ onClick={() => setOpenPopover(!openPopover)}
+ />
+ </Popover>
+ </div>
+ </div>
+
+ <motion.div
+ initial={false}
+ animate={{ height: showDetails ? "auto" : 0 }}
+ className="overflow-hidden"
+ >
+ {showDetails && <EmailDomainDnsRecords domain={domain} />}
+ </motion.div>
+ </div>
+ </div>
+ </>
+ );
+}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/domains/email/email-domain-dns-records.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/domains/email/email-domain-dns-records.tsx
new file mode 100644
index 0000000000..e2fb57ea26
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/domains/email/email-domain-dns-records.tsx
@@ -0,0 +1,255 @@
+import useWorkspace from "@/lib/swr/use-workspace";
+import { EmailDomainProps } from "@/lib/types";
+import { GetDomainResponseSuccess } from "@dub/email/resend/types";
+import { CircleCheck, CopyButton, StatusBadge, Table, useTable } from "@dub/ui";
+import { capitalize, fetcher } from "@dub/utils";
+import useSWRImmutable from "swr/immutable";
+import { EMAIL_DOMAIN_STATUS_TO_VARIANT } from "./constants";
+
+interface EmailDomainDnsRecordsProps {
+ domain: EmailDomainProps;
+}
+
+interface DomainRecord {
+ record: string;
+ type: string;
+ name: string;
+ value: string;
+ ttl: string;
+ priority?: number | null;
+ status?:
+ | "not_started"
+ | "verified"
+ | "pending"
+ | "failed"
+ | "temporary_failure";
+}
+
+interface DnsRecordsTableProps {
+ title: string;
+ description: React.ReactNode;
+ records: DomainRecord[];
+ showPriority?: boolean;
+ showStatus?: boolean;
+}
+
+function DnsRecordsTable({
+ title,
+ description,
+ records,
+ showPriority = false,
+ showStatus = false,
+}: DnsRecordsTableProps) {
+ const columns = [
+ {
+ id: "type",
+ header: "Type",
+ cell: ({ row }: { row: { original: DomainRecord } }) => (
+ <span className="text-content-default font-mono text-sm">
+ {row.original.type}
+ </span>
+ ),
+ size: 80,
+ minSize: 80,
+ maxSize: 100,
+ },
+ {
+ id: "name",
+ header: "Name",
+ cell: ({ row }: { row: { original: DomainRecord } }) => (
+ <div className="flex min-w-0 items-center gap-2">
+ <span
+ className="text-content-default truncate text-sm"
+ title={row.original.name}
+ >
+ {row.original.name}
+ </span>
+ <CopyButton
+ variant="neutral"
+ className="flex-shrink-0"
+ value={row.original.name}
+ />
+ </div>
+ ),
+ size: 150,
+ minSize: 120,
+ maxSize: 200,
+ },
+ {
+ id: "value",
+ header: "Value",
+ cell: ({ row }: { row: { original: DomainRecord } }) => (
+ <div className="flex min-w-0 items-center gap-2">
+ <span
+ className="text-content-default truncate text-sm"
+ title={row.original.value}
+ >
+ {row.original.value}
+ </span>
+ <CopyButton
+ variant="neutral"
+ className="flex-shrink-0"
+ value={row.original.value}
+ />
+ </div>
+ ),
+ size: 300,
+ minSize: 200,
+ maxSize: 500,
+ },
+ {
+ id: "ttl",
+ header: "TTL",
+ cell: ({ row }: { row: { original: DomainRecord } }) => (
+ <span className="text-content-default text-sm">{row.original.ttl}</span>
+ ),
+ size: 80,
+ minSize: 60,
+ maxSize: 100,
+ },
+ ];
+
+ if (showPriority) {
+ columns.push({
+ id: "priority",
+ header: "Priority",
+ cell: ({ row }: { row: { original: DomainRecord } }) => (
+ <span className="text-content-default text-sm">
+ {row.original.priority ?? "-"}
+ </span>
+ ),
+ size: 80,
+ minSize: 60,
+ maxSize: 100,
+ });
+ }
+
+ if (showStatus) {
+ columns.push({
+ id: "status",
+ header: "Status",
+ cell: ({ row }: { row: { original: DomainRecord } }) => {
+ const status = row.original.status!;
+ const variant = EMAIL_DOMAIN_STATUS_TO_VARIANT[status];
+
+ return (
+ <StatusBadge variant={variant} icon={null}>
+ {capitalize(status.replace(/_/g, " "))}
+ </StatusBadge>
+ );
+ },
+ size: 120,
+ minSize: 100,
+ maxSize: 150,
+ });
+ }
+
+ const { table, ...tableProps } = useTable({
+ data: records,
+ columns,
+ getRowId: (row: DomainRecord) => `${row.type}-${row.name}`,
+ thClassName: "border-l-0 py-1.5",
+ tdClassName: "border-l-0 py-1.5",
+ });
+
+ return (
+ <div className="flex flex-col gap-2">
+ <h3 className="text-sm font-semibold text-neutral-900">{title}</h3>
+ {description}
+ <Table
+ {...tableProps}
+ table={table}
+ containerClassName="border-0 bg-transparent rounded-none"
+ scrollWrapperClassName="min-h-0"
+ emptyWrapperClassName="h-24"
+ className="[&_tbody]:bg-transparent"
+ />
+ </div>
+ );
+}
+
+export function EmailDomainDnsRecords({ domain }: EmailDomainDnsRecordsProps) {
+ const { id: workspaceId } = useWorkspace();
+
+ const { data, isValidating } = useSWRImmutable<GetDomainResponseSuccess>(
+ workspaceId &&
+ `/api/email-domains/${domain.slug}/verify?workspaceId=${workspaceId}`,
+ fetcher,
+ {
+ onError: (error) => {
+ console.error("Failed to fetch email domain verification", error);
+ },
+ },
+ );
+
+ const isVerified = data?.status === "verified";
+ const records = data?.records || [];
+
+ const dmarcRecords = [
+ {
+ record: "dmarc",
+ type: "TXT",
+ name: "_dmarc",
+ value: "v=DMARC1; p=none;",
+ ttl: "Auto",
+ },
+ ];
+
+ return (
+ <div className="mt-4 space-y-4">
+ {!records && !isValidating ? (
+ <div className="h-20 animate-pulse rounded-lg bg-neutral-200" />
+ ) : isVerified ? (
+ <div className="flex items-center gap-2 text-pretty rounded-lg bg-green-100/80 p-3 text-sm text-green-600">
+ <CircleCheck className="h-5 w-5 shrink-0" />
+ <div>
+ Good news! All the DNS records are verified. You are ready to start
+ sending emails with this domain.
+ </div>
+ </div>
+ ) : records && records.length > 0 ? (
+ <div className="flex flex-col gap-8">
+ <div className="flex flex-col gap-4 rounded-lg border border-neutral-200 bg-neutral-100 p-4">
+ <div className="flex flex-col gap-6">
+ {records.length > 0 && (
+ <DnsRecordsTable
+ title="DKIM and SPF (Required)"
+ description={
+ <p className="text-sm text-neutral-700">
+ To authorize Dub to send emails from{" "}
+ <strong>{domain.slug}</strong> to your partners, verify
+ that the DNS records listed below are properly configured
+ in your domain's DNS settings.
+ </p>
+ }
+ records={records}
+ showPriority
+ showStatus
+ />
+ )}
+ </div>
+ </div>
+
+ <div className="flex flex-col rounded-lg border border-neutral-200 bg-neutral-100 p-4">
+ {dmarcRecords.length > 0 && (
+ <DnsRecordsTable
+ title="DMARC (Recommended)"
+ description={
+ <p className="text-sm text-neutral-700">
+ Add DMARC record to build trust in your domain and protect
+ against email spoofing.
+ </p>
+ }
+ records={dmarcRecords}
+ />
+ )}
+ </div>
+ </div>
+ ) : (
+ <div className="rounded-lg bg-neutral-100/80 p-4 text-center text-sm text-neutral-600">
+ Loading verification records...
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/domains/email/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/domains/email/page-client.tsx
index 36c3b0b08c..a523c31cbf 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/domains/email/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/domains/email/page-client.tsx
@@ -1,17 +1,35 @@
"use client";
+import { getPlanCapabilities } from "@/lib/plan-capabilities";
+import { useEmailDomains } from "@/lib/swr/use-email-domains";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { EmailDomainProps } from "@/lib/types";
+import { useAddEditEmailDomainModal } from "@/ui/modals/add-edit-email-domain-modal";
import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
-import { ArrowTurnRight2 } from "@dub/ui";
+import { ArrowTurnRight2, Button, buttonVariants } from "@dub/ui";
+import { cn } from "@dub/utils";
+import { EmailDomainCard } from "app/app.dub.co/(dashboard)/[slug]/settings/domains/email/email-domain-card";
import { Mail } from "lucide-react";
+import Link from "next/link";
export function EmailDomains() {
- return (
- <>
+ const { slug, plan } = useWorkspace();
+
+ const {
+ emailDomains,
+ loading: emailDomainsLoading,
+ error: emailDomainsError,
+ } = useEmailDomains();
+
+ const { canManageEmailDomains } = getPlanCapabilities(plan);
+
+ if (!canManageEmailDomains) {
+ return (
<div className="grid gap-5">
<div className="animate-fade-in">
<AnimatedEmptyState
- title="No email domains found"
- description="Add email domains for branded partner communications"
+ title="Connect email domains"
+ description="Add email domains for branded partner communications. Available on Advanced plans and higher"
cardContent={
<>
<Mail className="size-4 text-neutral-700" />
@@ -21,10 +39,109 @@ export function EmailDomains() {
</div>
</>
}
- pillContent="Coming soon"
+ addButton={
+ <Link
+ href={`/${slug}/upgrade`}
+ className={cn(
+ buttonVariants({ variant: "primary" }),
+ "flex h-9 items-center justify-center whitespace-nowrap rounded-lg border px-4 text-sm",
+ )}
+ >
+ Upgrade
+ </Link>
+ }
+ learnMoreHref="https://dub.co/help/article/email-domains"
/>
</div>
</div>
- </>
+ );
+ }
+
+ return emailDomainsLoading ? (
+ <EmailDomainSkeleton />
+ ) : emailDomainsError ? (
+ <NoEmailDomains />
+ ) : emailDomains && emailDomains.length > 0 ? (
+ <EmailDomainsList domains={emailDomains || []} />
+ ) : (
+ <NoEmailDomains />
);
}
+
+const NoEmailDomains = () => {
+ const { addEditEmailDomainModal, setIsOpen } = useAddEditEmailDomainModal({});
+
+ return (
+ <>
+ {addEditEmailDomainModal}
+ <div className="animate-fade-in">
+ <AnimatedEmptyState
+ title="No email domains"
+ description="Add email domains for branded partner communications"
+ cardContent={
+ <>
+ <Mail className="size-4 text-neutral-700" />
+ <div className="h-2.5 w-24 min-w-0 rounded-sm bg-neutral-200" />
+ <div className="xs:flex hidden grow items-center justify-end gap-1.5 text-neutral-500">
+ <ArrowTurnRight2 className="size-3.5" />
+ </div>
+ </>
+ }
+ addButton={
+ <Button
+ variant="primary"
+ text="Add domain"
+ onClick={() => setIsOpen(true)}
+ className="h-9 rounded-lg"
+ />
+ }
+ learnMoreHref="https://dub.co/help/article/email-domains"
+ />
+ </div>
+ </>
+ );
+};
+
+const EmailDomainSkeleton = () => {
+ return (
+ <div className="grid gap-5">
+ <div className="animate-fade-in space-y-3">
+ {[...Array(1)].map((_, i) => (
+ <div
+ key={i}
+ className="rounded-xl border border-neutral-200 bg-white p-4 sm:p-5"
+ >
+ <div className="flex w-full items-center justify-between gap-2">
+ <div className="flex min-w-0 items-center gap-3">
+ <div className="size-10 shrink-0 animate-pulse rounded-full bg-neutral-200" />
+ <div className="flex min-w-0 flex-col gap-2">
+ <div className="h-4 w-32 animate-pulse rounded bg-neutral-200" />
+ <div className="h-3 w-40 animate-pulse rounded bg-neutral-200" />
+ </div>
+ </div>
+
+ <div className="flex items-center gap-2.5">
+ <div className="h-8 w-20 animate-pulse rounded-lg bg-neutral-200" />
+ <div className="size-8 animate-pulse rounded-lg bg-neutral-200" />
+ <div className="size-8 animate-pulse rounded-lg bg-neutral-200" />
+ <div className="size-8 animate-pulse rounded-lg bg-neutral-200" />
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+};
+
+const EmailDomainsList = ({ domains }: { domains: EmailDomainProps[] }) => {
+ return (
+ <div className="grid gap-5">
+ <div className="animate-fade-in space-y-3">
+ {domains.map((emailDomain) => (
+ <EmailDomainCard key={emailDomain.id} domain={emailDomain} />
+ ))}
+ </div>
+ </div>
+ );
+};
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/domains/header.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/domains/header.tsx
index e2eaf9f51e..cf8877bdd5 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/domains/header.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/domains/header.tsx
@@ -9,7 +9,7 @@ export function DomainsHeader({
}: {
baseUrl?: `/${string}`;
}) {
- const { slug } = useWorkspace();
+ const { slug, defaultProgramId } = useWorkspace();
const selectedLayoutSegment = useSelectedLayoutSegment();
const page = selectedLayoutSegment === null ? "" : selectedLayoutSegment;
@@ -22,6 +22,15 @@ export function DomainsHeader({
label: "Custom domains",
href: `/${slug}${baseUrl}`,
},
+ ...(defaultProgramId
+ ? [
+ {
+ id: "email",
+ label: "Email domains",
+ href: `/${slug}${baseUrl}/email`,
+ },
+ ]
+ : []),
{
id: "default",
label: "Default domains",
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 18cd73caf7..0d2533764d 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."),
+ from: z.string().email().optional(),
emailAddresses: z
.array(z.string().email())
.min(1)
@@ -31,7 +32,7 @@ export const sendCampaignPreviewEmail = authActionClient
.schema(sendPreviewEmailSchema)
.action(async ({ parsedInput, ctx }) => {
const { workspace } = ctx;
- const { campaignId, subject, bodyJson, emailAddresses } = parsedInput;
+ const { campaignId, subject, from, bodyJson, emailAddresses } = parsedInput;
const programId = getDefaultProgramIdOrThrow(workspace);
@@ -47,10 +48,14 @@ export const sendCampaignPreviewEmail = authActionClient
}),
]);
- await sendBatchEmail(
+ const variant =
+ campaign.type === "marketing" ? "marketing" : "notifications";
+
+ const { error } = await sendBatchEmail(
emailAddresses.map((email) => ({
- variant: "notifications",
+ variant,
to: email,
+ ...(from && { from: `${program.name} <${from}>` }),
subject: `[TEST] ${subject}`,
react: CampaignEmail({
program: {
@@ -73,4 +78,8 @@ export const sendCampaignPreviewEmail = authActionClient
}),
})),
);
+
+ if (error) {
+ throw new Error(error.message);
+ }
});
diff --git a/apps/web/lib/api/campaigns/constants.ts b/apps/web/lib/api/campaigns/constants.ts
index 07cab34a14..4fe24f865b 100644
--- a/apps/web/lib/api/campaigns/constants.ts
+++ b/apps/web/lib/api/campaigns/constants.ts
@@ -1,4 +1,36 @@
+import { CampaignStatus, CampaignType } from "@prisma/client";
+
export const DEFAULT_CAMPAIGN_BODY = {
type: "doc",
content: [],
};
+
+export const CAMPAIGN_STATUS_TRANSITIONS: Record<
+ CampaignType,
+ Partial<Record<CampaignStatus, CampaignStatus[]>>
+> = {
+ marketing: {
+ draft: ["scheduled"],
+ scheduled: ["sending", "canceled"],
+ sending: ["sent", "canceled"],
+ sent: [],
+ canceled: [],
+ },
+ transactional: {
+ draft: ["active"],
+ active: ["paused"],
+ paused: ["active"],
+ },
+} as const;
+
+export const CAMPAIGN_EDITABLE_STATUSES: CampaignStatus[] = [
+ "draft",
+ "paused",
+ "scheduled",
+];
+
+export const CAMPAIGN_READONLY_STATUSES: CampaignStatus[] = [
+ "sending",
+ "sent",
+ "canceled",
+];
diff --git a/apps/web/lib/api/campaigns/get-campaigns.ts b/apps/web/lib/api/campaigns/get-campaigns.ts
deleted file mode 100644
index 3548653ba7..0000000000
--- a/apps/web/lib/api/campaigns/get-campaigns.ts
+++ /dev/null
@@ -1,108 +0,0 @@
-import {
- CampaignListSchema,
- getCampaignsQuerySchema,
-} from "@/lib/zod/schemas/campaigns";
-import { prisma } from "@dub/prisma";
-import { Prisma } from "@prisma/client";
-import { z } from "zod";
-
-interface QueryResult {
- id: string;
- name: string;
- type: string;
- status: string;
- createdAt: Date;
- updatedAt: Date;
- sent: number;
- delivered: number;
- bounced: number;
- opened: number;
- groups: { id: string }[];
-}
-
-interface GetCampaignsParams extends z.infer<typeof getCampaignsQuerySchema> {
- programId: string;
-}
-
-const SORT_COLUMNS_MAP = {
- createdAt: "c.createdAt",
- updatedAt: "c.updatedAt",
- status: "c.status",
- sent: "sent",
- delivered: "delivered",
- bounced: "bounced",
- opened: "opened",
-} as const;
-
-export const getCampaigns = async ({
- programId,
- sortBy,
- sortOrder,
- status,
- search,
- type,
- page,
- pageSize,
-}: GetCampaignsParams) => {
- // Aggregate metrics for each campaign
- const metricsSubquery = Prisma.sql`
- SELECT
- campaignId,
- COUNT(*) AS sent,
- SUM(CASE WHEN deliveredAt IS NOT NULL THEN 1 ELSE 0 END) AS delivered,
- SUM(CASE WHEN openedAt IS NOT NULL THEN 1 ELSE 0 END) AS opened,
- SUM(CASE WHEN bouncedAt IS NOT NULL THEN 1 ELSE 0 END) AS bounced
- FROM NotificationEmail
- WHERE
- programId = ${programId}
- AND campaignId IS NOT NULL
- GROUP BY campaignId
- `;
-
- const results = await prisma.$queryRaw<QueryResult[]>`
- SELECT
- c.id,
- c.name,
- c.type,
- c.status,
- c.createdAt,
- c.updatedAt,
- COALESCE(metrics.sent, 0) AS sent,
- COALESCE(metrics.delivered, 0) AS delivered,
- COALESCE(metrics.opened, 0) AS opened,
- COALESCE(metrics.bounced, 0) AS bounced,
- COALESCE(
- (
- SELECT JSON_ARRAYAGG(JSON_OBJECT('id', cg.groupId))
- FROM CampaignGroup cg
- WHERE cg.campaignId = c.id
- ),
- JSON_ARRAY()
- ) AS groups
- FROM Campaign c
- LEFT JOIN (${metricsSubquery}) metrics ON c.id = metrics.campaignId
- WHERE
- c.programId = ${programId}
- ${status ? Prisma.sql`AND c.status = ${status}` : Prisma.sql``}
- ${type ? Prisma.sql`AND c.type = ${type}` : Prisma.sql``}
- ${search ? Prisma.sql`AND LOWER(c.name) LIKE LOWER(${`%${search}%`})` : Prisma.sql``}
- ORDER BY ${Prisma.raw(SORT_COLUMNS_MAP[sortBy])} ${Prisma.raw(sortOrder)}
- LIMIT ${pageSize} OFFSET ${(page - 1) * pageSize}
- `;
-
- const campaigns = results.map((result) => ({
- id: result.id,
- name: result.name,
- type: result.type,
- status: result.status,
- createdAt: result.createdAt,
- updatedAt: result.updatedAt,
- sent: Number(result.sent),
- delivered: Number(result.delivered),
- bounced: Number(result.bounced),
- opened: Number(result.opened),
- groups: result.groups || [],
- }));
-
- return z.array(CampaignListSchema).parse(campaigns);
-};
diff --git a/apps/web/lib/api/campaigns/schedule-campaigns.ts b/apps/web/lib/api/campaigns/schedule-campaigns.ts
new file mode 100644
index 0000000000..99a5e2a650
--- /dev/null
+++ b/apps/web/lib/api/campaigns/schedule-campaigns.ts
@@ -0,0 +1,125 @@
+import { qstash } from "@/lib/cron";
+import { WORKFLOW_SCHEDULES } from "@/lib/zod/schemas/workflows";
+import { prisma } from "@dub/prisma";
+import { Campaign, Workflow } from "@dub/prisma/client";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import { isScheduledWorkflow } from "../workflows/utils";
+
+// Schedule a marketing campaign
+export const scheduleMarketingCampaign = async ({
+ campaign,
+ updatedCampaign,
+}: {
+ campaign: Campaign;
+ updatedCampaign: Campaign;
+}) => {
+ if (updatedCampaign.status === "draft") {
+ return;
+ }
+
+ const scheduleChanged =
+ campaign.scheduledAt?.getTime() !== updatedCampaign.scheduledAt?.getTime();
+
+ const statusChanged =
+ (campaign.status === "draft" && updatedCampaign.status === "scheduled") ||
+ (campaign.status === "scheduled" && updatedCampaign.status === "canceled");
+
+ if (!statusChanged && !scheduleChanged) {
+ return;
+ }
+
+ let qstashMessageId = updatedCampaign.qstashMessageId;
+
+ // Delete the existing message
+ if (campaign.qstashMessageId) {
+ try {
+ await qstash.messages.delete(campaign.qstashMessageId);
+ qstashMessageId = null;
+ } catch (error) {
+ console.warn(
+ `Failed to delete QStash message ${campaign.qstashMessageId}:`,
+ error,
+ );
+ }
+ }
+
+ // Queue a new message
+ if (updatedCampaign.status === "scheduled") {
+ const notBefore = updatedCampaign.scheduledAt
+ ? Math.floor(updatedCampaign.scheduledAt.getTime() / 1000)
+ : null;
+
+ try {
+ const response = await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/campaigns/broadcast`,
+ method: "POST",
+ ...(notBefore && { notBefore }),
+ body: {
+ campaignId: campaign.id,
+ },
+ });
+
+ qstashMessageId = response.messageId;
+ } catch (error) {
+ console.warn(
+ `Failed to queue QStash message for campaign ${campaign.id}:`,
+ error,
+ );
+ }
+ }
+
+ await prisma.campaign.update({
+ where: {
+ id: campaign.id,
+ },
+ data: {
+ qstashMessageId,
+ },
+ });
+};
+
+// Schedule a transactional campaign
+export const scheduleTransactionalCampaign = async ({
+ campaign,
+ updatedCampaign,
+}: {
+ campaign: Campaign;
+ updatedCampaign: Campaign & {
+ workflow: Workflow | null;
+ };
+}) => {
+ if (!updatedCampaign.workflow) {
+ return;
+ }
+
+ if (!isScheduledWorkflow(updatedCampaign.workflow)) {
+ return;
+ }
+
+ const shouldSchedule =
+ (campaign.status === "draft" || campaign.status === "paused") &&
+ updatedCampaign.status === "active";
+
+ const cronSchedule = WORKFLOW_SCHEDULES[updatedCampaign.workflow.trigger];
+
+ if (!cronSchedule) {
+ throw new Error(
+ `Cron schedule not found for trigger ${updatedCampaign.workflow.trigger}`,
+ );
+ }
+
+ if (shouldSchedule) {
+ return await qstash.schedules.create({
+ destination: `${APP_DOMAIN_WITH_NGROK}/api/cron/workflows/${updatedCampaign.workflow.id}`,
+ cron: cronSchedule,
+ scheduleId: updatedCampaign.workflow.id,
+ });
+ }
+
+ const shouldDeleteSchedule =
+ campaign.status === "active" && updatedCampaign.status === "paused";
+
+ if (shouldDeleteSchedule) {
+ return await qstash.schedules.delete(updatedCampaign.workflow.id);
+ }
+};
diff --git a/apps/web/lib/api/campaigns/validate-campaign.ts b/apps/web/lib/api/campaigns/validate-campaign.ts
new file mode 100644
index 0000000000..532b2f3878
--- /dev/null
+++ b/apps/web/lib/api/campaigns/validate-campaign.ts
@@ -0,0 +1,128 @@
+import { updateCampaignSchema } from "@/lib/zod/schemas/campaigns";
+import { prisma } from "@dub/prisma";
+import { Campaign, EmailDomain } from "@dub/prisma/client";
+import { z } from "zod";
+import { DubApiError } from "../errors";
+import {
+ CAMPAIGN_EDITABLE_STATUSES,
+ CAMPAIGN_STATUS_TRANSITIONS,
+} from "./constants";
+
+interface ValidateCampaignParams {
+ input: Partial<z.infer<typeof updateCampaignSchema>>;
+ campaign: Campaign;
+}
+
+export async function validateCampaign({
+ input,
+ campaign,
+}: ValidateCampaignParams) {
+ if (input.status) {
+ const validNextStatuses =
+ CAMPAIGN_STATUS_TRANSITIONS[campaign.type][campaign.status];
+
+ const canTransition = validNextStatuses?.includes(input.status);
+
+ if (!canTransition) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: `A ${campaign.status} campaign can't be moved to ${input.status}.`,
+ });
+ }
+ }
+
+ if (
+ input.name ||
+ input.subject ||
+ input.bodyJson ||
+ input.groupIds ||
+ input.triggerCondition ||
+ input.from ||
+ input.scheduledAt
+ ) {
+ if (!CAMPAIGN_EDITABLE_STATUSES.includes(campaign.status)) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: `You can't make changes to a "${campaign.status}" campaign.`,
+ });
+ }
+ }
+
+ if (campaign.type === "marketing") {
+ delete input.triggerCondition;
+ }
+
+ if (campaign.type === "transactional") {
+ delete input.scheduledAt;
+ }
+
+ // Validate that the from address uses a verified email domain
+ if (input.from) {
+ const emailDomains = await prisma.emailDomain.findMany({
+ where: {
+ programId: campaign.programId,
+ },
+ });
+
+ validateCampaignFromAddress({
+ campaign: {
+ ...campaign,
+ from: input.from,
+ },
+ emailDomains,
+ });
+ }
+
+ return input;
+}
+
+export function validateCampaignFromAddress({
+ campaign,
+ emailDomains,
+}: {
+ campaign: Pick<Campaign, "id" | "from" | "programId">;
+ emailDomains: Pick<EmailDomain, "slug" | "status">[];
+}) {
+ if (emailDomains.length === 0) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: `No email domains found for program (${campaign.programId}).`,
+ });
+ }
+
+ if (!campaign.from) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: `Campaign (${campaign.id}) from address is required.`,
+ });
+ }
+
+ const parts = campaign.from.split("@");
+
+ if (parts.length !== 2) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: `Campaign (${campaign.id}) has an invalid email address format for 'from' field.`,
+ });
+ }
+
+ const domainPart = parts[1];
+
+ const emailDomain = emailDomains.find(
+ (emailDomain) => emailDomain.slug === domainPart,
+ );
+
+ if (!emailDomain) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: `Email domain (${domainPart}) not found in the program (${campaign.programId}) for campaign (${campaign.id}).`,
+ });
+ }
+
+ if (emailDomain.status !== "verified") {
+ throw new DubApiError({
+ code: "bad_request",
+ message: `Email domain (${domainPart}) is not verified in the program (${campaign.programId}) for campaign (${campaign.id}).`,
+ });
+ }
+}
diff --git a/apps/web/lib/api/domains/get-email-domain-or-throw.ts b/apps/web/lib/api/domains/get-email-domain-or-throw.ts
new file mode 100644
index 0000000000..2e3c6b1464
--- /dev/null
+++ b/apps/web/lib/api/domains/get-email-domain-or-throw.ts
@@ -0,0 +1,33 @@
+import { prisma } from "@dub/prisma";
+import { DubApiError } from "../errors";
+
+export const getEmailDomainOrThrow = async ({
+ programId,
+ domain,
+}: {
+ programId: string;
+ domain: string;
+}) => {
+ const emailDomain = await prisma.emailDomain.findUnique({
+ where: {
+ slug: domain,
+ },
+ });
+
+ if (!emailDomain) {
+ throw new DubApiError({
+ code: "not_found",
+ message: `Email domain (${domain}) not found.`,
+ });
+ }
+
+ if (emailDomain.programId !== programId) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: `Email domain (${domain}) is not associated with the program.`,
+ });
+ }
+
+ return emailDomain;
+};
+
diff --git a/apps/web/lib/api/programs/get-program-or-throw.ts b/apps/web/lib/api/programs/get-program-or-throw.ts
index 519e7eeaa2..1b6283592a 100644
--- a/apps/web/lib/api/programs/get-program-or-throw.ts
+++ b/apps/web/lib/api/programs/get-program-or-throw.ts
@@ -1,4 +1,3 @@
-import { ProgramProps } from "@/lib/types";
import { ProgramSchema } from "@/lib/zod/schemas/programs";
import { prisma } from "@dub/prisma";
import { DubApiError } from "../errors";
@@ -10,17 +9,16 @@ export const getProgramOrThrow = async ({
workspaceId: string;
programId: string;
}) => {
- const program = (await prisma.program.findUnique({
+ const program = await prisma.program.findUnique({
where: {
id: programId,
- workspaceId,
},
- })) as ProgramProps | null;
+ });
- if (!program) {
+ if (!program || program.workspaceId !== workspaceId) {
throw new DubApiError({
code: "not_found",
- message: "Program not found",
+ message: "Program not found.",
});
}
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 f571db3d96..eae4816c60 100644
--- a/apps/web/lib/api/workflows/execute-send-campaign-workflow.ts
+++ b/apps/web/lib/api/workflows/execute-send-campaign-workflow.ts
@@ -12,6 +12,7 @@ import { prisma } from "@dub/prisma";
import { NotificationEmailType, Prisma, Workflow } from "@dub/prisma/client";
import { chunk } from "@dub/utils";
import { addHours, differenceInDays, subDays } from "date-fns";
+import { validateCampaignFromAddress } from "../campaigns/validate-campaign";
import { createId } from "../create-id";
import { evaluateWorkflowCondition } from "./execute-workflows";
import { parseWorkflowConfig } from "./parse-workflow-config";
@@ -45,8 +46,16 @@ export const executeSendCampaignWorkflow = async ({
id: campaignId,
},
include: {
- program: true,
groups: true,
+ program: {
+ include: {
+ emailDomains: {
+ where: {
+ status: "verified",
+ },
+ },
+ },
+ },
},
});
@@ -114,6 +123,16 @@ export const executeSendCampaignWorkflow = async ({
return;
}
+ const program = campaign.program;
+
+ // TODO: We should make the from address required. There are existing campaign without from adress
+ if (campaign.from) {
+ validateCampaignFromAddress({
+ campaign,
+ emailDomains: program.emailDomains,
+ });
+ }
+
const programEnrollmentsChunks = chunk(programEnrollments, 100);
for (const programEnrollmentChunk of programEnrollmentsChunks) {
@@ -156,12 +175,11 @@ export const executeSendCampaignWorkflow = async ({
`Workflow ${workflow.id} created ${messages.count} messages for campaign ${campaignId}.`,
);
- const { program } = campaign;
-
// Send emails
const { data } = await sendBatchEmail(
partnerUsers.map((partnerUser) => ({
variant: "notifications",
+ ...(campaign.from ? { from: campaign.from } : {}),
to: partnerUser.email!,
subject: campaign.subject,
replyTo: program.supportEmail || "noreply",
diff --git a/apps/web/lib/api/workflows/utils.ts b/apps/web/lib/api/workflows/utils.ts
index f8d02c22b4..da83d8b942 100644
--- a/apps/web/lib/api/workflows/utils.ts
+++ b/apps/web/lib/api/workflows/utils.ts
@@ -6,9 +6,6 @@ import { parseWorkflowConfig } from "./parse-workflow-config";
export const isCurrencyAttribute = (activity: WorkflowConditionAttribute) =>
activity === "totalCommissions" || activity === "totalSaleAmount";
-export const isDaysAttribute = (activity: WorkflowConditionAttribute) =>
- activity === "partnerEnrolledDays";
-
export const isScheduledWorkflow = (workflow: Workflow) => {
const { condition } = parseWorkflowConfig(workflow);
diff --git a/apps/web/lib/plan-capabilities.ts b/apps/web/lib/plan-capabilities.ts
index 74d088aa59..f82d2a2187 100644
--- a/apps/web/lib/plan-capabilities.ts
+++ b/apps/web/lib/plan-capabilities.ts
@@ -17,5 +17,6 @@ export const getPlanCapabilities = (
canMessagePartners: !!plan && ["enterprise", "advanced"].includes(plan),
canSendEmailCampaigns: !!plan && ["enterprise", "advanced"].includes(plan),
canDiscoverPartners: !!plan && ["enterprise"].includes(plan),
+ canManageEmailDomains: !!plan && ["enterprise", "advanced"].includes(plan),
};
};
diff --git a/apps/web/lib/swr/use-email-domains.ts b/apps/web/lib/swr/use-email-domains.ts
new file mode 100644
index 0000000000..f364b0dc73
--- /dev/null
+++ b/apps/web/lib/swr/use-email-domains.ts
@@ -0,0 +1,25 @@
+import { EmailDomainProps } from "@/lib/types";
+import { fetcher } from "@dub/utils";
+import useSWR from "swr";
+import useWorkspace from "./use-workspace";
+
+export function useEmailDomains() {
+ const { id: workspaceId, defaultProgramId } = useWorkspace();
+
+ const { data, error, mutate } = useSWR<EmailDomainProps[]>(
+ workspaceId && defaultProgramId
+ ? `/api/email-domains?workspaceId=${workspaceId}`
+ : null,
+ fetcher,
+ {
+ dedupingInterval: 60000,
+ },
+ );
+
+ return {
+ emailDomains: data || [],
+ loading: !data && !error,
+ mutate,
+ error,
+ };
+}
diff --git a/apps/web/lib/swr/use-partners-count-bounty.ts b/apps/web/lib/swr/use-partners-count-by-groupids.ts
similarity index 59%
rename from apps/web/lib/swr/use-partners-count-bounty.ts
rename to apps/web/lib/swr/use-partners-count-by-groupids.ts
index 412caa9ef4..c4dfdfc7e2 100644
--- a/apps/web/lib/swr/use-partners-count-bounty.ts
+++ b/apps/web/lib/swr/use-partners-count-by-groupids.ts
@@ -1,11 +1,10 @@
import { useMemo } from "react";
-import { BountyProps } from "../types";
import usePartnersCount from "./use-partners-count";
-export function usePartnersCountBounty({
- bounty,
+export function usePartnersCountByGroupIds({
+ groupIds,
}: {
- bounty?: Pick<BountyProps, "groups">;
+ groupIds?: string[] | null;
}) {
const { partnersCount: groupCount, loading } = usePartnersCount<
| {
@@ -16,24 +15,24 @@ export function usePartnersCountBounty({
>({
groupBy: "groupId",
ignoreParams: true,
- enabled: !!bounty,
+ enabled: !!groupIds,
});
- const totalPartnersForBounty = useMemo(() => {
- if (!bounty || bounty.groups.length === 0) {
+ const totalPartners = useMemo(() => {
+ if (!groupIds || groupIds.length === 0) {
// if no groups set, return all partners
return groupCount?.reduce((acc, curr) => acc + curr._count, 0) ?? 0;
}
return (
groupCount?.reduce((acc, curr) => {
- if (bounty.groups.some((group) => group.id === curr.groupId)) {
+ if (groupIds.includes(curr.groupId)) {
return acc + curr._count;
}
return acc;
}, 0) ?? 0
);
- }, [groupCount, bounty]);
+ }, [groupCount, groupIds]);
- return { totalPartnersForBounty, loading };
+ return { totalPartners, loading };
}
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index 93e1b0674f..fa2164a9f4 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -54,6 +54,7 @@ import {
} from "./zod/schemas/customers";
import { dashboardSchema } from "./zod/schemas/dashboard";
import { DiscountCodeSchema, DiscountSchema } from "./zod/schemas/discount";
+import { EmailDomainSchema } from "./zod/schemas/email-domains";
import { FolderSchema } from "./zod/schemas/folders";
import { GroupWithProgramSchema } from "./zod/schemas/group-with-program";
import {
@@ -657,3 +658,5 @@ export interface CampaignWorkflowAttributeConfig {
}
export type WorkflowAttribute = (typeof WORKFLOW_ATTRIBUTES)[number];
+
+export type EmailDomainProps = z.infer<typeof EmailDomainSchema>;
diff --git a/apps/web/lib/zod/schemas/campaigns.ts b/apps/web/lib/zod/schemas/campaigns.ts
index 15360d4886..ac780bf5cd 100644
--- a/apps/web/lib/zod/schemas/campaigns.ts
+++ b/apps/web/lib/zod/schemas/campaigns.ts
@@ -7,6 +7,7 @@ import { z } from "zod";
import { GroupSchema } from "./groups";
import { getPaginationQuerySchema } from "./misc";
import { EnrolledPartnerSchema } from "./partners";
+import { parseDateSchema } from "./utils";
import { workflowConditionSchema } from "./workflows";
export const EMAIL_TEMPLATE_VARIABLES = [
@@ -49,11 +50,13 @@ export const CampaignSchema = z.object({
id: z.string(),
name: z.string(),
subject: z.string(),
+ from: z.string().nullable(),
bodyJson: z.record(z.string(), z.any()),
type: z.nativeEnum(CampaignType),
status: z.nativeEnum(CampaignStatus),
triggerCondition: workflowConditionSchema.nullable().default(null),
groups: z.array(GroupSchema.pick({ id: true })),
+ scheduledAt: z.date().nullable(),
createdAt: z.date(),
updatedAt: z.date(),
});
@@ -64,10 +67,7 @@ export const CampaignListSchema = z.object({
name: z.string(),
type: z.nativeEnum(CampaignType),
status: z.nativeEnum(CampaignStatus),
- delivered: z.number(),
- sent: z.number(),
- bounced: z.number(),
- opened: z.number(),
+ scheduledAt: z.date().nullable(),
createdAt: z.date(),
updatedAt: z.date(),
groups: z.array(GroupSchema.pick({ id: true })),
@@ -84,13 +84,17 @@ export const updateCampaignSchema = z
.string()
.trim()
.max(100, "Subject must be less than 100 characters."),
+ from: z.string().email().trim().toLowerCase(),
bodyJson: z.record(z.string(), z.any()),
triggerCondition: workflowConditionSchema.nullish(),
groupIds: z.array(z.string()).nullable(),
+ scheduledAt: parseDateSchema.nullish(),
status: z.enum([
CampaignStatus.draft,
CampaignStatus.active,
CampaignStatus.paused,
+ CampaignStatus.scheduled,
+ CampaignStatus.canceled,
]),
})
.partial();
@@ -99,19 +103,6 @@ export const getCampaignsQuerySchema = z
.object({
type: z.nativeEnum(CampaignType).optional(),
status: z.nativeEnum(CampaignStatus).optional(),
- sortBy: z
- .enum([
- "createdAt",
- "updatedAt",
- "status",
- "sent",
- "delivered",
- "opened",
- "bounced",
- ])
- .optional()
- .default("createdAt"),
- sortOrder: z.enum(["asc", "desc"]).optional().default("desc"),
search: z.string().optional(),
})
.merge(getPaginationQuerySchema({ pageSize: 100 }));
diff --git a/apps/web/lib/zod/schemas/email-domains.ts b/apps/web/lib/zod/schemas/email-domains.ts
new file mode 100644
index 0000000000..351e5a1a4e
--- /dev/null
+++ b/apps/web/lib/zod/schemas/email-domains.ts
@@ -0,0 +1,31 @@
+import {
+ isValidDomain,
+ isValidDomainFormat,
+} from "@/lib/api/domains/is-valid-domain";
+import z from "@/lib/zod";
+import { EmailDomainStatus } from "@dub/prisma/client";
+
+export const EmailDomainSchema = z.object({
+ id: z.string(),
+ slug: z.string(),
+ status: z.nativeEnum(EmailDomainStatus),
+ resendDomainId: z.string().nullable(),
+ lastChecked: z.date(),
+ createdAt: z.date(),
+ updatedAt: z.date(),
+});
+
+export const createEmailDomainBodySchema = z.object({
+ slug: z
+ .string({ required_error: "Email domain is required" })
+ .min(5, "Email domain is too short")
+ .max(50, "Email domain is too long")
+ .refine(isValidDomainFormat, { message: "Please use a valid domain name." })
+ .refine(isValidDomain, {
+ message: "You are not allowed to use this domain name",
+ })
+ .transform((value) => value.toLowerCase()),
+});
+
+export const updateEmailDomainBodySchema =
+ createEmailDomainBodySchema.partial();
diff --git a/apps/web/lib/zod/schemas/partner-profile.ts b/apps/web/lib/zod/schemas/partner-profile.ts
index d8ccd85c40..615c13277c 100644
--- a/apps/web/lib/zod/schemas/partner-profile.ts
+++ b/apps/web/lib/zod/schemas/partner-profile.ts
@@ -137,6 +137,7 @@ export const partnerNotificationTypes = z.enum([
"commissionCreated",
"applicationApproved",
"newMessageFromProgram",
+ "marketingCampaign",
]);
export const PartnerBountySchema = BountySchema.omit({
diff --git a/apps/web/tests/campaigns/index.test.ts b/apps/web/tests/campaigns/index.test.ts
index 90cf7a77ba..226f068558 100644
--- a/apps/web/tests/campaigns/index.test.ts
+++ b/apps/web/tests/campaigns/index.test.ts
@@ -32,6 +32,9 @@ const campaign: z.infer<typeof updateCampaignSchema> = {
const expectedCampaign: Partial<Campaign> = {
...campaign,
type: "transactional",
+ status: expect.any(String),
+ from: null,
+ scheduledAt: null,
groups: [{ id: E2E_PARTNER_GROUP.id }],
createdAt: expect.any(String),
updatedAt: expect.any(String),
@@ -51,7 +54,7 @@ describe.sequential("/campaigns/**", async () => {
},
});
- expect(status).toEqual(200);
+ expect(status).toEqual(201);
expect(data).toMatchObject({
id: expect.any(String),
});
@@ -173,17 +176,8 @@ describe.sequential("/campaigns/**", async () => {
const campaign = campaigns.find((c) => c.id === campaignId);
expect(campaign).toStrictEqual({
+ ...expectedCampaign,
id: campaignId,
- name: expectedCampaign.name,
- type: expectedCampaign.type,
- status: "active",
- groups: [{ id: E2E_PARTNER_GROUP.id }],
- delivered: 0,
- sent: 0,
- bounced: 0,
- opened: 0,
- createdAt: expect.any(String),
- updatedAt: expect.any(String),
});
});
diff --git a/apps/web/ui/modals/add-edit-email-domain-modal.tsx b/apps/web/ui/modals/add-edit-email-domain-modal.tsx
new file mode 100644
index 0000000000..28d47e4863
--- /dev/null
+++ b/apps/web/ui/modals/add-edit-email-domain-modal.tsx
@@ -0,0 +1,186 @@
+import { mutatePrefix } from "@/lib/swr/mutate";
+import { useApiMutation } from "@/lib/swr/use-api-mutation";
+import { createEmailDomainBodySchema } from "@/lib/zod/schemas/email-domains";
+import { Button, Modal } from "@dub/ui";
+import { cn } from "@dub/utils";
+import { Dispatch, SetStateAction, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+interface AddEditEmailDomainModalProps {
+ setIsOpen: Dispatch<SetStateAction<boolean>>;
+ emailDomain?: {
+ id: string;
+ slug: string;
+ };
+}
+
+type FormData = z.input<typeof createEmailDomainBodySchema>;
+
+function AddEditEmailDomainModalContent({
+ setIsOpen,
+ emailDomain,
+}: AddEditEmailDomainModalProps) {
+ const { makeRequest: createEmailDomain, isSubmitting: isCreating } =
+ useApiMutation();
+ const { makeRequest: updateEmailDomain, isSubmitting: isUpdating } =
+ useApiMutation();
+
+ const {
+ register,
+ handleSubmit,
+ watch,
+ formState: { errors },
+ } = useForm<FormData>({
+ defaultValues: {
+ slug: emailDomain?.slug || "",
+ },
+ });
+
+ const onSubmit = async (data: FormData) => {
+ if (!emailDomain) {
+ return await createEmailDomain("/api/email-domains", {
+ method: "POST",
+ body: data,
+ onSuccess: async () => {
+ toast.success("Email domain created successfully!");
+ setIsOpen(false);
+ await mutatePrefix("/api/email-domains");
+ },
+ });
+ }
+
+ return await updateEmailDomain(`/api/email-domains/${emailDomain.slug}`, {
+ method: "PATCH",
+ body: data,
+ onSuccess: async () => {
+ toast.success("Email domain updated successfully!");
+ setIsOpen(false);
+ await mutatePrefix("/api/email-domains");
+ },
+ });
+ };
+
+ const slug = watch("slug");
+
+ return (
+ <form onSubmit={handleSubmit(onSubmit)}>
+ <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">
+ <h2 className="text-lg font-semibold">
+ {emailDomain ? "Edit email domain" : "Add email domain"}
+ </h2>
+ </div>
+ </div>
+
+ <div className="flex-1 overflow-y-auto bg-neutral-50">
+ <div className="space-y-6 p-6">
+ <div>
+ <label
+ htmlFor="slug"
+ className="text-sm font-medium text-neutral-800"
+ >
+ Domain or subdomain
+ </label>
+ <div className="mt-1.5">
+ <input
+ type="text"
+ id="slug"
+ autoFocus
+ className={cn(
+ "block w-full rounded-md border-neutral-300 px-3 py-2 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",
+ errors.slug &&
+ "border-red-600 focus:border-red-500 focus:ring-red-600",
+ )}
+ {...register("slug", {
+ required: "Domain is required",
+ validate: (value) => {
+ if (!value) {
+ return "Domain is required";
+ }
+
+ const domainRegex =
+ /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
+
+ if (!domainRegex.test(value)) {
+ return "Please enter a valid domain";
+ }
+
+ return true;
+ },
+ })}
+ placeholder="mail.dub.co"
+ />
+ {errors.slug && (
+ <p className="mt-1 text-sm text-red-600">
+ {errors.slug.message}
+ </p>
+ )}
+ <p className="mt-2 text-xs text-neutral-500">
+ This domain will be used to send campaign emails. You can
+ configure specific "from" addresses when creating campaigns.
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div className="sticky bottom-0 z-10 border-t border-neutral-200 bg-white">
+ <div className="flex items-center justify-end gap-2 p-5">
+ <Button
+ type="button"
+ variant="secondary"
+ onClick={() => setIsOpen(false)}
+ text="Cancel"
+ className="h-9 w-fit"
+ disabled={isCreating || isUpdating}
+ />
+
+ <Button
+ type="submit"
+ variant="primary"
+ text={emailDomain ? "Update domain" : "Add domain"}
+ className="h-9 w-fit"
+ loading={isCreating || isUpdating}
+ disabled={!slug}
+ />
+ </div>
+ </div>
+ </form>
+ );
+}
+
+export function AddEditEmailDomainModal({
+ isOpen,
+ setIsOpen,
+ emailDomain,
+}: AddEditEmailDomainModalProps & {
+ isOpen: boolean;
+}) {
+ return (
+ <Modal showModal={isOpen} setShowModal={setIsOpen}>
+ <AddEditEmailDomainModalContent
+ setIsOpen={setIsOpen}
+ emailDomain={emailDomain}
+ />
+ </Modal>
+ );
+}
+
+export function useAddEditEmailDomainModal(
+ props: Omit<AddEditEmailDomainModalProps, "setIsOpen">,
+) {
+ const [isOpen, setIsOpen] = useState(false);
+
+ return {
+ addEditEmailDomainModal: (
+ <AddEditEmailDomainModal
+ setIsOpen={setIsOpen}
+ isOpen={isOpen}
+ {...props}
+ />
+ ),
+ setIsOpen,
+ };
+}
diff --git a/apps/web/ui/modals/add-folder-modal.tsx b/apps/web/ui/modals/add-folder-modal.tsx
index 5fba15a277..d74498d2b7 100644
--- a/apps/web/ui/modals/add-folder-modal.tsx
+++ b/apps/web/ui/modals/add-folder-modal.tsx
@@ -50,7 +50,7 @@ function AddFolderButton({
text="Create folder"
shortcut="C"
onClick={() => setShowAddFolderModal(true)}
- className="w-fit"
+ className="h-9 w-fit"
disabledTooltip={
plan === "free" && (
<TooltipContent
diff --git a/apps/web/ui/modals/confirm-modal.tsx b/apps/web/ui/modals/confirm-modal.tsx
index d4a2546773..78fd252fe4 100644
--- a/apps/web/ui/modals/confirm-modal.tsx
+++ b/apps/web/ui/modals/confirm-modal.tsx
@@ -62,7 +62,7 @@ function ConfirmModal({
{title}
</h3>
{description && (
- <p className="text-content-subtle mt-1 text-sm">{description}</p>
+ <div className="text-content-subtle mt-1 text-sm">{description}</div>
)}
</div>
diff --git a/apps/web/ui/modals/delete-email-domain-modal.tsx b/apps/web/ui/modals/delete-email-domain-modal.tsx
new file mode 100644
index 0000000000..5656b268a0
--- /dev/null
+++ b/apps/web/ui/modals/delete-email-domain-modal.tsx
@@ -0,0 +1,151 @@
+import { mutatePrefix } from "@/lib/swr/mutate";
+import { useApiMutation } from "@/lib/swr/use-api-mutation";
+import { EmailDomainProps } from "@/lib/types";
+import { Button, Modal, useMediaQuery } from "@dub/ui";
+import { FormEvent, useCallback, useMemo, useState } from "react";
+import { toast } from "sonner";
+
+interface DeleteEmailDomainModalProps {
+ emailDomain: Pick<EmailDomainProps, "id" | "slug">;
+ showModal: boolean;
+ setShowModal: (showModal: boolean) => void;
+ onDelete?: () => void;
+}
+
+const DeleteEmailDomainModal = ({
+ emailDomain,
+ showModal,
+ setShowModal,
+ onDelete,
+}: DeleteEmailDomainModalProps) => {
+ const { isMobile } = useMediaQuery();
+ const { makeRequest: deleteEmailDomain, isSubmitting } = useApiMutation();
+
+ const onSubmit = async (e: FormEvent<HTMLFormElement>) => {
+ e.preventDefault();
+
+ await deleteEmailDomain(`/api/email-domains/${emailDomain.slug}`, {
+ method: "DELETE",
+ onSuccess: async () => {
+ setShowModal(false);
+ await mutatePrefix("/api/email-domains");
+ toast.success("Email domain deleted successfully!");
+ onDelete?.();
+ },
+ });
+ };
+
+ return (
+ <Modal showModal={showModal} setShowModal={setShowModal}>
+ <div className="border-b border-neutral-200 px-4 py-4 sm:px-6">
+ <h3 className="truncate text-lg font-medium">Delete email domain</h3>
+ </div>
+
+ <div className="bg-neutral-50">
+ <form onSubmit={onSubmit}>
+ <div className="flex flex-col gap-y-4 px-4 py-6 text-left sm:px-6">
+ <div className="text-sm font-normal text-neutral-800">
+ <h4 className="mb-2">
+ Deleting <strong>{emailDomain.slug}</strong> domain will do the
+ following:
+ </h4>
+
+ <ul className="mt-0.5 list-outside list-disc space-y-1.5 pl-4">
+ <li>
+ All DNS records associated with this domain will be removed.
+ </li>
+ <li>
+ You will no longer be able to send emails from this domain.
+ </li>
+ <li>
+ Any marketing campaigns configured to use this domain will
+ need to be updated.
+ </li>
+ </ul>
+
+ <p className="mt-4">
+ This action cannot be undone – proceed with caution.
+ </p>
+ </div>
+
+ <div>
+ <div className="flex items-center gap-2">
+ <p className="block text-sm text-neutral-500">
+ To verify, type{" "}
+ <span className="font-medium text-neutral-700">
+ confirm delete {emailDomain.slug}
+ </span>{" "}
+ below
+ </p>
+ </div>
+
+ <div className="mt-2">
+ <div className="-m-1 rounded-[0.625rem] p-1">
+ <input
+ type="text"
+ required
+ autoComplete="off"
+ className="block w-full rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
+ aria-invalid="true"
+ autoFocus={!isMobile}
+ pattern={`confirm delete ${emailDomain.slug}`}
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div className="flex justify-end gap-2 border-t border-neutral-200 px-4 py-4 sm:px-6">
+ <Button
+ type="button"
+ variant="secondary"
+ text="Cancel"
+ className="h-9 w-fit"
+ onClick={() => setShowModal(false)}
+ disabled={isSubmitting}
+ />
+ <Button
+ type="submit"
+ text="Delete email domain"
+ variant="danger"
+ loading={isSubmitting}
+ className="h-9 w-fit"
+ />
+ </div>
+ </form>
+ </div>
+ </Modal>
+ );
+};
+
+export function useDeleteEmailDomainModal(
+ emailDomain: Pick<EmailDomainProps, "id" | "slug">,
+ onDelete?: () => void,
+) {
+ const [showDeleteEmailDomainModal, setShowDeleteEmailDomainModal] =
+ useState(false);
+
+ const DeleteEmailDomainModalCallback = useCallback(() => {
+ return (
+ <DeleteEmailDomainModal
+ showModal={showDeleteEmailDomainModal}
+ setShowModal={setShowDeleteEmailDomainModal}
+ emailDomain={emailDomain}
+ onDelete={onDelete}
+ />
+ );
+ }, [
+ showDeleteEmailDomainModal,
+ setShowDeleteEmailDomainModal,
+ onDelete,
+ emailDomain,
+ ]);
+
+ return useMemo(
+ () => ({
+ setShowDeleteEmailDomainModal,
+ DeleteEmailDomainModal: DeleteEmailDomainModalCallback,
+ }),
+ [setShowDeleteEmailDomainModal, DeleteEmailDomainModalCallback],
+ );
+}
diff --git a/apps/web/vercel.json b/apps/web/vercel.json
index 21ae6df592..9e62a553ee 100644
--- a/apps/web/vercel.json
+++ b/apps/web/vercel.json
@@ -4,6 +4,10 @@
"path": "/api/cron/domains/verify",
"schedule": "0 * * * *"
},
+ {
+ "path": "/api/cron/email-domains/verify",
+ "schedule": "0 * * * *"
+ },
{
"path": "/api/cron/domains/renewal-reminders",
"schedule": "0 8 * * *"
diff --git a/packages/email/src/resend/types.ts b/packages/email/src/resend/types.ts
index 051c0ae375..19a774feb4 100644
--- a/packages/email/src/resend/types.ts
+++ b/packages/email/src/resend/types.ts
@@ -8,3 +8,5 @@ export interface ResendEmailOptions
}
export type ResendBulkEmailOptions = ResendEmailOptions[];
+
+export type { GetDomainResponseSuccess } from "resend";
diff --git a/packages/email/src/templates/campaign-email.tsx b/packages/email/src/templates/campaign-email.tsx
index a3a00856c7..0f669aa53e 100644
--- a/packages/email/src/templates/campaign-email.tsx
+++ b/packages/email/src/templates/campaign-email.tsx
@@ -1,15 +1,18 @@
import { DUB_WORDMARK } from "@dub/utils";
+
import {
Body,
Container,
Head,
Heading,
+ Hr,
Html,
Img,
Link,
Preview,
Section,
Tailwind,
+ Text,
} from "@react-email/components";
export default function CampaignEmail({
@@ -20,7 +23,7 @@ export default function CampaignEmail({
messagingEnabledAt: new Date(),
},
campaign = {
- type: "transactional",
+ 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>`,
},
@@ -29,7 +32,7 @@ export default function CampaignEmail({
name: string;
slug: string;
logo: string | null;
- messagingEnabledAt: Date | null | undefined;
+ messagingEnabledAt?: Date | null | undefined;
};
campaign?: {
type: "transactional" | "marketing";
@@ -103,6 +106,22 @@ export default function CampaignEmail({
</Link>
</Section>
)}
+
+ {campaign.type === "marketing" && (
+ <Section className="border-t border-neutral-200">
+ <Hr className="mx-0 my-3 w-full border border-neutral-200" />
+ <Text className="text-[12px] leading-6 text-neutral-500">
+ Don't want to receive marketing emails from any programs on
+ Dub?{" "}
+ <Link
+ className="text-neutral-700 underline"
+ href="https://partners.dub.co/profile/notifications"
+ >
+ Update your notification settings here.
+ </Link>
+ </Text>
+ </Section>
+ )}
</Container>
</Body>
</Tailwind>
diff --git a/packages/prisma/client.ts b/packages/prisma/client.ts
index 4641062809..37324296c8 100644
--- a/packages/prisma/client.ts
+++ b/packages/prisma/client.ts
@@ -9,6 +9,7 @@ export {
CampaignType,
CommissionStatus,
CommissionType,
+ EmailDomainStatus,
EventType,
FolderType,
FolderUserRole,
diff --git a/packages/prisma/schema/campaign.prisma b/packages/prisma/schema/campaign.prisma
index 228535756e..d2d9933748 100644
--- a/packages/prisma/schema/campaign.prisma
+++ b/packages/prisma/schema/campaign.prisma
@@ -11,27 +11,31 @@ enum CampaignStatus {
paused
// Marketing
- sent
scheduled
+ sending
+ sent
+ canceled
}
model Campaign {
- id String @id @default(cuid())
- programId String
- workflowId String? @unique
- userId String
- type CampaignType
- status CampaignStatus @default(draft)
- name String
- subject String
- bodyJson Json @db.Json
- scheduledAt DateTime?
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
- program Program @relation(fields: [programId], references: [id])
- workflow Workflow? @relation(fields: [workflowId], references: [id], onDelete: Cascade)
- groups CampaignGroup[]
- emails NotificationEmail[]
+ id String @id @default(cuid())
+ programId String
+ workflowId String? @unique
+ userId String
+ qstashMessageId String? @unique
+ type CampaignType
+ status CampaignStatus @default(draft)
+ name String
+ subject String
+ from String?
+ bodyJson Json @db.Json
+ scheduledAt DateTime?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ program Program @relation(fields: [programId], references: [id])
+ workflow Workflow? @relation(fields: [workflowId], references: [id], onDelete: Cascade)
+ groups CampaignGroup[]
+ emails NotificationEmail[]
@@index(programId)
}
diff --git a/packages/prisma/schema/domain.prisma b/packages/prisma/schema/domain.prisma
index 062cf24da1..95360030f3 100644
--- a/packages/prisma/schema/domain.prisma
+++ b/packages/prisma/schema/domain.prisma
@@ -59,3 +59,28 @@ model DefaultDomains {
projectId String @unique
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
}
+
+enum EmailDomainStatus {
+ pending
+ verified
+ failed
+ temporary_failure
+ not_started
+}
+
+model EmailDomain {
+ id String @id @default(cuid())
+ workspaceId String
+ programId String
+ slug String @unique
+ status EmailDomainStatus @default(pending)
+ resendDomainId String? @unique
+ lastChecked DateTime @default(now())
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ program Program @relation(fields: [programId], references: [id], onDelete: Cascade)
+
+ @@index(lastChecked(sort: Asc))
+ @@index(programId)
+}
diff --git a/packages/prisma/schema/notification.prisma b/packages/prisma/schema/notification.prisma
index 3b2467f0cd..851c3d2c49 100644
--- a/packages/prisma/schema/notification.prisma
+++ b/packages/prisma/schema/notification.prisma
@@ -51,6 +51,7 @@ model PartnerNotificationPreferences {
commissionCreated Boolean @default(true)
applicationApproved Boolean @default(true)
newMessageFromProgram Boolean @default(true)
+ marketingCampaign Boolean @default(true)
partnerUser PartnerUser @relation(fields: [partnerUserId], references: [id], onDelete: Cascade)
}
diff --git a/packages/prisma/schema/program.prisma b/packages/prisma/schema/program.prisma
index 9acffe67c8..804da4a797 100644
--- a/packages/prisma/schema/program.prisma
+++ b/packages/prisma/schema/program.prisma
@@ -70,6 +70,7 @@ model Program {
campaigns Campaign[]
discoveredPartners DiscoveredPartner[]
industryInterests ProgramIndustryInterest[]
+ emailDomains EmailDomain[]
@@index(workspaceId)
@@index(domain)
diff --git a/packages/ui/src/icons/nucleo/media-pause.tsx b/packages/ui/src/icons/nucleo/media-pause.tsx
index af475d785e..acf9cf805f 100644
--- a/packages/ui/src/icons/nucleo/media-pause.tsx
+++ b/packages/ui/src/icons/nucleo/media-pause.tsx
@@ -13,16 +13,16 @@ export function MediaPause(props: SVGProps<SVGSVGElement>) {
<path
d="M5.16656 2.44434H3.83322C3.34231 2.44434 2.94434 2.84231 2.94434 3.33322V12.6666C2.94434 13.1575 3.34231 13.5554 3.83322 13.5554H5.16656C5.65748 13.5554 6.05545 13.1575 6.05545 12.6666V3.33322C6.05545 2.84231 5.65748 2.44434 5.16656 2.44434Z"
stroke="#171717"
- stroke-width="1.5"
- stroke-linecap="round"
- stroke-linejoin="round"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ strokeLinejoin="round"
/>
<path
d="M13.1666 2.44434H11.8332C11.3423 2.44434 10.9443 2.84231 10.9443 3.33322V12.6666C10.9443 13.1575 11.3423 13.5554 11.8332 13.5554H13.1666C13.6575 13.5554 14.0554 13.1575 14.0554 12.6666V3.33322C14.0554 2.84231 13.6575 2.44434 13.1666 2.44434Z"
stroke="#171717"
- stroke-width="1.5"
- stroke-linecap="round"
- stroke-linejoin="round"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ strokeLinejoin="round"
/>
</svg>
);
diff --git a/packages/ui/src/icons/nucleo/media-play.tsx b/packages/ui/src/icons/nucleo/media-play.tsx
index a55e3e329f..8eda189c36 100644
--- a/packages/ui/src/icons/nucleo/media-play.tsx
+++ b/packages/ui/src/icons/nucleo/media-play.tsx
@@ -13,9 +13,9 @@ export function MediaPlay(props: SVGProps<SVGSVGElement>) {
<path
d="M5.1619 2.55825L13.5992 7.23025C14.2081 7.56714 14.2081 8.43292 13.5992 8.7698L5.1619 13.4418C4.56723 13.7716 3.83301 13.3458 3.83301 12.672V3.32803C3.83301 2.65425 4.56634 2.22847 5.1619 2.55825Z"
stroke="#171717"
- stroke-width="1.5"
- stroke-linecap="round"
- stroke-linejoin="round"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ strokeLinejoin="round"
/>
</svg>
);
diff --git a/packages/ui/src/menu-item.tsx b/packages/ui/src/menu-item.tsx
index 8e41e6671d..712bebc73a 100644
--- a/packages/ui/src/menu-item.tsx
+++ b/packages/ui/src/menu-item.tsx
@@ -13,14 +13,14 @@ import { DynamicTooltipWrapper } from "./tooltip";
export const menuItemVariants = cva(
[
"flex h-9 w-full rounded-md px-2 items-center justify-center gap-2 transition-colors cursor-pointer",
- "whitespace-nowrap text-sm font-medium text-content-default enabled:hover:bg-bg-subtle transition-colors",
+ "whitespace-nowrap text-sm font-medium text-content-default transition-colors",
"disabled:opacity-50 disabled:cursor-default",
],
{
variants: {
variant: {
default: "text-content-default hover:bg-bg-subtle",
- danger: "text-content-error hover:bg-bg-error",
+ danger: "text-content-error hover:bg-red-50 dark:hover:bg-red-950/20",
},
disabled: {
true: "opacity-50 cursor-default text-content-disabled hover:bg-bg-default",
diff --git a/packages/ui/src/rich-text-area/index.tsx b/packages/ui/src/rich-text-area/index.tsx
index c2aea802fc..f66507de6b 100644
--- a/packages/ui/src/rich-text-area/index.tsx
+++ b/packages/ui/src/rich-text-area/index.tsx
@@ -26,6 +26,7 @@ interface RichTextAreaProps {
editorClassName?: string;
uploadImage?: (file: File) => Promise<string | null>;
variables?: string[];
+ editable?: boolean;
}
export interface RichTextAreaRef {
@@ -42,6 +43,7 @@ export const RichTextArea = forwardRef<RichTextAreaRef, RichTextAreaProps>(
editorClassName,
uploadImage,
variables,
+ editable = true,
},
ref,
) {
@@ -75,6 +77,7 @@ export const RichTextArea = forwardRef<RichTextAreaRef, RichTextAreaProps>(
};
const editor = useEditor({
+ editable,
extensions: [
...richTextAreaExtensions,
Placeholder.configure({