Skip to content

Open source CapCut alternative.

TypeScript

feat(site): a nightly scan lists free accounts spending credits

David Le95bd04836b40
diff --git a/site/prisma/Auth.prisma b/site/prisma/Auth.prisma
index a909e6be..88fb5938 100644
--- a/site/prisma/Auth.prisma
+++ b/site/prisma/Auth.prisma
@@ -26,6 +26,7 @@ model User {
avatar UserAvatar?
onboarding UserOnboarding?
emailSettings UserEmailSettings?
+ outreach UserOutreach[]
@@map("user")
}
diff --git a/site/prisma/Marketing.prisma b/site/prisma/Marketing.prisma
new file mode 100644
index 00000000..c27d17fe
--- /dev/null
+++ b/site/prisma/Marketing.prisma
@@ -0,0 +1,53 @@
+// Founder outreach: one row per account per campaign, seeded by the nightly
+// outreach-scan job (src/lib/jobs/outreach-scan.ts) and worked by hand from
+// /app/su/outreach. The row is a marker, not a mailbox — it carries status,
+// timestamps, and the scan's credit snapshot, never a subject or a message
+// body. The conversation itself lives in the operator's inbox.
+
+model UserOutreach {
+ id String @id @default(cuid())
+ userId String
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ // Campaign ids live in code (src/lib/marketing/campaigns.ts).
+ campaign String
+ // "todo" | "sent" | "replied" | "ignored". The scan creates and retires
+ // "todo" rows; every other status is set by a person or by an inbound reply.
+ status String @default("todo")
+ sentCount Int @default(0)
+ firstSentAt DateTime?
+ lastSentAt DateTime?
+ repliedAt DateTime?
+ ignoredAt DateTime?
+ // The super user whose click sent or filed the row.
+ actorUserId String?
+ // The scan's snapshot, so the list renders from this table alone.
+ spentMicros BigInt @default(0)
+ balanceMicros BigInt @default(0)
+ lastActiveAt DateTime?
+ // When the balance last reached zero; null for an account still in credit.
+ ranOutAt DateTime?
+ scannedAt DateTime @default(now())
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@unique([userId, campaign])
+ @@index([campaign, status, lastActiveAt])
+}
+
+// A saved outreach template: the words the operator wrote, kept so the next
+// note can start from them. Templates live here rather than in the repo, so
+// writing one never needs a deploy. Sending still sends whatever is in the
+// dialog at the time — a template is a starting point, not a contract.
+
+model OutreachTemplate {
+ id String @id @default(cuid())
+ // What the send dialog calls it. Unique, so saving under an existing name
+ // updates that template instead of leaving two the operator can't tell apart.
+ name String @unique
+ subject String
+ body String
+ // The super user who last saved it.
+ actorUserId String?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+}
diff --git a/site/src/app/api/marketing/outreach/scan/route.ts b/site/src/app/api/marketing/outreach/scan/route.ts
new file mode 100644
index 00000000..8d996094
--- /dev/null
+++ b/site/src/app/api/marketing/outreach/scan/route.ts
@@ -0,0 +1,16 @@
+import { NextRequest, NextResponse } from "next/server";
+
+import { isVercelCron, notFoundResponse } from "@/lib/donkey-api-auth";
+import { enqueueJob } from "@/lib/jobs/queue";
+
+// Without a queue configured (local dev) the job runs inline before the
+// response; give it room.
+export const maxDuration = 300;
+
+// The nightly outreach scan. Vercel's cron authenticates with the CRON_SECRET
+// bearer token; the Outreach tab's Scan now button goes through the super-user
+// POST /api/jobs instead.
+export const GET = async (request: NextRequest) => {
+ if (!isVercelCron(request)) return notFoundResponse();
+ return NextResponse.json(await enqueueJob("outreach-scan", {}, "vercel-cron"));
+};
diff --git a/site/src/lib/billing/pro-subscription.ts b/site/src/lib/billing/pro-subscription.ts
index c9ce31bf..5ee10e15 100644
--- a/site/src/lib/billing/pro-subscription.ts
+++ b/site/src/lib/billing/pro-subscription.ts
@@ -12,8 +12,11 @@ import { prisma } from "@/lib/prisma";
// Donkey Pro: the Mac app subscription.
export const proPlanKey = "pro";
-// Stripe subscription statuses that include the Pro allowance.
-const activeStatuses = new Set(["active", "trialing"]);
+// Stripe subscription statuses that include the Pro allowance. Exported as a
+// list so a database filter can reuse it (src/lib/jobs/outreach-scan.ts).
+export const ACTIVE_PRO_STATUSES = ["active", "trialing"] as const;
+
+const activeStatuses = new Set<string>(ACTIVE_PRO_STATUSES);
export function isActiveProStatus(status: string): boolean {
return activeStatuses.has(status);
diff --git a/site/src/lib/jobs/outreach-scan.ts b/site/src/lib/jobs/outreach-scan.ts
new file mode 100644
index 00000000..3a4bab27
--- /dev/null
+++ b/site/src/lib/jobs/outreach-scan.ts
@@ -0,0 +1,116 @@
+import { z } from "zod";
+
+import { ACTIVE_PRO_STATUSES } from "@/lib/billing/pro-subscription";
+import { zeroCreditMicros } from "@/lib/credits/amounts";
+import { defineJob } from "@/lib/jobs/registry";
+import {
+ CREDIT_SPENDERS_CAMPAIGN,
+ OUTREACH_ACTIVE_WINDOW_DAYS,
+ OUTREACH_RECONTACT_DAYS,
+} from "@/lib/marketing/campaigns";
+import { prisma } from "@/lib/prisma";
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+// Upserts go out in batches so one scan is a handful of round trips.
+const BATCH = 50;
+
+// Rolls credit 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 /su page shows is written here, so the page itself
+// never touches the credit tables.
+export const outreachScanJob = defineJob(z.object({}).strict(), async () => {
+ const startedAt = new Date();
+ const since = new Date(startedAt.getTime() - OUTREACH_ACTIVE_WINDOW_DAYS * DAY_MS);
+ const recontactBefore = new Date(startedAt.getTime() - OUTREACH_RECONTACT_DAYS * DAY_MS);
+ const campaign = CREDIT_SPENDERS_CAMPAIGN;
+
+ // Free accounts that have spent credits and are still warm. Any amount of
+ // spend qualifies; what is left is a column on the row, not a filter.
+ const accounts = await prisma.userCreditAccount.findMany({
+ select: { balanceMicros: true, lifetimeChargedMicros: true, userId: true },
+ where: {
+ lifetimeChargedMicros: { gt: zeroCreditMicros },
+ user: {
+ // 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] } } },
+ },
+ inferenceUsageEvents: {
+ some: { billingStatus: "charged", createdAt: { gte: since } },
+ },
+ },
+ },
+ });
+
+ const userIds = accounts.map((account) => account.userId);
+ if (userIds.length === 0) {
+ const { count: dropped } = await prisma.userOutreach.deleteMany({
+ where: { campaign, scannedAt: { lt: startedAt }, status: "todo" },
+ });
+ return { added: 0, dropped, scanned: 0 };
+ }
+
+ const [lastActive, ranOut, existing] = await Promise.all([
+ prisma.inferenceUsageEvent.groupBy({
+ _max: { createdAt: true },
+ by: ["userId"],
+ where: { billingStatus: "charged", userId: { in: userIds } },
+ }),
+ // The moment the balance last hit zero. Absent for an account still in
+ // credit, which is exactly what the list wants to show.
+ prisma.userCreditLedgerEntry.groupBy({
+ _max: { createdAt: true },
+ by: ["userId"],
+ where: { balanceAfterMicros: zeroCreditMicros, userId: { in: userIds } },
+ }),
+ prisma.userOutreach.findMany({
+ select: { lastSentAt: true, status: true, userId: true },
+ where: { campaign, userId: { in: userIds } },
+ }),
+ ]);
+
+ const lastActiveBy = new Map(lastActive.map((row) => [row.userId, row._max.createdAt]));
+ const ranOutBy = new Map(ranOut.map((row) => [row.userId, row._max.createdAt]));
+ const existingBy = new Map(existing.map((row) => [row.userId, row]));
+
+ 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,
+ };
+ 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,
+ where: { userId_campaign: { campaign, userId: account.userId } },
+ });
+ });
+
+ for (let i = 0; i < writes.length; i += BATCH) {
+ await prisma.$transaction(writes.slice(i, i + BATCH));
+ }
+
+ // Anything this run did not touch no longer qualifies — unsubscribed, went
+ // Pro, or went cold. Only untouched candidates go; a contacted row is
+ // history and stays.
+ const { count: dropped } = await prisma.userOutreach.deleteMany({
+ where: { campaign, scannedAt: { lt: startedAt }, status: "todo" },
+ });
+
+ return {
+ added: accounts.length - existingBy.size,
+ dropped,
+ scanned: accounts.length,
+ };
+});
diff --git a/site/src/lib/jobs/registry.ts b/site/src/lib/jobs/registry.ts
index 6200fc71..20e8348e 100644
--- a/site/src/lib/jobs/registry.ts
+++ b/site/src/lib/jobs/registry.ts
@@ -3,6 +3,7 @@ import type { z } from "zod";
import type { Prisma } from "@/generated/prisma/client";
import { analyticsDailyJob } from "@/lib/jobs/analytics-daily";
import { deleteUserJob } from "@/lib/jobs/delete-user";
+import { outreachScanJob } from "@/lib/jobs/outreach-scan";
// Thrown by an executor when the job can never succeed — the message lands on
// the job row as its error. Anything else thrown is transient: the claim is
@@ -26,4 +27,5 @@ export function defineJob<S extends z.ZodType<unknown>>(
export const jobKinds: Record<string, JobKind> = {
"analytics-daily": analyticsDailyJob,
"delete-user": deleteUserJob,
+ "outreach-scan": outreachScanJob,
};
diff --git a/site/src/lib/marketing/campaigns.ts b/site/src/lib/marketing/campaigns.ts
new file mode 100644
index 00000000..00db9a74
--- /dev/null
+++ b/site/src/lib/marketing/campaigns.ts
@@ -0,0 +1,16 @@
+// The outreach campaigns the scan and the /su surface know about. Ids are
+// code, not data: adding one here is what makes it scannable and listable.
+
+/** Free accounts that have spent credits — the people worth a personal note. */
+export const CREDIT_SPENDERS_CAMPAIGN = "credit_spenders";
+
+/** How recently an account must have billed a model call to still count as
+ * warm. Past this it is a cold list, not outreach. */
+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;
+
+export const OUTREACH_STATUSES = ["todo", "sent", "replied", "ignored"] as const;
+
+export type OutreachStatus = (typeof OUTREACH_STATUSES)[number];
diff --git a/site/vercel.json b/site/vercel.json
index 37039e9e..18f8392a 100644
--- a/site/vercel.json
+++ b/site/vercel.json
@@ -1,6 +1,7 @@
{
"crons": [
{ "path": "/api/cut-cloud/gc", "schedule": "0 4 * * *" },
- { "path": "/api/analytics/run", "schedule": "0 1 * * *" }
+ { "path": "/api/analytics/run", "schedule": "0 1 * * *" },
+ { "path": "/api/marketing/outreach/scan", "schedule": "0 2 * * *" }
]
}