Open source CapCut alternative.
TypeScript
feat(site): an outreach note can be mailed to yourself first
David Le3e7bd0ef3200
diff --git a/site/src/app/api/marketing/outreach/route.ts b/site/src/app/api/marketing/outreach/route.tsindex 3b8f98b8..545093e9 100644--- a/site/src/app/api/marketing/outreach/route.ts+++ b/site/src/app/api/marketing/outreach/route.ts@@ -31,9 +31,17 @@ const listQuerySchema = z.object({status: z.enum(OUTREACH_STATUSES).optional(),});-// Four shapes: start a conversation with a user who is on the list, send-// them a promotion as it stands, file a row that is already on it, or put an-// account on the list by its address.+const noteSchema = z.object({+ body: z.string().trim().min(1).max(5000),+ outreachId: z.string().trim().min(1),+ subject: z.string().trim().min(1).max(200),+ unsubscribeLink: z.boolean(),+ creditOffer: creditOfferTermsSchema.nullable().default(null),+});++// Five shapes: start a conversation with a user who is on the list, mail+// the note to yourself first, send them a promotion as it stands, file a row+// that is already on it, or put an account on the list by its address.const actionSchema = z.union([z.object({@@ -42,17 +50,8 @@ const actionSchema = z.union([promotionId: z.string().trim().min(1),}).strict(),- z- .object({- action: z.literal("send"),- 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(),- creditOffer: creditOfferTermsSchema.nullable().default(null),- })- .strict(),+ noteSchema.extend({ action: z.literal("send"), trackReplies: z.boolean() }).strict(),+ noteSchema.extend({ action: z.literal("test") }).strict(),z.object({ action: z.literal("add"), email: z.string().trim().min(1).max(320) }).strict(),z.object({@@ -283,7 +282,7 @@ export const POST = withSuperUser(async (request) => {const now = new Date();const actorUserId = request.donkey.userId;- if (parsed.data.action === "send") {+ if (parsed.data.action === "send" || parsed.data.action === "test") {const attempt = outreach.sentCount + 1;const vars = {balance: creditMicrosToString(outreach.balanceMicros),@@ -302,6 +301,32 @@ export const POST = withSuperUser(async (request) => {if (issue) {return NextResponse.json({ error: "Invalid request", issues: [{ message: issue, path: "body" }] }, { status: 400 });}+ // A test goes to the operator with the row's values filled in, so the+ // note reads as the person would read it; the row is left as it is.+ if (parsed.data.action === "test") {+ const operator = await prisma.user.findUnique({ select: { email: true }, where: { id: actorUserId } });+ if (!operator) return notFoundResponse();+ const delivery = await deliverEmail({+ idempotencyKey: `outreach-test:${outreach.id}:${Date.now()}`,+ kind: "outreach-test",+ payload: {+ actorUserId,+ attempt,+ body: parsed.data.body,+ creditOffer: parsed.data.creditOffer,+ outreachId: outreach.id,+ subject: parsed.data.subject,+ trackReplies: false,+ unsubscribeLink: parsed.data.unsubscribeLink,+ vars,+ },+ userId: actorUserId,+ });+ if (delivery.state === "failed") {+ return NextResponse.json({ error: "not_sendable", message: delivery.error }, { status: 409 });+ }+ return NextResponse.json({ delivery: delivery.state, row: serialize(outreach), sentTo: operator.email });+ }const delivery = await deliverEmail({idempotencyKey: outreachIdempotencyKey(outreach.id, attempt),kind: "outreach",diff --git a/site/src/app/su/outreach/page.tsx b/site/src/app/su/outreach/page.tsxindex 3871af11..4beef222 100644--- a/site/src/app/su/outreach/page.tsx+++ b/site/src/app/su/outreach/page.tsx@@ -175,6 +175,7 @@ export default function SuOutreachPage() {const [unsubscribeLink, setUnsubscribeLink] = useState(true);const [trackReplies, setTrackReplies] = useState(true);const [creditOffer, setCreditOffer] = useState<CreditOfferTerms | null>(null);+ const [testNotice, setTestNotice] = useState<string | null>(null);const offerDefaults = useCreditOfferDefaults();const saved = templates.data?.templates ?? [];@@ -325,9 +326,22 @@ export default function SuOutreachPage() {});};+ // The note as it stands goes to the operator's own inbox, filled with the+ // row's values, so the words can be read as mail before they are sent.+ const submitTest = () => {+ const target = sendTarget;+ if (!target || !sendable || selectedPromotion) return;+ setTestNotice(null);+ act.mutate(+ { action: "test", body, creditOffer, outreachId: target.id, subject, unsubscribeLink },+ { onSuccess: (result) => setTestNotice(`Test sent to ${result.sentTo}.`) },+ );+ };+const submitSend = () => {const target = sendTarget;if (!target || !sendable) return;+ setTestNotice(null);if (selectedPromotion) {act.mutate({ action: "promote", outreachId: target.id, promotionId: selectedPromotion.id },@@ -392,7 +406,9 @@ export default function SuOutreachPage() {const sending = sendTarget !== null && busy.has(sendTarget.id);// A failed send keeps its dialog open, so the reason belongs in there with// the words that still need fixing; the server names a bad placeholder.- const sendFailed = act.isError && (act.variables?.action === "send" || act.variables?.action === "promote");+ const sendFailed =+ act.isError &&+ (act.variables?.action === "send" || act.variables?.action === "test" || act.variables?.action === "promote");const sendIssue = sendFailed && act.error instanceof ApiError ? act.error.issues[0]?.message : undefined;const addFailed = act.isError && act.variables?.action === "add";const adding = act.isPending && act.variables?.action === "add";@@ -570,10 +586,13 @@ export default function SuOutreachPage() {) : null}<Dialog- onOpenChange={(open) => setSendTarget(open ? sendTarget : null)}+ onOpenChange={(open) => {+ if (!open) setTestNotice(null);+ setSendTarget(open ? sendTarget : null);+ }}open={sendTarget !== null}>- <DialogContent className="grid max-h-[85vh] grid-rows-[auto_minmax(0,1fr)_auto] sm:max-w-3xl">+ <DialogContent className="grid max-h-[85vh] grid-rows-[auto_minmax(0,1fr)_auto] sm:max-w-5xl"><DialogHeader><DialogTitle>Email {sendTarget?.name}</DialogTitle><DialogDescription>@@ -586,7 +605,7 @@ export default function SuOutreachPage() {</DialogDescription></DialogHeader>- <div className="grid min-h-0 min-w-0 gap-4 md:grid-cols-[15rem_minmax(0,1fr)]">+ <div className="grid min-h-0 min-w-0 gap-4 md:grid-cols-[18rem_minmax(0,1fr)]"><div className="flex min-h-0 flex-col gap-2 md:border-r md:pr-4"><span className="text-xs font-medium text-muted-foreground">Start from@@ -731,6 +750,8 @@ export default function SuOutreachPage() {{sendIssue ??"That didn’t go through. The account may have unsubscribed since the last scan, or the text may name a placeholder that doesn’t exist."}</p>+ ) : testNotice ? (+ <p className="text-sm text-muted-foreground">{testNotice}</p>) : null}</div>)}@@ -741,6 +762,9 @@ export default function SuOutreachPage() {last keeps them painted above the send buttons there. */}{selectedPromotion ? null : (<div className="flex flex-wrap items-center gap-x-4 gap-y-2 max-sm:order-last sm:mr-auto">+ <Button disabled={sending || !sendable} onClick={submitTest} variant="outline">+ Send test to me+ </Button><Label className="gap-2 font-normal text-muted-foreground"><Switchchecked={unsubscribeLink}diff --git a/site/src/lib/email/kindIds.ts b/site/src/lib/email/kindIds.tsindex b609637d..39cad64a 100644--- a/site/src/lib/email/kindIds.ts+++ b/site/src/lib/email/kindIds.ts@@ -7,6 +7,7 @@ export const EMAIL_KIND_IDS = ["credit-offer","outreach","promotion-hand",+ "outreach-test","promotion-test","welcome","credit-expiry",@@ -23,6 +24,7 @@ export const DEFAULT_EMAIL_PRIORITIES: Record<EmailKindId, number> = {"credit-offer": 90,outreach: 80,"promotion-hand": 75,+ "outreach-test": 72,"promotion-test": 70,welcome: 60,"credit-expiry": 50,diff --git a/site/src/lib/email/kinds.ts b/site/src/lib/email/kinds.tsindex ffb8dc8c..6db3cc1a 100644--- a/site/src/lib/email/kinds.ts+++ b/site/src/lib/email/kinds.ts@@ -15,7 +15,12 @@ import { buildReplyForwardEmail, replyForwardPayloadSchema } from "@/lib/marketiimport { UnknownPlaceholderError } from "@/lib/marketing/placeholders";import { creditOfferTermsOf } from "@/lib/credits/offerTerms";import { buildPromotionEmail, promotionCopyOf } from "@/lib/marketing/promotions";-import { buildOutreachEmail, outreachPayloadSchema, recordOutreachSent } from "@/lib/marketing/send-outreach";+import {+ buildOutreachEmail,+ outreachPayloadSchema,+ outreachTestOfferScope,+ recordOutreachSent,+} from "@/lib/marketing/send-outreach";import { prisma } from "@/lib/prisma";// What each kind of email is on the server: whose quota it spends, what its@@ -104,6 +109,18 @@ const outreach = define({afterSend: async (payload) => recordOutreachSent(payload),});+// The note as it stands, mailed to the operator with the row's values filled+// in. A credit offer gives them their own working claim link; replies go to+// the sending address, since the row's alias would file the row.+const outreachTest = define({+ quota: "manual",+ payload: outreachPayloadSchema,+ build: async (payload, row) => {+ const user = await userOf(row);+ return user ? buildOutreachEmail({ ...payload, trackReplies: false }, user, outreachTestOfferScope(row.id)) : null;+ },+});+const replyForward = define({quota: "manual",payload: replyForwardPayloadSchema,@@ -192,6 +209,7 @@ export const EMAIL_KINDS: Record<EmailKindId, EmailKind> = {"reply-forward": replyForward as EmailKind,"credit-offer": creditOffer as EmailKind,outreach: outreach as EmailKind,+ "outreach-test": outreachTest as EmailKind,"promotion-hand": promotionHand as EmailKind,"promotion-test": promotionTest as EmailKind,welcome: welcome as EmailKind,diff --git a/site/src/lib/marketing/send-outreach.ts b/site/src/lib/marketing/send-outreach.tsindex 6680ad5b..6459371a 100644--- a/site/src/lib/marketing/send-outreach.ts+++ b/site/src/lib/marketing/send-outreach.ts@@ -61,16 +61,26 @@ export function outreachOfferScope(outreachId: string, attempt: number): stringreturn `outreach:${outreachId}:${attempt}`;}+/** The scope of the offer a test note makes: the outbox row that carries it,+ * so every test mints the operator a fresh link. */+export function outreachTestOfferScope(outboxRowId: string): string {+ return `outreach-test:${outboxRowId}`;+}+// Builds 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 buildOutreachEmail(payload: OutreachPayload, user: EmailUser): Promise<EmailMessage> {+export async function buildOutreachEmail(+ payload: OutreachPayload,+ user: EmailUser,+ offerScope = outreachOfferScope(payload.outreachId, payload.attempt),+): Promise<EmailMessage> {const from = emailFrom();if (!from) throw new PermanentSendError("RESEND_FROM_EMAIL is not configured.");if (await isMarketingUnsubscribed(user.id)) throw new PermanentSendError("That account is unsubscribed.");const offer = payload.creditOffer? await createTermsCreditOffer({- scope: outreachOfferScope(payload.outreachId, payload.attempt),+ scope: offerScope,userId: user.id,terms: payload.creditOffer,offeredByUserId: payload.actorUserId,diff --git a/site/src/queries/outreach.ts b/site/src/queries/outreach.tsindex 2acb719b..2c46e549 100644--- a/site/src/queries/outreach.ts+++ b/site/src/queries/outreach.ts@@ -99,6 +99,15 @@ type OutreachAction =trackReplies: boolean;creditOffer: CreditOfferTerms | null;}+ // Mails the note to the operator with the row's values filled in.+ | {+ action: "test";+ outreachId: string;+ subject: string;+ body: string;+ unsubscribeLink: boolean;+ creditOffer: CreditOfferTerms | null;+ }// Sends a saved promotion to the row's account as it stands.| { action: "promote"; outreachId: string; promotionId: string }| { action: "ignore" | "unignore" | "replied"; outreachId: string }@@ -114,7 +123,7 @@ export function useOutreachAction() {const queryClient = useQueryClient();return useMutation({mutationFn: (input: OutreachAction) =>- apiFetch<{ row: OutreachRow }>("/api/marketing/outreach", {+ apiFetch<{ row: OutreachRow; sentTo?: string }>("/api/marketing/outreach", {body: JSON.stringify(input),method: "POST",}),