Skip to content

Open source CapCut alternative.

TypeScript

feat(site): a daily job reminds accounts before given credits expire

David Le7b1f8c479783
diff --git a/site/scripts/send-credits-expiring.ts b/site/scripts/send-credits-expiring.ts
index d6984511..776a0acd 100644
--- a/site/scripts/send-credits-expiring.ts
+++ b/site/scripts/send-credits-expiring.ts
@@ -1,52 +1,58 @@
#!/usr/bin/env bun
/**
- * Tells every account with unspent signup credits the day they expire. One
- * notice per grant: the send is recorded on the grant's metadata, so a re-run
- * only reaches accounts the last run missed. Accounts that unsubscribed from
- * product email are skipped.
+ * Runs the credit-expiry notice by hand. The daily job mails accounts whose
+ * given credit expires inside the creditExpiryNotice window; this widens the
+ * window for a one-off, and can send a single preview to an account's own
+ * address. Each grant is noticed once whichever path sends, so a run here and
+ * the job never double-mail.
*
* Run from site/ with production credentials in the environment:
- * NODE_ENV=production bun run scripts/send-credits-expiring.ts # dry run
- * NODE_ENV=production bun run scripts/send-credits-expiring.ts --to [email protected] # one preview
- * NODE_ENV=production bun run scripts/send-credits-expiring.ts --apply
+ * NODE_ENV=production bun run scripts/send-credits-expiring.ts # dry run
+ * NODE_ENV=production bun run scripts/send-credits-expiring.ts --to [email protected] # one preview
+ * NODE_ENV=production bun run scripts/send-credits-expiring.ts --apply --within 30
*/
+import { getGlobalSetting } from "../src/lib/config/effective";
import { creditMicrosToString, zeroCreditMicros } from "../src/lib/credits/amounts";
+import {
+ expiryNoticed,
+ NOTICED_GRANT_SOURCES,
+ sendDueCreditExpiryNotices,
+} from "../src/lib/email/credit-expiry-notices";
import { sendCreditsExpiringEmail } from "../src/lib/email/send-credits-expiring";
-import { isMarketingUnsubscribed } from "../src/lib/email/unsubscribe";
-import { isJsonObject } from "../src/lib/inference/json";
import { prisma } from "../src/lib/prisma";
const args = process.argv.slice(2);
const apply = args.includes("--apply");
-const previewTo = args[args.indexOf("--to") + 1];
-const preview = args.includes("--to") ? previewTo : null;
+const preview = args.includes("--to") ? args[args.indexOf("--to") + 1] : null;
if (args.includes("--to") && !preview) {
console.error("--to needs an address");
process.exit(1);
}
+const withinDays = args.includes("--within")
+ ? Number(args[args.indexOf("--within") + 1])
+ : (await getGlobalSetting("creditExpiryNotice")).daysBefore;
+if (!Number.isInteger(withinDays) || withinDays < 1) {
+ console.error("--within needs a whole number of days");
+ process.exit(1);
+}
const now = new Date();
+const DAY_MS = 24 * 60 * 60 * 1000;
const grants = await prisma.userCreditGrant.findMany({
- orderBy: { createdAt: "asc" },
- select: {
- id: true,
- expiresAt: true,
- metadata: true,
- remainingAmountMicros: true,
- user: { select: { email: true, id: true, name: true } },
- },
+ orderBy: { expiresAt: "asc" },
+ select: { expiresAt: true, metadata: true, remainingAmountMicros: true, userId: true },
where: {
- expiresAt: { gt: now },
+ expiresAt: { gt: now, lte: new Date(now.getTime() + withinDays * DAY_MS) },
remainingAmountMicros: { gt: zeroCreditMicros },
- source: "signup",
+ source: { in: [...NOTICED_GRANT_SOURCES] },
status: "active",
},
});
-const pending = grants.filter(
- (g) => !(isJsonObject(g.metadata) && typeof g.metadata.expiryNoticeSentAt === "string"),
+const pending = grants.filter((g) => !expiryNoticed(g.metadata));
+console.log(
+ `${grants.length} given grants expire within ${withinDays} days, ${pending.length} not yet notified`,
);
-console.log(`${grants.length} live signup grants, ${pending.length} not yet notified`);
if (preview) {
const sample = pending[0] ?? grants[0];
@@ -54,8 +60,14 @@ if (preview) {
console.error("nothing to preview");
process.exit(1);
}
+ // The footer's unsubscribe link is the previewer's own, never a customer's.
+ const previewer = await prisma.user.findUnique({ select: { id: true }, where: { email: preview } });
+ if (!previewer) {
+ console.error(`${preview} has no account; previews go to an account's address`);
+ process.exit(1);
+ }
await sendCreditsExpiringEmail(
- { email: preview, id: sample.user.id, name: "Ada" },
+ { email: preview, id: previewer.id, name: "Ada" },
creditMicrosToString(sample.remainingAmountMicros),
sample.expiresAt,
// Every preview is its own send, whatever the copy did in between.
@@ -63,39 +75,10 @@ if (preview) {
);
console.log(`preview sent to ${preview}`);
} else if (apply) {
- let sent = 0;
- let skipped = 0;
- let failed = 0;
- for (const grant of pending) {
- if (!grant.expiresAt) continue;
- if (await isMarketingUnsubscribed(grant.user.id)) {
- skipped++;
- continue;
- }
- try {
- await sendCreditsExpiringEmail(
- grant.user,
- creditMicrosToString(grant.remainingAmountMicros),
- grant.expiresAt,
- );
- await prisma.userCreditGrant.update({
- data: {
- metadata: {
- ...(isJsonObject(grant.metadata) ? grant.metadata : {}),
- expiryNoticeSentAt: new Date().toISOString(),
- },
- },
- where: { id: grant.id },
- });
- sent++;
- } catch (error) {
- failed++;
- console.error(`${grant.user.id}: ${error instanceof Error ? error.message : String(error)}`);
- }
- }
- console.log(`sent ${sent}, skipped ${skipped} unsubscribed, failed ${failed}`);
+ const result = await sendDueCreditExpiryNotices({ now, withinDays });
+ console.log(`sent ${result.sent}, failed ${result.failed}`);
} else {
- console.log("dry run; pass --to <address> for one preview, --apply to send to everyone");
+ console.log("dry run; pass --to <address> for one preview, --apply to send");
}
await prisma.$disconnect();
diff --git a/site/src/app/api/credits/expiry-notices/route.ts b/site/src/app/api/credits/expiry-notices/route.ts
new file mode 100644
index 00000000..1b1180ba
--- /dev/null
+++ b/site/src/app/api/credits/expiry-notices/route.ts
@@ -0,0 +1,15 @@
+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 daily credit-expiry notice. Vercel's cron authenticates with the
+// CRON_SECRET bearer token; a manual run goes through POST /api/jobs.
+export const GET = async (request: NextRequest) => {
+ if (!isVercelCron(request)) return notFoundResponse();
+ return NextResponse.json(await enqueueJob("credit-expiry-notice", {}, "vercel-cron"));
+};
diff --git a/site/src/app/api/credits/grants/route.ts b/site/src/app/api/credits/grants/route.ts
deleted file mode 100644
index bd2a6fe8..00000000
--- a/site/src/app/api/credits/grants/route.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-import { NextResponse } from "next/server";
-import { z } from "zod";
-
-import { creditMicrosToString, creditStringToMicros } from "@/lib/credits/amounts";
-import { getCreditBalance, grantCredits } from "@/lib/credits/inference";
-import {
- creditGrantExpiry,
- maxCreditGrantDollars,
- maxCreditGrantExpiryDays,
-} from "@/lib/credits/top-up";
-import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";
-import { prisma } from "@/lib/prisma";
-
-// The target is identified by userId (grant to self) or by email (grant to
-// another user). At least one is required. A single grant is capped to guard
-// against typos. The caller states how long the grant lives; null keeps it
-// forever.
-const creditGrantRequestSchema = z
- .object({
- amountDollars: z.coerce.number().int().positive().max(maxCreditGrantDollars),
- description: z.string().trim().min(1).max(500).optional(),
- email: z.string().trim().email().optional(),
- expiresAfterDays: z.number().int().min(1).max(maxCreditGrantExpiryDays).nullable(),
- sourceId: z.string().trim().min(1).max(160).optional(),
- userId: z.string().trim().min(1).optional(),
- })
- .strict()
- .refine((data) => Boolean(data.userId || data.email), {
- message: "Provide a userId or an email.",
- });
-
-export const POST = withSuperUser(async (request) => {
- const parsed = creditGrantRequestSchema.safeParse(await request.json());
- if (!parsed.success) {
- return NextResponse.json(
- {
- error: "Invalid request",
- issues: parsed.error.issues.map((issue) => ({
- path: issue.path.join("."),
- message: issue.message,
- })),
- },
- { status: 400 },
- );
- }
-
- const targetUser = await prisma.user.findUnique({
- select: {
- email: true,
- id: true,
- },
- where: parsed.data.userId
- ? { id: parsed.data.userId }
- : { email: parsed.data.email },
- });
-
- if (!targetUser) {
- return notFoundResponse();
- }
-
- const amountMicros = creditStringToMicros(String(parsed.data.amountDollars));
- const sourceId =
- parsed.data.sourceId ?? `manual-dollar:${targetUser.id}:${crypto.randomUUID()}`;
- const description =
- parsed.data.description ?? `Manual $${parsed.data.amountDollars} credit grant`;
-
- const grant = await grantCredits({
- amountMicros,
- description,
- expiresAt: creditGrantExpiry(parsed.data.expiresAfterDays),
- metadata: {
- amountDollars: String(parsed.data.amountDollars),
- expiresAfterDays: parsed.data.expiresAfterDays,
- grantedByUserId: request.donkey.userId,
- targetUserId: targetUser.id,
- },
- source: "manual_dollar",
- sourceId,
- userId: targetUser.id,
- });
- const balance = await getCreditBalance(targetUser.id);
-
- return NextResponse.json({
- amountDollars: parsed.data.amountDollars,
- creditMicrosGranted: amountMicros.toString(),
- creditsGranted: creditMicrosToString(amountMicros),
- grant: {
- expiresAt: grant.expiresAt?.toISOString() ?? null,
- id: grant.id,
- source: grant.source,
- sourceId: grant.sourceId,
- },
- targetUser: {
- email: targetUser.email,
- id: targetUser.id,
- },
- balance,
- });
-});
diff --git a/site/src/lib/config/registry.ts b/site/src/lib/config/registry.ts
index 6a6ce1f7..d6a3cebb 100644
--- a/site/src/lib/config/registry.ts
+++ b/site/src/lib/config/registry.ts
@@ -67,11 +67,23 @@ export const SETTINGS = defineSettings({
title: "Signup credits",
description: "USD a new account is granted at signup, and how many days the grant lives.",
},
+ creditExpiryNotice: {
+ schema: z
+ .object({
+ // How many days before a given grant expires its account is emailed.
+ daysBefore: z.number().int().min(1).max(maxCreditGrantExpiryDays),
+ })
+ .strict(),
+ default: { daysBefore: 3 },
+ public: false,
+ title: "Credit expiry notice",
+ description: "How many days before signup or manually granted credits expire the account is emailed.",
+ },
});
// The settings su shows on its Product tab: what an account gets. The
// settings tab under Experiments still lists every key.
-export const PRODUCT_SETTING_KEYS = ["signupCredits"] as const satisfies readonly SettingKey[];
+export const PRODUCT_SETTING_KEYS = ["signupCredits", "creditExpiryNotice"] as const satisfies readonly SettingKey[];
export type SettingKey = keyof typeof SETTINGS;
export type Settings = SettingsOf<typeof SETTINGS>;
diff --git a/site/src/lib/credits/format-usd.ts b/site/src/lib/credits/format-usd.ts
index dff9995c..abee5cae 100644
--- a/site/src/lib/credits/format-usd.ts
+++ b/site/src/lib/credits/format-usd.ts
@@ -11,3 +11,17 @@ export function formatUsd(value: string | null | undefined): string {
}
return parsed.toLocaleString("en-US", { currency: "USD", style: "currency" });
}
+
+// Money in a sentence: whole dollars carry no cents ("$25"), anything else
+// its two ("$2.57").
+export function formatUsdPlain(value: string): string {
+ const parsed = Number.parseFloat(value);
+ if (!Number.isFinite(parsed)) return "$0";
+ const whole = Number.isInteger(parsed);
+ return parsed.toLocaleString("en-US", {
+ currency: "USD",
+ maximumFractionDigits: whole ? 0 : 2,
+ minimumFractionDigits: whole ? 0 : 2,
+ style: "currency",
+ });
+}
diff --git a/site/src/lib/email/credit-expiry-notices.ts b/site/src/lib/email/credit-expiry-notices.ts
new file mode 100644
index 00000000..cbbc03bb
--- /dev/null
+++ b/site/src/lib/email/credit-expiry-notices.ts
@@ -0,0 +1,77 @@
+import type { Prisma } from "@/generated/prisma/client";
+import { creditMicrosToString, zeroCreditMicros } from "@/lib/credits/amounts";
+import { bulkFrom, isResendConfigured, ResendNotConfiguredError } from "@/lib/email/resend";
+import { sendCreditsExpiringEmail } from "@/lib/email/send-credits-expiring";
+import { prisma } from "@/lib/prisma";
+
+// The grants an account is warned about: credit it was given. Purchased
+// credit never expires, and the Pro allowance turns over every month.
+export const NOTICED_GRANT_SOURCES = ["signup", "manual_dollar"] as const;
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+function metadataObject(metadata: Prisma.JsonValue | null): Prisma.JsonObject {
+ return metadata !== null && typeof metadata === "object" && !Array.isArray(metadata)
+ ? metadata
+ : {};
+}
+
+/** Whether the grant's account has already been told this grant expires. */
+export function expiryNoticed(metadata: Prisma.JsonValue | null): boolean {
+ return typeof metadataObject(metadata).expiryNoticeSentAt === "string";
+}
+
+// Emails every account holding a given grant that expires inside the window,
+// once per grant: the send is recorded on the grant's metadata, so the next
+// run reaches only what this one missed. Credit on the account is account
+// mail, so the marketing opt-out does not apply; the footer still offers it.
+export async function sendDueCreditExpiryNotices(input: { now?: Date; withinDays: number }) {
+ if (!isResendConfigured()) throw new ResendNotConfiguredError();
+ if (!bulkFrom()) throw new Error("No bulk sender configured.");
+ const now = input.now ?? new Date();
+ const grants = await prisma.userCreditGrant.findMany({
+ orderBy: { expiresAt: "asc" },
+ select: {
+ id: true,
+ expiresAt: true,
+ metadata: true,
+ remainingAmountMicros: true,
+ user: { select: { email: true, id: true, name: true } },
+ },
+ where: {
+ expiresAt: { gt: now, lte: new Date(now.getTime() + input.withinDays * DAY_MS) },
+ remainingAmountMicros: { gt: zeroCreditMicros },
+ source: { in: [...NOTICED_GRANT_SOURCES] },
+ status: "active",
+ },
+ });
+ const pending = grants.filter((g) => !expiryNoticed(g.metadata));
+
+ let sent = 0;
+ let failed = 0;
+ for (const grant of pending) {
+ if (!grant.expiresAt) continue;
+ try {
+ await sendCreditsExpiringEmail(
+ grant.user,
+ creditMicrosToString(grant.remainingAmountMicros),
+ grant.expiresAt,
+ `credits-expiring:${grant.id}`,
+ );
+ await prisma.userCreditGrant.update({
+ data: {
+ metadata: {
+ ...metadataObject(grant.metadata),
+ expiryNoticeSentAt: new Date().toISOString(),
+ },
+ },
+ where: { id: grant.id },
+ });
+ sent++;
+ } catch (error) {
+ failed++;
+ console.error("[credit-expiry-notice] failed to send", { error, userId: grant.user.id });
+ }
+ }
+ return { due: grants.length, failed, pending: pending.length, sent };
+}
diff --git a/site/src/lib/email/send-credits-expiring.ts b/site/src/lib/email/send-credits-expiring.ts
index 88665a15..6449a963 100644
--- a/site/src/lib/email/send-credits-expiring.ts
+++ b/site/src/lib/email/send-credits-expiring.ts
@@ -4,7 +4,7 @@ import {
DONKEY_LOGO_PNG_BASE64,
} from "@/emails/_components/logo";
import CreditsExpiringEmail from "@/emails/credits-expiring";
-import { formatUsd } from "@/lib/credits/format-usd";
+import { formatUsdPlain } from "@/lib/credits/format-usd";
import { formatCreditExpiry } from "@/lib/credits/top-up";
import {
bulkFrom,
@@ -19,15 +19,16 @@ import {
unsubscribePageUrl,
} from "@/lib/email/unsubscribe";
-// Tells one account what is left of its signup credits and the day they
-// expire. `credits` is the remaining amount as a decimal string. The caller
-// decides who gets it and records that it went; here the idempotency key keeps
-// a retry within 24 hours from sending twice.
+// Tells one account what is left of a grant and the day it expires.
+// `credits` is the remaining amount as a decimal string. The caller decides
+// who gets it, records that it went, and names the send: one key per grant,
+// so a retry within 24 hours cannot send twice and two grants on one account
+// each get their own mail.
export async function sendCreditsExpiringEmail(
user: EmailUser,
credits: string,
expiresAt: Date,
- idempotencyKey = `credits-expiring:${user.id}:${expiresAt.toISOString().slice(0, 10)}`,
+ idempotencyKey: string,
): Promise<void> {
if (!isResendConfigured()) throw new ResendNotConfiguredError();
const from = bulkFrom();
@@ -39,9 +40,9 @@ export async function sendCreditsExpiringEmail(
from,
to: user.email,
replyTo: emailFrom() || from,
- subject: `Your ${formatUsd(credits)} in AI credits expires ${formatCreditExpiry(expiresAt)}`,
+ subject: `Your ${formatUsdPlain(credits)} in AI credits expires ${formatCreditExpiry(expiresAt)}`,
react: CreditsExpiringEmail({
- credits: formatUsd(credits),
+ credits: formatUsdPlain(credits),
editorUrl: `${DONKEYCUT_CANONICAL}/app`,
expiresOn: formatCreditExpiry(expiresAt),
name: firstName,
diff --git a/site/src/lib/jobs/credit-expiry-notice.ts b/site/src/lib/jobs/credit-expiry-notice.ts
new file mode 100644
index 00000000..9def959d
--- /dev/null
+++ b/site/src/lib/jobs/credit-expiry-notice.ts
@@ -0,0 +1,21 @@
+import { z } from "zod";
+
+import { getGlobalSetting } from "@/lib/config/effective";
+import { sendDueCreditExpiryNotices } from "@/lib/email/credit-expiry-notices";
+import { ResendNotConfiguredError } from "@/lib/email/resend";
+import { defineJob, JobFailure } from "@/lib/jobs/registry";
+
+// The daily credit-expiry notice. Every account holding signup or manually
+// granted credit that expires within the creditExpiryNotice window gets one
+// email naming what is left and the day it goes. Runs from
+// /api/credits/expiry-notices.
+export const creditExpiryNoticeJob = defineJob(z.object({}).strict(), async () => {
+ const setting = await getGlobalSetting("creditExpiryNotice");
+ try {
+ return await sendDueCreditExpiryNotices({ withinDays: setting.daysBefore });
+ } catch (e) {
+ // Permanent: an unconfigured sender never clears on retry.
+ if (e instanceof ResendNotConfiguredError) throw new JobFailure(e.message);
+ throw e;
+ }
+});
diff --git a/site/src/lib/jobs/registry.ts b/site/src/lib/jobs/registry.ts
index 9cb48332..f4a469d2 100644
--- a/site/src/lib/jobs/registry.ts
+++ b/site/src/lib/jobs/registry.ts
@@ -4,6 +4,7 @@ import type { Prisma } from "@/generated/prisma/client";
import { analyticsDailyJob } from "@/lib/jobs/analytics-daily";
import { billingRefreshJob } from "@/lib/jobs/billing-refresh";
import { creditExpiryJob } from "@/lib/jobs/credit-expiry";
+import { creditExpiryNoticeJob } from "@/lib/jobs/credit-expiry-notice";
import { deleteUserJob } from "@/lib/jobs/delete-user";
import { experimentResultsJob } from "@/lib/jobs/experiment-results";
import { outreachScanJob } from "@/lib/jobs/outreach-scan";
@@ -31,6 +32,7 @@ export const jobKinds: Record<string, JobKind> = {
"analytics-daily": analyticsDailyJob,
"billing-refresh": billingRefreshJob,
"credit-expiry": creditExpiryJob,
+ "credit-expiry-notice": creditExpiryNoticeJob,
"delete-user": deleteUserJob,
"experiment-results": experimentResultsJob,
"outreach-scan": outreachScanJob,
diff --git a/site/vercel.json b/site/vercel.json
index 26971ead..f3a7378f 100644
--- a/site/vercel.json
+++ b/site/vercel.json
@@ -1,6 +1,7 @@
{
"crons": [
{ "path": "/api/credits/expire", "schedule": "30 0 * * *" },
+ { "path": "/api/credits/expiry-notices", "schedule": "0 16 * * *" },
{ "path": "/api/cut-cloud/gc", "schedule": "0 4 * * *" },
{ "path": "/api/analytics/run", "schedule": "0 1 * * *" },
{ "path": "/api/experiments/results", "schedule": "0 3 * * *" },