Open source CapCut alternative.
TypeScript
feat(site): outreach lists the walls people hit, by reason
David Lef721cd998745
diff --git a/site/prisma/Marketing.prisma b/site/prisma/Marketing.prismaindex 1f5c7861..4f786883 100644--- a/site/prisma/Marketing.prisma+++ b/site/prisma/Marketing.prisma@@ -28,6 +28,10 @@ model UserOutreach {lastActiveAt DateTime?// When the balance last reached zero; null for an account still in credit.ranOutAt DateTime?+ // Why the scan listed the account (ids in src/lib/marketing/campaigns.ts).+ reasons String[] @default([])+ // The latest declined Stripe charge inside the payment window.+ paymentFailedAt DateTime?scannedAt DateTime @default(now())createdAt DateTime @default(now())updatedAt DateTime @updatedAtdiff --git a/site/prisma/migrations/20260905035202/migration.sql b/site/prisma/migrations/20260905035202/migration.sqlnew file mode 100644index 00000000..f11dff53--- /dev/null+++ b/site/prisma/migrations/20260905035202/migration.sql@@ -0,0 +1,3 @@+-- AlterTable+ALTER TABLE "UserOutreach" ADD COLUMN "paymentFailedAt" TIMESTAMP(3),+ADD COLUMN "reasons" TEXT[] DEFAULT ARRAY[]::TEXT[];diff --git a/site/src/app/api/marketing/outreach/counts/route.ts b/site/src/app/api/marketing/outreach/counts/route.tsindex fb457d5e..e6002b99 100644--- a/site/src/app/api/marketing/outreach/counts/route.ts+++ b/site/src/app/api/marketing/outreach/counts/route.ts@@ -3,7 +3,9 @@ import { NextResponse } from "next/server";import { withSuperUser } from "@/lib/donkey-api-auth";import {CREDIT_SPENDERS_CAMPAIGN,+ OUTREACH_REASONS,OUTREACH_STATUSES,+ type OutreachReason,type OutreachStatus,} from "@/lib/marketing/campaigns";import { prisma } from "@/lib/prisma";@@ -12,11 +14,20 @@ import { prisma } from "@/lib/prisma";// because the number belongs to every list at once: the totals stay put while a// list is being fetched, and one action refreshes all four.export const GET = withSuperUser(async () => {- const grouped = await prisma.userOutreach.groupBy({- _count: { _all: true },- by: ["status"],- where: { campaign: CREDIT_SPENDERS_CAMPAIGN },- });+ const [grouped, ...byReason] = await Promise.all([+ prisma.userOutreach.groupBy({+ _count: { _all: true },+ by: ["status"],+ where: { campaign: CREDIT_SPENDERS_CAMPAIGN },+ }),+ // How many of the accounts still to email carry each reason; one account+ // can count under several.+ ...OUTREACH_REASONS.map((reason) =>+ prisma.userOutreach.count({+ where: { campaign: CREDIT_SPENDERS_CAMPAIGN, reasons: { has: reason }, status: "todo" },+ }),+ ),+ ]);const counts = Object.fromEntries(OUTREACH_STATUSES.map((status) => [status, 0]),@@ -27,5 +38,9 @@ export const GET = withSuperUser(async () => {}}- return NextResponse.json({ counts });+ const reasons = Object.fromEntries(+ OUTREACH_REASONS.map((reason, i) => [reason, byReason[i]]),+ ) as Record<OutreachReason, number>;++ return NextResponse.json({ counts, reasons });});diff --git a/site/src/app/api/marketing/outreach/route.ts b/site/src/app/api/marketing/outreach/route.tsindex fe98066f..106888c0 100644--- a/site/src/app/api/marketing/outreach/route.ts+++ b/site/src/app/api/marketing/outreach/route.ts@@ -6,6 +6,7 @@ import { creditMicrosToString } from "@/lib/credits/amounts";import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";import {CREDIT_SPENDERS_CAMPAIGN,+ OUTREACH_REASONS,OUTREACH_STATUSES,} from "@/lib/marketing/campaigns";import {@@ -16,6 +17,7 @@ import { prisma } from "@/lib/prisma";const listQuerySchema = z.object({q: z.string().trim().min(1).max(200).optional(),+ reason: z.enum(OUTREACH_REASONS).optional(),status: z.enum(OUTREACH_STATUSES).optional(),});@@ -46,7 +48,9 @@ const rowSelect = {id: true,lastActiveAt: true,lastSentAt: true,+ paymentFailedAt: true,ranOutAt: true,+ reasons: true,repliedAt: true,sentCount: true,spentMicros: true,@@ -61,7 +65,9 @@ type OutreachRow = {id: string;lastActiveAt: Date | null;lastSentAt: Date | null;+ paymentFailedAt: Date | null;ranOutAt: Date | null;+ reasons: string[];repliedAt: Date | null;sentCount: number;spentMicros: bigint;@@ -81,7 +87,9 @@ function serialize(row: OutreachRow) {lastActiveAt: row.lastActiveAt?.toISOString() ?? null,lastSentAt: row.lastSentAt?.toISOString() ?? null,name: row.user.name,+ paymentFailedAt: row.paymentFailedAt?.toISOString() ?? null,ranOutAt: row.ranOutAt?.toISOString() ?? null,+ reasons: row.reasons,repliedAt: row.repliedAt?.toISOString() ?? null,sentCount: row.sentCount,signedUpAt: row.user.createdAt.toISOString(),@@ -98,6 +106,7 @@ export const GET = withSuperUser(async (request) => {const params = new URL(request.url).searchParams;const parsed = listQuerySchema.safeParse({q: params.get("q") ?? undefined,+ reason: params.get("reason") ?? undefined,status: params.get("status") ?? undefined,});if (!parsed.success) {@@ -154,11 +163,16 @@ export const GET = withSuperUser(async (request) => {} as const;const status = parsed.data.status ?? "todo";+ // A reason narrows the list to the accounts the scan listed for it.const rows = await prisma.userOutreach.findMany({orderBy: orderBy[status],select: rowSelect,take: 200,- where: { campaign: CREDIT_SPENDERS_CAMPAIGN, status },+ where: {+ campaign: CREDIT_SPENDERS_CAMPAIGN,+ status,+ ...(parsed.data.reason ? { reasons: { has: parsed.data.reason } } : {}),+ },});return NextResponse.json({ rows: rows.map(serialize) });diff --git a/site/src/app/su/outreach/page.tsx b/site/src/app/su/outreach/page.tsxindex 481aa993..895be1ac 100644--- a/site/src/app/su/outreach/page.tsx+++ b/site/src/app/su/outreach/page.tsx@@ -24,7 +24,13 @@ import { Switch } from "@/components/ui/switch";import { Textarea } from "@/components/ui/textarea";import { formatBytes } from "@/lib/bytes";import { cn } from "@/lib/utils";-import type { OutreachStatus } from "@/lib/marketing/campaigns";+import {+ OUTREACH_REASON_LABELS,+ OUTREACH_REASONS,+ OUTREACH_WALL_REASONS,+ type OutreachReason,+ type OutreachStatus,+} from "@/lib/marketing/campaigns";import { OUTREACH_PLACEHOLDERS } from "@/lib/marketing/placeholders";import {useBusyOutreachIds,@@ -73,6 +79,14 @@ function ago(iso: string | null): string {return `${Math.floor(mins / (60 * 24))}d ago`;}+// The walls the scan found lead the row in the warning tone, so a person+// who was declined or is leaving Pro stands out at a glance. Out of credits+// is carried by the balance badge that follows, and the two use reasons by+// the spent and stored badges, so those never repeat here.+const REASON_BADGES: readonly OutreachReason[] = OUTREACH_WALL_REASONS.filter(+ (reason) => reason !== "no_credits",+);+// The list carries the numbers the scan wrote; the badges say what they mean// without a second read. Storage shows only when there is any, so a row with// the badge is someone with media parked in the cloud.@@ -82,6 +96,14 @@ function RowBadges({ row, group }: { row: OutreachRow; group?: string }) {return (<div className="mt-1 flex flex-wrap items-center gap-1.5">{group ? <Badge>{group}</Badge> : null}+ {REASON_BADGES.filter((reason) => row.reasons.includes(reason)).map((reason) => (+ <Badge key={reason} variant="destructive">+ {OUTREACH_REASON_LABELS[reason]}+ {reason === "payment_failed" && row.paymentFailedAt+ ? ` · ${ago(row.paymentFailedAt)}`+ : ""}+ </Badge>+ ))}<Badge variant="secondary">${row.spent} spent</Badge><Badge variant={broke ? "destructive" : "outline"}>{broke ? `$0 left · ${ago(row.ranOutAt)}` : `$${row.balance} left`}@@ -103,6 +125,8 @@ function RowBadges({ row, group }: { row: OutreachRow; group?: string }) {export default function SuOutreachPage() {const [status, setStatus] = useState<OutreachStatus>("todo");+ // The to-email list narrows to one reason; the other lists show all.+ const [reason, setReason] = useState<OutreachReason | undefined>();const [query, setQuery] = useState("");// A search starts wide — matches from every tab in one list — and clicking// a tab pins it to that group until the next search begins.@@ -124,11 +148,12 @@ export default function SuOutreachPage() {const timer = setTimeout(() => setNeedle(trimmed), 300);return () => clearTimeout(timer);}, [query]);- const list = useOutreach(status);+ const list = useOutreach(status, status === "todo" ? reason : undefined);// Search matches in the database across every tab, so a hit past the page// cap is still found and every tab reports its true match count.const search = useOutreachSearch(needle, scoped ? status : undefined);- const counts = useOutreachCounts().data?.counts;+ const countsData = useOutreachCounts().data;+ const counts = countsData?.counts;const act = useOutreachAction();const busy = useBusyOutreachIds();const templates = useOutreachTemplates();@@ -358,6 +383,33 @@ export default function SuOutreachPage() {))}</div>+ {status === "todo" && !allTabs ? (+ <div className="flex flex-wrap items-center gap-1.5">+ {[undefined, ...OUTREACH_REASONS].map((id) => {+ const on = reason === id;+ const count = id ? countsData?.reasons?.[id] : counts?.todo;+ return (+ <button+ key={id ?? "all"}+ type="button"+ aria-pressed={on}+ onClick={() => setReason(id)}+ className={cn(+ "flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs transition-colors",+ on ? "border-foreground" : "border-border text-muted-foreground hover:bg-muted/60",+ id && OUTREACH_WALL_REASONS.includes(id) && !on && "text-destructive",+ )}+ >+ {id ? OUTREACH_REASON_LABELS[id] : "All"}+ {count !== undefined ? (+ <span className="tabular-nums opacity-60">{count}</span>+ ) : null}+ </button>+ );+ })}+ </div>+ ) : null}+<div className="rounded-xl border bg-card">{rows.length > 0 ? (<ul className="divide-y">diff --git a/site/src/lib/jobs/outreach-scan.ts b/site/src/lib/jobs/outreach-scan.tsindex 395ec0d3..bd57cb57 100644--- a/site/src/lib/jobs/outreach-scan.ts+++ b/site/src/lib/jobs/outreach-scan.ts@@ -1,14 +1,29 @@import { z } from "zod";-import { ACTIVE_PRO_STATUSES } from "@/lib/billing/pro-subscription";+import { cutLimitsForTier } from "@/cut/server/cloud/limits";+import {+ ACTIVE_PRO_STATUSES,+ isActiveProStatus,+ subscriptionIsPro,+} from "@/lib/billing/pro-subscription";+import {+ drainStripe,+ getStripe,+ stripeId,+ StripeListTooLongError,+ StripeNotConfiguredError,+} from "@/lib/billing/stripe";import { creditStringToMicros, zeroCreditMicros } from "@/lib/credits/amounts";-import { defineJob } from "@/lib/jobs/registry";+import { defineJob, JobFailure } from "@/lib/jobs/registry";import {CREDIT_SPENDERS_CAMPAIGN,OUTREACH_ACTIVE_WINDOW_DAYS,OUTREACH_MIN_SPENT_CREDITS,OUTREACH_MIN_STORAGE_BYTES,+ OUTREACH_PAYMENT_WINDOW_DAYS,OUTREACH_RECONTACT_DAYS,+ OUTREACH_STORAGE_FULL_SHARE,+ type OutreachReason,} from "@/lib/marketing/campaigns";import { prisma } from "@/lib/prisma";@@ -24,91 +39,181 @@ function newest(...dates: (Date | null | undefined)[]): Date | null {return best;}-type Candidate = {- balanceMicros: bigint;- lifetimeChargedMicros: bigint;- userId: string;-};--// Rolls product usage into the outreach list. Runs nightly from-// /api/marketing/outreach/scan and by hand from the Outreach tab's Scan now-// button. Everything the Outreach tab shows is written here or read alongside-// it, so the page itself never touches the credit tables.+// Rolls product usage and billing state into the outreach list. Runs nightly+// from /api/marketing/outreach/scan and by hand from the Outreach tab's Scan+// now button. Everything the Outreach tab shows is written here or read+// alongside it, so the page itself never touches the credit tables.+//+// Two kinds of people make the list. Free accounts using the product well —+// spending credits or holding media, and warm — are the ones worth a personal+// note. And anyone who hit a wall: ran out of credits, filled their storage,+// had a card declined, fell behind on Pro, or is leaving it. A wall counts+// however long ago the account was last seen, because that is when the+// person went quiet.export const outreachScanJob = defineJob(z.object({}).strict(), async () => {+ try {+ return await scan();+ } catch (e) {+ // Permanent: an unconfigured Stripe or a list past the cap never clears+ // on retry.+ if (e instanceof StripeNotConfiguredError || e instanceof StripeListTooLongError) {+ throw new JobFailure(e.message);+ }+ throw e;+ }+});++async function scan() {const startedAt = new Date();const since = new Date(startedAt.getTime() - OUTREACH_ACTIVE_WINDOW_DAYS * DAY_MS);+ const paymentSince = new Date(startedAt.getTime() - OUTREACH_PAYMENT_WINDOW_DAYS * DAY_MS);const recontactBefore = new Date(startedAt.getTime() - OUTREACH_RECONTACT_DAYS * DAY_MS);const campaign = CREDIT_SPENDERS_CAMPAIGN;const minSpentMicros = creditStringToMicros(OUTREACH_MIN_SPENT_CREDITS);- // A free account that has not opted out of marketing.+ // An account that has not opted out of marketing. No settings row means it+ // never opted out.const marketable = {- // An account with no settings row has never opted out.OR: [{ emailSettings: { is: null } },{ emailSettings: { is: { marketingUnsubscribedAt: null } } },],- NOT: {- proSubscription: { is: { status: { in: [...ACTIVE_PRO_STATUSES] } } },- },};+ // A free account: a Pro subscriber already pays, so use alone is no reason.+ const free = {+ ...marketable,+ NOT: { proSubscription: { is: { status: { in: [...ACTIVE_PRO_STATUSES] } } } },+ };+ const freeStorageBytes = cutLimitsForTier({ pro: false, superUser: false }).storageBytes ?? 0;- const [spenderAccounts, heavy] = await Promise.all([- // Accounts that have spent a real share of their credits and are still- // warm. What is left is a column on the row; the floor is on what went out.+ // Declined charges and ended subscriptions come from Stripe; the customer+ // id on each is the one stored on the user at their first checkout. The+ // pull runs alongside the database reads.+ const failedAtByCustomer = new Map<string, Date>();+ const endedCustomerIds = new Set<string>();+ const [spenders, storage] = await Promise.all([+ // Free accounts that spent a real share of their credits and are still+ // warm. The floor is on what went out.prisma.userCreditAccount.findMany({- select: { balanceMicros: true, lifetimeChargedMicros: true, userId: true },+ select: { userId: true },where: {lifetimeChargedMicros: { gte: minSpentMicros },user: {- ...marketable,+ ...free,inferenceUsageEvents: {some: { billingStatus: "charged", createdAt: { gte: since } },},},},}),- // Accounts holding most of the free quota. Uploading costs no credits, so+ // Accounts holding a real amount of media. Uploading costs no credits, so// these people are invisible to the spend query. Starter media is- // quotaExempt and never counted, so it names nobody.+ // quotaExempt and never counted, so it names nobody. The storage counter+ // has no relation to the user, so opt-out, Pro and the tier's quota are+ // settled below.prisma.cutStorageUsage.findMany({- select: { userId: true },- where: { bytes: { gte: OUTREACH_MIN_STORAGE_BYTES } },+ select: { bytes: true, userId: true },+ where: {+ bytes: {+ gte:+ OUTREACH_MIN_STORAGE_BYTES <+ BigInt(Math.floor(freeStorageBytes * OUTREACH_STORAGE_FULL_SHARE))+ ? OUTREACH_MIN_STORAGE_BYTES+ : BigInt(Math.floor(freeStorageBytes * OUTREACH_STORAGE_FULL_SHARE)),+ },+ },}),+ (async () => {+ const stripe = getStripe();+ // A subscription that ended inside the payment window, by the date it+ // ended; the row in our database carries no end date of its own.+ for (const sub of await drainStripe(+ stripe.subscriptions.list({ limit: 100, status: "canceled" }),+ )) {+ const endedAt = sub.ended_at ?? sub.canceled_at;+ const customerId = stripeId(sub.customer);+ if (!subscriptionIsPro(sub)) continue;+ if (customerId && endedAt !== null && endedAt * 1000 >= paymentSince.getTime()) {+ endedCustomerIds.add(customerId);+ }+ }+ for (const charge of await drainStripe(+ stripe.charges.list({+ created: { gte: Math.floor(paymentSince.getTime() / 1000) },+ limit: 100,+ }),+ )) {+ const customerId = stripeId(charge.customer);+ if (charge.status !== "failed" || !customerId) continue;+ const at = new Date(charge.created * 1000);+ failedAtByCustomer.set(customerId, newest(at, failedAtByCustomer.get(customerId))!);+ }+ })(),]);- const spenders: Candidate[] = spenderAccounts;- const spenderIds = new Set(spenders.map((account) => account.userId));- const heavyIds = heavy.map((row) => row.userId).filter((userId) => !spenderIds.has(userId));- // Opt-out and Pro come off first, so nothing further is read for an account- // that can never be mailed. A credit account is provisioned at signup, so- // the zero fallback is for a row that never landed.- const holders: Candidate[] =- heavyIds.length > 0- ? (- await prisma.user.findMany({- select: {- creditAccount: { select: { balanceMicros: true, lifetimeChargedMicros: true } },- id: true,- },- where: { ...marketable, id: { in: heavyIds } },- })- ).map((user) => ({- balanceMicros: user.creditAccount?.balanceMicros ?? zeroCreditMicros,- lifetimeChargedMicros: user.creditAccount?.lifetimeChargedMicros ?? zeroCreditMicros,- userId: user.id,- }))- : [];const retire = async () => {- // Anything this run did not touch no longer qualifies — unsubscribed, went- // Pro, went cold, or never came back. Only untouched candidates go; a- // contacted row is history and stays.+ // Anything this run did not touch no longer qualifies — unsubscribed,+ // went cold, cleared the wall, or never came back. Only untouched+ // candidates go; a contacted row is history and stays.const { count } = await prisma.userOutreach.deleteMany({where: { campaign, scannedAt: { lt: startedAt }, status: "todo" },});return count;};- const userIds = [...spenders, ...holders].map((account) => account.userId);++ const spenderIds = new Set(spenders.map((row) => row.userId));+ const heavyIds = new Set(+ storage.filter((row) => row.bytes >= OUTREACH_MIN_STORAGE_BYTES).map((row) => row.userId),+ );+ const stripeCustomerIds = [...new Set([...failedAtByCustomer.keys(), ...endedCustomerIds])];++ // One read names every candidate and carries what the reason pass needs:+ // the use-based ids from above, the walls found on the user's own rows —+ // credits used up, a Pro subscription behind or ending — and the Stripe+ // customers with a declined charge or an ended subscription. Opt-out comes+ // off here for all of them, so nothing further is read for an account+ // that can never be mailed.+ const users = await prisma.user.findMany({+ select: {+ creditAccount: { select: { balanceMicros: true, lifetimeChargedMicros: true } },+ id: true,+ proSubscription: { select: { cancelAtPeriodEnd: true, status: true } },+ stripeCustomerId: true,+ superUser: true,+ },+ where: {+ AND: [+ marketable,+ {+ OR: [+ { id: { in: [...new Set([...spenderIds, ...storage.map((row) => row.userId)])] } },+ {+ creditAccount: {+ is: {+ balanceMicros: { lte: zeroCreditMicros },+ lifetimeChargedMicros: { gte: minSpentMicros },+ },+ },+ },+ {+ proSubscription: {+ is: {+ OR: [+ { status: { in: ["past_due", "unpaid"] } },+ { cancelAtPeriodEnd: true, status: { in: [...ACTIVE_PRO_STATUSES] } },+ ],+ },+ },+ },+ ...(stripeCustomerIds.length > 0+ ? [{ stripeCustomerId: { in: stripeCustomerIds } }]+ : []),+ ],+ },+ ],+ },+ });+ const userIds = users.map((user) => user.id);if (userIds.length === 0) {return { added: 0, dropped: await retire(), scanned: 0 };}@@ -164,32 +269,67 @@ export const outreachScanJob = defineJob(z.object({}).strict(), async () => {const ranOutBy = new Map(ranOut.map((row) => [row.userId, row._max.createdAt]));const existingBy = new Map(existing.map((row) => [row.userId, row]));- // Spenders billed a call inside the window, so they are warm by- // construction. Holders have to be warm: something of theirs moved inside- // the window.- const warm = holders.filter((account) => {- const lastActiveAt = lastActiveBy.get(account.userId);- return lastActiveAt !== undefined && lastActiveAt >= since;+ const accounts = users.flatMap((user) => {+ const balanceMicros = user.creditAccount?.balanceMicros ?? zeroCreditMicros;+ const spentMicros = user.creditAccount?.lifetimeChargedMicros ?? zeroCreditMicros;+ const storageBytes = storedBy.get(user.id) ?? BigInt(0);+ const lastActiveAt = lastActiveBy.get(user.id) ?? null;+ const sub = user.proSubscription;+ const pro = sub !== null && isActiveProStatus(sub.status);+ const quota = cutLimitsForTier({ pro, superUser: user.superUser }).storageBytes;+ const paymentFailedAt = user.stripeCustomerId+ ? (failedAtByCustomer.get(user.stripeCustomerId) ?? null)+ : null;++ const reasons: OutreachReason[] = [];+ // Spenders billed a call inside the window, so they are warm by+ // construction. Holders have to be warm: something of theirs moved+ // inside the window.+ if (spenderIds.has(user.id)) reasons.push("spent");+ if (!pro && heavyIds.has(user.id) && lastActiveAt !== null && lastActiveAt >= since) {+ reasons.push("storage");+ }+ if (balanceMicros <= zeroCreditMicros && spentMicros >= minSpentMicros) {+ reasons.push("no_credits");+ }+ if (quota !== null && Number(storageBytes) >= quota * OUTREACH_STORAGE_FULL_SHARE) {+ reasons.push("storage_full");+ }+ if (paymentFailedAt) reasons.push("payment_failed");+ if (sub?.status === "past_due" || sub?.status === "unpaid") reasons.push("past_due");+ if (pro && sub.cancelAtPeriodEnd) reasons.push("canceling");+ // An ended subscription is a reason only while nothing replaced it.+ if (!pro && user.stripeCustomerId && endedCustomerIds.has(user.stripeCustomerId)) {+ reasons.push("canceled");+ }+ if (reasons.length === 0) return [];++ return [+ {+ snapshot: {+ balanceMicros,+ lastActiveAt,+ paymentFailedAt,+ ranOutAt: ranOutBy.get(user.id) ?? null,+ reasons,+ scannedAt: startedAt,+ spentMicros,+ storageBytes,+ },+ userId: user.id,+ },+ ];});- const accounts = [...spenders, ...warm];const writes = accounts.map((account) => {- const snapshot = {- balanceMicros: account.balanceMicros,- lastActiveAt: lastActiveBy.get(account.userId) ?? null,- ranOutAt: ranOutBy.get(account.userId) ?? null,- scannedAt: startedAt,- spentMicros: account.lifetimeChargedMicros,- storageBytes: storedBy.get(account.userId) ?? BigInt(0),- };const prior = existingBy.get(account.userId);// A contacted row rests for OUTREACH_RECONTACT_DAYS, then comes back// around. Replied and ignored stay put until a person clears them.const revive =prior?.status === "sent" && (!prior.lastSentAt || prior.lastSentAt < recontactBefore);return prisma.userOutreach.upsert({- create: { campaign, status: "todo", userId: account.userId, ...snapshot },- update: revive ? { status: "todo", ...snapshot } : snapshot,+ create: { campaign, status: "todo", userId: account.userId, ...account.snapshot },+ update: revive ? { status: "todo", ...account.snapshot } : account.snapshot,where: { userId_campaign: { campaign, userId: account.userId } },});});@@ -203,4 +343,4 @@ export const outreachScanJob = defineJob(z.object({}).strict(), async () => {dropped: await retire(),scanned: accounts.length,};-});+}diff --git a/site/src/lib/marketing/campaigns.ts b/site/src/lib/marketing/campaigns.tsindex e5e2644d..9674ff49 100644--- a/site/src/lib/marketing/campaigns.ts+++ b/site/src/lib/marketing/campaigns.ts@@ -25,6 +25,50 @@ export const OUTREACH_ACTIVE_WINDOW_DAYS = 30;/** How long a contacted account rests before the scan offers it again. */export const OUTREACH_RECONTACT_DAYS = 60;+/** How far back a declined charge or an ended subscription still counts as+ * a reason to reach out. */+export const OUTREACH_PAYMENT_WINDOW_DAYS = 60;++/** The share of the storage quota at which an account counts as full. */+export const OUTREACH_STORAGE_FULL_SHARE = 0.9;++/** Why an account is on the list. The first two are people using the product+ * well; the rest are walls they hit — the moment a note can turn into a+ * top-up, an upgrade, or a saved subscription. An account can carry several. */+export const OUTREACH_REASONS = [+ "spent",+ "storage",+ "no_credits",+ "storage_full",+ "payment_failed",+ "past_due",+ "canceling",+ "canceled",+] as const;++export type OutreachReason = (typeof OUTREACH_REASONS)[number];++export const OUTREACH_REASON_LABELS: Record<OutreachReason, string> = {+ canceled: "Canceled Pro",+ canceling: "Canceling Pro",+ no_credits: "Out of credits",+ past_due: "Payment past due",+ payment_failed: "Payment declined",+ spent: "Spending credits",+ storage: "Holding media",+ storage_full: "Storage full",+};++/** The reasons that are a wall the person ran into, shown in the warning tone. */+export const OUTREACH_WALL_REASONS: readonly OutreachReason[] = [+ "no_credits",+ "storage_full",+ "payment_failed",+ "past_due",+ "canceling",+ "canceled",+];+export const OUTREACH_STATUSES = ["todo", "sent", "replied", "ignored"] as const;export type OutreachStatus = (typeof OUTREACH_STATUSES)[number];diff --git a/site/src/queries/outreach.ts b/site/src/queries/outreach.tsindex 277d1018..3635202a 100644--- a/site/src/queries/outreach.ts+++ b/site/src/queries/outreach.ts@@ -8,7 +8,7 @@ import {useQueryClient,} from "@tanstack/react-query";-import type { OutreachStatus } from "@/lib/marketing/campaigns";+import type { OutreachReason, OutreachStatus } from "@/lib/marketing/campaigns";import { apiFetch } from "@/queries/apiClient";import type { AsyncJobStatus } from "@/queries/jobs";@@ -26,6 +26,9 @@ export type OutreachRow = {storageBytes: string;lastActiveAt: string | null;ranOutAt: string | null;+ // Why the scan listed the account; a wall reason is the moment to write.+ reasons: OutreachReason[];+ paymentFailedAt: string | null;signedUpAt: string;sentCount: number;firstSentAt: string | null;@@ -33,15 +36,18 @@ export type OutreachRow = {repliedAt: string | null;};-export const outreachQueryKey = (status: OutreachStatus) =>- ["outreach", status] as const;+export const outreachQueryKey = (status: OutreachStatus, reason?: OutreachReason) =>+ ["outreach", status, reason ?? "all"] as const;-// Super-user only: one page of the outreach list for a status.-export function useOutreach(status: OutreachStatus) {+// Super-user only: one page of the outreach list for a status, narrowed to+// one reason when asked.+export function useOutreach(status: OutreachStatus, reason?: OutreachReason) {return useQuery({queryFn: () =>- apiFetch<{ rows: OutreachRow[] }>(`/api/marketing/outreach?status=${status}`),- queryKey: outreachQueryKey(status),+ apiFetch<{ rows: OutreachRow[] }>(+ `/api/marketing/outreach?status=${status}${reason ? `&reason=${reason}` : ""}`,+ ),+ queryKey: outreachQueryKey(status, reason),});}@@ -68,14 +74,16 @@ export function useOutreachSearch(q: string, status?: OutreachStatus) {export const outreachCountsQueryKey = ["outreach", "counts"] as const;-// How many rows every status holds. One key for all four, so switching lists-// never blanks the totals.+// How many rows every status holds, and how many of the to-email rows carry+// each reason. One key for all of them, so switching lists never blanks the+// totals.export function useOutreachCounts() {return useQuery({queryFn: () =>- apiFetch<{ counts: Record<OutreachStatus, number> }>(- "/api/marketing/outreach/counts",- ),+ apiFetch<{+ counts: Record<OutreachStatus, number>;+ reasons: Record<OutreachReason, number>;+ }>("/api/marketing/outreach/counts"),queryKey: outreachCountsQueryKey,});}diff --git a/site/vercel.json b/site/vercel.jsonindex 06d56b06..70982861 100644--- a/site/vercel.json+++ b/site/vercel.json@@ -3,6 +3,6 @@{ "path": "/api/cut-cloud/gc", "schedule": "0 4 * * *" },{ "path": "/api/analytics/run", "schedule": "0 1 * * *" },{ "path": "/api/experiments/results", "schedule": "0 3 * * *" },- { "path": "/api/marketing/outreach/scan", "schedule": "0 2 * * *" }+ { "path": "/api/marketing/outreach/scan", "schedule": "15 1 * * *" }]}