Skip to content

Open source CapCut alternative.

TypeScript

feat(site): manual credit is offered and lands when the person claims it

David Le653536e92321
diff --git a/docs/guides/backend-apis.md b/docs/guides/backend-apis.md
index 253faf1c..d7039c91 100644
--- a/docs/guides/backend-apis.md
+++ b/docs/guides/backend-apis.md
@@ -150,10 +150,11 @@ balance short of one flat-priced generation also returns the price it could not
cover, and that account can still run chat and the other metered calls, so a
client knows to keep the rest of the surface working.
-Manual credit grants go through `POST /api/credits/grants/`. The caller must be
-signed in with `user.superUser` set, and the target user is addressed by
-internal id. The route reads a whole-dollar amount as credits — `$1` is one
-credit, or `1,000,000` micros — then writes the grant and its ledger entry.
+Credit given by hand is an offer. The caller must be signed in with
+`user.superUser` set, and the target user is addressed by internal id or by
+email. The route records the offer and emails a claim link; the grant and its
+ledger entry are written when the person claims, with the credit's lifetime
+counted from that moment.
Known OpenAI, Gemini, and ElevenLabs models fall back to backend-owned prices
unless a database rate overrides them. The fallbacks mirror current public
diff --git a/site/prisma/Auth.prisma b/site/prisma/Auth.prisma
index 13f16380..a0bcac45 100644
--- a/site/prisma/Auth.prisma
+++ b/site/prisma/Auth.prisma
@@ -17,6 +17,7 @@ model User {
accounts Account[]
creditAccount UserCreditAccount?
creditGrants UserCreditGrant[]
+ creditOffers CreditOffer[]
creditLedgerEntries UserCreditLedgerEntry[]
inferenceUsageEvents InferenceUsageEvent[]
creditLimits UserCreditLimit[]
diff --git a/site/prisma/Credits.prisma b/site/prisma/Credits.prisma
index 45a7fcb9..da1b32dd 100644
--- a/site/prisma/Credits.prisma
+++ b/site/prisma/Credits.prisma
@@ -33,6 +33,7 @@ model UserCreditGrant {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
ledgerEntries UserCreditLedgerEntry[]
+ offer CreditOffer?
@@unique([userId, source, sourceId])
@@index([accountId])
@@ -40,6 +41,27 @@ model UserCreditGrant {
@@map("user_credit_grant")
}
+// Credit given by hand waits here until the person claims it from the email
+// they were sent. The claim makes the grant, with the lifetime counted from
+// the claim; until then nothing reaches the balance.
+model CreditOffer {
+ id String @id @default(cuid())
+ userId String
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ amountMicros BigInt
+ expiresAfterDays Int?
+ description String?
+ offeredByUserId String
+ emailSentAt DateTime?
+ claimedAt DateTime?
+ grantId String? @unique
+ grant UserCreditGrant? @relation(fields: [grantId], references: [id], onDelete: SetNull)
+ createdAt DateTime @default(now())
+
+ @@index([userId])
+ @@map("credit_offer")
+}
+
model UserCreditLedgerEntry {
id String @id @default(cuid())
accountId String
diff --git a/site/prisma/migrations/20260907061325/migration.sql b/site/prisma/migrations/20260907061325/migration.sql
new file mode 100644
index 00000000..ba4c5efb
--- /dev/null
+++ b/site/prisma/migrations/20260907061325/migration.sql
@@ -0,0 +1,27 @@
+-- CreateTable
+CREATE TABLE "credit_offer" (
+ "id" TEXT NOT NULL,
+ "userId" TEXT NOT NULL,
+ "amountMicros" BIGINT NOT NULL,
+ "expiresAfterDays" INTEGER,
+ "description" TEXT,
+ "offeredByUserId" TEXT NOT NULL,
+ "emailSentAt" TIMESTAMP(3),
+ "claimedAt" TIMESTAMP(3),
+ "grantId" TEXT,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "credit_offer_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "credit_offer_grantId_key" ON "credit_offer"("grantId");
+
+-- CreateIndex
+CREATE INDEX "credit_offer_userId_idx" ON "credit_offer"("userId");
+
+-- AddForeignKey
+ALTER TABLE "credit_offer" ADD CONSTRAINT "credit_offer_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "credit_offer" ADD CONSTRAINT "credit_offer_grantId_fkey" FOREIGN KEY ("grantId") REFERENCES "user_credit_grant"("id") ON DELETE SET NULL ON UPDATE CASCADE;
diff --git a/site/src/app/api/credits/offers/claim/route.ts b/site/src/app/api/credits/offers/claim/route.ts
new file mode 100644
index 00000000..9eac7634
--- /dev/null
+++ b/site/src/app/api/credits/offers/claim/route.ts
@@ -0,0 +1,39 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+
+import { creditMicrosToString } from "@/lib/credits/amounts";
+import { getCreditBalance } from "@/lib/credits/inference";
+import {
+ claimCreditOffer,
+ CreditOfferNotYoursError,
+ verifyCreditOfferToken,
+} from "@/lib/credits/offers";
+import { forbiddenResponse, notFoundResponse, withDonkeyAuth } from "@/lib/donkey-api-auth";
+
+const claimRequestSchema = z.object({ token: z.string().min(1) }).strict();
+
+// Claims a credit offer for the signed-in account. The token names the offer
+// and proves the link came from its email; the session has to be the offered
+// account's.
+export const POST = withDonkeyAuth(async (request) => {
+ const parsed = claimRequestSchema.safeParse(await request.json());
+ if (!parsed.success) {
+ return NextResponse.json({ error: "Invalid request" }, { status: 400 });
+ }
+ const offerId = verifyCreditOfferToken(parsed.data.token);
+ if (!offerId) return notFoundResponse();
+
+ try {
+ const claimed = await claimCreditOffer(offerId, request.donkey.userId);
+ if (!claimed) return notFoundResponse();
+ const balance = await getCreditBalance(request.donkey.userId);
+ return NextResponse.json({
+ balance: balance.balance,
+ credits: creditMicrosToString(claimed.grant.originalAmountMicros),
+ expiresAt: claimed.grant.expiresAt?.toISOString() ?? null,
+ });
+ } catch (error) {
+ if (error instanceof CreditOfferNotYoursError) return forbiddenResponse();
+ throw error;
+ }
+});
diff --git a/site/src/app/api/credits/offers/route.ts b/site/src/app/api/credits/offers/route.ts
new file mode 100644
index 00000000..18b7ac87
--- /dev/null
+++ b/site/src/app/api/credits/offers/route.ts
@@ -0,0 +1,65 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+
+import { creditStringToMicros } from "@/lib/credits/amounts";
+import { createCreditOffer } from "@/lib/credits/offers";
+import { maxCreditGrantDollars, maxCreditGrantExpiryDays } from "@/lib/credits/top-up";
+import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";
+import { prisma } from "@/lib/prisma";
+
+// Offers credit to an account: the amount waits until the person claims it
+// from the email this sends. The target is identified by userId (offer to
+// self) or by email. A single offer is capped to guard against typos. The
+// caller states how long the credit lives once claimed; null keeps it forever.
+const creditOfferRequestSchema = 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(),
+ 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 = creditOfferRequestSchema.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, name: true },
+ where: parsed.data.userId ? { id: parsed.data.userId } : { email: parsed.data.email },
+ });
+ if (!targetUser) return notFoundResponse();
+
+ const offer = await createCreditOffer({
+ amountMicros: creditStringToMicros(String(parsed.data.amountDollars)),
+ description: parsed.data.description,
+ expiresAfterDays: parsed.data.expiresAfterDays,
+ offeredByUserId: request.donkey.userId,
+ user: targetUser,
+ });
+
+ return NextResponse.json({
+ amountDollars: parsed.data.amountDollars,
+ offer: {
+ emailSentAt: offer.emailSentAt?.toISOString() ?? null,
+ expiresAfterDays: offer.expiresAfterDays,
+ id: offer.id,
+ },
+ targetUser: { email: targetUser.email, id: targetUser.id },
+ });
+});
diff --git a/site/src/app/claim/ClaimCredits.tsx b/site/src/app/claim/ClaimCredits.tsx
new file mode 100644
index 00000000..d814808b
--- /dev/null
+++ b/site/src/app/claim/ClaimCredits.tsx
@@ -0,0 +1,95 @@
+"use client";
+
+import { useState } from "react";
+
+import { CUT_APP_BASE } from "@/cut/lib/appBase";
+import { authClient } from "@/lib/auth-client";
+import { formatCreditExpiry } from "@/lib/credits/top-up";
+
+type Props = {
+ claimed: boolean;
+ credits: string;
+ lifetime: string | null;
+ token: string;
+};
+
+// One button between the email link and the credit. Claiming needs the
+// offered account's session; without one the button goes to sign-in and
+// comes back here.
+export function ClaimCredits({ claimed, credits, lifetime, token }: Props) {
+ const { data: session, isPending: sessionPending } = authClient.useSession();
+ const [state, setState] = useState<
+ | { kind: "idle" }
+ | { kind: "pending" }
+ | { kind: "done"; expiresAt: string | null }
+ | { kind: "error"; message: string }
+ >(claimed ? { kind: "done", expiresAt: null } : { kind: "idle" });
+
+ const claim = async () => {
+ setState({ kind: "pending" });
+ const response = await fetch("/api/credits/offers/claim", {
+ body: JSON.stringify({ token }),
+ headers: { "Content-Type": "application/json" },
+ method: "POST",
+ });
+ if (response.status === 403) {
+ setState({
+ kind: "error",
+ message: "This offer belongs to a different account. Sign in with the address the email was sent to.",
+ });
+ return;
+ }
+ if (!response.ok) {
+ setState({ kind: "error", message: "That didn't go through. Try again." });
+ return;
+ }
+ const body = (await response.json()) as { expiresAt: string | null };
+ setState({ kind: "done", expiresAt: body.expiresAt });
+ };
+
+ if (state.kind === "done") {
+ return (
+ <>
+ <p>
+ {credits} in AI credits is on your account.
+ {state.expiresAt ? ` It expires ${formatCreditExpiry(new Date(state.expiresAt))}.` : ""}
+ </p>
+ <a
+ href={CUT_APP_BASE}
+ className="inline-block rounded-lg bg-[#0F0E0D] px-6 py-3 text-sm font-semibold text-[#F5EFE0] no-underline"
+ >
+ Open the editor
+ </a>
+ </>
+ );
+ }
+
+ const here = `/claim?token=${encodeURIComponent(token)}`;
+ return (
+ <>
+ <p>
+ {credits} in AI credits is waiting for you.
+ {lifetime ? ` Once claimed, it is good for ${lifetime}.` : ""}
+ </p>
+ {session ? (
+ <button
+ type="button"
+ onClick={claim}
+ disabled={state.kind === "pending"}
+ className="cursor-pointer rounded-lg bg-[#0F0E0D] px-6 py-3 text-sm font-semibold text-[#F5EFE0] disabled:opacity-60"
+ >
+ Claim {credits}
+ </button>
+ ) : (
+ <a
+ href={`/sign-in?callbackURL=${encodeURIComponent(here)}`}
+ aria-disabled={sessionPending}
+ className="inline-block rounded-lg bg-[#0F0E0D] px-6 py-3 text-sm font-semibold text-[#F5EFE0] no-underline"
+ >
+ Sign in to claim
+ </a>
+ )}
+ {state.kind === "error" && <p className="text-red-600">{state.message}</p>}
+ </>
+ );
+}
diff --git a/site/src/app/claim/page.tsx b/site/src/app/claim/page.tsx
new file mode 100644
index 00000000..e5818d0c
--- /dev/null
+++ b/site/src/app/claim/page.tsx
@@ -0,0 +1,50 @@
+import { Suspense } from "react";
+
+import { ClaimCredits } from "@/app/claim/ClaimCredits";
+import { LegalPageShell } from "@/app/legal/LegalPageShell";
+import { creditMicrosToString } from "@/lib/credits/amounts";
+import { formatUsdPlain } from "@/lib/credits/format-usd";
+import { verifyCreditOfferToken } from "@/lib/credits/offers";
+import { describeCreditLifetime } from "@/lib/email/send-credits-offered";
+import { prisma } from "@/lib/prisma";
+
+// Where the claim button in a credit offer email lands. The token is verified
+// here, but the credit waits for a button press: link-prefetching mail
+// scanners open URLs on the recipient's behalf, and a claim on load would
+// start the credit's lifetime before the person ever saw it.
+export default function ClaimPage({
+ searchParams,
+}: {
+ searchParams: Promise<{ token?: string }>;
+}) {
+ return (
+ <LegalPageShell>
+ <h1>Your credits</h1>
+ <Suspense fallback={<p>Checking this link…</p>}>
+ <Offer searchParams={searchParams} />
+ </Suspense>
+ </LegalPageShell>
+ );
+}
+
+async function Offer({ searchParams }: { searchParams: Promise<{ token?: string }> }) {
+ const { token } = await searchParams;
+ const offerId = token ? verifyCreditOfferToken(token) : null;
+ const offer = offerId
+ ? await prisma.creditOffer.findUnique({
+ select: { amountMicros: true, claimedAt: true, expiresAfterDays: true },
+ where: { id: offerId },
+ })
+ : null;
+ if (!offer || !token) {
+ return <p>This link is no longer valid.</p>;
+ }
+ return (
+ <ClaimCredits
+ claimed={offer.claimedAt !== null}
+ credits={formatUsdPlain(creditMicrosToString(offer.amountMicros))}
+ lifetime={describeCreditLifetime(offer.expiresAfterDays)}
+ token={token}
+ />
+ );
+}
diff --git a/site/src/app/su/credits/page.tsx b/site/src/app/su/credits/page.tsx
index 95b5ef92..3ff62c88 100644
--- a/site/src/app/su/credits/page.tsx
+++ b/site/src/app/su/credits/page.tsx
@@ -29,7 +29,7 @@ import {
maxCreditGrantDollars,
maxCreditGrantExpiryDays,
} from "@/lib/credits/top-up";
-import { useAccount, useGrantCredits } from "@/queries/credits";
+import { useAccount, useOfferCredits } from "@/queries/credits";
// Quick-pick amounts mirror the pay-as-you-go presets; super users can also type
// a custom dollar value. The grant route caps a single grant at
@@ -49,7 +49,7 @@ function describeExpiry(days: number | null): string {
export default function SuCreditsPage() {
const account = useAccount();
- const grant = useGrantCredits();
+ const grant = useOfferCredits();
// null means "use the current user's email as the default recipient"; once the
// super user edits the field we track their override here.
const [emailOverride, setEmailOverride] = useState<string | null>(null);
@@ -101,11 +101,12 @@ export default function SuCreditsPage() {
},
{
onSuccess: (result) => {
- const expires = result.grant.expiresAt
- ? `expires ${new Date(result.grant.expiresAt).toLocaleDateString()}`
- : "never expires";
setLastResult(
- `Added $${amountDollars} to ${result.targetUser.email} (${expires}) — new balance $${result.balance.balance}.`,
+ `Offered $${amountDollars} to ${result.targetUser.email}. The credit lands when they claim it from the email${
+ result.offer.expiresAfterDays === null
+ ? " and never expires."
+ : `, and ${describeExpiry(result.offer.expiresAfterDays)} from then.`
+ }`,
);
// Reset back to the default recipient (the current user).
setEmailOverride(null);
@@ -119,10 +120,10 @@ export default function SuCreditsPage() {
<div className="max-w-2xl space-y-6 pb-9">
<Card>
<CardHeader>
- <CardTitle>Grant credits</CardTitle>
+ <CardTitle>Offer credits</CardTitle>
<CardDescription>
- Defaults to your account — change the recipient to grant to another
- user.
+ The recipient gets an email with a claim button; the credit lands
+ when they click it. Defaults to your account.
</CardDescription>
</CardHeader>
<CardContent className="space-y-5">
@@ -201,18 +202,17 @@ export default function SuCreditsPage() {
disabled={grant.isPending || !amountValid || !expiryValid}
onClick={() => setConfirmOpen(true)}
>
- {grant.isPending ? "Granting…" : `Grant $${amountDollars}`}
+ {grant.isPending ? "Sending…" : `Offer $${amountDollars}`}
</Button>
<Dialog onOpenChange={setConfirmOpen} open={confirmOpen}>
<DialogContent>
<DialogHeader>
- <DialogTitle>Confirm credit grant</DialogTitle>
+ <DialogTitle>Confirm credit offer</DialogTitle>
<DialogDescription>
- Grant <span className="font-medium">${amountDollars}</span> in
- credits to{" "}
- <span className="font-medium">{recipientLabel}</span>? The
- grant {expiryLabel}.
+ Email <span className="font-medium">{recipientLabel}</span> an
+ offer of <span className="font-medium">${amountDollars}</span> in
+ credits? Once claimed, the credit {expiryLabel}.
</DialogDescription>
</DialogHeader>
<DialogFooter>
@@ -220,7 +220,7 @@ export default function SuCreditsPage() {
Cancel
</DialogClose>
<Button disabled={grant.isPending} onClick={submit}>
- {grant.isPending ? "Granting…" : `Grant $${amountDollars}`}
+ {grant.isPending ? "Sending…" : `Offer $${amountDollars}`}
</Button>
</DialogFooter>
</DialogContent>
@@ -231,7 +231,7 @@ export default function SuCreditsPage() {
) : null}
{grant.isError ? (
<p className="text-sm text-destructive">
- Grant failed. Check the email and amount, then try again.
+ Offer failed. Check the email and amount, then try again.
</p>
) : null}
</CardContent>
diff --git a/site/src/app/su/nav.ts b/site/src/app/su/nav.ts
index 3a450981..9eaf46fb 100644
--- a/site/src/app/su/nav.ts
+++ b/site/src/app/su/nav.ts
@@ -57,7 +57,7 @@ export const SU_NAV: SuSurface[] = [
label: "Credits",
icon: CreditCard,
title: "Credits",
- description: "Grant credits to a user.",
+ description: "Offer credits to a user.",
},
{
href: "/product",
diff --git a/site/src/emails/credits-offered.tsx b/site/src/emails/credits-offered.tsx
new file mode 100644
index 00000000..d2b9e6ac
--- /dev/null
+++ b/site/src/emails/credits-offered.tsx
@@ -0,0 +1,97 @@
+import {
+ Body,
+ Button,
+ Container,
+ Head,
+ Hr,
+ Html,
+ Link,
+ Preview,
+ Tailwind,
+ Text,
+ pixelBasedPreset,
+} from "react-email";
+
+import { DonkeyMark } from "./_components/DonkeyMark";
+
+// The email behind a credit offer: David added credit to the account, and
+// one button claims it. Sent by src/lib/email/send-credits-offered.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 CreditsOfferedEmailProps = {
+ name: string;
+ // The offer, as USD ("$25.00").
+ credits: string;
+ // How long the credits live once claimed, already worded ("7 days"), or
+ // null when they never expire.
+ lifetime: string | null;
+ claimUrl: string;
+ unsubscribeUrl: string;
+};
+
+export default function CreditsOfferedEmail({
+ name,
+ credits,
+ lifetime,
+ claimUrl,
+ unsubscribeUrl,
+}: CreditsOfferedEmailProps) {
+ return (
+ <Html>
+ <Head />
+ <Preview>{credits} in AI credits is waiting on your Donkey Cut account.</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">
+ I added {credits} in AI credits to your Donkey Cut account. Click
+ below to claim them.
+ </Text>
+ <Button
+ href={claimUrl}
+ className="rounded-lg bg-[#0F0E0D] px-6 py-3 text-[15px] font-semibold text-[#F5EFE0]"
+ >
+ Claim {credits} in credits
+ </Button>
+ <Text className="text-[15px] leading-relaxed">
+ {lifetime !== null
+ ? `Once claimed, they are good for ${lifetime}. `
+ : ""}
+ You can use them for Edit with Chat, or to generate videos,
+ images, audio, and voice.
+ </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&apos;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>
+ );
+}
+
+CreditsOfferedEmail.PreviewProps = {
+ name: "Ada",
+ credits: "$25.00",
+ lifetime: "7 days",
+ claimUrl: "https://donkeycut.com/claim?token=preview",
+ unsubscribeUrl: "https://donkeycut.com/unsubscribe?token=preview",
+} satisfies CreditsOfferedEmailProps;
diff --git a/site/src/lib/credits/offers.ts b/site/src/lib/credits/offers.ts
new file mode 100644
index 00000000..a2c8dad7
--- /dev/null
+++ b/site/src/lib/credits/offers.ts
@@ -0,0 +1,108 @@
+import { createHmac, timingSafeEqual } from "node:crypto";
+
+import { DONKEYCUT_CANONICAL } from "@/cut/lib/hosts";
+import { grantCredits } from "@/lib/credits/inference";
+import { creditGrantExpiry } from "@/lib/credits/top-up";
+import { sendCreditsOfferedEmail } from "@/lib/email/send-credits-offered";
+import { prisma } from "@/lib/prisma";
+
+// Claim links authenticate with an HMAC over the offer id, keyed by a
+// domain-separated derivation of the auth secret, the same shape as the
+// unsubscribe link. The claim itself also needs the offered account's session.
+const TOKEN_DOMAIN = "donkey-credit-offer-v1";
+
+function signature(offerId: string): Buffer {
+ const secret = process.env.BETTER_AUTH_SECRET;
+ if (!secret) throw new Error("BETTER_AUTH_SECRET is not set.");
+ const key = createHmac("sha256", secret).update(TOKEN_DOMAIN).digest();
+ return createHmac("sha256", key).update(offerId).digest();
+}
+
+export function creditOfferToken(offerId: string): string {
+ return `${offerId}.${signature(offerId).toString("base64url")}`;
+}
+
+export function verifyCreditOfferToken(token: string): string | null {
+ const dot = token.lastIndexOf(".");
+ if (dot <= 0) return null;
+ const offerId = token.slice(0, dot);
+ const expected = signature(offerId);
+ const given = Buffer.from(token.slice(dot + 1), "base64url");
+ if (given.length !== expected.length || !timingSafeEqual(given, expected)) return null;
+ return offerId;
+}
+
+export function creditOfferClaimUrl(offerId: string): string {
+ return `${DONKEYCUT_CANONICAL}/claim?token=${encodeURIComponent(creditOfferToken(offerId))}`;
+}
+
+// Records the offer and emails the claim link. The row comes first so the
+// link can name it, and stays if the send fails: the next attempt with the
+// same recipient, amount and lifetime picks the unsent offer up again, and
+// the send keys on the offer id, so the person gets one link however many
+// times the operator retries.
+export async function createCreditOffer(input: {
+ amountMicros: bigint;
+ description?: string;
+ expiresAfterDays: number | null;
+ offeredByUserId: string;
+ user: { email: string; id: string; name: string };
+}) {
+ const offer =
+ (await prisma.creditOffer.findFirst({
+ where: {
+ amountMicros: input.amountMicros,
+ claimedAt: null,
+ emailSentAt: null,
+ expiresAfterDays: input.expiresAfterDays,
+ userId: input.user.id,
+ },
+ })) ??
+ (await prisma.creditOffer.create({
+ data: {
+ amountMicros: input.amountMicros,
+ description: input.description,
+ expiresAfterDays: input.expiresAfterDays,
+ offeredByUserId: input.offeredByUserId,
+ userId: input.user.id,
+ },
+ }));
+ await sendCreditsOfferedEmail(input.user, {
+ amountMicros: offer.amountMicros,
+ claimUrl: creditOfferClaimUrl(offer.id),
+ expiresAfterDays: offer.expiresAfterDays,
+ id: offer.id,
+ });
+ return prisma.creditOffer.update({
+ data: { emailSentAt: new Date() },
+ where: { id: offer.id },
+ });
+}
+
+export class CreditOfferNotYoursError extends Error {}
+
+// Makes the grant for a claimed offer. The grant dedupes on the offer id, so
+// a second click returns the first claim.
+export async function claimCreditOffer(offerId: string, userId: string) {
+ const offer = await prisma.creditOffer.findUnique({ where: { id: offerId } });
+ if (!offer) return null;
+ if (offer.userId !== userId) throw new CreditOfferNotYoursError();
+ if (offer.claimedAt && offer.grantId) {
+ const grant = await prisma.userCreditGrant.findUnique({ where: { id: offer.grantId } });
+ if (grant) return { grant, offer };
+ }
+ const grant = await grantCredits({
+ amountMicros: offer.amountMicros,
+ description: offer.description ?? "Manual credit grant",
+ expiresAt: creditGrantExpiry(offer.expiresAfterDays),
+ metadata: { expiresAfterDays: offer.expiresAfterDays, offerId: offer.id, offeredByUserId: offer.offeredByUserId },
+ source: "manual_dollar",
+ sourceId: `offer:${offer.id}`,
+ userId,
+ });
+ const claimed = await prisma.creditOffer.update({
+ data: { claimedAt: new Date(), grantId: grant.id },
+ where: { id: offer.id },
+ });
+ return { grant, offer: claimed };
+}
diff --git a/site/src/lib/email/send-credits-offered.ts b/site/src/lib/email/send-credits-offered.ts
new file mode 100644
index 00000000..f32ae2d5
--- /dev/null
+++ b/site/src/lib/email/send-credits-offered.ts
@@ -0,0 +1,74 @@
+import {
+ DONKEY_LOGO_CID,
+ DONKEY_LOGO_PNG_BASE64,
+} from "@/emails/_components/logo";
+import CreditsOfferedEmail from "@/emails/credits-offered";
+import { creditMicrosToString } from "@/lib/credits/amounts";
+import { formatUsdPlain } from "@/lib/credits/format-usd";
+import {
+ bulkFrom,
+ emailFrom,
+ getResend,
+ isResendConfigured,
+ ResendNotConfiguredError,
+ type EmailUser,
+} from "@/lib/email/resend";
+import {
+ unsubscribeActionUrl,
+ unsubscribePageUrl,
+} from "@/lib/email/unsubscribe";
+
+// How long a claimed offer lives, as people read it.
+export function describeCreditLifetime(days: number | null): string | null {
+ if (days === null) return null;
+ if (days % 365 === 0) return days === 365 ? "a year" : `${days / 365} years`;
+ if (days % 30 === 0) return days === 30 ? "a month" : `${days / 30} months`;
+ if (days % 7 === 0) return days === 7 ? "a week" : `${days / 7} weeks`;
+ return days === 1 ? "a day" : `${days} days`;
+}
+
+// Tells the account credit is waiting and hands it the claim link. Credit
+// given by hand is account mail, so it goes whatever the marketing choice;
+// the footer still offers the opt-out.
+export async function sendCreditsOfferedEmail(
+ user: EmailUser,
+ offer: { amountMicros: bigint; claimUrl: string; expiresAfterDays: number | null; id: string },
+): Promise<void> {
+ if (!isResendConfigured()) throw new ResendNotConfiguredError();
+ const from = bulkFrom();
+ if (!from) throw new Error("No bulk sender configured.");
+
+ const credits = formatUsdPlain(creditMicrosToString(offer.amountMicros));
+ const firstName = user.name.trim().split(/\s+/)[0] || user.name;
+ const { error } = await getResend().emails.send(
+ {
+ from,
+ to: user.email,
+ replyTo: emailFrom() || from,
+ subject: `${credits} in AI credits is waiting for you`,
+ react: CreditsOfferedEmail({
+ claimUrl: offer.claimUrl,
+ credits,
+ lifetime: describeCreditLifetime(offer.expiresAfterDays),
+ 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: `credits-offered:${offer.id}` },
+ );
+ if (error) {
+ throw new Error(`Resend send failed: ${error.name}: ${error.message}`);
+ }
+}
diff --git a/site/src/queries/credits.ts b/site/src/queries/credits.ts
index 1c5c03c5..09671191 100644
--- a/site/src/queries/credits.ts
+++ b/site/src/queries/credits.ts
@@ -89,26 +89,23 @@ export function useUpdateCreditAutoReload() {
});
}
-// Super-user only: grant credits to a user (by email) or to self (by userId).
-export function useGrantCredits() {
- const queryClient = useQueryClient();
+// Super-user only: offer credits to a user (by email) or to self (by userId).
+// The credit lands when the person claims it from the email.
+export function useOfferCredits() {
return useMutation({
mutationFn: (input: {
amountDollars: number;
email?: string;
- // Days until the grant expires; null keeps it forever.
+ // Days the credit lives once claimed; null keeps it forever.
expiresAfterDays: number | null;
userId?: string;
}) =>
apiFetch<{
- balance: CreditBalance;
- grant: { expiresAt: string | null };
+ offer: { expiresAfterDays: number | null; id: string };
targetUser: { email: string };
}>(
- "/api/credits/grants",
+ "/api/credits/offers",
{ body: JSON.stringify(input), method: "POST" },
),
- onSuccess: () =>
- queryClient.invalidateQueries({ queryKey: creditBalanceQueryKey }),
});
}