Skip to content

Open source CapCut alternative.

TypeScript

feat(site): promotions send one email to a segment from su

David Le7f335b93cf2e
diff --git a/docs/guides/config-and-experiments.md b/docs/guides/config-and-experiments.md
index c432d9bc..0ffcf2f8 100644
--- a/docs/guides/config-and-experiments.md
+++ b/docs/guides/config-and-experiments.md
@@ -128,6 +128,10 @@ ship at a looser p-value or demand a larger sample without a deploy. The
exposure property rides every PostHog event, so any funnel there breaks down
by variant as well.
+## Promotions
+
+A promotion is one email from su to an audience, minus anyone an earlier promotion reached; the Pro offers behind it (subscribe bonus, allowance multiplier) are Product-tab settings.
+
## Verification
The registry, audience, assignment, experiment schema, statistics and verdict
diff --git a/site/prisma/Auth.prisma b/site/prisma/Auth.prisma
index a0bcac45..968bab41 100644
--- a/site/prisma/Auth.prisma
+++ b/site/prisma/Auth.prisma
@@ -28,6 +28,7 @@ model User {
onboarding UserOnboarding?
emailSettings UserEmailSettings?
outreach UserOutreach[]
+ promotionsReceived PromotionRecipient[]
experimentAssignments ExperimentAssignment[]
experimentHoldout ExperimentHoldout?
diff --git a/site/prisma/Marketing.prisma b/site/prisma/Marketing.prisma
index 4f786883..18c22700 100644
--- a/site/prisma/Marketing.prisma
+++ b/site/prisma/Marketing.prisma
@@ -61,3 +61,54 @@ model OutreachTemplate {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
+
+// A promotion is one email written on su and sent to a segment: an audience
+// (the experiment rules, minus country) and, optionally, everyone who already
+// received earlier promotions left out. The words live here so a draft can be
+// edited, test-sent and counted before anything goes out. Sending resolves the
+// segment into recipient rows once and hands them to the promotion-send job.
+
+model Promotion {
+ id String @id @default(cuid())
+ name String
+ subject String
+ body String
+ ctaLabel String?
+ ctaUrl String?
+ // "bulk" sends from the list address, "personal" from the operator's own.
+ sender String @default("bulk")
+ // Who gets it (src/lib/config/audience via @donkeycut/abexp). {} admits everyone.
+ audience Json @default("{}")
+ // Earlier promotions whose recipients are skipped.
+ excludePromotionIds String[] @default([])
+ // "draft" | "sending" | "sent"
+ status String @default("draft")
+ startedAt DateTime?
+ finishedAt DateTime?
+ actorUserId String?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ recipients PromotionRecipient[]
+
+ @@index([status, createdAt])
+}
+
+// One row per account a promotion resolved to. sentAt marks the send; error
+// holds why one did not go out. The pair is unique, so a retried send can
+// never mail an account twice.
+model PromotionRecipient {
+ id String @id @default(cuid())
+ promotionId String
+ promotion Promotion @relation(fields: [promotionId], references: [id], onDelete: Cascade)
+ userId String
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ sentAt DateTime?
+ // Sends tried so far; the last error stays on the row. A row is given up
+ // after MAX_SEND_ATTEMPTS (src/lib/marketing/promotionInput.ts).
+ attempts Int @default(0)
+ error String?
+ createdAt DateTime @default(now())
+
+ @@unique([promotionId, userId])
+ @@index([promotionId, sentAt])
+}
diff --git a/site/src/app/api/marketing/outreach/route.ts b/site/src/app/api/marketing/outreach/route.ts
index 106888c0..cbca4670 100644
--- a/site/src/app/api/marketing/outreach/route.ts
+++ b/site/src/app/api/marketing/outreach/route.ts
@@ -9,6 +9,7 @@ import {
OUTREACH_REASONS,
OUTREACH_STATUSES,
} from "@/lib/marketing/campaigns";
+import { firstNameOf } from "@/lib/marketing/placeholders";
import {
OutreachNotSendableError,
sendOutreachEmail,
@@ -217,7 +218,7 @@ export const POST = withSuperUser(async (request) => {
vars: {
balance: creditMicrosToString(outreach.balanceMicros),
email: outreach.user.email,
- firstName: outreach.user.name.trim().split(/\s+/)[0] || outreach.user.name,
+ firstName: firstNameOf(outreach.user.name),
name: outreach.user.name,
spent: creditMicrosToString(outreach.spentMicros),
storage: formatBytes(Number(outreach.storageBytes)),
diff --git a/site/src/app/api/marketing/promotions/[id]/route.ts b/site/src/app/api/marketing/promotions/[id]/route.ts
new file mode 100644
index 00000000..5ce917e4
--- /dev/null
+++ b/site/src/app/api/marketing/promotions/[id]/route.ts
@@ -0,0 +1,45 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+
+import { invalidResponse } from "@/lib/config/experimentList";
+import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";
+import { promotionInputSchema } from "@/lib/marketing/promotionInput";
+import { listPromotions } from "@/lib/marketing/promotions";
+import { copyIssue, promotionData } from "@/lib/marketing/promotionSave";
+import { prisma } from "@/lib/prisma";
+
+type Params = { params: Promise<{ id: string }> };
+const idSchema = z.string().trim().min(1);
+
+// A draft is edited in place; anything that has started sending is history
+// and stays as it went out.
+export const PUT = withSuperUser(async (request, { params }: Params) => {
+ const id = idSchema.safeParse((await params).id);
+ if (!id.success) return notFoundResponse();
+ const parsed = promotionInputSchema.safeParse(await request.json());
+ if (!parsed.success) return invalidResponse(parsed.error.issues);
+ const refused = copyIssue(parsed.data);
+ if (refused) return refused;
+
+ const existing = await prisma.promotion.findUnique({ select: { status: true }, where: { id: id.data } });
+ if (!existing) return notFoundResponse();
+ if (existing.status !== "draft") {
+ return invalidResponse([{ path: ["status"], message: "A promotion that has been sent cannot change." }]);
+ }
+ await prisma.promotion.update({ data: promotionData(parsed.data, request.donkey.userId), where: { id: id.data } });
+ return NextResponse.json({ id: id.data, promotions: await listPromotions() });
+});
+
+// Deleting a sent promotion drops its recipient rows too, so a later
+// promotion can no longer skip the people it reached.
+export const DELETE = withSuperUser(async (_request, { params }: Params) => {
+ const id = idSchema.safeParse((await params).id);
+ if (!id.success) return notFoundResponse();
+ const existing = await prisma.promotion.findUnique({ select: { status: true }, where: { id: id.data } });
+ if (!existing) return notFoundResponse();
+ if (existing.status === "sending") {
+ return invalidResponse([{ path: ["status"], message: "A promotion that is sending cannot be deleted." }]);
+ }
+ await prisma.promotion.delete({ where: { id: id.data } });
+ return NextResponse.json({ promotions: await listPromotions() });
+});
diff --git a/site/src/app/api/marketing/promotions/[id]/send/route.ts b/site/src/app/api/marketing/promotions/[id]/send/route.ts
new file mode 100644
index 00000000..3ee1a3fa
--- /dev/null
+++ b/site/src/app/api/marketing/promotions/[id]/send/route.ts
@@ -0,0 +1,60 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+
+import { invalidResponse } from "@/lib/config/experimentList";
+import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";
+import { enqueueJob } from "@/lib/jobs/queue";
+import {
+ listPromotions,
+ promotionAudienceOf,
+ resolvePromotionSegment,
+} from "@/lib/marketing/promotions";
+import { prisma } from "@/lib/prisma";
+
+// Resolving a segment reads facts for every account, and without a queue the
+// job's first run happens inside this request, so the budget matches the
+// worker's.
+export const maxDuration = 300;
+
+type Params = { params: Promise<{ id: string }> };
+const idSchema = z.string().trim().min(1);
+
+// Starts a send: the segment is resolved into recipient rows once, here, and
+// the promotion-send job mails them. The rows are the send's memory — a later
+// promotion that excludes this one reads them, and a re-run of the job skips
+// the ones already marked sent.
+export const POST = withSuperUser(async (request, { params }: Params) => {
+ const id = idSchema.safeParse((await params).id);
+ if (!id.success) return notFoundResponse();
+ const promotion = await prisma.promotion.findUnique({ where: { id: id.data } });
+ if (!promotion) return notFoundResponse();
+ if (promotion.status !== "draft") {
+ return invalidResponse([{ path: ["status"], message: "This promotion has already been sent." }]);
+ }
+
+ const segment = await resolvePromotionSegment({
+ audience: promotionAudienceOf(promotion.audience),
+ excludePromotionIds: promotion.excludePromotionIds,
+ });
+ if (segment.users.length === 0) {
+ return invalidResponse([{ path: ["audience"], message: "Nobody is in this segment." }]);
+ }
+
+ await prisma.$transaction([
+ prisma.promotionRecipient.createMany({
+ data: segment.users.map((user) => ({ promotionId: promotion.id, userId: user.id })),
+ skipDuplicates: true,
+ }),
+ prisma.promotion.update({
+ data: { startedAt: new Date(), status: "sending" },
+ where: { id: promotion.id },
+ }),
+ ]);
+ const { jobId } = await enqueueJob("promotion-send", { promotionId: promotion.id }, request.donkey.userId);
+
+ return NextResponse.json({
+ jobId,
+ promotions: await listPromotions(),
+ recipients: segment.users.length,
+ });
+});
diff --git a/site/src/app/api/marketing/promotions/[id]/test/route.ts b/site/src/app/api/marketing/promotions/[id]/test/route.ts
new file mode 100644
index 00000000..1bb6a8b6
--- /dev/null
+++ b/site/src/app/api/marketing/promotions/[id]/test/route.ts
@@ -0,0 +1,40 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+
+import { invalidResponse } from "@/lib/config/experimentList";
+import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";
+import { UnknownPlaceholderError } from "@/lib/marketing/placeholders";
+import { promotionCopyOf, sendPromotionEmail } from "@/lib/marketing/promotions";
+import { prisma } from "@/lib/prisma";
+
+type Params = { params: Promise<{ id: string }> };
+const idSchema = z.string().trim().min(1);
+
+// Mails the saved copy to the operator, placeholders filled with their own
+// account, from the sender the promotion names. Every click sends again.
+export const POST = withSuperUser(async (request, { params }: Params) => {
+ const id = idSchema.safeParse((await params).id);
+ if (!id.success) return notFoundResponse();
+ const [promotion, operator] = await Promise.all([
+ prisma.promotion.findUnique({ where: { id: id.data } }),
+ prisma.user.findUnique({
+ select: { email: true, id: true, name: true },
+ where: { id: request.donkey.userId },
+ }),
+ ]);
+ if (!promotion || !operator) return notFoundResponse();
+
+ try {
+ await sendPromotionEmail({
+ copy: promotionCopyOf(promotion),
+ idempotencyKey: `promotion-test:${promotion.id}:${Date.now()}`,
+ user: operator,
+ });
+ } catch (error) {
+ if (error instanceof UnknownPlaceholderError) {
+ return invalidResponse([{ path: ["body"], message: error.message }]);
+ }
+ throw error;
+ }
+ return NextResponse.json({ sentTo: operator.email });
+});
diff --git a/site/src/app/api/marketing/promotions/route.ts b/site/src/app/api/marketing/promotions/route.ts
new file mode 100644
index 00000000..7b26ef27
--- /dev/null
+++ b/site/src/app/api/marketing/promotions/route.ts
@@ -0,0 +1,27 @@
+import { NextResponse } from "next/server";
+
+import { invalidResponse } from "@/lib/config/experimentList";
+import { withSuperUser } from "@/lib/donkey-api-auth";
+import { promotionInputSchema } from "@/lib/marketing/promotionInput";
+import { listPromotions, promotionSenders } from "@/lib/marketing/promotions";
+import { copyIssue, promotionData } from "@/lib/marketing/promotionSave";
+import { prisma } from "@/lib/prisma";
+
+// Promotions: the list with the addresses the senders stand for, and a new
+// draft.
+
+export const GET = withSuperUser(async () => {
+ return NextResponse.json({ promotions: await listPromotions(), senders: promotionSenders() });
+});
+
+export const POST = withSuperUser(async (request) => {
+ const parsed = promotionInputSchema.safeParse(await request.json());
+ if (!parsed.success) return invalidResponse(parsed.error.issues);
+ const refused = copyIssue(parsed.data);
+ if (refused) return refused;
+ const promotion = await prisma.promotion.create({
+ data: promotionData(parsed.data, request.donkey.userId),
+ select: { id: true },
+ });
+ return NextResponse.json({ id: promotion.id, promotions: await listPromotions() });
+});
diff --git a/site/src/app/api/marketing/promotions/segment/route.ts b/site/src/app/api/marketing/promotions/segment/route.ts
new file mode 100644
index 00000000..c41d175a
--- /dev/null
+++ b/site/src/app/api/marketing/promotions/segment/route.ts
@@ -0,0 +1,25 @@
+import { NextResponse } from "next/server";
+import { audienceSchema } from "@donkeycut/abexp";
+import { z } from "zod";
+
+import { invalidResponse } from "@/lib/config/experimentList";
+import { withSuperUser } from "@/lib/donkey-api-auth";
+import { resolvePromotionSegment } from "@/lib/marketing/promotions";
+
+export const maxDuration = 120;
+
+const segmentSchema = z
+ .object({
+ audience: audienceSchema,
+ excludePromotionIds: z.array(z.string().min(1)).max(100),
+ })
+ .strict();
+
+// How many accounts a segment reaches right now, and where the rest went.
+// The dialog asks before a send; the send resolves again on its own.
+export const POST = withSuperUser(async (request) => {
+ const parsed = segmentSchema.safeParse(await request.json());
+ if (!parsed.success) return invalidResponse(parsed.error.issues);
+ const { recipients, unsubscribed, alreadyReceived, outsideAudience } = await resolvePromotionSegment(parsed.data);
+ return NextResponse.json({ alreadyReceived, outsideAudience, recipients, unsubscribed });
+});
diff --git a/site/src/app/su/nav.ts b/site/src/app/su/nav.ts
index 9eaf46fb..33af2b02 100644
--- a/site/src/app/su/nav.ts
+++ b/site/src/app/su/nav.ts
@@ -4,6 +4,7 @@ import {
FlaskConical,
ListChecks,
Mail,
+ Megaphone,
Package,
UserRound,
} from "lucide-react";
@@ -73,6 +74,13 @@ export const SU_NAV: SuSurface[] = [
title: "Outreach",
Action: ScanOutreachButton,
},
+ {
+ href: "/promotions",
+ label: "Promotions",
+ icon: Megaphone,
+ title: "Promotions",
+ description: "One email to a segment of accounts.",
+ },
{
href: "/experiments",
label: "Experiments",
diff --git a/site/src/app/su/promotions/PromotionDialog.tsx b/site/src/app/su/promotions/PromotionDialog.tsx
new file mode 100644
index 00000000..e5b3c760
--- /dev/null
+++ b/site/src/app/su/promotions/PromotionDialog.tsx
@@ -0,0 +1,374 @@
+"use client";
+
+import { useState } from "react";
+
+import {
+ AudienceFields,
+ audienceDraftFrom,
+ audienceInputFrom,
+ blankAudienceDraft,
+ type AudienceDraft,
+} from "@/app/su/experiments/AudienceFields";
+import { Field } from "@/app/su/Field";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import { Textarea } from "@/components/ui/textarea";
+import { PROMOTION_PLACEHOLDERS } from "@/lib/marketing/placeholders";
+import { BUTTON_MARK } from "@/lib/marketing/promotionCopy";
+import {
+ promotionInputSchema,
+ type PromotionInput,
+ type PromotionSender,
+ type SegmentCount,
+} from "@/lib/marketing/promotionInput";
+import {
+ useCountSegment,
+ useSavePromotion,
+ useSendPromotion,
+ useTestPromotion,
+ type PromotionSummary,
+} from "@/queries/promotions";
+
+// One form writes a promotion and sends it: the words, the button, which
+// address it comes from, who gets it, and which earlier promotions' readers
+// are left out. A sent promotion opens read-only.
+
+type Draft = {
+ name: string;
+ subject: string;
+ body: string;
+ ctaLabel: string;
+ ctaUrl: string;
+ sender: PromotionSender;
+ audience: AudienceDraft;
+ excludePromotionIds: string[];
+};
+
+const blank = (): Draft => ({
+ name: "",
+ subject: "",
+ body: "",
+ ctaLabel: "",
+ ctaUrl: "",
+ sender: "bulk",
+ audience: blankAudienceDraft(),
+ excludePromotionIds: [],
+});
+
+const fromSummary = (p: PromotionSummary): Draft => ({
+ name: p.name,
+ subject: p.subject,
+ body: p.body,
+ ctaLabel: p.ctaLabel ?? "",
+ ctaUrl: p.ctaUrl ?? "",
+ sender: p.sender,
+ audience: audienceDraftFrom(p.audience),
+ excludePromotionIds: p.excludePromotionIds,
+});
+
+function toInput(draft: Draft): unknown {
+ return {
+ name: draft.name.trim(),
+ subject: draft.subject.trim(),
+ body: draft.body.trim(),
+ ctaLabel: draft.ctaLabel.trim() || null,
+ ctaUrl: draft.ctaUrl.trim() || null,
+ sender: draft.sender,
+ audience: audienceInputFrom(draft.audience),
+ excludePromotionIds: draft.excludePromotionIds,
+ };
+}
+
+const placeholders = PROMOTION_PLACEHOLDERS.map((k) => `{{${k}}}`).join(", ");
+
+export function PromotionDialog({
+ existing,
+ seed,
+ promotions,
+ senders,
+ open,
+ onOpenChange,
+}: {
+ existing: PromotionSummary | null;
+ // A copy to start from, when the promotion is new.
+ seed: PromotionSummary | null;
+ promotions: PromotionSummary[];
+ senders: Record<PromotionSender, string>;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const [draft, setDraft] = useState<Draft>(() =>
+ existing ? fromSummary(existing) : seed ? { ...fromSummary(seed), name: `${seed.name} (copy)` } : blank(),
+ );
+ const [savedId, setSavedId] = useState<string | null>(existing?.id ?? null);
+ const [issues, setIssues] = useState<string[]>([]);
+ const [notice, setNotice] = useState<string | null>(null);
+ const [confirm, setConfirm] = useState<{ id: string; count: SegmentCount } | null>(null);
+ const save = useSavePromotion();
+ const send = useSendPromotion();
+ const test = useTestPromotion();
+ const count = useCountSegment();
+
+ const readOnly = existing !== null && existing.status !== "draft";
+ const busy = save.isPending || send.isPending || test.isPending || count.isPending;
+ // Earlier promotions that reached anyone; the one being edited is not a
+ // choice against itself.
+ const earlier = promotions.filter((p) => p.id !== existing?.id && p.status !== "draft");
+
+ const setAudience = (patch: Partial<AudienceDraft>) =>
+ setDraft((d) => ({ ...d, audience: { ...d.audience, ...patch } }));
+ const toggleExclude = (id: string, on: boolean) =>
+ setDraft((d) => ({
+ ...d,
+ excludePromotionIds: on
+ ? Array.from(new Set([...d.excludePromotionIds, id]))
+ : d.excludePromotionIds.filter((x) => x !== id),
+ }));
+
+ const parse = (): PromotionInput | null => {
+ const parsed = promotionInputSchema.safeParse(toInput(draft));
+ if (!parsed.success) {
+ setIssues(parsed.error.issues.map((i) => `${i.path.join(".") || "form"}: ${i.message}`));
+ return null;
+ }
+ setIssues([]);
+ return parsed.data;
+ };
+
+ const fail = (e: Error) => setIssues([e.message]);
+
+ // Every action past a plain save goes through the saved row, so the test
+ // and the send read exactly what is stored.
+ const ensureSaved = async (): Promise<string | null> => {
+ const input = parse();
+ if (!input) return null;
+ try {
+ const result = await save.mutateAsync({ id: savedId, ...input });
+ setSavedId(result.id);
+ return result.id;
+ } catch (e) {
+ fail(e as Error);
+ return null;
+ }
+ };
+
+ const onSave = async () => {
+ const id = await ensureSaved();
+ if (id) onOpenChange(false);
+ };
+
+ const onTest = async () => {
+ setNotice(null);
+ const id = readOnly ? existing.id : await ensureSaved();
+ if (!id) return;
+ test.mutate(id, {
+ onSuccess: (r) => setNotice(`Test sent to ${r.sentTo}.`),
+ onError: fail,
+ });
+ };
+
+ const onSend = async () => {
+ setNotice(null);
+ const id = await ensureSaved();
+ if (!id) return;
+ const input = parse();
+ if (!input) return;
+ count.mutate(
+ { audience: input.audience, excludePromotionIds: input.excludePromotionIds },
+ { onSuccess: (c) => setConfirm({ id, count: c }), onError: fail },
+ );
+ };
+
+ const onConfirmSend = () => {
+ if (!confirm) return;
+ send.mutate(confirm.id, {
+ onSuccess: () => onOpenChange(false),
+ onError: (e) => {
+ setConfirm(null);
+ fail(e);
+ },
+ });
+ };
+
+ const senderLabel = (s: PromotionSender) =>
+ `${s === "bulk" ? "Bulk" : "Personal"} · ${senders[s] || "not configured"}`;
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-3xl">
+ <DialogHeader>
+ <DialogTitle>{readOnly ? draft.name : existing ? "Edit promotion" : "New promotion"}</DialogTitle>
+ <DialogDescription>
+ {readOnly
+ ? "Sent as it reads here."
+ : "One email to everyone in the segment. Unsubscribed accounts are always left out."}
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="grid gap-5">
+ <div className="grid grid-cols-2 gap-3">
+ <Field label="Name" htmlFor="promo-name">
+ <Input
+ id="promo-name"
+ placeholder="Founding Pro, October"
+ disabled={readOnly}
+ value={draft.name}
+ onChange={(e) => setDraft({ ...draft, name: e.target.value })}
+ />
+ </Field>
+ <Field label="From" htmlFor="promo-sender">
+ <Select
+ disabled={readOnly}
+ value={draft.sender}
+ onValueChange={(v) => setDraft({ ...draft, sender: v as PromotionSender })}
+ >
+ <SelectTrigger id="promo-sender">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="bulk">{senderLabel("bulk")}</SelectItem>
+ <SelectItem value="personal">{senderLabel("personal")}</SelectItem>
+ </SelectContent>
+ </Select>
+ </Field>
+ </div>
+ <Field label="Subject" htmlFor="promo-subject">
+ <Input
+ id="promo-subject"
+ disabled={readOnly}
+ value={draft.subject}
+ onChange={(e) => setDraft({ ...draft, subject: e.target.value })}
+ />
+ </Field>
+ <Field label="Body" htmlFor="promo-body">
+ <Textarea
+ id="promo-body"
+ rows={12}
+ disabled={readOnly}
+ value={draft.body}
+ onChange={(e) => setDraft({ ...draft, body: e.target.value })}
+ />
+ <p className="text-xs text-muted-foreground">
+ A blank line starts a new paragraph. {placeholders} fill in per person. A line that is only{" "}
+ {BUTTON_MARK} places the button; without it the button comes last.
+ </p>
+ </Field>
+ <div className="grid grid-cols-2 gap-3">
+ <Field label="Button label (optional)" htmlFor="promo-cta-label">
+ <Input
+ id="promo-cta-label"
+ placeholder="Get Pro"
+ disabled={readOnly}
+ value={draft.ctaLabel}
+ onChange={(e) => setDraft({ ...draft, ctaLabel: e.target.value })}
+ />
+ </Field>
+ <Field label="Button link" htmlFor="promo-cta-url">
+ <Input
+ id="promo-cta-url"
+ placeholder="https://donkeycut.com/app/settings"
+ disabled={readOnly}
+ value={draft.ctaUrl}
+ onChange={(e) => setDraft({ ...draft, ctaUrl: e.target.value })}
+ />
+ </Field>
+ </div>
+
+ <AudienceFields value={draft.audience} onChange={setAudience} countries={false} disabled={readOnly} />
+
+ <div className="space-y-3">
+ <Label>Skip anyone who received</Label>
+ {earlier.length === 0 ? (
+ <p className="text-sm text-muted-foreground">No earlier promotions.</p>
+ ) : (
+ <div className="grid gap-2">
+ {earlier.map((p) => (
+ <label key={p.id} className="flex items-center justify-between gap-3 text-sm">
+ <span className="min-w-0 truncate">
+ {p.name}
+ <span className="text-muted-foreground"> · {p.counts.sent} sent</span>
+ </span>
+ <Switch
+ disabled={readOnly}
+ checked={draft.excludePromotionIds.includes(p.id)}
+ onCheckedChange={(on) => toggleExclude(p.id, on)}
+ />
+ </label>
+ ))}
+ </div>
+ )}
+ </div>
+
+ {issues.length > 0 ? (
+ <ul className="list-disc space-y-1 pl-5 text-sm text-destructive">
+ {issues.map((issue) => (
+ <li key={issue}>{issue}</li>
+ ))}
+ </ul>
+ ) : null}
+ {notice ? <p className="text-sm text-muted-foreground">{notice}</p> : null}
+ </div>
+
+ <DialogFooter className="gap-2 sm:justify-between">
+ <Button type="button" variant="outline" disabled={busy} onClick={onTest}>
+ {test.isPending ? "Sending test…" : "Send test to me"}
+ </Button>
+ <div className="flex gap-2">
+ {readOnly ? (
+ <Button type="button" variant="secondary" onClick={() => onOpenChange(false)}>
+ Close
+ </Button>
+ ) : (
+ <>
+ <Button type="button" variant="secondary" disabled={busy} onClick={onSave}>
+ {save.isPending ? "Saving…" : "Save draft"}
+ </Button>
+ <Button type="button" disabled={busy} onClick={onSend}>
+ {count.isPending ? "Counting…" : "Send…"}
+ </Button>
+ </>
+ )}
+ </div>
+ </DialogFooter>
+
+ {confirm ? (
+ <Dialog open onOpenChange={(isOpen) => !isOpen && setConfirm(null)}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Send to {confirm.count.recipients} people?</DialogTitle>
+ <DialogDescription>
+ From {senders[draft.sender]}. Left out: {confirm.count.unsubscribed} unsubscribed,{" "}
+ {confirm.count.alreadyReceived} already received an excluded promotion,{" "}
+ {confirm.count.outsideAudience} outside the audience.
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <Button type="button" variant="secondary" disabled={send.isPending} onClick={() => setConfirm(null)}>
+ Not yet
+ </Button>
+ <Button
+ type="button"
+ disabled={send.isPending || confirm.count.recipients === 0}
+ onClick={onConfirmSend}
+ >
+ {send.isPending ? "Starting…" : "Send now"}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ ) : null}
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/site/src/app/su/promotions/page.tsx b/site/src/app/su/promotions/page.tsx
new file mode 100644
index 00000000..98333090
--- /dev/null
+++ b/site/src/app/su/promotions/page.tsx
@@ -0,0 +1,165 @@
+"use client";
+
+import { useState } from "react";
+import { describeAudience } from "@donkeycut/abexp";
+
+import { PromotionDialog } from "@/app/su/promotions/PromotionDialog";
+import { SuStandIn } from "@/app/su/SuStandIn";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import type { PromotionSender, PromotionStatus } from "@/lib/marketing/promotionInput";
+import { useDeletePromotion, usePromotions, type PromotionSummary } from "@/queries/promotions";
+
+type BadgeVariant = "default" | "secondary" | "outline" | "destructive";
+
+const STATUS_VARIANT: Record<PromotionStatus, BadgeVariant> = {
+ draft: "outline",
+ sending: "default",
+ sent: "secondary",
+};
+
+const when = (iso: string) => new Date(iso).toLocaleString();
+
+// A dialog opens on a row to edit it, or on a copy of one (its exclusions
+// pre-set to the original) to write the next promotion to everyone else.
+type Opened = { key: number; existing: PromotionSummary | null; seed: PromotionSummary | null };
+
+export default function SuPromotionsPage() {
+ const promotions = usePromotions();
+ const [opened, setOpened] = useState<Opened | null>(null);
+ const [counter, setCounter] = useState(0);
+ const open = (existing: PromotionSummary | null, seed: PromotionSummary | null) => {
+ setCounter((k) => k + 1);
+ setOpened({ key: counter + 1, existing, seed });
+ };
+
+ if (!promotions.data) return <SuStandIn />;
+ const { promotions: rows, senders } = promotions.data;
+
+ return (
+ <div className="space-y-6 pb-9">
+ <div className="flex justify-end">
+ <Button onClick={() => open(null, null)}>New promotion</Button>
+ </div>
+ {rows.length === 0 ? <p className="text-sm text-muted-foreground">No promotions yet.</p> : null}
+ {rows.map((p) => (
+ <PromotionRow
+ key={p.id}
+ promotion={p}
+ all={rows}
+ senders={senders}
+ onOpen={() => open(p, null)}
+ onDuplicate={() =>
+ open(null, {
+ ...p,
+ excludePromotionIds: Array.from(new Set([p.id, ...p.excludePromotionIds])),
+ })
+ }
+ />
+ ))}
+ {opened ? (
+ <PromotionDialog
+ key={opened.key}
+ existing={opened.existing}
+ seed={opened.seed}
+ promotions={rows}
+ senders={senders}
+ open
+ onOpenChange={(isOpen) => {
+ if (!isOpen) setOpened(null);
+ }}
+ />
+ ) : null}
+ </div>
+ );
+}
+
+function PromotionRow({
+ promotion: p,
+ all,
+ senders,
+ onOpen,
+ onDuplicate,
+}: {
+ promotion: PromotionSummary;
+ all: PromotionSummary[];
+ senders: Record<PromotionSender, string>;
+ onOpen: () => void;
+ onDuplicate: () => void;
+}) {
+ const remove = useDeletePromotion();
+ const [confirmDelete, setConfirmDelete] = useState(false);
+ const skipped = p.excludePromotionIds
+ .map((id) => all.find((other) => other.id === id)?.name ?? "a deleted promotion")
+ .join(", ");
+ const { recipients, sent, failed } = p.counts;
+
+ return (
+ <div className="rounded-lg border p-4">
+ <div className="flex items-start justify-between gap-4">
+ <div className="min-w-0">
+ <div className="flex items-center gap-2">
+ <span className="font-medium">{p.name}</span>
+ <Badge variant={STATUS_VARIANT[p.status]}>{p.status}</Badge>
+ </div>
+ <p className="mt-1 truncate text-sm text-muted-foreground">{p.subject}</p>
+ <p className="mt-1 text-xs text-muted-foreground">
+ From {senders[p.sender] || `${p.sender} (not configured)`} · {describeAudience(p.audience)}
+ {skipped ? ` · skips recipients of ${skipped}` : ""}
+ </p>
+ <p className="mt-1 text-xs text-muted-foreground">
+ {p.status === "draft"
+ ? `Draft · saved ${when(p.updatedAt)}`
+ : `${sent} of ${recipients} sent${failed ? ` · ${failed} failed` : ""}${
+ p.startedAt ? ` · started ${when(p.startedAt)}` : ""
+ }${p.finishedAt ? ` · finished ${when(p.finishedAt)}` : ""}`}
+ </p>
+ </div>
+ <div className="flex shrink-0 items-center gap-2">
+ <Button size="sm" variant={p.status === "draft" ? "default" : "outline"} onClick={onOpen}>
+ {p.status === "draft" ? "Edit" : "View"}
+ </Button>
+ <Button size="sm" variant="outline" onClick={onDuplicate}>
+ Duplicate
+ </Button>
+ {p.status !== "sending" ? (
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={remove.isPending}
+ onClick={() => setConfirmDelete(true)}
+ >
+ Delete
+ </Button>
+ ) : null}
+ </div>
+ </div>
+ <AlertDialog open={confirmDelete} onOpenChange={setConfirmDelete}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete “{p.name}”?</AlertDialogTitle>
+ <AlertDialogDescription>
+ {p.status === "sent"
+ ? "Its recipient list goes with it, so a later promotion can no longer skip the people it reached."
+ : "The draft is removed."}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Keep</AlertDialogCancel>
+ <AlertDialogAction onClick={() => remove.mutate(p.id)}>Delete</AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ );
+}
diff --git a/site/src/emails/promotion.tsx b/site/src/emails/promotion.tsx
new file mode 100644
index 00000000..5c1d5929
--- /dev/null
+++ b/site/src/emails/promotion.tsx
@@ -0,0 +1,99 @@
+import {
+ Body,
+ Button,
+ Container,
+ Head,
+ Hr,
+ Html,
+ Link,
+ Preview,
+ Tailwind,
+ Text,
+ pixelBasedPreset,
+} from "react-email";
+import { Fragment } from "react";
+
+import { DonkeyMark } from "./_components/DonkeyMark";
+
+// A promotion written on su: its paragraphs, an optional button, and the
+// opt-out footer. Sent by src/lib/marketing/promotions.ts; preview with
+// `npm run email:dev`. This module stays pure — the react-email preview server
+// bundles it on its own, so everything it needs comes in as props.
+
+type Block = { kind: "text"; text: string } | { kind: "button" };
+
+type PromotionEmailProps = {
+ preview: string;
+ blocks: Block[];
+ cta: { label: string; url: string } | null;
+ unsubscribeUrl: string;
+};
+
+function lines(text: string) {
+ const parts = text.split("\n");
+ return parts.map((line, i) => (
+ <Fragment key={i}>
+ {i > 0 ? <br /> : null}
+ {line}
+ </Fragment>
+ ));
+}
+
+export default function PromotionEmail({
+ preview,
+ blocks,
+ cta,
+ unsubscribeUrl,
+}: PromotionEmailProps) {
+ return (
+ <Html>
+ <Head />
+ <Preview>{preview}</Preview>
+ <Tailwind config={{ presets: [pixelBasedPreset] }}>
+ <Body className="bg-white font-sans text-[#0F0E0D]">
+ <Container className="mx-auto max-w-[520px] px-6 py-12">
+ <DonkeyMark />
+ {blocks.map((block, i) =>
+ block.kind === "button" && cta ? (
+ <Button
+ key={i}
+ href={cta.url}
+ className="my-4 rounded-lg bg-[#0F0E0D] px-6 py-3 text-[15px] font-semibold text-[#F5EFE0]"
+ >
+ {cta.label}
+ </Button>
+ ) : block.kind === "text" ? (
+ <Text key={i} className="text-[15px] leading-relaxed">
+ {lines(block.text)}
+ </Text>
+ ) : null,
+ )}
+ <Hr className="mt-6 border-[#0F0E0D]/15" />
+ <Text className="text-[12px] leading-relaxed text-[#0F0E0D]/60">
+ You&apos;re receiving this because you created a Donkey Cut
+ account.{" "}
+ <Link
+ href={unsubscribeUrl}
+ className="text-[#0F0E0D]/60 underline"
+ >
+ Unsubscribe
+ </Link>
+ </Text>
+ </Container>
+ </Body>
+ </Tailwind>
+ </Html>
+ );
+}
+
+PromotionEmail.PreviewProps = {
+ preview: "Hey Ada,",
+ blocks: [
+ { kind: "text", text: "Hey Ada," },
+ { kind: "text", text: "Get Pro before October 29 and every month that starts by then includes $100 of AI, 5× the usual $20." },
+ { kind: "button" },
+ { kind: "text", text: "David" },
+ ],
+ cta: { label: "Get Pro", url: "https://donkeycut.com/app/settings" },
+ unsubscribeUrl: "https://donkeycut.com/unsubscribe?token=preview",
+} satisfies PromotionEmailProps;
diff --git a/site/src/lib/jobs/promotion-send.ts b/site/src/lib/jobs/promotion-send.ts
new file mode 100644
index 00000000..2c42cb79
--- /dev/null
+++ b/site/src/lib/jobs/promotion-send.ts
@@ -0,0 +1,102 @@
+import { z } from "zod";
+
+import { ResendNotConfiguredError } from "@/lib/email/resend";
+import { isMarketingUnsubscribed } from "@/lib/email/unsubscribe";
+import { defineJob, JobFailure } from "@/lib/jobs/registry";
+import { UnknownPlaceholderError } from "@/lib/marketing/placeholders";
+import { MAX_SEND_ATTEMPTS } from "@/lib/marketing/promotionInput";
+import { promotionCopyOf, sendPromotionEmail } from "@/lib/marketing/promotions";
+import { prisma } from "@/lib/prisma";
+
+// Sends a promotion to the recipient rows its send resolved. One email at a
+// time, paced under the provider's rate limit, each keyed on the recipient so
+// a re-run mails nobody twice. The opt-out is read again right before each
+// send, so someone who unsubscribed after the segment was resolved is
+// skipped. A failed send is tried again later in the run, up to MAX_SEND_ATTEMPTS,
+// with a pause after each failure so a provider blip does not burn the list.
+// A run stops inside the worker's time budget and queues its own
+// continuation; the last run marks the promotion sent.
+
+const TAKE = 50;
+const PACE_MS = 550;
+const FAILURE_PAUSE_MS = 5_000;
+// Under the worker's 300 s maxDuration, with room for the pause and the
+// continuation's own writes.
+const BUDGET_MS = 200_000;
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+const payloadSchema = z.object({ promotionId: z.string().min(1) }).strict();
+
+export const promotionSendJob = defineJob(payloadSchema, async ({ promotionId }) => {
+ const promotion = await prisma.promotion.findUnique({ where: { id: promotionId } });
+ if (!promotion) throw new JobFailure("The promotion no longer exists.");
+ if (promotion.status !== "sending") return { promotionId, skipped: promotion.status };
+ const copy = promotionCopyOf(promotion);
+
+ const startedAt = Date.now();
+ let sent = 0;
+ let failed = 0;
+ let skipped = 0;
+ const continueLater = async () => {
+ const { enqueueJob } = await import("@/lib/jobs/queue");
+ await enqueueJob("promotion-send", { promotionId }, promotion.actorUserId ?? "system");
+ return { continued: true, failed, promotionId, sent, skipped };
+ };
+
+ for (;;) {
+ // Rows still owed a send: never sent, not given up on. A row that failed
+ // earlier in this run comes back at the end of the order.
+ const pending = await prisma.promotionRecipient.findMany({
+ orderBy: [{ attempts: "asc" }, { createdAt: "asc" }],
+ select: { attempts: true, id: true, user: { select: { email: true, id: true, name: true } } },
+ take: TAKE,
+ where: { attempts: { lt: MAX_SEND_ATTEMPTS }, promotionId, sentAt: null },
+ });
+ if (pending.length === 0) break;
+ for (const recipient of pending) {
+ if (Date.now() - startedAt > BUDGET_MS) return continueLater();
+
+ if (await isMarketingUnsubscribed(recipient.user.id)) {
+ await prisma.promotionRecipient.update({
+ data: { attempts: MAX_SEND_ATTEMPTS, error: "Unsubscribed before the send." },
+ where: { id: recipient.id },
+ });
+ skipped++;
+ continue;
+ }
+ try {
+ await sendPromotionEmail({
+ copy,
+ idempotencyKey: `promotion:${promotionId}:${recipient.user.id}`,
+ user: recipient.user,
+ });
+ await prisma.promotionRecipient.update({
+ data: { error: null, sentAt: new Date() },
+ where: { id: recipient.id },
+ });
+ sent++;
+ await sleep(PACE_MS);
+ } catch (error) {
+ // Permanent for the whole send: the draft comes back so the operator
+ // can fix it, and the unsent rows go with it.
+ if (error instanceof ResendNotConfiguredError || error instanceof UnknownPlaceholderError) {
+ await prisma.promotionRecipient.deleteMany({ where: { promotionId, sentAt: null } });
+ await prisma.promotion.update({ data: { status: "draft" }, where: { id: promotionId } });
+ throw new JobFailure(error.message);
+ }
+ await prisma.promotionRecipient.update({
+ data: {
+ attempts: { increment: 1 },
+ error: error instanceof Error ? error.message : String(error),
+ },
+ where: { id: recipient.id },
+ });
+ if (recipient.attempts + 1 >= MAX_SEND_ATTEMPTS) failed++;
+ await sleep(FAILURE_PAUSE_MS);
+ }
+ }
+ }
+ await prisma.promotion.update({ data: { finishedAt: new Date(), status: "sent" }, where: { id: promotionId } });
+ return { failed, promotionId, sent, skipped };
+});
diff --git a/site/src/lib/jobs/registry.ts b/site/src/lib/jobs/registry.ts
index f4a469d2..653a408c 100644
--- a/site/src/lib/jobs/registry.ts
+++ b/site/src/lib/jobs/registry.ts
@@ -8,6 +8,7 @@ import { creditExpiryNoticeJob } from "@/lib/jobs/credit-expiry-notice";
import { deleteUserJob } from "@/lib/jobs/delete-user";
import { experimentResultsJob } from "@/lib/jobs/experiment-results";
import { outreachScanJob } from "@/lib/jobs/outreach-scan";
+import { promotionSendJob } from "@/lib/jobs/promotion-send";
// Thrown by an executor when the job can never succeed — the message lands on
// the job row as its error. Anything else thrown is transient: the claim is
@@ -36,4 +37,5 @@ export const jobKinds: Record<string, JobKind> = {
"delete-user": deleteUserJob,
"experiment-results": experimentResultsJob,
"outreach-scan": outreachScanJob,
+ "promotion-send": promotionSendJob,
};
diff --git a/site/src/lib/marketing/placeholders.ts b/site/src/lib/marketing/placeholders.ts
index 9c4b7dc9..01864cd1 100644
--- a/site/src/lib/marketing/placeholders.ts
+++ b/site/src/lib/marketing/placeholders.ts
@@ -26,6 +26,20 @@ export const OUTREACH_PLACEHOLDERS = [
"storage",
] as const satisfies readonly (keyof OutreachVars)[];
+/** What a promotion may name: the account itself, nothing that costs a query
+ * per recipient. */
+export type PromotionVars = {
+ firstName: string;
+ name: string;
+ email: string;
+};
+
+export const PROMOTION_PLACEHOLDERS = [
+ "firstName",
+ "name",
+ "email",
+] as const satisfies readonly (keyof PromotionVars)[];
+
const PLACEHOLDER = /\{\{\s*([a-zA-Z]+)\s*\}\}/g;
export class UnknownPlaceholderError extends Error {
@@ -35,13 +49,27 @@ export class UnknownPlaceholderError extends Error {
}
}
-/** Fills a subject or body for one recipient. An unknown placeholder throws
- * rather than mailing the braces out, so a typo is caught before the send. */
-export function fillOutreachText(text: string, vars: OutreachVars): string {
+/** First word of an account name, the way a note addresses someone. */
+export function firstNameOf(name: string): string {
+ return name.trim().split(/\s+/)[0] || name;
+}
+
+function fill(text: string, vars: Record<string, string>, allowed: readonly string[]): string {
return text.replace(PLACEHOLDER, (_match, key: string) => {
- if (!(OUTREACH_PLACEHOLDERS as readonly string[]).includes(key)) {
+ if (!allowed.includes(key)) {
throw new UnknownPlaceholderError(key);
}
- return vars[key as keyof OutreachVars];
+ return vars[key];
});
}
+
+/** Fills a subject or body for one recipient. An unknown placeholder throws
+ * rather than mailing the braces out, so a typo is caught before the send. */
+export function fillOutreachText(text: string, vars: OutreachVars): string {
+ return fill(text, vars, OUTREACH_PLACEHOLDERS);
+}
+
+/** The promotion fill: the same rule over the smaller set. */
+export function fillPromotionText(text: string, vars: PromotionVars): string {
+ return fill(text, vars, PROMOTION_PLACEHOLDERS);
+}
diff --git a/site/src/lib/marketing/promotionCopy.test.ts b/site/src/lib/marketing/promotionCopy.test.ts
new file mode 100644
index 00000000..9d9b930d
--- /dev/null
+++ b/site/src/lib/marketing/promotionCopy.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, test } from "bun:test";
+
+import { UnknownPlaceholderError } from "./placeholders";
+import { promotionBlocks, renderPromotion, SAMPLE_RECIPIENT } from "./promotionCopy";
+
+const copy = {
+ subject: "{{firstName}}, 5x AI on Pro",
+ body: "Hey {{firstName}},\n\nGet Pro before October 29.\nEvery month includes $100 of AI.\n\n{{button}}\n\nDavid",
+ ctaLabel: "Get Pro",
+ ctaUrl: "https://donkeycut.com/app/settings",
+ sender: "bulk" as const,
+};
+
+describe("promotionBlocks", () => {
+ test("splits at blank lines and keeps a line break inside a paragraph", () => {
+ expect(promotionBlocks("one\ntwo\n\n\nthree", false)).toEqual([
+ { kind: "text", text: "one\ntwo" },
+ { kind: "text", text: "three" },
+ ]);
+ });
+
+ test("places the button where the mark is, once", () => {
+ expect(promotionBlocks("a\n\n{{button}}\n\nb\n\n{{button}}", true)).toEqual([
+ { kind: "text", text: "a" },
+ { kind: "button" },
+ { kind: "text", text: "b" },
+ ]);
+ });
+
+ test("a body without the mark gets the button last", () => {
+ expect(promotionBlocks("a\n\nb", true)).toEqual([
+ { kind: "text", text: "a" },
+ { kind: "text", text: "b" },
+ { kind: "button" },
+ ]);
+ });
+
+ test("the mark is dropped when there is no button", () => {
+ expect(promotionBlocks("a\n\n{{button}}", false)).toEqual([{ kind: "text", text: "a" }]);
+ });
+});
+
+describe("renderPromotion", () => {
+ test("fills the subject, body and button label for the recipient", () => {
+ const rendered = renderPromotion(copy, SAMPLE_RECIPIENT);
+ expect(rendered.subject).toBe("Ada, 5x AI on Pro");
+ expect(rendered.blocks).toEqual([
+ { kind: "text", text: "Hey Ada," },
+ { kind: "text", text: "Get Pro before October 29.\nEvery month includes $100 of AI." },
+ { kind: "button" },
+ { kind: "text", text: "David" },
+ ]);
+ expect(rendered.cta).toEqual({ label: "Get Pro", url: copy.ctaUrl });
+ expect(rendered.preview).toBe("Hey Ada,");
+ });
+
+ test("an unknown placeholder refuses the copy", () => {
+ let refused = false;
+ try {
+ renderPromotion({ ...copy, body: "{{balance}}" }, SAMPLE_RECIPIENT);
+ } catch (e) {
+ refused = e instanceof UnknownPlaceholderError;
+ }
+ expect(refused).toBe(true);
+ });
+
+ test("no button leaves the body as paragraphs", () => {
+ const rendered = renderPromotion({ ...copy, ctaLabel: null, ctaUrl: null }, SAMPLE_RECIPIENT);
+ expect(rendered.cta).toBeNull();
+ expect(rendered.blocks.some((b) => b.kind === "button")).toBe(false);
+ });
+});
diff --git a/site/src/lib/marketing/promotionCopy.ts b/site/src/lib/marketing/promotionCopy.ts
new file mode 100644
index 00000000..9c6d4c61
--- /dev/null
+++ b/site/src/lib/marketing/promotionCopy.ts
@@ -0,0 +1,79 @@
+import type { EmailUser } from "@/lib/email/resend";
+import {
+ fillPromotionText,
+ firstNameOf,
+ type PromotionVars,
+} from "@/lib/marketing/placeholders";
+import type { PromotionSender } from "@/lib/marketing/promotionInput";
+
+// The words of a promotion, turned into what one recipient reads: the subject
+// and body with placeholders filled, the body cut into paragraphs, and the
+// button placed. Pure, so the send, the test send and the tests share it.
+
+export type PromotionCopy = {
+ subject: string;
+ body: string;
+ ctaLabel: string | null;
+ ctaUrl: string | null;
+ sender: PromotionSender;
+};
+
+export type PromotionBlock = { kind: "text"; text: string } | { kind: "button" };
+
+/** A paragraph that is only this places the button there. */
+export const BUTTON_MARK = "{{button}}";
+
+/** Splits a body into paragraphs at blank lines. With a button, the first
+ * paragraph reading `{{button}}` places it; without one it follows the last
+ * paragraph. A line break inside a paragraph is kept. */
+export function promotionBlocks(body: string, hasButton: boolean): PromotionBlock[] {
+ const blocks: PromotionBlock[] = [];
+ let placed = false;
+ for (const raw of body.replace(/\r\n/g, "\n").split(/\n[ \t]*\n/)) {
+ const text = raw.trim();
+ if (!text) continue;
+ if (text === BUTTON_MARK) {
+ if (hasButton && !placed) {
+ blocks.push({ kind: "button" });
+ placed = true;
+ }
+ continue;
+ }
+ blocks.push({ kind: "text", text });
+ }
+ if (hasButton && !placed) blocks.push({ kind: "button" });
+ return blocks;
+}
+
+export function promotionVars(user: EmailUser): PromotionVars {
+ return { firstName: firstNameOf(user.name), name: user.name, email: user.email };
+}
+
+export type RenderedPromotion = {
+ subject: string;
+ blocks: PromotionBlock[];
+ cta: { label: string; url: string } | null;
+ // The inbox preview line: the first line of the body.
+ preview: string;
+};
+
+/** What one recipient reads. Throws UnknownPlaceholderError on a typo, so a
+ * save or a send fails before any mail leaves. */
+export function renderPromotion(copy: PromotionCopy, user: EmailUser): RenderedPromotion {
+ const vars = promotionVars(user);
+ const subject = fillPromotionText(copy.subject, vars);
+ const cta =
+ copy.ctaLabel !== null && copy.ctaUrl !== null
+ ? { label: fillPromotionText(copy.ctaLabel, vars), url: copy.ctaUrl }
+ : null;
+ const body = fillPromotionText(copy.body.replaceAll(BUTTON_MARK, "\u0000button\u0000"), vars).replaceAll(
+ "\u0000button\u0000",
+ BUTTON_MARK,
+ );
+ const blocks = promotionBlocks(body, cta !== null);
+ const first = blocks.find((b): b is { kind: "text"; text: string } => b.kind === "text");
+ return { subject, blocks, cta, preview: first ? first.text.split("\n")[0] : subject };
+}
+
+/** A stand-in recipient, for validating copy and for the test send. */
+export const SAMPLE_RECIPIENT: EmailUser = { id: "sample", email: "[email protected]", name: "Ada Lovelace" };
diff --git a/site/src/lib/marketing/promotionInput.ts b/site/src/lib/marketing/promotionInput.ts
new file mode 100644
index 00000000..fb669f3b
--- /dev/null
+++ b/site/src/lib/marketing/promotionInput.ts
@@ -0,0 +1,60 @@
+import { audienceSchema, type Audience } from "@donkeycut/abexp";
+import { z } from "zod";
+
+// The shape of a promotion as su writes it and the routes validate it.
+// Client-safe: zod only, so the dialog parses the same schema the server does.
+
+export const PROMOTION_SENDERS = ["bulk", "personal"] as const;
+export type PromotionSender = (typeof PROMOTION_SENDERS)[number];
+
+export const PROMOTION_STATUSES = ["draft", "sending", "sent"] as const;
+
+// Sends tried on one recipient before the row is given up.
+export const MAX_SEND_ATTEMPTS = 5;
+export type PromotionStatus = (typeof PROMOTION_STATUSES)[number];
+
+export const promotionInputSchema = z
+ .object({
+ name: z.string().trim().min(1).max(80),
+ subject: z.string().trim().min(1).max(200),
+ body: z.string().trim().min(1).max(10_000),
+ ctaLabel: z.string().trim().min(1).max(80).nullable(),
+ ctaUrl: z.url().max(2000).nullable(),
+ sender: z.enum(PROMOTION_SENDERS),
+ audience: audienceSchema,
+ // Earlier promotions whose recipients are left out.
+ excludePromotionIds: z.array(z.string().min(1)).max(100),
+ })
+ .strict()
+ .refine((d) => (d.ctaLabel === null) === (d.ctaUrl === null), {
+ message: "A button needs both a label and a link.",
+ path: ["ctaLabel"],
+ });
+
+export type PromotionInput = z.output<typeof promotionInputSchema>;
+
+export type PromotionSummary = {
+ id: string;
+ name: string;
+ subject: string;
+ body: string;
+ ctaLabel: string | null;
+ ctaUrl: string | null;
+ sender: PromotionSender;
+ audience: Audience;
+ excludePromotionIds: string[];
+ status: PromotionStatus;
+ startedAt: string | null;
+ finishedAt: string | null;
+ createdAt: string;
+ updatedAt: string;
+ counts: { recipients: number; sent: number; failed: number };
+};
+
+// What a segment resolves to before anything is sent.
+export type SegmentCount = {
+ recipients: number;
+ unsubscribed: number;
+ alreadyReceived: number;
+ outsideAudience: number;
+};
diff --git a/site/src/lib/marketing/promotionSave.ts b/site/src/lib/marketing/promotionSave.ts
new file mode 100644
index 00000000..82fd1082
--- /dev/null
+++ b/site/src/lib/marketing/promotionSave.ts
@@ -0,0 +1,35 @@
+import type { Prisma } from "@/generated/prisma/client";
+import { invalidResponse } from "@/lib/config/experimentList";
+import { UnknownPlaceholderError } from "@/lib/marketing/placeholders";
+import { renderPromotion, SAMPLE_RECIPIENT } from "@/lib/marketing/promotionCopy";
+import type { PromotionInput } from "@/lib/marketing/promotionInput";
+
+// What a save of a promotion shares between create and edit: the copy is
+// rendered for a stand-in recipient, so a placeholder typo is refused at the
+// save and never reaches a send; and the row data the input maps to.
+
+export function copyIssue(input: PromotionInput): Response | null {
+ try {
+ renderPromotion(input, SAMPLE_RECIPIENT);
+ return null;
+ } catch (error) {
+ if (error instanceof UnknownPlaceholderError) {
+ return invalidResponse([{ path: ["body"], message: error.message }]);
+ }
+ throw error;
+ }
+}
+
+export function promotionData(input: PromotionInput, actorUserId: string) {
+ return {
+ actorUserId,
+ audience: input.audience as Prisma.InputJsonValue,
+ body: input.body,
+ ctaLabel: input.ctaLabel,
+ ctaUrl: input.ctaUrl,
+ excludePromotionIds: input.excludePromotionIds,
+ name: input.name,
+ sender: input.sender,
+ subject: input.subject,
+ };
+}
diff --git a/site/src/lib/marketing/promotions.ts b/site/src/lib/marketing/promotions.ts
new file mode 100644
index 00000000..cf4090ba
--- /dev/null
+++ b/site/src/lib/marketing/promotions.ts
@@ -0,0 +1,228 @@
+import { audienceNeeds, audienceSchema, matchesAudience, type Audience } from "@donkeycut/abexp";
+
+import type { Prisma } from "@/generated/prisma/client";
+import { DONKEY_LOGO_CID, DONKEY_LOGO_PNG_BASE64 } from "@/emails/_components/logo";
+import PromotionEmail from "@/emails/promotion";
+import { collectFacts } from "@/lib/config/audienceFacts";
+import {
+ bulkFrom,
+ emailFrom,
+ getResend,
+ isResendConfigured,
+ ResendNotConfiguredError,
+ type EmailUser,
+} from "@/lib/email/resend";
+import { unsubscribeActionUrl, unsubscribePageUrl } from "@/lib/email/unsubscribe";
+import { renderPromotion, type PromotionCopy } from "@/lib/marketing/promotionCopy";
+import {
+ MAX_SEND_ATTEMPTS,
+ PROMOTION_SENDERS,
+ PROMOTION_STATUSES,
+ type PromotionSender,
+ type PromotionStatus,
+ type PromotionSummary,
+ type SegmentCount,
+} from "@/lib/marketing/promotionInput";
+import { prisma } from "@/lib/prisma";
+
+// Promotions on the server: which address each sender is, who a segment
+// resolves to, one send, and the list su reads.
+
+/** The address each sender name stands for. Empty when unconfigured. */
+export function promotionSenders(): Record<PromotionSender, string> {
+ return { bulk: bulkFrom(), personal: emailFrom() };
+}
+
+const isSender = (s: string): s is PromotionSender => (PROMOTION_SENDERS as readonly string[]).includes(s);
+const isStatus = (s: string): s is PromotionStatus => (PROMOTION_STATUSES as readonly string[]).includes(s);
+
+function senderOf(value: string): PromotionSender {
+ if (!isSender(value)) throw new Error(`Unknown promotion sender "${value}".`);
+ return value;
+}
+
+function statusOf(value: string): PromotionStatus {
+ if (!isStatus(value)) throw new Error(`Unknown promotion status "${value}".`);
+ return value;
+}
+
+export function promotionCopyOf(row: {
+ subject: string;
+ body: string;
+ ctaLabel: string | null;
+ ctaUrl: string | null;
+ sender: string;
+}): PromotionCopy {
+ return { subject: row.subject, body: row.body, ctaLabel: row.ctaLabel, ctaUrl: row.ctaUrl, sender: senderOf(row.sender) };
+}
+
+// A stored audience that no longer parses is an error: widening a send to
+// everyone is the one thing a bad row must never do.
+export function promotionAudienceOf(raw: Prisma.JsonValue): Audience {
+ return audienceSchema.parse(raw);
+}
+
+/** Sends one promotion email. The idempotency key is the caller's: the job
+ * keys on the recipient so a retried run cannot mail anyone twice. */
+export async function sendPromotionEmail(input: {
+ copy: PromotionCopy;
+ user: EmailUser;
+ idempotencyKey: string;
+}): Promise<void> {
+ if (!isResendConfigured()) throw new ResendNotConfiguredError();
+ const from = promotionSenders()[input.copy.sender];
+ if (!from) throw new Error(`The ${input.copy.sender} sender is not configured.`);
+ const rendered = renderPromotion(input.copy, input.user);
+ const { error } = await getResend().emails.send(
+ {
+ from,
+ to: input.user.email,
+ replyTo: emailFrom() || from,
+ subject: rendered.subject,
+ react: PromotionEmail({
+ blocks: rendered.blocks,
+ cta: rendered.cta,
+ preview: rendered.preview,
+ unsubscribeUrl: unsubscribePageUrl(input.user.id),
+ }),
+ attachments: [
+ {
+ content: DONKEY_LOGO_PNG_BASE64,
+ contentId: DONKEY_LOGO_CID,
+ contentType: "image/png",
+ filename: "donkey-cut.png",
+ },
+ ],
+ headers: {
+ "List-Unsubscribe": `<${unsubscribeActionUrl(input.user.id)}>`,
+ "List-Unsubscribe-Post": "List-Unsubscribe=One-Click",
+ },
+ },
+ { idempotencyKey: input.idempotencyKey },
+ );
+ if (error) {
+ throw new Error(`Resend send failed: ${error.name}: ${error.message}`);
+ }
+}
+
+export type PromotionSegment = { audience: Audience; excludePromotionIds: string[] };
+
+export type SegmentResolution = SegmentCount & { users: EmailUser[] };
+
+const USER_PAGE = 500;
+const FACTS_CONCURRENCY = 10;
+
+/** Everyone a segment reaches: the accounts the audience rules admit, less
+ * the unsubscribed, less the recipients of the excluded promotions. The
+ * counts of those left out are taken inside the audience, so they describe
+ * the segment. Country is never known here, so a countries rule admits
+ * nobody. */
+export async function resolvePromotionSegment(
+ segment: PromotionSegment,
+ now = new Date(),
+): Promise<SegmentResolution> {
+ const [unsubscribedRows, receivedRows] = await Promise.all([
+ prisma.userEmailSettings.findMany({
+ select: { userId: true },
+ where: { marketingUnsubscribedAt: { not: null } },
+ }),
+ segment.excludePromotionIds.length > 0
+ ? prisma.promotionRecipient.findMany({
+ distinct: ["userId"],
+ select: { userId: true },
+ where: { promotionId: { in: segment.excludePromotionIds }, sentAt: { not: null } },
+ })
+ : Promise.resolve([]),
+ ]);
+ const unsubscribed = new Set(unsubscribedRows.map((r) => r.userId));
+ const received = new Set(receivedRows.map((r) => r.userId));
+ const needs = audienceNeeds(segment.audience);
+
+ const result: SegmentResolution = {
+ users: [],
+ recipients: 0,
+ unsubscribed: 0,
+ alreadyReceived: 0,
+ outsideAudience: 0,
+ };
+ let cursor: string | undefined;
+ for (;;) {
+ const page = await prisma.user.findMany({
+ orderBy: { id: "asc" },
+ select: { createdAt: true, email: true, id: true, name: true },
+ take: USER_PAGE,
+ ...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}),
+ });
+ if (page.length === 0) break;
+ cursor = page[page.length - 1].id;
+
+ for (let i = 0; i < page.length; i += FACTS_CONCURRENCY) {
+ const slice = page.slice(i, i + FACTS_CONCURRENCY);
+ const matched = await Promise.all(
+ slice.map(async (user) => {
+ const facts = await collectFacts(user.id, { country: null, createdAt: user.createdAt }, needs);
+ return matchesAudience(segment.audience, facts, now);
+ }),
+ );
+ slice.forEach((user, j) => {
+ if (!matched[j]) result.outsideAudience++;
+ else if (unsubscribed.has(user.id)) result.unsubscribed++;
+ else if (received.has(user.id)) result.alreadyReceived++;
+ else result.users.push({ email: user.email, id: user.id, name: user.name });
+ });
+ }
+ }
+ result.recipients = result.users.length;
+ return result;
+}
+
+type PromotionRow = NonNullable<Awaited<ReturnType<typeof prisma.promotion.findUnique>>>;
+
+function summarize(
+ row: PromotionRow,
+ counts: { recipients: number; sent: number; failed: number },
+): PromotionSummary {
+ return {
+ id: row.id,
+ name: row.name,
+ subject: row.subject,
+ body: row.body,
+ ctaLabel: row.ctaLabel,
+ ctaUrl: row.ctaUrl,
+ sender: senderOf(row.sender),
+ audience: promotionAudienceOf(row.audience),
+ excludePromotionIds: row.excludePromotionIds,
+ status: statusOf(row.status),
+ startedAt: row.startedAt?.toISOString() ?? null,
+ finishedAt: row.finishedAt?.toISOString() ?? null,
+ createdAt: row.createdAt.toISOString(),
+ updatedAt: row.updatedAt.toISOString(),
+ counts,
+ };
+}
+
+/** Every promotion, newest first, with how far its send got. */
+export async function listPromotions(): Promise<PromotionSummary[]> {
+ const [rows, all, sent, failed] = await Promise.all([
+ prisma.promotion.findMany({ orderBy: { createdAt: "desc" } }),
+ prisma.promotionRecipient.groupBy({ _count: true, by: ["promotionId"] }),
+ prisma.promotionRecipient.groupBy({ _count: true, by: ["promotionId"], where: { sentAt: { not: null } } }),
+ prisma.promotionRecipient.groupBy({
+ _count: true,
+ by: ["promotionId"],
+ where: { attempts: { gte: MAX_SEND_ATTEMPTS }, sentAt: null },
+ }),
+ ]);
+ const countOf = (groups: { promotionId: string; _count: number }[]) =>
+ new Map(groups.map((g) => [g.promotionId, g._count]));
+ const recipients = countOf(all);
+ const sentBy = countOf(sent);
+ const failedBy = countOf(failed);
+ return rows.map((row) =>
+ summarize(row, {
+ recipients: recipients.get(row.id) ?? 0,
+ sent: sentBy.get(row.id) ?? 0,
+ failed: failedBy.get(row.id) ?? 0,
+ }),
+ );
+}
diff --git a/site/src/queries/promotions.ts b/site/src/queries/promotions.ts
new file mode 100644
index 00000000..34584044
--- /dev/null
+++ b/site/src/queries/promotions.ts
@@ -0,0 +1,87 @@
+"use client";
+
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import type { Audience } from "@donkeycut/abexp";
+
+import type {
+ PromotionInput,
+ PromotionSender,
+ PromotionSummary,
+ SegmentCount,
+} from "@/lib/marketing/promotionInput";
+import { apiFetch } from "@/queries/apiClient";
+
+export type { PromotionSummary };
+
+export const promotionsQueryKey = ["su", "promotions"] as const;
+
+type Body = { promotions: PromotionSummary[]; senders: Record<PromotionSender, string> };
+
+// Super-user only: every promotion with how far its send got, and the address
+// each sender stands for. Polls while a send is running.
+export function usePromotions() {
+ return useQuery({
+ queryFn: () => apiFetch<Body>("/api/marketing/promotions"),
+ queryKey: promotionsQueryKey,
+ refetchInterval: (query) =>
+ query.state.data?.promotions.some((p) => p.status === "sending") ? 3000 : false,
+ });
+}
+
+// A new draft, or an edit of one. Answers with the saved id.
+export function useSavePromotion() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: ({ id, ...input }: PromotionInput & { id: string | null }) =>
+ apiFetch<{ id: string; promotions: PromotionSummary[] }>(
+ id ? `/api/marketing/promotions/${encodeURIComponent(id)}` : "/api/marketing/promotions",
+ { body: JSON.stringify(input), method: id ? "PUT" : "POST" },
+ ),
+ onSuccess: () => queryClient.invalidateQueries({ queryKey: promotionsQueryKey }),
+ });
+}
+
+export function useDeletePromotion() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (id: string) =>
+ apiFetch<{ promotions: PromotionSummary[] }>(`/api/marketing/promotions/${encodeURIComponent(id)}`, {
+ method: "DELETE",
+ }),
+ onSuccess: () => queryClient.invalidateQueries({ queryKey: promotionsQueryKey }),
+ });
+}
+
+// Starts the send; the list's polling follows it to sent.
+export function useSendPromotion() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (id: string) =>
+ apiFetch<{ jobId: string; recipients: number }>(
+ `/api/marketing/promotions/${encodeURIComponent(id)}/send`,
+ { method: "POST" },
+ ),
+ onSuccess: () => queryClient.invalidateQueries({ queryKey: promotionsQueryKey }),
+ });
+}
+
+// Mails the saved copy to the operator.
+export function useTestPromotion() {
+ return useMutation({
+ mutationFn: (id: string) =>
+ apiFetch<{ sentTo: string }>(`/api/marketing/promotions/${encodeURIComponent(id)}/test`, {
+ method: "POST",
+ }),
+ });
+}
+
+// How many accounts a segment reaches right now.
+export function useCountSegment() {
+ return useMutation({
+ mutationFn: (segment: { audience: Audience; excludePromotionIds: string[] }) =>
+ apiFetch<SegmentCount>("/api/marketing/promotions/segment", {
+ body: JSON.stringify(segment),
+ method: "POST",
+ }),
+ });
+}