Open source CapCut alternative.
TypeScript
feat(site): a promotion goes to one person by hand from their Outreach row
David Le07b921c5435d
diff --git a/docs/guides/config-and-experiments.md b/docs/guides/config-and-experiments.mdindex b0811409..6d35a82f 100644--- a/docs/guides/config-and-experiments.md+++ b/docs/guides/config-and-experiments.md@@ -130,7 +130,7 @@ 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.+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. A draft saves however it stands and is checked whole at a test or a send. The Outreach tab sends a promotion to one person by hand, as the same email under the same per-person outbox key, so it counts in the promotion and a later segment send skips them.Every outbound email is a row in one outbox, sent by one drainer in priority order under the email plan's monthly allowance, shared by the whole site. A promotion is read from the accounts table a page at a time by a job, queues its most recently active recipients first, and stops at what the rest of the billing cycle is forecast to need for welcome and credit emails, and for mail sent by hand on the work days left, then picks up the slots that go unused as the cycle runs down. The allowance, the renewal day, the reserves and the work hours are the Email send budget setting, and the order between kinds is the Email priorities setting.A credit promotion is a credit offer: one row that promises an account andiff --git a/site/src/app/api/marketing/outreach/route.ts b/site/src/app/api/marketing/outreach/route.tsindex 32b66b54..3b8f98b8 100644--- a/site/src/app/api/marketing/outreach/route.ts+++ b/site/src/app/api/marketing/outreach/route.ts@@ -20,6 +20,8 @@ import {UnknownPlaceholderError,type OutreachVars,} from "@/lib/marketing/placeholders";+import { promotionIdempotencyKey } from "@/lib/marketing/promotions";+import { sendIssue } from "@/lib/marketing/promotionSave";import { outreachIdempotencyKey } from "@/lib/marketing/send-outreach";import { prisma } from "@/lib/prisma";@@ -29,9 +31,17 @@ const listQuerySchema = z.object({status: z.enum(OUTREACH_STATUSES).optional(),});-// Three shapes: start a conversation with a user who is on the list, file a-// row that is already on it, or put an account on the list by its address.+// 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 actionSchema = z.union([+ z+ .object({+ action: z.literal("promote"),+ outreachId: z.string().trim().min(1),+ promotionId: z.string().trim().min(1),+ })+ .strict(),z.object({action: z.literal("send"),@@ -315,6 +325,37 @@ export const POST = withSuperUser(async (request) => {return NextResponse.json({ delivery: delivery.state, row: serialize(row) });}+ // The promotion goes out as the segment send would send it, under the same+ // per-person key, so it counts in the promotion and a later segment send+ // skips this person. Someone it already reached is refused, since the key+ // stands for the mail that went.+ if (parsed.data.action === "promote") {+ const promotion = await prisma.promotion.findUnique({ where: { id: parsed.data.promotionId } });+ if (!promotion) return notFoundResponse();+ const refused = sendIssue(promotion);+ if (refused) return refused;+ const idempotencyKey = promotionIdempotencyKey(promotion.id, outreach.user.id);+ const earlier = await prisma.emailSend.findUnique({ select: { state: true }, where: { idempotencyKey } });+ if (earlier && earlier.state !== "failed") {+ const message =+ earlier.state === "sent" ? "They already received this promotion." : "This promotion is already on its way to them.";+ return NextResponse.json({ error: "Invalid request", issues: [{ message, path: "promotion" }] }, { status: 400 });+ }+ if (earlier) await prisma.emailSend.delete({ where: { idempotencyKey } });+ const delivery = await deliverEmail({+ idempotencyKey,+ kind: "promotion-hand",+ payload: { actorUserId, outreachId: outreach.id, promotionId: promotion.id },+ promotionId: promotion.id,+ userId: outreach.user.id,+ });+ if (delivery.state === "failed") {+ return NextResponse.json({ error: "not_sendable", message: delivery.error }, { status: 409 });+ }+ const row = await prisma.userOutreach.findUniqueOrThrow({ select: rowSelect, where: { id: outreach.id } });+ return NextResponse.json({ delivery: delivery.state, row: serialize(row) });+ }+const data =parsed.data.action === "ignore"? { actorUserId, ignoredAt: now, status: "ignored" }diff --git a/site/src/app/su/outreach/page.tsx b/site/src/app/su/outreach/page.tsxindex 70d7044c..3871af11 100644--- a/site/src/app/su/outreach/page.tsx+++ b/site/src/app/su/outreach/page.tsx@@ -24,7 +24,7 @@ import { Label } from "@/components/ui/label";import { Switch } from "@/components/ui/switch";import { Textarea } from "@/components/ui/textarea";import { formatBytes } from "@/lib/bytes";-import { creditOfferTermsIfValid, type CreditOfferTerms } from "@/lib/credits/offerTerms";+import { creditOfferTermsIfValid, OFFER_CLAIM_NAMES, type CreditOfferTerms } from "@/lib/credits/offerTerms";import { cn } from "@/lib/utils";import {OUTREACH_REASON_LABELS,@@ -35,6 +35,7 @@ import {} from "@/lib/marketing/campaigns";import { isOfferPlaceholder, OUTREACH_PLACEHOLDERS } from "@/lib/marketing/placeholders";import { ApiError } from "@/queries/apiClient";+import { usePromotions, type PromotionSummary } from "@/queries/promotions";import {useBusyOutreachIds,useOutreach,@@ -58,9 +59,11 @@ 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 dialog —-// words, send toggles and the credit offer alike — is what goes out.+// A place a note can start from: a saved template, something this browser+// already sent, or a promotion. The first two are starting points; whatever+// ends up in the dialog — words, send toggles and the credit offer alike —+// is what goes out. A promotion goes out as it is saved, the same email its+// segment send mails, so it is read here and not edited.type StartPoint = {id: string;title: string;@@ -73,8 +76,11 @@ type StartPoint = {at: number;remove?: () => void;busy?: boolean;+ promotion?: PromotionSummary;};+const promotionStartId = (id: string) => `promo:${id}`;+function ago(iso: string | null): string {if (!iso) return "—";const mins = Math.floor((Date.now() - new Date(iso).getTime()) / 60000);@@ -161,6 +167,7 @@ export default function SuOutreachPage() {const act = useOutreachAction();const busy = useBusyOutreachIds();const templates = useOutreachTemplates();+ const promotions = usePromotions();const saveTemplate = useSaveOutreachTemplate();const deleteTemplate = useDeleteOutreachTemplate();const { drafts, forget, remember } = useOutreachDrafts();@@ -210,6 +217,18 @@ export default function SuOutreachPage() {trackReplies: draft.trackReplies,unsubscribeLink: draft.unsubscribeLink,})),+ ...(promotions.data?.promotions ?? []).map((promotion) => ({+ at: new Date(promotion.updatedAt).getTime(),+ body: promotion.body,+ creditOffer: promotion.creditOffer,+ id: promotionStartId(promotion.id),+ meta: `Promotion · ${promotion.counts.sent} sent`,+ promotion,+ subject: promotion.subject,+ title: promotion.name || "Untitled",+ trackReplies: false,+ unsubscribeLink: true,+ })),].sort((a, b) => b.at - a.at);const sources: StartPoint[] = [@@ -227,7 +246,10 @@ export default function SuOutreachPage() {...starts,];- const sendable = subject.trim() !== "" && body.trim() !== "";+ // A promotion is checked whole by the server when it is sent, so the+ // button is live and a blank field comes back as the reason.+ const selectedPromotion = sources.find((s) => s.id === source)?.promotion;+ const sendable = selectedPromotion !== undefined || (subject.trim() !== "" && body.trim() !== "");const selectedTemplate = source.startsWith("tpl:")? saved.find((template) => `tpl:${template.id}` === source): undefined;@@ -305,7 +327,19 @@ export default function SuOutreachPage() {const submitSend = () => {const target = sendTarget;- if (!target || subject.trim() === "" || body.trim() === "") return;+ if (!target || !sendable) return;+ if (selectedPromotion) {+ act.mutate(+ { action: "promote", outreachId: target.id, promotionId: selectedPromotion.id },+ {+ onSuccess: () => {+ setLastStart(source);+ setSendTarget((current) => (current?.id === target.id ? null : current));+ },+ },+ );+ return;+ }// 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);@@ -358,7 +392,7 @@ 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";+ const sendFailed = act.isError && (act.variables?.action === "send" || 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";@@ -544,9 +578,11 @@ export default function SuOutreachPage() {<DialogTitle>Email {sendTarget?.name}</DialogTitle><DialogDescription>Goes to {sendTarget?.email}.{" "}- {trackReplies- ? "Replies come back to your inbox and mark this row replied."- : "Replies come straight back to your own address; the Mark replied button files the row."}+ {selectedPromotion+ ? "The promotion goes as its segment send would send it, counts in the promotion, and a later segment send skips this person."+ : trackReplies+ ? "Replies come back to your inbox and mark this row replied."+ : "Replies come straight back to your own address; the Mark replied button files the row."}</DialogDescription></DialogHeader>@@ -623,7 +659,7 @@ export default function SuOutreachPage() {</div>) : (<Button- disabled={!sendable}+ disabled={!sendable || selectedPromotion !== undefined}onClick={() => {setTemplateName(selectedTemplate?.name ?? "");setNaming(true);@@ -646,6 +682,9 @@ export default function SuOutreachPage() {) : null}</div>+ {selectedPromotion ? (+ <PromotionPreview promotion={selectedPromotion} issue={sendFailed ? sendIssue : undefined} />+ ) : (<div className="flex min-h-0 min-w-0 flex-col gap-2"><Label htmlFor="outreach-subject">Subject</Label><Input@@ -694,11 +733,13 @@ export default function SuOutreachPage() {</p>) : null}</div>+ )}</div><DialogFooter>{/* The footer column is reversed below sm, so ordering the toggleslast 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"><Label className="gap-2 font-normal text-muted-foreground"><Switch@@ -712,9 +753,10 @@ export default function SuOutreachPage() {Track replies</Label></div>+ )}<DialogClose render={<Button variant="outline" />}>Cancel</DialogClose><Button disabled={sending || !sendable} onClick={submitSend}>- {sending ? "Sending…" : "Send"}+ {sending ? "Sending…" : selectedPromotion ? "Send promotion" : "Send"}</Button></DialogFooter></DialogContent>@@ -722,3 +764,32 @@ export default function SuOutreachPage() {</div>);}++// A promotion as it will go: the subject, the words, the button and the+// offer, read from the saved row. Its words change on the Promotions tab.+function PromotionPreview({ promotion, issue }: { promotion: PromotionSummary; issue: string | undefined }) {+ const offer = promotion.creditOffer;+ return (+ <div className="flex min-h-0 min-w-0 flex-col gap-2">+ <span className="text-xs font-medium text-muted-foreground">Subject</span>+ <p className="text-sm">{promotion.subject || <span className="text-muted-foreground">No subject yet</span>}</p>+ <span className="mt-1 text-xs font-medium text-muted-foreground">Message</span>+ <div className="min-h-0 flex-1 overflow-y-auto rounded-lg border px-3 py-2 text-sm whitespace-pre-wrap">+ {promotion.body || <span className="text-muted-foreground">No message yet</span>}+ </div>+ {promotion.ctaLabel ? (+ <p className="text-xs text-muted-foreground">+ Button: {promotion.ctaLabel} → {promotion.ctaUrl}+ </p>+ ) : null}+ {offer ? (+ <p className="text-xs text-muted-foreground">+ Credit offer: ${offer.dollars}, landed by {OFFER_CLAIM_NAMES[offer.claim].toLowerCase()}, {offer.claimWindowDays} days to claim,+ lives {offer.expiresAfterDays} days.+ </p>+ ) : null}+ <p className="text-xs text-muted-foreground">Edit the words on the Promotions tab.</p>+ {issue ? <p className="text-sm text-destructive">{issue}</p> : null}+ </div>+ );+}diff --git a/site/src/app/su/promotions/page.tsx b/site/src/app/su/promotions/page.tsxindex e721cc40..a810a630 100644--- a/site/src/app/su/promotions/page.tsx+++ b/site/src/app/su/promotions/page.tsx@@ -137,7 +137,7 @@ function PromotionRow({<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>+ <span className="font-medium">{p.name || "Untitled"}</span><Badge variant={STATUS_VARIANT[p.status]}>{p.status}</Badge></div><p className="mt-1 truncate text-sm text-muted-foreground">{p.subject}</p>@@ -152,7 +152,7 @@ function PromotionRow({p.finishedAt ? ` · finished ${when(p.finishedAt)}` : ""}`}</p>- {p.status !== "draft" ? (+ {p.status !== "draft" || recipients > 0 ? (<dl className="mt-4 flex flex-wrap gap-x-8 gap-y-2">{[["Sent", `${sent} of ${recipients}`],@@ -215,7 +215,7 @@ function PromotionRow({<AlertDialogHeader><AlertDialogTitle>Delete “{p.name}”?</AlertDialogTitle><AlertDialogDescription>- {p.status === "sent"+ {recipients > 0? "Its recipient list goes with it, so a later promotion can no longer skip the people it reached.": "The draft is removed."}</AlertDialogDescription>diff --git a/site/src/lib/config/registry.ts b/site/src/lib/config/registry.tsindex 5f2df40d..5b702faa 100644--- a/site/src/lib/config/registry.ts+++ b/site/src/lib/config/registry.ts@@ -141,7 +141,13 @@ export const SETTINGS = defineSettings({},emailPriorities: {schema: z- .object(Object.fromEntries(EMAIL_KIND_IDS.map((id) => [id, z.number().int().min(0).max(1000)])))+ // A kind added after the override was saved reads its default, so the+ // saved order for the rest keeps holding.+ .object(+ Object.fromEntries(+ EMAIL_KIND_IDS.map((id) => [id, z.number().int().min(0).max(1000).default(DEFAULT_EMAIL_PRIORITIES[id])]),+ ),+ ).strict(),default: { ...DEFAULT_EMAIL_PRIORITIES },public: false,diff --git a/site/src/lib/email/kindIds.ts b/site/src/lib/email/kindIds.tsindex 1a726955..b609637d 100644--- a/site/src/lib/email/kindIds.ts+++ b/site/src/lib/email/kindIds.ts@@ -6,6 +6,7 @@ export const EMAIL_KIND_IDS = ["reply-forward","credit-offer","outreach",+ "promotion-hand","promotion-test","welcome","credit-expiry",@@ -15,11 +16,13 @@ export const EMAIL_KIND_IDS = [export type EmailKindId = (typeof EMAIL_KIND_IDS)[number];// Higher goes first. A reply from a user beats everything; a campaign yields-// to every email a single account is waiting on.+// to every email a single account is waiting on, and a promotion sent by hand+// to one person goes with the other mail sent by hand.export const DEFAULT_EMAIL_PRIORITIES: Record<EmailKindId, number> = {"reply-forward": 100,"credit-offer": 90,outreach: 80,+ "promotion-hand": 75,"promotion-test": 70,welcome: 60,"credit-expiry": 50,diff --git a/site/src/lib/email/kinds.ts b/site/src/lib/email/kinds.tsindex 9eadd679..ffb8dc8c 100644--- a/site/src/lib/email/kinds.ts+++ b/site/src/lib/email/kinds.ts@@ -171,10 +171,28 @@ const promotionTest = define({},});+// The same promotion email, sent to one person from their Outreach row. It+// spends the manual quota so it goes now, and its outbox row is keyed like+// the segment send's, so the promotion counts it and never mails the person+// again. The row's outreach entry is filed as sent, like a note.+const promotionHand = define({+ quota: "manual",+ payload: z+ .object({ promotionId: z.string().min(1), outreachId: z.string().min(1), actorUserId: z.string().min(1) })+ .strict(),+ build: async ({ promotionId }, row) => {+ const [user, promotion] = await Promise.all([userOf(row), promotionRowOf(promotionId)]);+ if (!user || (await isMarketingUnsubscribed(user.id))) return null;+ return promotionEmailFor(promotion, user, (url) => clickUrl(row.id, url));+ },+ afterSend: async ({ outreachId, actorUserId }) => recordOutreachSent({ outreachId, actorUserId }),+});+export const EMAIL_KINDS: Record<EmailKindId, EmailKind> = {"reply-forward": replyForward as EmailKind,"credit-offer": creditOffer as EmailKind,outreach: outreach as EmailKind,+ "promotion-hand": promotionHand as EmailKind,"promotion-test": promotionTest as EmailKind,welcome: welcome as EmailKind,"credit-expiry": creditExpiry as EmailKind,diff --git a/site/src/lib/jobs/promotion-queue.ts b/site/src/lib/jobs/promotion-queue.tsindex 8c5b2e79..7a3ba8d6 100644--- a/site/src/lib/jobs/promotion-queue.ts+++ b/site/src/lib/jobs/promotion-queue.ts@@ -3,7 +3,7 @@ import { z } from "zod";import { queueEmails, scheduleDrain } from "@/lib/email/outbox";import { defineJob, JobFailure } from "@/lib/jobs/registry";import { activityRank, lastActiveByUser } from "@/lib/marketing/lastActive";-import { promotionAudienceOf, resolvePromotionSegment } from "@/lib/marketing/promotions";+import { promotionAudienceOf, promotionIdempotencyKey, resolvePromotionSegment } from "@/lib/marketing/promotions";import { prisma } from "@/lib/prisma";// Turns a promotion's segment into outbox rows, a page of accounts at a@@ -40,7 +40,7 @@ export const promotionQueueJob = defineJob(const lastActiveBy = await lastActiveByUser(users.map((u) => u.id));queued += await queueEmails(users.map((user) => ({- idempotencyKey: `promotion:${promotionId}:${user.id}`,+ idempotencyKey: promotionIdempotencyKey(promotionId, user.id),kind: "promotion",payload: { promotionId },promotionId,diff --git a/site/src/lib/marketing/promotions.ts b/site/src/lib/marketing/promotions.tsindex b3aebbe9..e43bda05 100644--- a/site/src/lib/marketing/promotions.ts+++ b/site/src/lib/marketing/promotions.ts@@ -19,7 +19,7 @@ import {import { prisma } from "@/lib/prisma";import { PROMOTION_OFFER_KINDS } from "@/lib/credits/offerKinds";import type { OfferVars } from "@/lib/credits/offerTerms";-import { creditOfferTermsOf } from "@/lib/credits/offerTerms";+import { creditOfferDraftOf } from "@/lib/credits/offerTerms";// Promotions on the server: which address each sender is, who a segment// resolves to, one send, and the list su reads.@@ -99,6 +99,12 @@ export function buildPromotionEmail(export type PromotionSegment = { audience: Audience; excludePromotionIds: string[] };+/** The outbox key for one person's copy of a promotion. The segment send and+ * a send by hand share it, so a person gets a promotion once. */+export function promotionIdempotencyKey(promotionId: string, userId: string): string {+ return `promotion:${promotionId}:${userId}`;+}+export type SegmentResolution = SegmentCount & {// Where the walk stopped: the last account read when the deadline came,// null once the whole list was seen. A caller resumes by passing it back.@@ -185,7 +191,7 @@ type PromotionRow = NonNullable<Awaited<ReturnType<typeof prisma.promotion.findUfunction summarize(row: PromotionRow, counts: PromotionSummary["counts"]): PromotionSummary {return {id: row.id,- creditOffer: creditOfferTermsOf(row.creditOffer),+ creditOffer: creditOfferDraftOf(row.creditOffer),name: row.name,subject: row.subject,body: row.body,diff --git a/site/src/lib/marketing/send-outreach.ts b/site/src/lib/marketing/send-outreach.tsindex 5c18ffd5..6680ad5b 100644--- a/site/src/lib/marketing/send-outreach.ts+++ b/site/src/lib/marketing/send-outreach.ts@@ -95,7 +95,7 @@ export async function buildOutreachEmail(payload: OutreachPayload, user: EmailUs};}-export async function recordOutreachSent(payload: OutreachPayload): Promise<void> {+export async function recordOutreachSent(payload: Pick<OutreachPayload, "outreachId" | "actorUserId">): Promise<void> {const now = new Date();const row = await prisma.userOutreach.findUnique({ select: { firstSentAt: true }, where: { id: payload.outreachId } });if (!row) return;diff --git a/site/src/queries/outreach.ts b/site/src/queries/outreach.tsindex b94d12d4..2acb719b 100644--- a/site/src/queries/outreach.ts+++ b/site/src/queries/outreach.ts@@ -99,6 +99,8 @@ type OutreachAction =trackReplies: 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 }// Puts the account with this address on the list, and answers with its row.| { action: "add"; email: string };