Open source CapCut alternative.
TypeScript
feat(site): outreach sends toggle the unsubscribe footer and reply tracking per template
David Le71ae901e492e
diff --git a/site/prisma/Marketing.prisma b/site/prisma/Marketing.prismaindex 4a089714..112ba1c6 100644--- a/site/prisma/Marketing.prisma+++ b/site/prisma/Marketing.prisma@@ -46,6 +46,10 @@ model OutreachTemplate {name String @uniquesubject Stringbody String+ // The send toggles the template opens with: the opt-out footer, and routing+ // replies through the signed alias that marks the row replied.+ unsubscribeLink Boolean @default(false)+ trackReplies Boolean @default(false)// The super user who last saved it.actorUserId String?createdAt DateTime @default(now())diff --git a/site/src/app/api/marketing/outreach/route.ts b/site/src/app/api/marketing/outreach/route.tsindex 5bfecdf8..f49b70b2 100644--- a/site/src/app/api/marketing/outreach/route.ts+++ b/site/src/app/api/marketing/outreach/route.ts@@ -26,6 +26,8 @@ const actionSchema = z.union([body: z.string().trim().min(1).max(5000),outreachId: z.string().trim().min(1),subject: z.string().trim().min(1).max(200),+ trackReplies: z.boolean(),+ unsubscribeLink: z.boolean(),}).strict(),z@@ -146,6 +148,8 @@ export const POST = withSuperUser(async (request) => {body: parsed.data.body,outreachId: outreach.id,subject: parsed.data.subject,+ trackReplies: parsed.data.trackReplies,+ unsubscribeLink: parsed.data.unsubscribeLink,user: outreach.user,vars: {balance: creditMicrosToString(outreach.balanceMicros),diff --git a/site/src/app/api/marketing/templates/route.ts b/site/src/app/api/marketing/templates/route.tsindex f94db22d..f3675fa3 100644--- a/site/src/app/api/marketing/templates/route.ts+++ b/site/src/app/api/marketing/templates/route.ts@@ -12,6 +12,8 @@ const saveSchema = zbody: z.string().trim().min(1).max(5000),name: z.string().trim().min(1).max(80),subject: z.string().trim().min(1).max(200),+ trackReplies: z.boolean(),+ unsubscribeLink: z.boolean(),}).strict();@@ -20,6 +22,8 @@ const templateSelect = {id: true,name: true,subject: true,+ trackReplies: true,+ unsubscribeLink: true,updatedAt: true,} as const;@@ -28,6 +32,8 @@ type TemplateRow = {id: string;name: string;subject: string;+ trackReplies: boolean;+ unsubscribeLink: boolean;updatedAt: Date;};@@ -37,6 +43,8 @@ function serialize(row: TemplateRow) {id: row.id,name: row.name,subject: row.subject,+ trackReplies: row.trackReplies,+ unsubscribeLink: row.unsubscribeLink,updatedAt: row.updatedAt.toISOString(),};}@@ -66,11 +74,24 @@ export const POST = withSuperUser(async (request) => {);}- const { body, name, subject } = parsed.data;+ const { body, name, subject, trackReplies, unsubscribeLink } = parsed.data;const template = await prisma.outreachTemplate.upsert({- create: { actorUserId: request.donkey.userId, body, name, subject },+ create: {+ actorUserId: request.donkey.userId,+ body,+ name,+ subject,+ trackReplies,+ unsubscribeLink,+ },select: templateSelect,- update: { actorUserId: request.donkey.userId, body, subject },+ update: {+ actorUserId: request.donkey.userId,+ body,+ subject,+ trackReplies,+ unsubscribeLink,+ },where: { name },});return NextResponse.json({ template: serialize(template) });diff --git a/site/src/app/su/outreach/drafts.ts b/site/src/app/su/outreach/drafts.tsindex 3c2e2f32..de5983a5 100644--- a/site/src/app/su/outreach/drafts.ts+++ b/site/src/app/su/outreach/drafts.ts@@ -6,10 +6,23 @@ import { useLocalPref } from "@/cut/lib/uiState";// What was sent last, kept in this browser so the next note can start from it// and be edited. It stays here on purpose: the server keeps status and-// timestamps for a conversation, never the words.+// timestamps for a conversation, never the words. The two send toggles ride+// along, so a start point recalls how it went out as well as what it said.export type OutreachDraft = {subject: string;body: string;+ unsubscribeLink: boolean;+ trackReplies: boolean;+ savedAt: string;+};++// The toggles are optional on disk: entries written before they existed read+// as off, which is how those notes went out.+type StoredDraft = {+ subject: string;+ body: string;+ unsubscribeLink?: boolean;+ trackReplies?: boolean;savedAt: string;};@@ -17,13 +30,16 @@ const KEY = "donkey.outreach.drafts";const START_KEY = "donkey.outreach.lastStart";const LIMIT = 20;-function isDraft(value: unknown): value is OutreachDraft {+function isDraft(value: unknown): value is StoredDraft {if (typeof value !== "object" || value === null) return false;const draft = value as Record<string, unknown>;return (typeof draft.subject === "string" &&typeof draft.body === "string" &&- typeof draft.savedAt === "string"+ typeof draft.savedAt === "string" &&+ (draft.unsubscribeLink === undefined ||+ typeof draft.unsubscribeLink === "boolean") &&+ (draft.trackReplies === undefined || typeof draft.trackReplies === "boolean"));}@@ -38,31 +54,46 @@ export function useLastOutreachStart(): [string | null, (id: string) => void] {export function useOutreachDrafts(): {drafts: OutreachDraft[];- remember: (draft: { subject: string; body: string }) => string;+ remember: (draft: Omit<OutreachDraft, "savedAt">) => string;forget: (savedAt: string) => void;} {- const [drafts, setDrafts] = useLocalPref<OutreachDraft[]>(KEY, [], (value) =>+ const [stored, setStored] = useLocalPref<StoredDraft[]>(KEY, [], (value) =>Array.isArray(value) && value.every(isDraft),);+ const drafts: OutreachDraft[] = stored.map((draft) => ({+ ...draft,+ trackReplies: draft.trackReplies ?? false,+ unsubscribeLink: draft.unsubscribeLink ?? false,+ }));+const remember = useCallback(- ({ body, subject }: { subject: string; body: string }) => {- // Sending the same words twice moves the entry up rather than doubling it.- const rest = drafts.filter(- (draft) => draft.subject !== subject || draft.body !== body,+ ({ body, subject, trackReplies, unsubscribeLink }: Omit<OutreachDraft, "savedAt">) => {+ // Sending the same note twice moves the entry up rather than doubling it.+ const rest = stored.filter(+ (draft) =>+ draft.subject !== subject ||+ draft.body !== body ||+ (draft.unsubscribeLink ?? false) !== unsubscribeLink ||+ (draft.trackReplies ?? false) !== trackReplies,);const savedAt = new Date().toISOString();- setDrafts([{ body, savedAt, subject }, ...rest].slice(0, LIMIT));+ setStored(+ [{ body, savedAt, subject, trackReplies, unsubscribeLink }, ...rest].slice(+ 0,+ LIMIT,+ ),+ );return savedAt;},- [drafts, setDrafts],+ [stored, setStored],);const forget = useCallback((savedAt: string) => {- setDrafts(drafts.filter((draft) => draft.savedAt !== savedAt));+ setStored(stored.filter((draft) => draft.savedAt !== savedAt));},- [drafts, setDrafts],+ [stored, setStored],);return { drafts, forget, remember };diff --git a/site/src/app/su/outreach/page.tsx b/site/src/app/su/outreach/page.tsxindex a7d46773..9c7c292b 100644--- a/site/src/app/su/outreach/page.tsx+++ b/site/src/app/su/outreach/page.tsx@@ -20,6 +20,7 @@ import {} from "@/components/ui/dialog";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";+import { Switch } from "@/components/ui/switch";import { Textarea } from "@/components/ui/textarea";import { cn } from "@/lib/utils";import type { OutreachStatus } from "@/lib/marketing/campaigns";@@ -47,14 +48,16 @@ const FILTERS: { status: OutreachStatus; label: string }[] = [const BLANK = "blank";// A place a note can start from: a saved template, or something this browser-// already sent. Both are starting points; whatever ends up in the fields is-// what goes out.+// already sent. Both are starting points; whatever ends up in the dialog —+// words and send toggles alike — is what goes out.type StartPoint = {id: string;title: string;meta: string;subject: string;body: string;+ unsubscribeLink: boolean;+ trackReplies: boolean;at: number;remove?: () => void;busy?: boolean;@@ -108,6 +111,8 @@ export default function SuOutreachPage() {const deleteTemplate = useDeleteOutreachTemplate();const { drafts, forget, remember } = useOutreachDrafts();const [lastStart, setLastStart] = useLastOutreachStart();+ const [unsubscribeLink, setUnsubscribeLink] = useState(false);+ const [trackReplies, setTrackReplies] = useState(false);const saved = templates.data?.templates ?? [];@@ -130,6 +135,8 @@ export default function SuOutreachPage() {}),subject: template.subject,title: template.name,+ trackReplies: template.trackReplies,+ unsubscribeLink: template.unsubscribeLink,})),...drafts.map((draft) => ({at: new Date(draft.savedAt).getTime(),@@ -142,11 +149,22 @@ export default function SuOutreachPage() {},subject: draft.subject,title: draft.subject,+ trackReplies: draft.trackReplies,+ unsubscribeLink: draft.unsubscribeLink,})),].sort((a, b) => b.at - a.at);const sources: StartPoint[] = [- { at: 0, body: "", id: BLANK, meta: "", subject: "", title: "Blank" },+ {+ at: 0,+ body: "",+ id: BLANK,+ meta: "",+ subject: "",+ title: "Blank",+ trackReplies: false,+ unsubscribeLink: false,+ },...starts,];@@ -161,6 +179,8 @@ export default function SuOutreachPage() {setSource(id);setSubject(picked.subject);setBody(picked.body);+ setUnsubscribeLink(picked.unsubscribeLink);+ setTrackReplies(picked.trackReplies);setNaming(false);};@@ -173,6 +193,8 @@ export default function SuOutreachPage() {setSource(start.id);setSubject(start.subject);setBody(start.body);+ setUnsubscribeLink(start.unsubscribeLink);+ setTrackReplies(start.trackReplies);setNaming(false);setSendTarget(row);};@@ -181,13 +203,17 @@ export default function SuOutreachPage() {const name = templateName.trim();if (name === "" || !sendable) return;saveTemplate.mutate(- { body, name, subject },+ { body, name, subject, trackReplies, unsubscribeLink },{onSuccess: (result) => {- // The words now live in a template, so the sent copy of them stops+ // The note now lives in a template, so the sent copy of it stops// being a second entry saying the same thing.const same = drafts.find(- (draft) => draft.subject === subject && draft.body === body,+ (draft) =>+ draft.subject === subject &&+ draft.body === body &&+ draft.unsubscribeLink === unsubscribeLink &&+ draft.trackReplies === trackReplies,);if (same) {forget(same.savedAt);@@ -219,15 +245,30 @@ export default function SuOutreachPage() {const submitSend = () => {const target = sendTarget;if (!target || subject.trim() === "" || body.trim() === "") return;- // Sending a start point word for word is that start point; only edited- // words become an entry of their own.+ // Sending a start point exactly as it is stays that start point; a change+ // to its words or its toggles becomes an entry of its own.const from = sources.find((option) => option.id === source);- const edited = from?.subject !== subject || from.body !== body;+ const edited =+ from?.subject !== subject ||+ from.body !== body ||+ from.unsubscribeLink !== unsubscribeLink ||+ from.trackReplies !== trackReplies;act.mutate(- { action: "send", body, outreachId: target.id, subject },+ {+ action: "send",+ body,+ outreachId: target.id,+ subject,+ trackReplies,+ unsubscribeLink,+ },{onSuccess: () => {- setLastStart(edited ? `draft:${remember({ body, subject })}` : source);+ setLastStart(+ edited+ ? `draft:${remember({ body, subject, trackReplies, unsubscribeLink })}`+ : source,+ );// A send in flight leaves the dialog free for the next row, so only// close it if that row is still the one on screen.setSendTarget((current) => (current?.id === target.id ? null : current));@@ -347,8 +388,10 @@ export default function SuOutreachPage() {<DialogHeader><DialogTitle>Email {sendTarget?.name}</DialogTitle><DialogDescription>- Goes to {sendTarget?.email}. Replies come back to your inbox and mark- this row replied.+ Goes to {sendTarget?.email}.{" "}+ {trackReplies+ ? "Replies come back to your inbox and mark this row replied."+ : "Replies come straight back to your own address."}</DialogDescription></DialogHeader>@@ -493,6 +536,19 @@ export default function SuOutreachPage() {</div><DialogFooter>+ <div className="flex flex-wrap items-center gap-x-4 gap-y-2 sm:mr-auto">+ <Label className="gap-2 font-normal text-muted-foreground">+ <Switch+ checked={unsubscribeLink}+ onCheckedChange={setUnsubscribeLink}+ />+ Add unsubscribe link+ </Label>+ <Label className="gap-2 font-normal text-muted-foreground">+ <Switch checked={trackReplies} onCheckedChange={setTrackReplies} />+ Track replies+ </Label>+ </div><DialogClose render={<Button variant="outline" />}>Cancel</DialogClose><Button disabled={sending || !sendable} onClick={submitSend}>{sending ? "Sending…" : "Send"}diff --git a/site/src/lib/marketing/forward-reply.ts b/site/src/lib/marketing/forward-reply.tsindex 0efe3bd6..82e7af2c 100644--- a/site/src/lib/marketing/forward-reply.ts+++ b/site/src/lib/marketing/forward-reply.ts@@ -27,7 +27,8 @@ type ReceivedEmail = {subject: string;};-// Handles an inbound reply to an outreach note: flips the row to replied and+// Handles an inbound reply to a note that carried the signed reply alias —+// one sent with reply tracking on. Flips the row to replied and// forwards the message on so it can be answered from a normal inbox. The// forward goes out as a fresh send rather than Resend's own forward call// because only a send takes a reply-to — that is what makes hitting reply indiff --git a/site/src/lib/marketing/send-outreach.ts b/site/src/lib/marketing/send-outreach.tsindex da82353f..d891077e 100644--- a/site/src/lib/marketing/send-outreach.ts+++ b/site/src/lib/marketing/send-outreach.ts@@ -31,24 +31,36 @@ type SendOutreachInput = {subject: string;body: string;vars: OutreachVars;+ // Whether the note carries the opt-out footer. The operator decides per+ // send; the unsubscribed check above the send always runs.+ unsubscribeLink: boolean;+ // Whether replies route through the row's signed alias, which forwards them+ // to the operator's inbox and marks the row replied. Off puts the sending+ // address itself on the wire, so the note reads like any personal thread and+ // the row is filed with the list's "Mark replied" button.+ trackReplies: boolean;};// One person writing to one person, so the message goes out as text/plain with// no markup, no template shell, and no bulk-mail headers. A mail provider reads// an HTML body or a `List-Unsubscribe` header as a mailing list and files the-// note under promotions; the opt-out still rides along as a line of text and-// the send still checks it first.-function outreachText(body: string, unsubscribeUrl: string): string {- return `${body.trim()}\n\n--\nUnsubscribe from product emails: ${unsubscribeUrl}\n`;+// note under promotions. When the operator turns the opt-out footer on, it+// rides along as a line of text.+function outreachText(body: string, unsubscribeUrl: string | null): string {+ const trimmed = body.trim();+ if (!unsubscribeUrl) return `${trimmed}\n`;+ return `${trimmed}\n\n--\nUnsubscribe from product emails: ${unsubscribeUrl}\n`;}-// Sends one outreach note. The reply-to is the row's own address: a reply comes-// back through Resend Inbound and finds its row without matching on the sender.+// Sends one outreach note. The reply target is the operator's call per send:+// the row's own signed alias, or the sending address itself.export async function sendOutreachEmail({attempt,body,outreachId,subject,+ trackReplies,+ unsubscribeLink,user,vars,}: SendOutreachInput): Promise<void> {@@ -79,9 +91,12 @@ export async function sendOutreachEmail({{from,to: user.email,- replyTo: outreachReplyAddress(outreachId),+ replyTo: trackReplies ? outreachReplyAddress(outreachId) : undefined,subject: filledSubject,- text: outreachText(filledBody, unsubscribePageUrl(user.id)),+ text: outreachText(+ filledBody,+ unsubscribeLink ? unsubscribePageUrl(user.id) : null,+ ),},{ idempotencyKey: `outreach:${outreachId}:${attempt}` },);diff --git a/site/src/queries/outreach.ts b/site/src/queries/outreach.tsindex 00addeee..6b5349e5 100644--- a/site/src/queries/outreach.ts+++ b/site/src/queries/outreach.ts@@ -56,7 +56,14 @@ export function useOutreachCounts() {}type OutreachAction =- | { action: "send"; outreachId: string; subject: string; body: string }+ | {+ action: "send";+ outreachId: string;+ subject: string;+ body: string;+ unsubscribeLink: boolean;+ trackReplies: boolean;+ }| { action: "ignore" | "unignore" | "replied"; outreachId: string };const outreachActionKey = ["outreach", "action"] as const;diff --git a/site/src/queries/outreachTemplates.ts b/site/src/queries/outreachTemplates.tsindex 7c9e8600..b56bd66d 100644--- a/site/src/queries/outreachTemplates.ts+++ b/site/src/queries/outreachTemplates.ts@@ -9,6 +9,8 @@ export type SavedTemplate = {name: string;subject: string;body: string;+ unsubscribeLink: boolean;+ trackReplies: boolean;updatedAt: string;};@@ -27,7 +29,13 @@ export function useOutreachTemplates() {export function useSaveOutreachTemplate() {const queryClient = useQueryClient();return useMutation({- mutationFn: (input: { name: string; subject: string; body: string }) =>+ mutationFn: (input: {+ name: string;+ subject: string;+ body: string;+ unsubscribeLink: boolean;+ trackReplies: boolean;+ }) =>apiFetch<{ template: SavedTemplate }>("/api/marketing/templates", {body: JSON.stringify(input),method: "POST",