Skip to content

Open source CapCut alternative.

TypeScript

feat(site): the Outreach tab works the list from /su

David Le11b5e3eeaed0
diff --git a/site/src/app/api/marketing/outreach/route.ts b/site/src/app/api/marketing/outreach/route.ts
new file mode 100644
index 00000000..5bfecdf8
--- /dev/null
+++ b/site/src/app/api/marketing/outreach/route.ts
@@ -0,0 +1,194 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+
+import { creditMicrosToString } from "@/lib/credits/amounts";
+import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";
+import {
+ CREDIT_SPENDERS_CAMPAIGN,
+ OUTREACH_STATUSES,
+} from "@/lib/marketing/campaigns";
+import {
+ OutreachNotSendableError,
+ sendOutreachEmail,
+} from "@/lib/marketing/send-outreach";
+import { prisma } from "@/lib/prisma";
+
+const listQuerySchema = z.object({
+ status: z.enum(OUTREACH_STATUSES).default("todo"),
+});
+
+// Two shapes: start a conversation with a user who is on the list, or file a
+// row that is already on it.
+const actionSchema = z.union([
+ 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),
+ })
+ .strict(),
+ z
+ .object({
+ action: z.enum(["ignore", "unignore", "replied"]),
+ outreachId: z.string().trim().min(1),
+ })
+ .strict(),
+]);
+
+const rowSelect = {
+ balanceMicros: true,
+ firstSentAt: true,
+ id: true,
+ lastActiveAt: true,
+ lastSentAt: true,
+ ranOutAt: true,
+ repliedAt: true,
+ sentCount: true,
+ spentMicros: true,
+ status: true,
+ user: { select: { createdAt: true, email: true, id: true, name: true } },
+} as const;
+
+type OutreachRow = {
+ balanceMicros: bigint;
+ firstSentAt: Date | null;
+ id: string;
+ lastActiveAt: Date | null;
+ lastSentAt: Date | null;
+ ranOutAt: Date | null;
+ repliedAt: Date | null;
+ sentCount: number;
+ spentMicros: bigint;
+ status: string;
+ user: { createdAt: Date; email: string; id: string; name: string };
+};
+
+// Micros are BigInt and dates are Date; the client wants neither.
+function serialize(row: OutreachRow) {
+ return {
+ balance: creditMicrosToString(row.balanceMicros),
+ email: row.user.email,
+ firstSentAt: row.firstSentAt?.toISOString() ?? null,
+ id: row.id,
+ lastActiveAt: row.lastActiveAt?.toISOString() ?? null,
+ lastSentAt: row.lastSentAt?.toISOString() ?? null,
+ name: row.user.name,
+ ranOutAt: row.ranOutAt?.toISOString() ?? null,
+ repliedAt: row.repliedAt?.toISOString() ?? null,
+ sentCount: row.sentCount,
+ signedUpAt: row.user.createdAt.toISOString(),
+ spent: creditMicrosToString(row.spentMicros),
+ status: row.status,
+ userId: row.user.id,
+ };
+}
+
+// The list is whatever the nightly outreach-scan job wrote, so this reads one
+// table and touches no credit data.
+export const GET = withSuperUser(async (request) => {
+ const parsed = listQuerySchema.safeParse({
+ status: new URL(request.url).searchParams.get("status") ?? undefined,
+ });
+ if (!parsed.success) {
+ return NextResponse.json({ error: "Invalid status" }, { status: 400 });
+ }
+
+ // Each list is about a different moment: when they last used the product,
+ // when the note went out, when they answered, when it was filed away.
+ const orderBy = {
+ ignored: { ignoredAt: "desc" },
+ replied: { repliedAt: "desc" },
+ sent: { lastSentAt: "desc" },
+ todo: { lastActiveAt: "desc" },
+ } as const;
+
+ const rows = await prisma.userOutreach.findMany({
+ orderBy: orderBy[parsed.data.status],
+ select: rowSelect,
+ take: 200,
+ where: { campaign: CREDIT_SPENDERS_CAMPAIGN, status: parsed.data.status },
+ });
+
+ return NextResponse.json({ rows: rows.map(serialize) });
+});
+
+export const POST = withSuperUser(async (request) => {
+ const parsed = actionSchema.safeParse(await request.json());
+ if (!parsed.success) {
+ return NextResponse.json(
+ {
+ error: "Invalid request",
+ issues: parsed.error.issues.map((issue) => ({
+ message: issue.message,
+ path: issue.path.join("."),
+ })),
+ },
+ { status: 400 },
+ );
+ }
+
+ const outreach = await prisma.userOutreach.findUnique({
+ select: rowSelect,
+ where: { id: parsed.data.outreachId },
+ });
+ if (!outreach) {
+ return notFoundResponse();
+ }
+
+ const now = new Date();
+ const actorUserId = request.donkey.userId;
+
+ if (parsed.data.action === "send") {
+ try {
+ await sendOutreachEmail({
+ attempt: outreach.sentCount + 1,
+ body: parsed.data.body,
+ outreachId: outreach.id,
+ subject: parsed.data.subject,
+ user: outreach.user,
+ vars: {
+ balance: creditMicrosToString(outreach.balanceMicros),
+ email: outreach.user.email,
+ firstName: outreach.user.name.trim().split(/\s+/)[0] || outreach.user.name,
+ name: outreach.user.name,
+ spent: creditMicrosToString(outreach.spentMicros),
+ },
+ });
+ } catch (error) {
+ if (error instanceof OutreachNotSendableError) {
+ return NextResponse.json(
+ { error: "not_sendable", message: error.message },
+ { status: 409 },
+ );
+ }
+ throw error;
+ }
+ const row = await prisma.userOutreach.update({
+ data: {
+ actorUserId,
+ firstSentAt: outreach.firstSentAt ?? now,
+ lastSentAt: now,
+ sentCount: { increment: 1 },
+ status: "sent",
+ },
+ select: rowSelect,
+ where: { id: outreach.id },
+ });
+ return NextResponse.json({ row: serialize(row) });
+ }
+
+ const data =
+ parsed.data.action === "ignore"
+ ? { actorUserId, ignoredAt: now, status: "ignored" }
+ : parsed.data.action === "unignore"
+ ? { actorUserId, ignoredAt: null, status: "todo" }
+ : { actorUserId, repliedAt: outreach.repliedAt ?? now, status: "replied" };
+
+ const row = await prisma.userOutreach.update({
+ data,
+ select: rowSelect,
+ where: { id: outreach.id },
+ });
+ return NextResponse.json({ row: serialize(row) });
+});
diff --git a/site/src/app/api/marketing/templates/route.ts b/site/src/app/api/marketing/templates/route.ts
new file mode 100644
index 00000000..f94db22d
--- /dev/null
+++ b/site/src/app/api/marketing/templates/route.ts
@@ -0,0 +1,89 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+
+import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";
+import { prisma } from "@/lib/prisma";
+
+// A template is written outside the repo and saved here, so adding one never
+// needs a deploy. Same length limits as a send, since a template is only ever
+// the starting text of one.
+const saveSchema = z
+ .object({
+ body: z.string().trim().min(1).max(5000),
+ name: z.string().trim().min(1).max(80),
+ subject: z.string().trim().min(1).max(200),
+ })
+ .strict();
+
+const templateSelect = {
+ body: true,
+ id: true,
+ name: true,
+ subject: true,
+ updatedAt: true,
+} as const;
+
+type TemplateRow = {
+ body: string;
+ id: string;
+ name: string;
+ subject: string;
+ updatedAt: Date;
+};
+
+function serialize(row: TemplateRow) {
+ return {
+ body: row.body,
+ id: row.id,
+ name: row.name,
+ subject: row.subject,
+ updatedAt: row.updatedAt.toISOString(),
+ };
+}
+
+export const GET = withSuperUser(async () => {
+ const templates = await prisma.outreachTemplate.findMany({
+ orderBy: { name: "asc" },
+ select: templateSelect,
+ });
+ return NextResponse.json({ templates: templates.map(serialize) });
+});
+
+// Saving under a name that already exists rewrites it, so editing a template is
+// the same action as writing one.
+export const POST = withSuperUser(async (request) => {
+ const parsed = saveSchema.safeParse(await request.json());
+ if (!parsed.success) {
+ return NextResponse.json(
+ {
+ error: "Invalid request",
+ issues: parsed.error.issues.map((issue) => ({
+ message: issue.message,
+ path: issue.path.join("."),
+ })),
+ },
+ { status: 400 },
+ );
+ }
+
+ const { body, name, subject } = parsed.data;
+ const template = await prisma.outreachTemplate.upsert({
+ create: { actorUserId: request.donkey.userId, body, name, subject },
+ select: templateSelect,
+ update: { actorUserId: request.donkey.userId, body, subject },
+ where: { name },
+ });
+ return NextResponse.json({ template: serialize(template) });
+});
+
+export const DELETE = withSuperUser(async (request) => {
+ const id = new URL(request.url).searchParams.get("id");
+ if (!id) {
+ return NextResponse.json({ error: "Missing id" }, { status: 400 });
+ }
+ const { count } = await prisma.outreachTemplate.deleteMany({ where: { id } });
+ if (count === 0) {
+ return notFoundResponse();
+ }
+ return NextResponse.json({ ok: true });
+});
diff --git a/site/src/app/cut/app/su/SuHeader.tsx b/site/src/app/cut/app/su/SuHeader.tsx
index 07401b04..2d0f2dde 100644
--- a/site/src/app/cut/app/su/SuHeader.tsx
+++ b/site/src/app/cut/app/su/SuHeader.tsx
@@ -4,6 +4,7 @@ import { usePathname } from "next/navigation";
import type { ComponentType } from "react";
import { RunAnalyticsButton } from "@/app/cut/app/su/analytics/RunAnalyticsButton";
+import { ScanOutreachButton } from "@/app/cut/app/su/outreach/ScanOutreachButton";
// Every surface owns a path, so the match is exact; the rail's order is the
// order here, and its first entry is what the section root opens.
@@ -29,6 +30,12 @@ const SECTIONS: {
title: "Credits",
description: "Grant credits to a user.",
},
+ {
+ suffix: "/su/outreach",
+ title: "Outreach",
+ description: "Free accounts spending credits, and where each conversation stands.",
+ Action: ScanOutreachButton,
+ },
];
export function SuHeader() {
diff --git a/site/src/app/cut/app/su/nav.ts b/site/src/app/cut/app/su/nav.ts
index dc610e89..b1b2ede0 100644
--- a/site/src/app/cut/app/su/nav.ts
+++ b/site/src/app/cut/app/su/nav.ts
@@ -1,4 +1,4 @@
-import { ChartColumn, CreditCard, UserRound } from "lucide-react";
+import { ChartColumn, CreditCard, Mail, UserRound } from "lucide-react";
// The super-user surfaces in rail order. The section root lands on the first
// one, so reordering this list moves where /app/su opens.
@@ -6,4 +6,5 @@ export const SU_NAV: { suffix: string; label: string; icon: typeof UserRound }[]
{ suffix: "/analytics", label: "Analytics", icon: ChartColumn },
{ suffix: "/users", label: "Users", icon: UserRound },
{ suffix: "/credits", label: "Credits", icon: CreditCard },
+ { suffix: "/outreach", label: "Outreach", icon: Mail },
];
diff --git a/site/src/app/cut/app/su/outreach/ScanOutreachButton.tsx b/site/src/app/cut/app/su/outreach/ScanOutreachButton.tsx
new file mode 100644
index 00000000..c559696b
--- /dev/null
+++ b/site/src/app/cut/app/su/outreach/ScanOutreachButton.tsx
@@ -0,0 +1,23 @@
+"use client";
+
+import { Button } from "@/components/ui/button";
+import { useRunOutreachScan } from "@/queries/outreach";
+
+export function ScanOutreachButton() {
+ const scan = useRunOutreachScan();
+ return (
+ <div className="flex items-center gap-3">
+ {scan.isError ? (
+ <span className="text-sm text-destructive">Scan failed.</span>
+ ) : null}
+ <Button
+ disabled={scan.isPending}
+ onClick={() => scan.mutate()}
+ size="sm"
+ variant="outline"
+ >
+ {scan.isPending ? "Scanning…" : "Scan now"}
+ </Button>
+ </div>
+ );
+}
diff --git a/site/src/app/cut/app/su/outreach/drafts.ts b/site/src/app/cut/app/su/outreach/drafts.ts
new file mode 100644
index 00000000..44320f61
--- /dev/null
+++ b/site/src/app/cut/app/su/outreach/drafts.ts
@@ -0,0 +1,51 @@
+"use client";
+
+import { useCallback } from "react";
+
+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.
+export type OutreachDraft = {
+ subject: string;
+ body: string;
+ savedAt: string;
+};
+
+const KEY = "donkey.outreach.drafts";
+const LIMIT = 20;
+
+function isDraft(value: unknown): value is OutreachDraft {
+ 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"
+ );
+}
+
+export function useOutreachDrafts(): {
+ drafts: OutreachDraft[];
+ remember: (draft: { subject: string; body: string }) => void;
+} {
+ const [drafts, setDrafts] = useLocalPref<OutreachDraft[]>(KEY, [], (value) =>
+ Array.isArray(value) && value.every(isDraft),
+ );
+
+ 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,
+ );
+ setDrafts(
+ [{ body, savedAt: new Date().toISOString(), subject }, ...rest].slice(0, LIMIT),
+ );
+ },
+ [drafts, setDrafts],
+ );
+
+ return { drafts, remember };
+}
diff --git a/site/src/app/cut/app/su/outreach/page.tsx b/site/src/app/cut/app/su/outreach/page.tsx
new file mode 100644
index 00000000..368fb251
--- /dev/null
+++ b/site/src/app/cut/app/su/outreach/page.tsx
@@ -0,0 +1,385 @@
+"use client";
+
+import { useState } from "react";
+
+import { useOutreachDrafts } from "@/app/cut/app/su/outreach/drafts";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogClose,
+ 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,
+} from "@/components/ui/select";
+import { Textarea } from "@/components/ui/textarea";
+import type { OutreachStatus } from "@/lib/marketing/campaigns";
+import { OUTREACH_PLACEHOLDERS } from "@/lib/marketing/placeholders";
+import { useOutreach, useOutreachAction, type OutreachRow } from "@/queries/outreach";
+import {
+ useDeleteOutreachTemplate,
+ useOutreachTemplates,
+ useSaveOutreachTemplate,
+} from "@/queries/outreachTemplates";
+
+const FILTERS: { status: OutreachStatus; label: string }[] = [
+ { status: "todo", label: "To email" },
+ { status: "sent", label: "Sent" },
+ { status: "replied", label: "Replied" },
+ { status: "ignored", label: "Ignored" },
+];
+
+const BLANK = "blank";
+
+function ago(iso: string | null): string {
+ if (!iso) return "—";
+ const mins = Math.floor((Date.now() - new Date(iso).getTime()) / 60000);
+ if (mins < 60) return `${Math.max(mins, 0)}m ago`;
+ if (mins < 60 * 24) return `${Math.floor(mins / 60)}h ago`;
+ return `${Math.floor(mins / (60 * 24))}d ago`;
+}
+
+// The list carries the numbers the scan wrote; the badges say what they mean
+// without a second read.
+function RowBadges({ row }: { row: OutreachRow }) {
+ const broke = Number(row.balance) <= 0;
+ return (
+ <div className="mt-1 flex flex-wrap items-center gap-1.5">
+ <Badge variant="secondary">${row.spent} spent</Badge>
+ <Badge variant={broke ? "destructive" : "outline"}>
+ {broke ? `$0 left · ${ago(row.ranOutAt)}` : `$${row.balance} left`}
+ </Badge>
+ <Badge variant="outline">active {ago(row.lastActiveAt)}</Badge>
+ <Badge variant="outline">joined {ago(row.signedUpAt)}</Badge>
+ {row.sentCount > 0 ? (
+ <Badge variant="outline">
+ emailed {ago(row.lastSentAt)}
+ {row.sentCount > 1 ? ` · ${row.sentCount}×` : ""}
+ </Badge>
+ ) : null}
+ </div>
+ );
+}
+
+export default function SuOutreachPage() {
+ const [status, setStatus] = useState<OutreachStatus>("todo");
+ const [sendTarget, setSendTarget] = useState<OutreachRow | null>(null);
+ const [source, setSource] = useState(BLANK);
+ const [subject, setSubject] = useState("");
+ const [body, setBody] = useState("");
+ const [templateName, setTemplateName] = useState("");
+ const [naming, setNaming] = useState(false);
+ const list = useOutreach(status);
+ const act = useOutreachAction();
+ const templates = useOutreachTemplates();
+ const saveTemplate = useSaveOutreachTemplate();
+ const deleteTemplate = useDeleteOutreachTemplate();
+ const { drafts, remember } = useOutreachDrafts();
+
+ const saved = templates.data?.templates ?? [];
+
+ // Saved templates are shared and outlive the browser; recent sends are this
+ // browser's own. Both are starting points: whatever ends up in the fields is
+ // what goes out.
+ const sources: { id: string; label: string; subject: string; body: string }[] = [
+ { id: BLANK, label: "Blank", subject: "", body: "" },
+ ...saved.map((template) => ({
+ id: `tpl:${template.id}`,
+ label: template.name,
+ subject: template.subject,
+ body: template.body,
+ })),
+ ...drafts.map((draft, index) => ({
+ id: `draft:${index}`,
+ label: `${draft.subject} · sent ${ago(draft.savedAt)}`,
+ subject: draft.subject,
+ body: draft.body,
+ })),
+ ];
+ const sourceLabels = Object.fromEntries(sources.map((s) => [s.id, s.label]));
+
+ const sendable = subject.trim() !== "" && body.trim() !== "";
+ const selectedTemplate = source.startsWith("tpl:")
+ ? saved.find((template) => `tpl:${template.id}` === source)
+ : undefined;
+
+ const pickSource = (id: string) => {
+ const picked = sources.find((s) => s.id === id);
+ if (!picked) return;
+ setSource(id);
+ setSubject(picked.subject);
+ setBody(picked.body);
+ setNaming(false);
+ };
+
+ const openSend = (row: OutreachRow) => {
+ // Open on the first saved template so the common case is one click from
+ // ready; with none saved yet, a blank note.
+ const start = sources[1] ?? sources[0];
+ setSource(start.id);
+ setSubject(start.subject);
+ setBody(start.body);
+ setNaming(false);
+ setSendTarget(row);
+ };
+
+ const submitTemplate = () => {
+ const name = templateName.trim();
+ if (name === "" || !sendable) return;
+ saveTemplate.mutate(
+ { body, name, subject },
+ {
+ onSuccess: (result) => {
+ setSource(`tpl:${result.template.id}`);
+ setNaming(false);
+ },
+ },
+ );
+ };
+
+ const removeTemplate = () => {
+ if (!selectedTemplate) return;
+ deleteTemplate.mutate(selectedTemplate.id, {
+ onSuccess: () => setSource(BLANK),
+ });
+ };
+
+ const submitSend = () => {
+ if (!sendTarget || subject.trim() === "" || body.trim() === "") return;
+ act.mutate(
+ { action: "send", body, outreachId: sendTarget.id, subject },
+ {
+ onSuccess: () => {
+ remember({ body, subject });
+ setSendTarget(null);
+ },
+ },
+ );
+ };
+
+ const rows = list.data?.rows ?? [];
+
+ return (
+ <div className="space-y-4 pb-9">
+ <div className="flex flex-wrap items-center gap-2">
+ {FILTERS.map((filter) => (
+ <Button
+ key={filter.status}
+ onClick={() => setStatus(filter.status)}
+ size="sm"
+ variant={status === filter.status ? "default" : "outline"}
+ >
+ {filter.label}
+ </Button>
+ ))}
+ </div>
+
+ <div className="rounded-xl border bg-card">
+ {rows.length > 0 ? (
+ <ul className="divide-y">
+ {rows.map((row) => (
+ <li
+ key={row.id}
+ className="flex flex-wrap items-start justify-between gap-3 p-5"
+ >
+ <div className="min-w-0">
+ <div className="flex flex-wrap items-baseline gap-x-2">
+ <span className="text-sm font-medium">{row.name}</span>
+ <span className="truncate text-sm text-muted-foreground">
+ {row.email}
+ </span>
+ </div>
+ <RowBadges row={row} />
+ </div>
+ <div className="flex shrink-0 items-center gap-2">
+ {row.status === "sent" ? (
+ <Button
+ disabled={act.isPending}
+ onClick={() =>
+ act.mutate({ action: "replied", outreachId: row.id })
+ }
+ size="sm"
+ variant="outline"
+ >
+ Mark replied
+ </Button>
+ ) : null}
+ {row.status === "ignored" ? (
+ <Button
+ disabled={act.isPending}
+ onClick={() =>
+ act.mutate({ action: "unignore", outreachId: row.id })
+ }
+ size="sm"
+ variant="outline"
+ >
+ Restore
+ </Button>
+ ) : (
+ <Button
+ disabled={act.isPending}
+ onClick={() =>
+ act.mutate({ action: "ignore", outreachId: row.id })
+ }
+ size="sm"
+ variant="ghost"
+ >
+ Ignore
+ </Button>
+ )}
+ <Button
+ disabled={act.isPending}
+ onClick={() => openSend(row)}
+ size="sm"
+ >
+ {row.sentCount > 0 ? "Email again" : "Email"}
+ </Button>
+ </div>
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="p-5 text-sm text-muted-foreground">
+ {list.isPending ? "Loading…" : "Nothing here. Run a scan to refresh."}
+ </p>
+ )}
+ </div>
+
+ {act.isError ? (
+ <p className="text-sm text-destructive">
+ That didn&apos;t go through. The account may have unsubscribed since the
+ last scan, or the text may name a placeholder that doesn&apos;t exist.
+ </p>
+ ) : null}
+
+ <Dialog
+ onOpenChange={(open) => setSendTarget(open ? sendTarget : null)}
+ open={sendTarget !== null}
+ >
+ <DialogContent className="max-w-xl">
+ <DialogHeader>
+ <DialogTitle>Email {sendTarget?.name}</DialogTitle>
+ <DialogDescription>
+ Goes to {sendTarget?.email}. Replies come back to your inbox and mark
+ this row replied.
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="space-y-4">
+ <div className="space-y-2">
+ <Label htmlFor="outreach-source">Start from</Label>
+ <div className="flex items-center gap-2">
+ <Select
+ items={sourceLabels}
+ onValueChange={(id) => pickSource(id as string)}
+ value={source}
+ >
+ <SelectTrigger className="flex-1" id="outreach-source">
+ <span className="truncate">{sourceLabels[source]}</span>
+ </SelectTrigger>
+ <SelectContent alignItemWithTrigger={false}>
+ {sources.map((option) => (
+ <SelectItem key={option.id} value={option.id}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ {selectedTemplate ? (
+ <Button
+ disabled={deleteTemplate.isPending}
+ onClick={removeTemplate}
+ size="sm"
+ variant="ghost"
+ >
+ Delete
+ </Button>
+ ) : null}
+ <Button
+ disabled={!sendable}
+ onClick={() => {
+ setTemplateName(selectedTemplate?.name ?? "");
+ setNaming(true);
+ }}
+ size="sm"
+ variant="outline"
+ >
+ Save as template
+ </Button>
+ </div>
+ {naming ? (
+ <div className="flex items-center gap-2">
+ <Input
+ aria-label="Template name"
+ autoFocus
+ maxLength={80}
+ onChange={(event) => setTemplateName(event.target.value)}
+ placeholder="Template name"
+ value={templateName}
+ />
+ <Button
+ disabled={saveTemplate.isPending || templateName.trim() === ""}
+ onClick={submitTemplate}
+ size="sm"
+ >
+ {saveTemplate.isPending ? "Saving…" : "Save"}
+ </Button>
+ <Button onClick={() => setNaming(false)} size="sm" variant="ghost">
+ Cancel
+ </Button>
+ </div>
+ ) : null}
+ {saveTemplate.isError || deleteTemplate.isError ? (
+ <p className="text-sm text-destructive">
+ Couldn&apos;t save that template. Try a different name.
+ </p>
+ ) : null}
+ </div>
+
+ <div className="space-y-2">
+ <Label htmlFor="outreach-subject">Subject</Label>
+ <Input
+ id="outreach-subject"
+ maxLength={200}
+ onChange={(event) => setSubject(event.target.value)}
+ value={subject}
+ />
+ </div>
+
+ <div className="space-y-2">
+ <Label htmlFor="outreach-body">Message</Label>
+ <Textarea
+ className="min-h-64"
+ id="outreach-body"
+ maxLength={5000}
+ onChange={(event) => setBody(event.target.value)}
+ value={body}
+ />
+ <p className="text-xs text-muted-foreground">
+ Blank line starts a paragraph. Placeholders:{" "}
+ {OUTREACH_PLACEHOLDERS.map((name) => `{{${name}}}`).join(" ")}
+ </p>
+ </div>
+ </div>
+
+ <DialogFooter>
+ <DialogClose render={<Button variant="outline" />}>Cancel</DialogClose>
+ <Button disabled={act.isPending || !sendable} onClick={submitSend}>
+ {act.isPending ? "Sending…" : "Send"}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </div>
+ );
+}
diff --git a/site/src/queries/outreach.ts b/site/src/queries/outreach.ts
new file mode 100644
index 00000000..b3f38919
--- /dev/null
+++ b/site/src/queries/outreach.ts
@@ -0,0 +1,75 @@
+"use client";
+
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+
+import type { OutreachStatus } from "@/lib/marketing/campaigns";
+import { apiFetch } from "@/queries/apiClient";
+import type { AsyncJobStatus } from "@/queries/jobs";
+
+export type OutreachRow = {
+ id: string;
+ userId: string;
+ name: string;
+ email: string;
+ status: OutreachStatus;
+ // USD strings, as the credits API returns them everywhere else.
+ spent: string;
+ balance: string;
+ lastActiveAt: string | null;
+ ranOutAt: string | null;
+ signedUpAt: string;
+ sentCount: number;
+ firstSentAt: string | null;
+ lastSentAt: string | null;
+ repliedAt: string | null;
+};
+
+export const outreachQueryKey = (status: OutreachStatus) =>
+ ["outreach", status] as const;
+
+// Super-user only: one page of the outreach list for a status.
+export function useOutreach(status: OutreachStatus) {
+ return useQuery({
+ queryFn: () =>
+ apiFetch<{ rows: OutreachRow[] }>(`/api/marketing/outreach?status=${status}`),
+ queryKey: outreachQueryKey(status),
+ });
+}
+
+type OutreachAction =
+ | { action: "send"; outreachId: string; subject: string; body: string }
+ | { action: "ignore" | "unignore" | "replied"; outreachId: string };
+
+// Any action moves a row between lists, so every list is invalidated.
+export function useOutreachAction() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (input: OutreachAction) =>
+ apiFetch<{ row: OutreachRow }>("/api/marketing/outreach", {
+ body: JSON.stringify(input),
+ method: "POST",
+ }),
+ onSuccess: () => queryClient.invalidateQueries({ queryKey: ["outreach"] }),
+ });
+}
+
+// Super-user only: roll credit usage into the list now and follow the job to
+// completion, then refetch so the list updates in place.
+export function useRunOutreachScan() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async () => {
+ const { jobId } = await apiFetch<{ jobId: string }>("/api/jobs", {
+ body: JSON.stringify({ kind: "outreach-scan", payload: {} }),
+ method: "POST",
+ });
+ for (;;) {
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+ const job = await apiFetch<AsyncJobStatus>(`/api/jobs/${jobId}`);
+ if (job.state === "done") return job;
+ if (job.state === "error") throw new Error(job.error ?? "The scan failed.");
+ }
+ },
+ onSuccess: () => queryClient.invalidateQueries({ queryKey: ["outreach"] }),
+ });
+}
diff --git a/site/src/queries/outreachTemplates.ts b/site/src/queries/outreachTemplates.ts
new file mode 100644
index 00000000..7c9e8600
--- /dev/null
+++ b/site/src/queries/outreachTemplates.ts
@@ -0,0 +1,51 @@
+"use client";
+
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+
+import { apiFetch } from "@/queries/apiClient";
+
+export type SavedTemplate = {
+ id: string;
+ name: string;
+ subject: string;
+ body: string;
+ updatedAt: string;
+};
+
+export const outreachTemplatesQueryKey = ["outreach", "templates"] as const;
+
+// Super-user only: every saved template, by name.
+export function useOutreachTemplates() {
+ return useQuery({
+ queryFn: () =>
+ apiFetch<{ templates: SavedTemplate[] }>("/api/marketing/templates"),
+ queryKey: outreachTemplatesQueryKey,
+ });
+}
+
+// Saving under an existing name rewrites that template.
+export function useSaveOutreachTemplate() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (input: { name: string; subject: string; body: string }) =>
+ apiFetch<{ template: SavedTemplate }>("/api/marketing/templates", {
+ body: JSON.stringify(input),
+ method: "POST",
+ }),
+ onSuccess: () =>
+ queryClient.invalidateQueries({ queryKey: outreachTemplatesQueryKey }),
+ });
+}
+
+export function useDeleteOutreachTemplate() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (id: string) =>
+ apiFetch<{ ok: true }>(
+ `/api/marketing/templates?id=${encodeURIComponent(id)}`,
+ { method: "DELETE" },
+ ),
+ onSuccess: () =>
+ queryClient.invalidateQueries({ queryKey: outreachTemplatesQueryKey }),
+ });
+}