Open source CapCut alternative.
TypeScript
feat(site): an email tells accounts the day their signup credits expire
David Le679611a1e748
diff --git a/site/scripts/send-credits-expiring.ts b/site/scripts/send-credits-expiring.tsnew file mode 100644index 00000000..d6984511--- /dev/null+++ b/site/scripts/send-credits-expiring.ts@@ -0,0 +1,101 @@+#!/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.+ *+ * 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+ */++import { creditMicrosToString, zeroCreditMicros } from "../src/lib/credits/amounts";+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;+if (args.includes("--to") && !preview) {+ console.error("--to needs an address");+ process.exit(1);+}++const now = new Date();+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 } },+ },+ where: {+ expiresAt: { gt: now },+ remainingAmountMicros: { gt: zeroCreditMicros },+ source: "signup",+ status: "active",+ },+});+const pending = grants.filter(+ (g) => !(isJsonObject(g.metadata) && typeof g.metadata.expiryNoticeSentAt === "string"),+);+console.log(`${grants.length} live signup grants, ${pending.length} not yet notified`);++if (preview) {+ const sample = pending[0] ?? grants[0];+ if (!sample?.expiresAt) {+ console.error("nothing to preview");+ process.exit(1);+ }+ await sendCreditsExpiringEmail(+ { email: preview, id: sample.user.id, name: "Ada" },+ creditMicrosToString(sample.remainingAmountMicros),+ sample.expiresAt,+ // Every preview is its own send, whatever the copy did in between.+ `credits-expiring-preview:${preview}:${Date.now()}`,+ );+ 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}`);+} else {+ console.log("dry run; pass --to <address> for one preview, --apply to send to everyone");+}++await prisma.$disconnect();diff --git a/site/src/emails/credits-expiring.tsx b/site/src/emails/credits-expiring.tsxnew file mode 100644index 00000000..094a31a1--- /dev/null+++ b/site/src/emails/credits-expiring.tsx@@ -0,0 +1,95 @@+import {+ Body,+ Container,+ Head,+ Hr,+ Html,+ Link,+ Preview,+ Tailwind,+ Text,+ pixelBasedPreset,+} from "react-email";++import { DonkeyMark } from "./_components/DonkeyMark";++// The one notice an account gets before its signup credits expire: a short+// note from David naming what is left and the day it goes. Sent by+// src/lib/email/send-credits-expiring.ts; preview with `npm run email:dev`.+// This module stays pure — the react-email preview server bundles it on its+// own, so everything it needs comes in as props and link URLs are absolute.++type CreditsExpiringEmailProps = {+ name: string;+ // What is left of the grant, as USD ("$2.57").+ credits: string;+ // The day it expires, already worded ("September 14, 2026").+ expiresOn: string;+ editorUrl: string;+ unsubscribeUrl: string;+};++export default function CreditsExpiringEmail({+ name,+ credits,+ expiresOn,+ editorUrl,+ unsubscribeUrl,+}: CreditsExpiringEmailProps) {+ return (+ <Html>+ <Head />+ <Preview>+ The {credits} in AI credits on your Donkey Cut account expires on {expiresOn}.+ </Preview>+ <Tailwind config={{ presets: [pixelBasedPreset] }}>+ <Body className="bg-white font-sans text-[#0F0E0D]">+ <Container className="mx-auto max-w-[520px] px-6 py-12">+ <DonkeyMark />+ <Text className="text-[15px] leading-relaxed">Hey {name},</Text>+ <Text className="text-[15px] leading-relaxed">+ Just a quick heads up: the {credits} in AI credits on your Donkey+ Cut account expires on {expiresOn}. Any unused credits will+ disappear after that.+ </Text>+ <Text className="text-[15px] leading-relaxed">+ You can use them for Edit with Chat, or to generate videos,+ images, audio, and voice.+ </Text>+ <Text className="text-[15px] leading-relaxed">+ <Link href={editorUrl} className="text-[#0F0E0D] underline">+ Open the editor+ </Link>{" "}+ and put them to use 🙂+ </Text>+ <Text className="text-[15px] leading-relaxed">+ If you have any questions, just reply to this email. It goes+ straight to my inbox.+ </Text>+ <Text className="text-[15px] leading-relaxed">David</Text>+ <Hr className="mt-6 border-[#0F0E0D]/15" />+ <Text className="text-[12px] leading-relaxed text-[#0F0E0D]/60">+ You're receiving this because you created a Donkey Cut+ account.{" "}+ <Link+ href={unsubscribeUrl}+ className="text-[#0F0E0D]/60 underline"+ >+ Unsubscribe+ </Link>{" "}+ from product emails.+ </Text>+ </Container>+ </Body>+ </Tailwind>+ </Html>+ );+}++CreditsExpiringEmail.PreviewProps = {+ name: "Ada",+ credits: "$2.57",+ expiresOn: "September 14, 2026",+ editorUrl: "https://donkeycut.com/app",+ unsubscribeUrl: "https://donkeycut.com/unsubscribe?token=preview",+} satisfies CreditsExpiringEmailProps;diff --git a/site/src/lib/email/send-credits-expiring.ts b/site/src/lib/email/send-credits-expiring.tsnew file mode 100644index 00000000..88665a15--- /dev/null+++ b/site/src/lib/email/send-credits-expiring.ts@@ -0,0 +1,68 @@+import { DONKEYCUT_CANONICAL } from "@/cut/lib/hosts";+import {+ DONKEY_LOGO_CID,+ DONKEY_LOGO_PNG_BASE64,+} from "@/emails/_components/logo";+import CreditsExpiringEmail from "@/emails/credits-expiring";+import { formatUsd } from "@/lib/credits/format-usd";+import { formatCreditExpiry } from "@/lib/credits/top-up";+import {+ bulkFrom,+ emailFrom,+ getResend,+ isResendConfigured,+ ResendNotConfiguredError,+ type EmailUser,+} from "@/lib/email/resend";+import {+ unsubscribeActionUrl,+ 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.+export async function sendCreditsExpiringEmail(+ user: EmailUser,+ credits: string,+ expiresAt: Date,+ idempotencyKey = `credits-expiring:${user.id}:${expiresAt.toISOString().slice(0, 10)}`,+): Promise<void> {+ if (!isResendConfigured()) throw new ResendNotConfiguredError();+ const from = bulkFrom();+ if (!from) throw new Error("No bulk sender configured.");++ const firstName = user.name.trim().split(/\s+/)[0] || user.name;+ const { error } = await getResend().emails.send(+ {+ from,+ to: user.email,+ replyTo: emailFrom() || from,+ subject: `Your ${formatUsd(credits)} in AI credits expires ${formatCreditExpiry(expiresAt)}`,+ react: CreditsExpiringEmail({+ credits: formatUsd(credits),+ editorUrl: `${DONKEYCUT_CANONICAL}/app`,+ expiresOn: formatCreditExpiry(expiresAt),+ name: firstName,+ unsubscribeUrl: unsubscribePageUrl(user.id),+ }),+ attachments: [+ {+ content: DONKEY_LOGO_PNG_BASE64,+ contentId: DONKEY_LOGO_CID,+ contentType: "image/png",+ filename: "donkey-cut.png",+ },+ ],+ headers: {+ "List-Unsubscribe": `<${unsubscribeActionUrl(user.id)}>`,+ "List-Unsubscribe-Post": "List-Unsubscribe=One-Click",+ },+ },+ { idempotencyKey },+ );+ if (error) {+ throw new Error(`Resend send failed: ${error.name}: ${error.message}`);+ }+}