Skip to content

Open source CapCut alternative.

TypeScript

feat(site): land a promotion's credit offer by subscribing to Pro

David Led4fc4bb07656
diff --git a/site/src/app/api/billing/checkout/route.ts b/site/src/app/api/billing/checkout/route.ts
index b2bc64d5..b07b8379 100644
--- a/site/src/app/api/billing/checkout/route.ts
+++ b/site/src/app/api/billing/checkout/route.ts
@@ -1,15 +1,22 @@
import { NextResponse } from "next/server";
+import { z } from "zod";
import { auth } from "@/lib/auth";
import { proPriceId } from "@/lib/billing/pro-subscription";
import { ensureStripeCustomer, getStripe } from "@/lib/billing/stripe";
-import { openSubscribeBonusOffer, SUBSCRIBE_BONUS_METADATA_KEY } from "@/lib/credits/subscribe-bonus-claim";
+import { verifyCreditOfferToken } from "@/lib/credits/offers";
+import { openOfferForSubscribing, SUBSCRIBE_BONUS_METADATA_KEY } from "@/lib/credits/subscribe-bonus-claim";
import {
notFoundResponse,
unauthorizedResponse,
withDonkeyAuth,
} from "@/lib/donkey-api-auth";
+// A checkout opened from an offer's claim link names the offer by its token,
+// so the credit that lands is the one the dialog described. No body is a
+// checkout from anywhere else.
+const bodySchema = z.object({ offerToken: z.string().min(1).optional() }).strict();
+
// Start a Stripe Checkout session for a Pro subscription. This route keeps its
// getSession call because it needs the user's email/name.
export const POST = withDonkeyAuth(async (request) => {
@@ -17,6 +24,12 @@ export const POST = withDonkeyAuth(async (request) => {
if (!session) {
return unauthorizedResponse();
}
+ const text = await request.text();
+ const parsed = bodySchema.safeParse(text ? JSON.parse(text) : {});
+ if (!parsed.success) {
+ return NextResponse.json({ error: "Invalid request" }, { status: 400 });
+ }
+ const namedOfferId = parsed.data.offerToken ? verifyCreditOfferToken(parsed.data.offerToken) : null;
// A not-yet-configured price stays a 404 (not 401) so the landing card does
// not treat it as a sign-in prompt.
@@ -30,9 +43,9 @@ export const POST = withDonkeyAuth(async (request) => {
name: session.user.name,
userId: session.user.id,
});
- // A checkout started while the subscribe bonus offer is open carries the
- // offer, so the webhook lands the bonus on the subscription it creates.
- const offer = await openSubscribeBonusOffer(session.user.id);
+ // A checkout started while an offer for subscribing is open carries the
+ // offer, so the webhook lands the credit on the subscription it creates.
+ const offer = await openOfferForSubscribing(session.user.id, namedOfferId);
const stripe = getStripe();
const origin = request.nextUrl.origin;
const checkout = await stripe.checkout.sessions.create({
diff --git a/site/src/app/api/credits/offers/claim/route.ts b/site/src/app/api/credits/offers/claim/route.ts
index 23785222..3e952200 100644
--- a/site/src/app/api/credits/offers/claim/route.ts
+++ b/site/src/app/api/credits/offers/claim/route.ts
@@ -1,15 +1,16 @@
import { NextResponse } from "next/server";
import { z } from "zod";
+import { getActiveProSubscription } from "@/lib/billing/pro-subscription";
import { creditMicrosToString } from "@/lib/credits/amounts";
import { formatUsdPlain } from "@/lib/credits/format-usd";
import { getCreditBalance } from "@/lib/credits/inference";
+import { isLinkClaimedKind, isSubscribeClaimedKind } from "@/lib/credits/offerKinds";
import {
claimCreditOffer,
CreditOfferClosedError,
CreditOfferNotYoursError,
creditOfferOpen,
- MANUAL_OFFER_KIND,
verifyCreditOfferToken,
} from "@/lib/credits/offers";
import { describeCreditLifetime } from "@/lib/email/send-credits-offered";
@@ -21,8 +22,12 @@ const claimRequestSchema = z.object({ token: z.string().min(1) }).strict();
// Describes the offer a claim link names, for the dialog that presents it.
// The token proves the link came from the offer's email; the session has to be
// the offered account's, and a different account is told so before it tries.
-// An offer whose claim window closed unclaimed is gone (410).
+// An offer whose claim window closed unclaimed is gone (410). An offer landed
+// by subscribing is presented to an account that already holds Pro as one it
+// cannot take up (409).
const goneResponse = () => NextResponse.json({ error: "This offer has closed." }, { status: 410 });
+const proHeldResponse = () =>
+ NextResponse.json({ error: "This offer is for accounts without Pro." }, { status: 409 });
export const GET = withDonkeyAuth(async (request) => {
const token = request.nextUrl.searchParams.get("token");
const offerId = token ? verifyCreditOfferToken(token) : null;
@@ -39,10 +44,15 @@ export const GET = withDonkeyAuth(async (request) => {
},
where: { id: offerId },
});
- if (!offer || (offer.kind !== MANUAL_OFFER_KIND && offer.kind !== "promotion_email")) return notFoundResponse();
+ const claim = !offer ? null : isLinkClaimedKind(offer.kind) ? "link" : isSubscribeClaimedKind(offer.kind) ? "subscribe" : null;
+ if (!offer || !claim) return notFoundResponse();
if (offer.userId !== request.donkey.userId) return forbiddenResponse();
if (!offer.claimedAt && !creditOfferOpen(offer, new Date())) return goneResponse();
+ if (!offer.claimedAt && claim === "subscribe" && (await getActiveProSubscription(offer.userId))) {
+ return proHeldResponse();
+ }
return NextResponse.json({
+ claim,
claimed: offer.claimedAt !== null,
closesAt: offer.closesAt?.toISOString() ?? null,
credits: formatUsdPlain(creditMicrosToString(offer.amountMicros)),
diff --git a/site/src/app/cut/app/(home)/settings/_components/ProCard.tsx b/site/src/app/cut/app/(home)/settings/_components/ProCard.tsx
index 03e67449..3ef4a12c 100644
--- a/site/src/app/cut/app/(home)/settings/_components/ProCard.tsx
+++ b/site/src/app/cut/app/(home)/settings/_components/ProCard.tsx
@@ -17,10 +17,9 @@ import {
} from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { activeProPromotion, CUT_PRO } from "@/app/cut/_components/landing/cutPricingPlans";
-import { formatDeadline, minutesLeft } from "@/cut/components/SubscribeBonusPill";
+import { creditLifeClause, formatDeadline, minutesLeft } from "@/cut/components/SubscribeBonusPill";
import { track } from "@/lib/analytics";
import { formatUsd } from "@/lib/credits/format-usd";
-import { formatCreditExpiry } from "@/lib/credits/top-up";
import { useSubscribeBonus } from "@/queries/credits";
import { useAccountConfig } from "@/queries/accountConfig";
@@ -114,18 +113,17 @@ export function ProCard() {
</div>
) : null}
{offer?.status === "claimed" ? (
- <div>Your {formatUsd(offer.dollars)} subscribe bonus landed in your credits.</div>
+ <div>
+ Your {formatUsd(offer.dollars)} {offer.origin === "app" ? "subscribe bonus" : "credit offer"} landed in
+ your credits.
+ </div>
) : null}
</div>
</CardContent>
) : offer && offerOpen ? (
<CardContent className="text-sm text-foreground">
Subscribe for {CUT_PRO.price} by {formatDeadline(offer.closesAt)} and get a one-time{" "}
- {formatUsd(offer.dollars)} in credits
- {offer.creditsExpireAt
- ? `, spendable through ${formatCreditExpiry(new Date(offer.creditsExpireAt))}`
- : ""}
- .
+ {formatUsd(offer.dollars)} in credits{creditLifeClause(offer)}.
</CardContent>
) : null}
<CardFooter className="gap-3">
diff --git a/site/src/app/su/CreditOfferFields.tsx b/site/src/app/su/CreditOfferFields.tsx
new file mode 100644
index 00000000..e26ff59f
--- /dev/null
+++ b/site/src/app/su/CreditOfferFields.tsx
@@ -0,0 +1,106 @@
+"use client";
+
+import { Field } from "@/app/su/Field";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import type { Settings } from "@/lib/config/registry";
+import {
+ CLAIM_URL_PLACEHOLDER,
+ OFFER_CLAIM_NAMES,
+ OFFER_CLAIMS,
+ type CreditOfferTerms,
+ type OfferClaim,
+} from "@/lib/credits/offerTerms";
+import { useSettings } from "@/queries/settings";
+
+// The credit offer an email carries, as one form: a switch that turns the
+// offer on with the default terms, and the terms themselves. A promotion and
+// an outreach note edit the same fields.
+
+const NUMBERS = [
+ ["dollars", "Dollars"],
+ ["claimWindowDays", "Days to claim"],
+ ["expiresAfterDays", "Days the credit lives"],
+] as const;
+
+/** The terms a new offer starts with: the Promotion credit offer setting,
+ * or nothing until the settings have loaded. */
+export function useCreditOfferDefaults(): CreditOfferTerms | undefined {
+ const settings = useSettings();
+ const value = settings.data?.settings.find((row) => row.key === "promotionCreditOffer")?.value as
+ | Settings["promotionCreditOffer"]
+ | undefined;
+ if (!value) return undefined;
+ const { dollars, claimWindowDays, expiresAfterDays, claim } = value;
+ return { dollars, claimWindowDays, expiresAfterDays, claim };
+}
+
+export function CreditOfferFields({
+ value,
+ defaults,
+ onChange,
+ disabled = false,
+ idPrefix = "offer",
+ hint = `Each recipient gets their own link for AI credits; ${CLAIM_URL_PLACEHOLDER} is the link and {{claimBy}} their last day to claim.`,
+}: {
+ value: CreditOfferTerms | null;
+ defaults: CreditOfferTerms | undefined;
+ onChange: (next: CreditOfferTerms | null) => void;
+ disabled?: boolean;
+ idPrefix?: string;
+ hint?: string;
+}) {
+ return (
+ <div className="space-y-3">
+ <div className="flex items-center justify-between gap-3">
+ <div>
+ <Label htmlFor={`${idPrefix}-on`}>Credit offer</Label>
+ <p className="text-xs text-muted-foreground">{hint}</p>
+ </div>
+ <Switch
+ id={`${idPrefix}-on`}
+ checked={value !== null}
+ disabled={disabled || (value === null && !defaults)}
+ onCheckedChange={(on) => onChange(on ? (defaults ?? null) : null)}
+ />
+ </div>
+ {value ? (
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
+ <Field label="Landed by" htmlFor={`${idPrefix}-claim`}>
+ <Select
+ disabled={disabled}
+ value={value.claim}
+ items={OFFER_CLAIM_NAMES}
+ onValueChange={(v) => onChange({ ...value, claim: v as OfferClaim })}
+ >
+ <SelectTrigger id={`${idPrefix}-claim`}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {OFFER_CLAIMS.map((claim) => (
+ <SelectItem key={claim} value={claim}>
+ {OFFER_CLAIM_NAMES[claim]}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+ {NUMBERS.map(([key, label]) => (
+ <Field key={key} label={label} htmlFor={`${idPrefix}-${key}`}>
+ <Input
+ id={`${idPrefix}-${key}`}
+ type="number"
+ min={1}
+ disabled={disabled}
+ value={value[key]}
+ onChange={(e) => onChange({ ...value, [key]: Number(e.target.value) })}
+ />
+ </Field>
+ ))}
+ </div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/site/src/app/su/promotions/PromotionDialog.tsx b/site/src/app/su/promotions/PromotionDialog.tsx
index f83ca9ad..8ed75493 100644
--- a/site/src/app/su/promotions/PromotionDialog.tsx
+++ b/site/src/app/su/promotions/PromotionDialog.tsx
@@ -3,6 +3,7 @@
import { ChevronRight } from "lucide-react";
import { useState } from "react";
+import { CreditOfferFields } from "@/app/su/CreditOfferFields";
import {
AudienceFields,
audienceDraftFrom,
@@ -28,7 +29,7 @@ import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import type { Settings } from "@/lib/config/registry";
import { cn } from "@/lib/utils";
-import { PROMOTION_PLACEHOLDERS } from "@/lib/marketing/placeholders";
+import { isOfferPlaceholder, PROMOTION_PLACEHOLDERS } from "@/lib/marketing/placeholders";
import { BUTTON_MARK } from "@/lib/marketing/promotionCopy";
import {
promotionInputSchema,
@@ -36,7 +37,12 @@ import {
type PromotionSender,
type SegmentCount,
} from "@/lib/marketing/promotionInput";
-import { CLAIM_URL_PLACEHOLDER, type PromotionOffer } from "@/lib/marketing/promotionOfferInput";
+import {
+ CLAIM_URL_PLACEHOLDER,
+ creditOfferTermsIfValid,
+ OFFER_BUTTON_LABELS,
+ type CreditOfferTerms,
+} from "@/lib/credits/offerTerms";
import {
useCountSegment,
useSavePromotion,
@@ -53,7 +59,7 @@ import { useOutreachTemplates, useSaveOutreachTemplate } from "@/queries/outreac
type OfferDefaults = Settings["promotionCreditOffer"];
type Draft = {
- creditOffer: PromotionOffer | null;
+ creditOffer: CreditOfferTerms | null;
name: string;
subject: string;
body: string;
@@ -64,12 +70,13 @@ type Draft = {
excludePromotionIds: string[];
};
-const CLAIM_LABEL = "Claim my AI credits";
+const CLAIM_LABEL_SET = new Set(Object.values(OFFER_BUTTON_LABELS));
-const offerOf = (d: OfferDefaults): PromotionOffer => ({
+const offerOf = (d: OfferDefaults): CreditOfferTerms => ({
dollars: d.dollars,
claimWindowDays: d.claimWindowDays,
expiresAfterDays: d.expiresAfterDays,
+ claim: d.claim,
});
// A new draft starts as a credit promotion on the setting's terms, reaching
@@ -78,7 +85,7 @@ const blank = (defaults: OfferDefaults): Draft => ({
name: "",
subject: "",
body: "",
- ctaLabel: CLAIM_LABEL,
+ ctaLabel: OFFER_BUTTON_LABELS[defaults.claim],
ctaUrl: CLAIM_URL_PLACEHOLDER,
creditOffer: offerOf(defaults),
sender: "bulk",
@@ -99,10 +106,18 @@ const fromSummary = (p: PromotionSummary): Draft => ({
});
// Turning the offer on makes the button the claim link; turning it off takes
-// that button away, since it pointed at nothing else.
-const withOffer = (d: Draft, offer: PromotionOffer | null): Draft => {
+// that button away, since it pointed at nothing else. A label the form wrote
+// for one claim follows a change of claim; one the operator typed stays.
+const withOffer = (d: Draft, offer: CreditOfferTerms | null): Draft => {
if (offer) {
- return { ...d, creditOffer: offer, ctaUrl: CLAIM_URL_PLACEHOLDER, ctaLabel: d.ctaLabel.trim() || CLAIM_LABEL };
+ const label = d.ctaLabel.trim();
+ const written = !label || CLAIM_LABEL_SET.has(label);
+ return {
+ ...d,
+ creditOffer: offer,
+ ctaUrl: CLAIM_URL_PLACEHOLDER,
+ ctaLabel: written ? OFFER_BUTTON_LABELS[offer.claim] : label,
+ };
}
const wasClaim = d.ctaUrl === CLAIM_URL_PLACEHOLDER;
return { ...d, creditOffer: null, ctaUrl: wasClaim ? "" : d.ctaUrl, ctaLabel: wasClaim ? "" : d.ctaLabel };
@@ -122,7 +137,11 @@ function toInput(draft: Draft): unknown {
};
}
-const placeholders = PROMOTION_PLACEHOLDERS.map((k) => `{{${k}}}`).join(", ");
+/** The placeholders the words may use: the offer's only while there is one. */
+const placeholdersFor = (offered: boolean) =>
+ PROMOTION_PLACEHOLDERS.filter((k) => offered || !isOfferPlaceholder(k))
+ .map((k) => `{{${k}}}`)
+ .join(", ");
export function PromotionDialog({
existing,
@@ -185,7 +204,8 @@ export function PromotionDialog({
if (!template) return;
setDraft((current) => {
const next = { ...current, subject: template.subject, body: template.body };
- return template.promotion ? withOffer(next, template.promotion as PromotionOffer) : next;
+ const offer = creditOfferTermsIfValid(template.promotion);
+ return offer ? withOffer(next, offer) : next;
});
};
@@ -351,7 +371,7 @@ export function PromotionDialog({
onChange={(e) => setDraft({ ...draft, body: e.target.value })}
/>
<p className="text-xs text-muted-foreground">
- A blank line starts a new paragraph. {placeholders} fill in per person. A line that is only{" "}
+ A blank line starts a new paragraph. {placeholdersFor(draft.creditOffer !== null)} fill in per person. A line that is only{" "}
{BUTTON_MARK} places the button; without it the button comes last.
</p>
</Field>
@@ -390,46 +410,13 @@ export function PromotionDialog({
</button>
<div id="promo-targeting" className={cn("content-start gap-5", showTargeting ? "grid" : "hidden lg:grid")}>
- <div className="space-y-3">
- <div className="flex items-center justify-between gap-3">
- <div>
- <Label htmlFor="promo-offer">Credit offer</Label>
- <p className="text-xs text-muted-foreground">
- Each recipient gets a claim link for AI credits; the button link becomes {CLAIM_URL_PLACEHOLDER}.
- </p>
- </div>
- <Switch
- id="promo-offer"
- checked={draft.creditOffer !== null}
- disabled={readOnly}
- onCheckedChange={(on) => setDraft(withOffer(draft, on ? offerOf(offerDefaults) : null))}
- />
- </div>
- {draft.creditOffer ? (
- <div className="grid grid-cols-3 gap-3">
- {(
- [
- ["dollars", "Dollars"],
- ["claimWindowDays", "Days to claim"],
- ["expiresAfterDays", "Days the credit lives"],
- ] as const
- ).map(([key, label]) => (
- <Field key={key} label={label} htmlFor={`promo-offer-${key}`}>
- <Input
- id={`promo-offer-${key}`}
- type="number"
- min={1}
- disabled={readOnly}
- value={draft.creditOffer![key]}
- onChange={(e) =>
- setDraft({ ...draft, creditOffer: { ...draft.creditOffer!, [key]: Number(e.target.value) } })
- }
- />
- </Field>
- ))}
- </div>
- ) : null}
- </div>
+ <CreditOfferFields
+ idPrefix="promo-offer"
+ value={draft.creditOffer}
+ defaults={offerOf(offerDefaults)}
+ disabled={readOnly}
+ onChange={(offer) => setDraft(withOffer(draft, offer))}
+ />
<AudienceFields value={draft.audience} onChange={setAudience} countries={false} disabled={readOnly} />
diff --git a/site/src/cut/components/ClaimCreditsDialog.tsx b/site/src/cut/components/ClaimCreditsDialog.tsx
index 966c51ae..107a5d3a 100644
--- a/site/src/cut/components/ClaimCreditsDialog.tsx
+++ b/site/src/cut/components/ClaimCreditsDialog.tsx
@@ -8,6 +8,8 @@
// start the credit's lifetime before the person saw it. The address is clean
// from the first paint, so a reload, a back step or a forward step opens
// nothing; the link itself opens a claimed offer as the credit it landed.
+// An offer landed by subscribing has a Subscribe button in place of Claim:
+// the press starts the Pro checkout, which carries the offer to the webhook.
import { useSearchParams } from "next/navigation";
import { Loader2, Sparkle } from "lucide-react";
import { useEffect, useState } from "react";
@@ -20,9 +22,12 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
+import { CUT_PRO } from "@/app/cut/_components/landing/cutPricingPlans";
import { useEngineUser } from "@/cut/lib/backend/hooks";
+import { track } from "@/lib/analytics";
import { formatCreditExpiry } from "@/lib/credits/top-up";
import { ApiError } from "@/queries/apiClient";
+import { useStartCheckout } from "@/queries/billing";
import { useClaimCreditOffer, useCreditOffer } from "@/queries/credits";
const PARAM = "claim";
@@ -61,6 +66,16 @@ function AddressedDialog() {
function OpenDialog({ token, onClose }: { token: string; onClose: () => void }) {
const offer = useCreditOffer(token);
const claim = useClaimCreditOffer();
+ const checkout = useStartCheckout();
+ const subscribe = () => {
+ if (!offer.data) return;
+ track("subscribe_bonus_checkout_started", {
+ dollars: Number(offer.data.credits.replace(/[^0-9.]/g, "")),
+ minutesLeft: offer.data.closesAt ? Math.max(0, Math.ceil((Date.parse(offer.data.closesAt) - Date.now()) / 60_000)) : 0,
+ source: "email",
+ });
+ checkout.mutate({ offerToken: token }, { onSuccess: (result) => window.location.assign(result.url) });
+ };
// The dialog opens at once, checking the link, at the size it keeps: the
// body reserves two lines and every state ends in one row of buttons.
const done = claim.data ?? (offer.data?.claimed ? { expiresAt: offer.data.expiresAt } : null);
@@ -85,19 +100,40 @@ function OpenDialog({ token, onClose }: { token: string; onClose: () => void })
);
} else if (offer.isError) {
const status = offer.error instanceof ApiError ? offer.error.status : null;
- title = status === 410 ? "This offer has expired" : "This link is no longer valid";
+ title =
+ status === 410 ? "This offer has expired" : status === 409 ? "You already have Pro" : "This link is no longer valid";
body =
status === 403
? "This offer belongs to a different account. Sign in with the address the email was sent to."
: status === 410
? "The claim window for this offer has closed."
- : "The offer it pointed to is gone.";
+ : status === 409
+ ? "This offer is for accounts without a Pro subscription."
+ : "The offer it pointed to is gone.";
footer = <Button onClick={onClose}>OK</Button>;
} else if (done) {
body = `${offer.data.credits} in AI credits is on your account.${
done.expiresAt ? ` It expires ${formatCreditExpiry(new Date(done.expiresAt))}.` : ""
}`;
footer = <Button onClick={onClose}>Start editing</Button>;
+ } else if (offer.data.claim === "subscribe") {
+ title = `Get ${offer.data.credits} in credits with Pro`;
+ body = `Subscribe to Pro for ${CUT_PRO.price}${
+ offer.data.closesAt ? ` by ${formatCreditExpiry(new Date(offer.data.closesAt))}` : ""
+ } and a one-time ${offer.data.credits} in AI credits lands in your account${
+ offer.data.lifetime ? `, good for ${offer.data.lifetime}` : ""
+ }.`;
+ footer = (
+ <>
+ <Button variant="ghost" onClick={onClose}>
+ Not now
+ </Button>
+ <Button disabled={checkout.isPending} onClick={subscribe}>
+ {checkout.isPending && <Loader2 className="animate-spin" data-icon="inline-start" />}
+ Subscribe to Pro
+ </Button>
+ </>
+ );
} else {
body = `You have ${offer.data.credits} in AI credits. They’re waiting for you.${
offer.data.lifetime ? ` Once claimed, it’s good for ${offer.data.lifetime}.` : ""
@@ -126,6 +162,9 @@ function OpenDialog({ token, onClose }: { token: string; onClose: () => void })
<DialogDescription className="min-h-12 text-base">{body}</DialogDescription>
</DialogHeader>
<DialogFooter className="mx-0 mb-0 items-center border-0 bg-transparent p-0">
+ {checkout.isError && (
+ <p className="text-sm text-destructive sm:mr-auto">Billing is unavailable right now.</p>
+ )}
{claim.isError && (
<p className="text-sm text-destructive sm:mr-auto">
{claim.error instanceof ApiError && claim.error.status === 403
diff --git a/site/src/cut/components/SubscribeBonusPill.tsx b/site/src/cut/components/SubscribeBonusPill.tsx
index a44d1aad..b6aed54a 100644
--- a/site/src/cut/components/SubscribeBonusPill.tsx
+++ b/site/src/cut/components/SubscribeBonusPill.tsx
@@ -1,8 +1,10 @@
"use client";
-// The subscribe bonus in the top bar: while the account's offer is open, a
-// pill names the credit and how long is left, and opens the offer itself. The
-// offer opens once on its own the first time this tab sees it.
+// The offer for subscribing in the top bar: while the account's offer is
+// open, a pill names the credit and how long is left, and opens the offer
+// itself. A bonus the app made opens once on its own the first time this tab
+// sees it; an offer that came by email was presented by the email, so the
+// pill only keeps it in view.
import { useEffect, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { Gift } from "lucide-react";
@@ -34,12 +36,20 @@ export function minutesLeft(closesAt: string, now: number): number {
return Math.max(0, Math.ceil((Date.parse(closesAt) - now) / 60_000));
}
-/** "5h left" past the hour, "40m left" inside it. */
+/** "3d left" past the day, "5h left" past the hour, "40m left" inside it. */
export function timeLeftLabel(minutes: number): string {
+ if (minutes >= 24 * 60) return `${Math.floor(minutes / (24 * 60))}d left`;
if (minutes >= 60) return `${Math.floor(minutes / 60)}h left`;
return `${minutes}m left`;
}
+/** How long the landed credit lasts, as a clause after the amount. */
+export function creditLifeClause(offer: { creditsExpireAt: string | null; creditsLifetime: string | null }): string {
+ if (offer.creditsExpireAt) return `, spendable through ${formatCreditExpiry(new Date(offer.creditsExpireAt))}`;
+ if (offer.creditsLifetime) return `, good for ${offer.creditsLifetime}`;
+ return "";
+}
+
/** The deadline as people read it in their own clock: "Sep 8, 3:14 PM". */
export function formatDeadline(closesAt: string): string {
return new Date(closesAt).toLocaleString("en-US", {
@@ -80,8 +90,9 @@ export function SubscribeBonusPill() {
function OpenOffer({ offer }: { offer: SubscribeBonus }) {
const queryClient = useQueryClient();
const checkout = useStartCheckout();
- // The offer presents itself once: the first time a tab sees it open.
- const [open, setOpen] = useState(() => !seenBefore(offer));
+ // A bonus the app made presents itself once: the first time a tab sees it
+ // open.
+ const [open, setOpen] = useState(() => offer.origin === "app" && !seenBefore(offer));
const [now, setNow] = useState(() => Date.now());
// The clock the label reads; a minute is as fine as the label gets.
@@ -89,9 +100,10 @@ function OpenOffer({ offer }: { offer: SubscribeBonus }) {
const id = setInterval(() => setNow(Date.now()), 60_000);
return () => clearInterval(id);
}, []);
- // The first showing is recorded, so the next load leaves the pill alone.
+ // The first showing of a bonus is recorded, so the next load leaves the
+ // pill alone.
useEffect(() => {
- if (seenBefore(offer)) return;
+ if (offer.origin !== "app" || seenBefore(offer)) return;
markSeen(offer);
track("subscribe_bonus_offered", { dollars: Number(offer.dollars) });
}, [offer]);
@@ -132,12 +144,9 @@ function OpenOffer({ offer }: { offer: SubscribeBonus }) {
<DialogHeader>
<DialogTitle>Get {dollars} in credits with Pro</DialogTitle>
<DialogDescription>
- You have used half of your signup credits. Subscribe to Pro for {CUT_PRO.price} by{" "}
- {formatDeadline(offer.closesAt)} and a one-time {dollars} in credits lands in your account
- {offer.creditsExpireAt
- ? `, spendable through ${formatCreditExpiry(new Date(offer.creditsExpireAt))}`
- : ""}
- .
+ {offer.origin === "app" ? "You have used half of your signup credits. " : ""}
+ Subscribe to Pro for {CUT_PRO.price} by {formatDeadline(offer.closesAt)} and a one-time {dollars} in
+ credits lands in your account{creditLifeClause(offer)}.
</DialogDescription>
</DialogHeader>
<DialogFooter>
diff --git a/site/src/lib/analytics.ts b/site/src/lib/analytics.ts
index 903e03d0..f7fd1606 100644
--- a/site/src/lib/analytics.ts
+++ b/site/src/lib/analytics.ts
@@ -58,7 +58,7 @@ export type AnalyticsEvents = {
};
// The subscribe bonus: shown once when the offer opens, and taken up.
subscribe_bonus_offered: { dollars: number };
- subscribe_bonus_checkout_started: { dollars: number; minutesLeft: number; source: "editor" | "settings" };
+ subscribe_bonus_checkout_started: { dollars: number; minutesLeft: number; source: "editor" | "settings" | "email" };
// Billing (settings).
pro_checkout_started: void;
billing_portal_opened: void;
diff --git a/site/src/lib/billing/pro-subscription.ts b/site/src/lib/billing/pro-subscription.ts
index 4888e559..e72c97ac 100644
--- a/site/src/lib/billing/pro-subscription.ts
+++ b/site/src/lib/billing/pro-subscription.ts
@@ -9,7 +9,7 @@ import { promotedAllowanceMicros } from "@/lib/billing/allowance-promotion";
import { getGlobalSetting } from "@/lib/config/effective";
import { creditMicrosPerCent, zeroCreditMicros } from "@/lib/credits/amounts";
import { grantCredits } from "@/lib/credits/inference";
-import { claimSubscribeBonus, SUBSCRIBE_BONUS_METADATA_KEY } from "@/lib/credits/subscribe-bonus-claim";
+import { claimOfferBySubscribing, SUBSCRIBE_BONUS_METADATA_KEY } from "@/lib/credits/subscribe-bonus-claim";
import { prisma } from "@/lib/prisma";
// Donkey Pro: the Mac app subscription.
@@ -131,11 +131,11 @@ export async function syncProSubscription(
where: { userId },
});
- // A subscription whose checkout was taken up from the subscribe bonus
- // offer names the offer; the claim dedupes, so every later event is a no-op.
+ // A subscription whose checkout was taken up from a credit offer names the
+ // offer; the claim dedupes, so every later event is a no-op.
const offerId = subscription.metadata?.[SUBSCRIBE_BONUS_METADATA_KEY];
if (isActiveProStatus(subscription.status) && offerId) {
- await claimSubscribeBonus(userId, offerId);
+ await claimOfferBySubscribing(userId, offerId);
}
// Grant the period's included allowance once it is active and the period is
diff --git a/site/src/lib/config/registry.ts b/site/src/lib/config/registry.ts
index 0df7b935..5f2df40d 100644
--- a/site/src/lib/config/registry.ts
+++ b/site/src/lib/config/registry.ts
@@ -9,7 +9,7 @@ import {
type SettingsOf,
} from "@donkeycut/abexp";
import { z } from "zod";
-import { promotionOfferSchema } from "@/lib/marketing/promotionOfferInput";
+import { creditOfferTermsSchema } from "@/lib/credits/offerTerms";
import { DEFAULT_EMAIL_PRIORITIES, EMAIL_KIND_IDS } from "@/lib/email/kindIds";
import { maxCreditGrantDollars, maxCreditGrantExpiryDays } from "@/lib/credits/top-up";
@@ -32,8 +32,8 @@ function validTimeZone(zone: string): boolean {
export const SETTINGS = defineSettings({
promotionCreditOffer: {
- schema: promotionOfferSchema.extend({ minimumAccountAgeDays: z.number().int().min(1).max(36500) }).strict(),
- default: { dollars: 15, claimWindowDays: 3, expiresAfterDays: 28, minimumAccountAgeDays: 7 },
+ schema: creditOfferTermsSchema.extend({ minimumAccountAgeDays: z.number().int().min(1).max(36500) }).strict(),
+ default: { dollars: 15, claimWindowDays: 3, expiresAfterDays: 28, claim: "link", minimumAccountAgeDays: 7 },
public: false,
title: "Promotion credit offer",
description: "Default credit offer and minimum account age for new promotion drafts. Saved drafts keep their terms.",
diff --git a/site/src/lib/credits/offerKinds.ts b/site/src/lib/credits/offerKinds.ts
new file mode 100644
index 00000000..9a3e97d7
--- /dev/null
+++ b/site/src/lib/credits/offerKinds.ts
@@ -0,0 +1,34 @@
+import type { OfferClaim } from "@/lib/credits/offerTerms";
+
+// The kinds of credit offer, and what lands each. A leaf module, so the
+// modules that make and claim offers can share the names without a cycle.
+
+// The kind su makes by hand, claimed from its email link.
+export const MANUAL_OFFER_KIND = "manual";
+// The kinds an email with offer terms makes, one per claim: the link in the
+// email, or a Pro subscription started inside the window. An id is the
+// email's scope and the account.
+export const PROMOTION_OFFER_KIND = "promotion_email";
+export const PROMOTION_SUBSCRIBE_OFFER_KIND = "promotion_subscribe";
+export const PROMOTION_OFFER_KINDS = [PROMOTION_OFFER_KIND, PROMOTION_SUBSCRIBE_OFFER_KIND] as const;
+// The subscribe bonus the app opens on its own; landed by subscribing.
+export const SUBSCRIBE_BONUS_KIND = "subscribe_bonus";
+
+export function promotionOfferKind(claim: OfferClaim): string {
+ return claim === "subscribe" ? PROMOTION_SUBSCRIBE_OFFER_KIND : PROMOTION_OFFER_KIND;
+}
+
+// The kinds a claim link lands: the ones su sends by hand and the ones a
+// promotion mails with a link. Every other kind lands from the act it rewards.
+export const LINK_CLAIMED_KINDS = [MANUAL_OFFER_KIND, PROMOTION_OFFER_KIND] as const;
+
+export function isLinkClaimedKind(kind: string): boolean {
+ return (LINK_CLAIMED_KINDS as readonly string[]).includes(kind);
+}
+
+// The kinds a subscription lands.
+export const SUBSCRIBE_CLAIMED_KINDS = [SUBSCRIBE_BONUS_KIND, PROMOTION_SUBSCRIBE_OFFER_KIND] as const;
+
+export function isSubscribeClaimedKind(kind: string): boolean {
+ return (SUBSCRIBE_CLAIMED_KINDS as readonly string[]).includes(kind);
+}
diff --git a/site/src/lib/credits/offerTerms.ts b/site/src/lib/credits/offerTerms.ts
new file mode 100644
index 00000000..dae25e20
--- /dev/null
+++ b/site/src/lib/credits/offerTerms.ts
@@ -0,0 +1,54 @@
+import { z } from "zod";
+
+// The terms of a credit offer an email carries, as su writes them: how much,
+// what lands it, how long the person has to take it up, and how long the
+// credit lives once it lands. A promotion to a segment and an outreach note
+// to one person share these terms, the placeholders that name the offer in
+// the words, and the form that edits them. Client-safe: zod only.
+
+// What lands the credit: the claim link in the email, or a Pro subscription
+// started inside the claim window.
+export const OFFER_CLAIMS = ["link", "subscribe"] as const;
+export type OfferClaim = (typeof OFFER_CLAIMS)[number];
+
+export const OFFER_CLAIM_NAMES: Record<OfferClaim, string> = {
+ link: "The claim link",
+ subscribe: "Subscribing to Pro",
+};
+
+// The button label an email starts with for each claim.
+export const OFFER_BUTTON_LABELS: Record<OfferClaim, string> = {
+ link: "Claim my AI credits",
+ subscribe: "Subscribe to Pro",
+};
+
+export const creditOfferTermsSchema = z
+ .object({
+ dollars: z.number().int().min(1).max(10000),
+ claimWindowDays: z.number().int().min(1).max(365),
+ expiresAfterDays: z.number().int().min(1).max(3650),
+ claim: z.enum(OFFER_CLAIMS).default("link"),
+ })
+ .strict();
+
+export type CreditOfferTerms = z.infer<typeof creditOfferTermsSchema>;
+
+/** Stored terms, or null for none. Throws on a row that no longer parses. */
+export function creditOfferTermsOf(value: unknown): CreditOfferTerms | null {
+ return value == null ? null : creditOfferTermsSchema.parse(value);
+}
+
+/** Stored terms when they parse, else null: what a form loads from a template. */
+export function creditOfferTermsIfValid(value: unknown): CreditOfferTerms | null {
+ if (value == null) return null;
+ const parsed = creditOfferTermsSchema.safeParse(value);
+ return parsed.success ? parsed.data : null;
+}
+
+/** What the words of an email with an offer may name: the recipient's own
+ * claim link, and their last day to claim as people read it. */
+export type OfferVars = { claimUrl: string; claimBy: string };
+
+export const OFFER_PLACEHOLDERS = ["claimUrl", "claimBy"] as const satisfies readonly (keyof OfferVars)[];
+
+export const CLAIM_URL_PLACEHOLDER = "{{claimUrl}}";
diff --git a/site/src/lib/credits/offers.ts b/site/src/lib/credits/offers.ts
index 3d4906c8..8cd2c74d 100644
--- a/site/src/lib/credits/offers.ts
+++ b/site/src/lib/credits/offers.ts
@@ -5,7 +5,9 @@ import { CUT_APP_BASE } from "@/cut/lib/appBase";
import { getGlobalSetting } from "@/lib/config/effective";
import { DONKEYCUT_CANONICAL } from "@/cut/lib/hosts";
import { grantCredits } from "@/lib/credits/inference";
-import { creditGrantExpiry } from "@/lib/credits/top-up";
+import { isLinkClaimedKind, MANUAL_OFFER_KIND, promotionOfferKind } from "@/lib/credits/offerKinds";
+import type { CreditOfferTerms, OfferVars } from "@/lib/credits/offerTerms";
+import { creditGrantExpiry, formatCreditExpiry } from "@/lib/credits/top-up";
import { deliverEmail } from "@/lib/email/outbox";
import { creditsOfferedIdempotencyKey } from "@/lib/email/send-credits-offered";
import { prisma } from "@/lib/prisma";
@@ -15,10 +17,6 @@ import { prisma } from "@/lib/prisma";
// unsubscribe link. The claim itself also needs the offered account's session.
const TOKEN_DOMAIN = "donkey-credit-offer-v1";
-// The kind su makes by hand; a promotion's offers carry the promotion's key.
-export const MANUAL_OFFER_KIND = "manual";
-// The kind of an offer a promotion email made; its id is `${promotionId}:${userId}`.
-export const PROMOTION_OFFER_KIND = "promotion_email";
function signature(offerId: string): Buffer {
const secret = process.env.BETTER_AUTH_SECRET;
@@ -135,11 +133,11 @@ export async function landCreditOffer(
return { grant: landed, offer: claimed };
}
-// Claims an offer from its email link: the ones su sends by hand and the ones
-// a promotion mails. Every other kind lands from the act it rewards.
+// Claims an offer from its email link. Every other kind lands from the act
+// it rewards.
export async function claimCreditOffer(offerId: string, userId: string) {
const offer = await prisma.creditOffer.findUnique({ where: { id: offerId } });
- if (!offer || (offer.kind !== MANUAL_OFFER_KIND && offer.kind !== PROMOTION_OFFER_KIND)) return null;
+ if (!offer || !isLinkClaimedKind(offer.kind)) return null;
if (offer.userId !== userId) throw new CreditOfferNotYoursError();
if (!offer.claimedAt && !creditOfferOpen(offer, new Date())) throw new CreditOfferClosedError();
return landCreditOffer(offer, {
@@ -149,30 +147,44 @@ export async function claimCreditOffer(offerId: string, userId: string) {
});
}
-export async function createPromotionCreditOffer(input: {
- promotionId: string;
+/** The offer an email with terms makes for one recipient, and what its
+ * words fill in. The id is the email's scope and the account, so the real
+ * send, the test send and a retry share one row and one link; the claim
+ * window runs from the first making. An unclaimed row takes the terms as
+ * they are now, so a test sent after a change of terms tests the change; a
+ * claimed row is what landed and stays. A promotion's scope is its id, an
+ * outreach note's names the row and the attempt. */
+export async function createTermsCreditOffer(input: {
+ scope: string;
userId: string;
- amountDollars: number;
- claimWindowDays: number;
- expiresAfterDays: number;
+ terms: CreditOfferTerms;
offeredByUserId: string | null;
now?: Date;
-}) {
+}): Promise<{ offer: CreditOffer; vars: OfferVars }> {
const now = input.now ?? new Date();
- const offerId = `${input.promotionId}:${input.userId}`;
- const offer = await prisma.creditOffer.upsert({
- where: { id: offerId },
- create: {
- id: offerId,
- userId: input.userId,
- kind: PROMOTION_OFFER_KIND,
- amountMicros: BigInt(input.amountDollars) * BigInt(1_000_000),
- expiresAfterDays: input.expiresAfterDays,
- closesAt: new Date(now.getTime() + input.claimWindowDays * 86_400_000),
- description: "Promotional AI credits",
- offeredByUserId: input.offeredByUserId,
- },
- update: {},
- });
- return { offer, claimUrl: creditOfferClaimUrl(offer.id) };
+ const offerId = `${input.scope}:${input.userId}`;
+ const terms = {
+ kind: promotionOfferKind(input.terms.claim),
+ amountMicros: BigInt(input.terms.dollars) * BigInt(1_000_000),
+ expiresAfterDays: input.terms.expiresAfterDays,
+ offeredByUserId: input.offeredByUserId,
+ };
+ const existing = await prisma.creditOffer.findUnique({ where: { id: offerId } });
+ const offer = existing
+ ? existing.claimedAt
+ ? existing
+ : await prisma.creditOffer.update({ data: terms, where: { id: offerId } })
+ : await prisma.creditOffer.create({
+ data: {
+ id: offerId,
+ userId: input.userId,
+ closesAt: new Date(now.getTime() + input.terms.claimWindowDays * 86_400_000),
+ description: "Promotional AI credits",
+ ...terms,
+ },
+ });
+ return {
+ offer,
+ vars: { claimUrl: creditOfferClaimUrl(offer.id), claimBy: formatCreditExpiry(offer.closesAt ?? offer.createdAt) },
+ };
}
diff --git a/site/src/lib/credits/subscribe-bonus-claim.ts b/site/src/lib/credits/subscribe-bonus-claim.ts
index 2ef9cc76..f1830c89 100644
--- a/site/src/lib/credits/subscribe-bonus-claim.ts
+++ b/site/src/lib/credits/subscribe-bonus-claim.ts
@@ -1,34 +1,68 @@
+import type { CreditOffer } from "@/generated/prisma/client";
+import { isSubscribeClaimedKind, SUBSCRIBE_BONUS_KIND, SUBSCRIBE_CLAIMED_KINDS } from "@/lib/credits/offerKinds";
import { creditOfferOpen, landCreditOffer } from "@/lib/credits/offers";
import { prisma } from "@/lib/prisma";
-// The subscribe bonus lands here, from the subscription webhook. A Pro
-// checkout started while the account's offer was open carries the offer's
-// id on the subscription it creates, so the claim is the checkout the person
-// took up from the offer, however long Stripe took. The grant keys on the
-// account, so the bonus lands once however many webhooks there are.
+// Credit that lands from a Pro subscription: the subscribe bonus the app opens
+// on its own, and a promotion emailed with a subscribe claim. A Pro checkout
+// started while such an offer is open carries the offer's id on the
+// subscription it creates, so the claim is the checkout the person took up
+// from the offer, however long Stripe took. The webhook lands it here.
-// The offer's kind, and the source of the grant it lands as.
-export const SUBSCRIBE_BONUS_KIND = "subscribe_bonus";
+// The source every subscription-landed grant carries.
export const SUBSCRIBE_BONUS_SOURCE = "subscribe_bonus";
// The subscription metadata key the checkout writes and the webhook reads.
export const SUBSCRIBE_BONUS_METADATA_KEY = "creditOfferId";
-/** The account's offer if it can be taken up right now. */
-export async function openSubscribeBonusOffer(userId: string, now = new Date()) {
- const offer = await prisma.creditOffer.findFirst({
- where: { userId, kind: SUBSCRIBE_BONUS_KIND },
+type Candidate = { amountMicros: bigint; claimedAt: Date | null; closesAt: Date | null; createdAt: Date };
+
+/** Of an account's offers, the one a subscription lands now: one per
+ * subscription, the largest open one, the earliest made among equals. */
+export function bestOfferForSubscribing<T extends Candidate>(offers: T[], now: Date): T | null {
+ let best: T | null = null;
+ for (const offer of offers) {
+ if (!creditOfferOpen(offer, now)) continue;
+ if (
+ !best ||
+ offer.amountMicros > best.amountMicros ||
+ (offer.amountMicros === best.amountMicros && offer.createdAt < best.createdAt)
+ ) {
+ best = offer;
+ }
+ }
+ return best;
+}
+
+/** Every offer of the account that a subscription can land, oldest first. */
+export function findOffersForSubscribing(userId: string) {
+ return prisma.creditOffer.findMany({
+ where: { userId, kind: { in: [...SUBSCRIBE_CLAIMED_KINDS] } },
orderBy: { createdAt: "asc" },
});
- return offer && creditOfferOpen(offer, now) ? offer : null;
}
-export async function claimSubscribeBonus(userId: string, offerId: string) {
- const offer = await prisma.creditOffer.findUnique({ where: { id: offerId } });
- if (!offer || offer.userId !== userId || offer.kind !== SUBSCRIBE_BONUS_KIND) return null;
- return landCreditOffer(offer, {
- description: "Pro subscribe bonus",
+/** The offer a checkout started now carries: the one the person was looking
+ * at, when it names one that is open and theirs; else the one the app shows,
+ * so the dialog and the landing always agree. */
+export async function openOfferForSubscribing(userId: string, offerId: string | null, now = new Date()) {
+ const offers = await findOffersForSubscribing(userId);
+ const named = offerId ? offers.find((offer) => offer.id === offerId) : undefined;
+ return named && creditOfferOpen(named, now) ? named : bestOfferForSubscribing(offers, now);
+}
+
+/** The grant an offer lands as. The bonus keys on the account, so it lands
+ * once however many offers a race opened; a promotion's keys on the offer. */
+function grantFor(offer: CreditOffer) {
+ return {
+ description: offer.kind === SUBSCRIBE_BONUS_KIND ? "Pro subscribe bonus" : "Promotional AI credits",
source: SUBSCRIBE_BONUS_SOURCE,
- sourceId: `subscribe-bonus:${userId}`,
- });
+ sourceId: offer.kind === SUBSCRIBE_BONUS_KIND ? `subscribe-bonus:${offer.userId}` : `offer:${offer.id}`,
+ };
+}
+
+export async function claimOfferBySubscribing(userId: string, offerId: string) {
+ const offer = await prisma.creditOffer.findUnique({ where: { id: offerId } });
+ if (!offer || offer.userId !== userId || !isSubscribeClaimedKind(offer.kind)) return null;
+ return landCreditOffer(offer, grantFor(offer));
}
diff --git a/site/src/lib/credits/subscribe-bonus.test.ts b/site/src/lib/credits/subscribe-bonus.test.ts
index 5714a908..97216513 100644
--- a/site/src/lib/credits/subscribe-bonus.test.ts
+++ b/site/src/lib/credits/subscribe-bonus.test.ts
@@ -2,9 +2,42 @@ import { describe, expect, test } from "bun:test";
import { creditStringToMicros } from "./amounts";
import { creditOutlivesWindow, crossedSpentShare, endOfUtcDay, subscribeBonusStatus } from "./subscribe-bonus";
+import { bestOfferForSubscribing } from "./subscribe-bonus-claim";
const usd = (s: string) => creditStringToMicros(s);
+const offer = (id: string, dollars: string, at: string, rest: Partial<{ claimedAt: Date; closesAt: Date }> = {}) => ({
+ id,
+ amountMicros: usd(dollars),
+ createdAt: new Date(at),
+ claimedAt: rest.claimedAt ?? null,
+ closesAt: rest.closesAt ?? null,
+});
+
+describe("the offer a subscription lands", () => {
+ const now = new Date("2026-09-12T12:00:00Z");
+
+ test("is the largest open one", () => {
+ const bonus = offer("bonus", "10", "2026-09-01T00:00:00Z");
+ const promotion = offer("promo:u", "60", "2026-09-10T00:00:00Z");
+ expect(bestOfferForSubscribing([bonus, promotion], now)?.id).toBe("promo:u");
+ });
+
+ test("the earliest made among equals", () => {
+ const first = offer("first", "10", "2026-09-01T00:00:00Z");
+ const second = offer("second", "10", "2026-09-02T00:00:00Z");
+ expect(bestOfferForSubscribing([second, first], now)?.id).toBe("first");
+ });
+
+ test("never one that closed or already landed", () => {
+ const closed = offer("closed", "100", "2026-09-01T00:00:00Z", { closesAt: new Date("2026-09-02T00:00:00Z") });
+ const landed = offer("landed", "100", "2026-09-01T00:00:00Z", { claimedAt: new Date("2026-09-03T00:00:00Z") });
+ const open = offer("open", "5", "2026-09-01T00:00:00Z", { closesAt: new Date("2026-09-30T00:00:00Z") });
+ expect(bestOfferForSubscribing([closed, landed, open], now)?.id).toBe("open");
+ expect(bestOfferForSubscribing([closed, landed], now)).toBeNull();
+ });
+});
+
describe("the subscribe bonus", () => {
test("opens once half of the signup grant is spent", () => {
const grant = { originalAmountMicros: usd("25"), remainingAmountMicros: usd("12.5") };
diff --git a/site/src/lib/credits/subscribe-bonus.ts b/site/src/lib/credits/subscribe-bonus.ts
index 4bba9f45..0c4db2b0 100644
--- a/site/src/lib/credits/subscribe-bonus.ts
+++ b/site/src/lib/credits/subscribe-bonus.ts
@@ -3,25 +3,35 @@ import { getActiveProSubscription } from "@/lib/billing/pro-subscription";
import { getSetting, type ConfigContext } from "@/lib/config/effective";
import { creditMicrosToString, creditStringToMicros, zeroCreditMicros } from "@/lib/credits/amounts";
import { creditOfferOpen } from "@/lib/credits/offers";
-import { SUBSCRIBE_BONUS_KIND } from "@/lib/credits/subscribe-bonus-claim";
+import { SUBSCRIBE_BONUS_KIND } from "@/lib/credits/offerKinds";
+import { bestOfferForSubscribing, findOffersForSubscribing } from "@/lib/credits/subscribe-bonus-claim";
+import { describeCreditLifetime } from "@/lib/email/send-credits-offered";
import { prisma } from "@/lib/prisma";
// The subscribe bonus: an account that has spent enough of its signup grant
// is offered credit for subscribing to Pro within a window. The offer is a
// credit offer of this kind, opened on the first read that finds the account
// past the share; it lands from the subscription webhook
-// (src/lib/credits/subscribe-bonus-claim.ts).
+// (src/lib/credits/subscribe-bonus-claim.ts). The app reads one offer for
+// subscribing at a time, and a promotion emailed with a subscribe claim is
+// read through the same view.
export const SIGNUP_GRANT_SOURCE = "signup";
export type SubscribeBonusStatus = "open" | "closed" | "claimed";
export type SubscribeBonusView = {
+ // Where the offer reached the person: the app opened the bonus on its own,
+ // a promotion came by email.
+ origin: "app" | "email";
// USD, as a credit string.
dollars: string;
openedAt: string;
closesAt: string;
+ // The credit's life once it lands: a fixed last moment, or a span from the
+ // claim as people read it ("a month"). Both null keeps it forever.
creditsExpireAt: string | null;
+ creditsLifetime: string | null;
status: SubscribeBonusStatus;
};
@@ -54,39 +64,44 @@ export function subscribeBonusStatus(
export function subscribeBonusView(offer: CreditOffer, facts: { now: Date; pro: boolean }): SubscribeBonusView {
return {
+ origin: offer.kind === SUBSCRIBE_BONUS_KIND ? "app" : "email",
dollars: creditMicrosToString(offer.amountMicros),
openedAt: offer.createdAt.toISOString(),
closesAt: (offer.closesAt ?? offer.createdAt).toISOString(),
creditsExpireAt: offer.expiresAt?.toISOString() ?? null,
+ creditsLifetime: offer.expiresAt ? null : describeCreditLifetime(offer.expiresAfterDays),
status: subscribeBonusStatus(offer, facts),
};
}
+/** The offer the app shows, of the account's offers for subscribing: the one
+ * a checkout would carry while any is open; past that, the latest to land,
+ * so the settings card can say so; past that, the latest to close. */
+export function shownOfferForSubscribing(offers: CreditOffer[], now: Date): CreditOffer | null {
+ const open = bestOfferForSubscribing(offers, now);
+ if (open) return open;
+ const latest = (rows: CreditOffer[]) =>
+ rows.reduce<CreditOffer | null>((best, row) => (!best || row.createdAt > best.createdAt ? row : best), null);
+ return latest(offers.filter((o) => o.claimedAt !== null)) ?? latest(offers);
+}
+
/** Whether credit expiring at the day's end outlives the whole window, so a
* subscription at the last minute of the window still lands live credit. */
export function creditOutlivesWindow(expiresAt: Date | null, closesAt: Date): boolean {
return expiresAt === null || expiresAt.getTime() > closesAt.getTime();
}
-/** The account's offer of this kind: the earliest, so two first reads that
- * raced agree on which one stands. */
-export function findSubscribeBonusOffer(userId: string) {
- return prisma.creditOffer.findFirst({
- where: { userId, kind: SUBSCRIBE_BONUS_KIND },
- orderBy: { createdAt: "asc" },
- });
-}
-
-/** The account's offer as it stands, opening it when the account has just
- * crossed the share. Null while there is nothing to offer: the setting makes
- * no offer for this account, the account holds Pro, or the signup grant is
- * not yet spent far enough. */
+/** The account's offer for subscribing as it stands, opening the subscribe
+ * bonus when the account has just crossed the share. Null while there is
+ * nothing to offer: no promotion reached the account, the setting makes no
+ * bonus for it, the account holds Pro, or the signup grant is not yet spent
+ * far enough. */
export async function readSubscribeBonusOffer(ctx: ConfigContext, now = new Date()): Promise<SubscribeBonusView | null> {
if (!ctx.hasAccount) return null;
- // The indexed reads come first: the offer row, then the two facts that rule
+ // The indexed reads come first: the offer rows, then the two facts that rule
// most accounts out before the configuration is resolved.
- const [existing, pro, grant] = await Promise.all([
- findSubscribeBonusOffer(ctx.userId),
+ const [offers, pro, grant] = await Promise.all([
+ findOffersForSubscribing(ctx.userId),
getActiveProSubscription(ctx.userId),
prisma.userCreditGrant.findFirst({
where: { userId: ctx.userId, source: SIGNUP_GRANT_SOURCE },
@@ -94,23 +109,27 @@ export async function readSubscribeBonusOffer(ctx: ConfigContext, now = new Date
}),
]);
const facts = { now, pro: pro !== null };
- if (existing) return subscribeBonusView(existing, facts);
- if (pro || !grant || grant.remainingAmountMicros >= grant.originalAmountMicros) return null;
+ const shown = () => {
+ const offer = shownOfferForSubscribing(offers, now);
+ return offer ? subscribeBonusView(offer, facts) : null;
+ };
+ if (offers.some((o) => o.kind === SUBSCRIBE_BONUS_KIND)) return shown();
+ if (pro || !grant || grant.remainingAmountMicros >= grant.originalAmountMicros) return shown();
const setting = await getSetting("subscribeBonus", ctx);
- if (setting.dollars <= 0) return null;
+ if (setting.dollars <= 0) return shown();
const lapsed = await prisma.userCreditLedgerEntry.aggregate({
_sum: { amountMicros: true },
where: { grantId: grant.id, type: "expiration" },
});
const lapsedMicros = -(lapsed._sum.amountMicros ?? zeroCreditMicros);
- if (!crossedSpentShare(grant, lapsedMicros, setting.spentPercent)) return null;
+ if (!crossedSpentShare(grant, lapsedMicros, setting.spentPercent)) return shown();
// A promise of credit that would be dead by the time it lands is no offer:
// the setting's last day has to lie past the whole window.
const closesAt = new Date(now.getTime() + setting.windowHours * 60 * 60 * 1000);
const expiresAt = setting.creditsExpireOn ? endOfUtcDay(setting.creditsExpireOn) : null;
- if (!creditOutlivesWindow(expiresAt, closesAt)) return null;
+ if (!creditOutlivesWindow(expiresAt, closesAt)) return shown();
await prisma.creditOffer.create({
data: {
@@ -123,6 +142,8 @@ export async function readSubscribeBonusOffer(ctx: ConfigContext, now = new Date
userId: ctx.userId,
},
});
- const row = await findSubscribeBonusOffer(ctx.userId);
- return row ? subscribeBonusView(row, facts) : null;
+ // Re-read rather than trust the create: two first reads that raced both
+ // wrote, and the earliest row is the one that stands.
+ const offer = shownOfferForSubscribing(await findOffersForSubscribing(ctx.userId), now);
+ return offer ? subscribeBonusView(offer, facts) : null;
}
diff --git a/site/src/lib/email/kinds.ts b/site/src/lib/email/kinds.ts
index 809330e1..9eadd679 100644
--- a/site/src/lib/email/kinds.ts
+++ b/site/src/lib/email/kinds.ts
@@ -1,6 +1,6 @@
import { z } from "zod";
-import { creditOfferClaimUrl, createPromotionCreditOffer } from "@/lib/credits/offers";
+import { creditOfferClaimUrl, createTermsCreditOffer } from "@/lib/credits/offers";
import { clickUrl } from "@/lib/email/click";
import { recordExpiryNoticeSent } from "@/lib/email/credit-expiry-notices";
import type { EmailSendKind } from "@/lib/email/send-budget";
@@ -13,7 +13,7 @@ import { buildWelcomeEmail, recordWelcomeSent } from "@/lib/email/send-welcome";
import { isMarketingUnsubscribed } from "@/lib/email/unsubscribe";
import { buildReplyForwardEmail, replyForwardPayloadSchema } from "@/lib/marketing/forward-reply";
import { UnknownPlaceholderError } from "@/lib/marketing/placeholders";
-import { promotionOfferOf } from "@/lib/marketing/promotionOfferInput";
+import { creditOfferTermsOf } from "@/lib/credits/offerTerms";
import { buildPromotionEmail, promotionCopyOf } from "@/lib/marketing/promotions";
import { buildOutreachEmail, outreachPayloadSchema, recordOutreachSent } from "@/lib/marketing/send-outreach";
import { prisma } from "@/lib/prisma";
@@ -126,28 +126,24 @@ async function abandonPromotion(promotionId: string, error: Error): Promise<void
await prisma.promotion.update({ data: { status: "draft" }, where: { id: promotionId } });
}
-// A promotion with a credit offer mails each person their own claim link,
-// backed by an offer row that the real send and the test send share. The
-// real send's button is counted when followed.
+// A promotion with a credit offer mails each person their own claim link and
+// the last day to use it, backed by an offer row that the real send and the
+// test send share. The real send's button is counted when followed.
async function promotionEmailFor(
promotion: Awaited<ReturnType<typeof promotionRowOf>>,
user: EmailUser,
trackClick?: (url: string) => string,
) {
- const offer = promotionOfferOf(promotion.creditOffer);
- const claimUrl = offer
- ? (
- await createPromotionCreditOffer({
- promotionId: promotion.id,
- userId: user.id,
- amountDollars: offer.dollars,
- claimWindowDays: offer.claimWindowDays,
- expiresAfterDays: offer.expiresAfterDays,
- offeredByUserId: promotion.actorUserId,
- })
- ).claimUrl
- : undefined;
- return buildPromotionEmail(promotionCopyOf(promotion), user, claimUrl, trackClick);
+ const terms = creditOfferTermsOf(promotion.creditOffer);
+ const offer = terms
+ ? await createTermsCreditOffer({
+ scope: promotion.id,
+ userId: user.id,
+ terms,
+ offeredByUserId: promotion.actorUserId,
+ })
+ : null;
+ return buildPromotionEmail(promotionCopyOf(promotion), user, offer?.vars, trackClick);
}
const promotion = define({
diff --git a/site/src/lib/marketing/placeholders.ts b/site/src/lib/marketing/placeholders.ts
index 53f2c40f..5badd6ce 100644
--- a/site/src/lib/marketing/placeholders.ts
+++ b/site/src/lib/marketing/placeholders.ts
@@ -1,7 +1,14 @@
+import { OFFER_PLACEHOLDERS, type OfferVars } from "@/lib/credits/offerTerms";
+
// What a subject or body may name, and where each value comes from. Saved
// templates and hand-typed notes go through the same fill, so a placeholder
// means the same thing either way.
+/** Whether a placeholder names the offer, so a note without one can say so. */
+export function isOfferPlaceholder(name: string): boolean {
+ return (OFFER_PLACEHOLDERS as readonly string[]).includes(name);
+}
+
/** The values a placeholder resolves to, for one recipient. */
export type OutreachVars = {
/** First word of the account name. */
@@ -15,7 +22,7 @@ export type OutreachVars = {
balance: string;
/** Cloud media the account is holding, already in reading units ("120 MB"). */
storage: string;
-};
+} & Partial<OfferVars>;
export const OUTREACH_PLACEHOLDERS = [
"firstName",
@@ -24,22 +31,22 @@ export const OUTREACH_PLACEHOLDERS = [
"spent",
"balance",
"storage",
+ ...OFFER_PLACEHOLDERS,
] as const satisfies readonly (keyof OutreachVars)[];
/** What a promotion may name: the account itself, nothing that costs a query
- * per recipient. */
+ * per recipient, and the offer when it carries one. */
export type PromotionVars = {
firstName: string;
name: string;
email: string;
- claimUrl?: string;
-};
+} & Partial<OfferVars>;
export const PROMOTION_PLACEHOLDERS = [
"firstName",
"name",
"email",
- "claimUrl",
+ ...OFFER_PLACEHOLDERS,
] as const satisfies readonly (keyof PromotionVars)[];
const PLACEHOLDER = /\{\{\s*([a-zA-Z]+)\s*\}\}/g;
diff --git a/site/src/lib/marketing/promotionCopy.test.ts b/site/src/lib/marketing/promotionCopy.test.ts
index 9d9b930d..e3473fed 100644
--- a/site/src/lib/marketing/promotionCopy.test.ts
+++ b/site/src/lib/marketing/promotionCopy.test.ts
@@ -27,6 +27,16 @@ describe("promotionBlocks", () => {
]);
});
+ test("a credit offer fills its link and last day", () => {
+ const rendered = renderPromotion(
+ { ...copy, body: "Subscribe by {{claimBy}}.", ctaUrl: "{{claimUrl}}" },
+ SAMPLE_RECIPIENT,
+ { claimUrl: "https://donkeycut.com/app?claim=t", claimBy: "September 30, 2026" },
+ );
+ expect(rendered.blocks[0]).toEqual({ kind: "text", text: "Subscribe by September 30, 2026." });
+ expect(rendered.cta?.url).toBe("https://donkeycut.com/app?claim=t");
+ });
+
test("a body without the mark gets the button last", () => {
expect(promotionBlocks("a\n\nb", true)).toEqual([
{ kind: "text", text: "a" },
diff --git a/site/src/lib/marketing/promotionCopy.ts b/site/src/lib/marketing/promotionCopy.ts
index e8000a4b..46ecbaa1 100644
--- a/site/src/lib/marketing/promotionCopy.ts
+++ b/site/src/lib/marketing/promotionCopy.ts
@@ -4,6 +4,7 @@ import {
firstNameOf,
type PromotionVars,
} from "@/lib/marketing/placeholders";
+import type { OfferVars } from "@/lib/credits/offerTerms";
import type { PromotionSender } from "@/lib/marketing/promotionInput";
// The words of a promotion, turned into what one recipient reads: the subject
@@ -59,8 +60,8 @@ export type RenderedPromotion = {
/** What one recipient reads. Throws UnknownPlaceholderError on a typo, so a
* save or a send fails before any mail leaves. */
-export function renderPromotion(copy: PromotionCopy, user: EmailUser, claimUrl?: string): RenderedPromotion {
- const vars = { ...promotionVars(user), claimUrl };
+export function renderPromotion(copy: PromotionCopy, user: EmailUser, offer?: OfferVars): RenderedPromotion {
+ const vars = { ...promotionVars(user), ...offer };
const subject = fillPromotionText(copy.subject, vars);
const cta =
copy.ctaLabel !== null && copy.ctaUrl !== null
diff --git a/site/src/lib/marketing/promotionInput.ts b/site/src/lib/marketing/promotionInput.ts
index 6cc97b62..0badbab2 100644
--- a/site/src/lib/marketing/promotionInput.ts
+++ b/site/src/lib/marketing/promotionInput.ts
@@ -1,6 +1,6 @@
import { audienceSchema, type Audience } from "@donkeycut/abexp";
import { z } from "zod";
-import { CLAIM_URL_PLACEHOLDER, promotionOfferSchema, type PromotionOffer } from "@/lib/marketing/promotionOfferInput";
+import { CLAIM_URL_PLACEHOLDER, creditOfferTermsSchema, type CreditOfferTerms } from "@/lib/credits/offerTerms";
// The shape of a promotion as su writes it and the routes validate it.
// Client-safe: zod only, so the dialog parses the same schema the server does.
@@ -26,7 +26,7 @@ export const promotionInputSchema = z
z.url({ protocol: /^https?$/, error: "Use an HTTP or HTTPS link." }).max(2000),
])
.nullable(),
- creditOffer: promotionOfferSchema.nullable().default(null),
+ creditOffer: creditOfferTermsSchema.nullable().default(null),
sender: z.enum(PROMOTION_SENDERS),
audience: audienceSchema,
// Earlier promotions whose recipients are left out.
@@ -45,7 +45,7 @@ export const promotionInputSchema = z
export type PromotionInput = z.output<typeof promotionInputSchema>;
export type PromotionSummary = {
- creditOffer: PromotionOffer | null;
+ creditOffer: CreditOfferTerms | null;
id: string;
name: string;
subject: string;
diff --git a/site/src/lib/marketing/promotionOfferInput.ts b/site/src/lib/marketing/promotionOfferInput.ts
deleted file mode 100644
index b68a5487..00000000
--- a/site/src/lib/marketing/promotionOfferInput.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { z } from "zod";
-
-export const promotionOfferSchema = z.object({
- dollars: z.number().int().min(1).max(10000),
- claimWindowDays: z.number().int().min(1).max(365),
- expiresAfterDays: z.number().int().min(1).max(3650),
-}).strict();
-
-export type PromotionOffer = z.infer<typeof promotionOfferSchema>;
-export const CLAIM_URL_PLACEHOLDER = "{{claimUrl}}";
-
-export function promotionOfferOf(value: unknown): PromotionOffer | null {
- return value == null ? null : promotionOfferSchema.parse(value);
-}
diff --git a/site/src/lib/marketing/promotionSave.ts b/site/src/lib/marketing/promotionSave.ts
index e08e6b6d..26d4b630 100644
--- a/site/src/lib/marketing/promotionSave.ts
+++ b/site/src/lib/marketing/promotionSave.ts
@@ -7,11 +7,12 @@ import type { PromotionInput } from "@/lib/marketing/promotionInput";
// What a save of a promotion shares between create and edit: the copy is
// rendered for a stand-in recipient, so a placeholder typo is refused at the
// save and never reaches a send; and the row data the input maps to. The
-// claim link is minted per person at the send, so the check fills it blank.
+// claim link and its last day are minted per person at the send, so the
+// check fills them blank.
export function copyIssue(input: PromotionInput): Response | null {
try {
- renderPromotion(input, SAMPLE_RECIPIENT, input.creditOffer ? "" : undefined);
+ renderPromotion(input, SAMPLE_RECIPIENT, input.creditOffer ? { claimUrl: "", claimBy: "" } : undefined);
return null;
} catch (error) {
if (error instanceof UnknownPlaceholderError) {
diff --git a/site/src/lib/marketing/promotions.ts b/site/src/lib/marketing/promotions.ts
index f6b21cfc..b3aebbe9 100644
--- a/site/src/lib/marketing/promotions.ts
+++ b/site/src/lib/marketing/promotions.ts
@@ -17,8 +17,9 @@ import {
type SegmentCount,
} from "@/lib/marketing/promotionInput";
import { prisma } from "@/lib/prisma";
-import { PROMOTION_OFFER_KIND } from "@/lib/credits/offers";
-import { promotionOfferOf } from "@/lib/marketing/promotionOfferInput";
+import { PROMOTION_OFFER_KINDS } from "@/lib/credits/offerKinds";
+import type { OfferVars } from "@/lib/credits/offerTerms";
+import { creditOfferTermsOf } from "@/lib/credits/offerTerms";
// Promotions on the server: which address each sender is, who a segment
// resolves to, one send, and the list su reads.
@@ -62,13 +63,13 @@ export function promotionAudienceOf(raw: Prisma.JsonValue): Audience {
export function buildPromotionEmail(
copy: PromotionCopy,
user: EmailUser,
- claimUrl: string | undefined,
+ offer: OfferVars | undefined,
// Wraps the button's link so the follow is counted; the test send has none.
trackClick?: (url: string) => string,
): EmailMessage {
const from = promotionSenders()[copy.sender];
if (!from) throw new PermanentSendError(`The ${copy.sender} sender is not configured.`);
- const rendered = renderPromotion(copy, user, claimUrl);
+ const rendered = renderPromotion(copy, user, offer);
const cta = rendered.cta && trackClick ? { ...rendered.cta, url: trackClick(rendered.cta.url) } : rendered.cta;
return {
from,
@@ -184,7 +185,7 @@ type PromotionRow = NonNullable<Awaited<ReturnType<typeof prisma.promotion.findU
function summarize(row: PromotionRow, counts: PromotionSummary["counts"]): PromotionSummary {
return {
id: row.id,
- creditOffer: promotionOfferOf(row.creditOffer),
+ creditOffer: creditOfferTermsOf(row.creditOffer),
name: row.name,
subject: row.subject,
body: row.body,
@@ -220,7 +221,10 @@ export async function listPromotions(): Promise<PromotionSummary[]> {
where: { clickedAt: { not: null }, promotionId: { not: null } },
}),
// A promotion's offers are keyed `${promotionId}:${userId}`.
- prisma.creditOffer.findMany({ select: { id: true }, where: { claimedAt: { not: null }, kind: PROMOTION_OFFER_KIND } }),
+ prisma.creditOffer.findMany({
+ select: { id: true },
+ where: { claimedAt: { not: null }, kind: { in: [...PROMOTION_OFFER_KINDS] } },
+ }),
]);
const countOf = (groups: { promotionId: string | null; _count: number }[]) =>
new Map(groups.flatMap((g) => (g.promotionId ? [[g.promotionId, g._count] as const] : [])));
diff --git a/site/src/queries/billing.ts b/site/src/queries/billing.ts
index 21326d9f..10a7120a 100644
--- a/site/src/queries/billing.ts
+++ b/site/src/queries/billing.ts
@@ -60,10 +60,15 @@ export function useUsage() {
// Mutations return the Stripe URL; the caller redirects the browser. We don't
// invalidate here because the user leaves the page for Stripe.
+// A checkout opened from an offer's claim link passes the offer's token, so
+// the credit that lands is the one the dialog described.
export function useStartCheckout() {
return useMutation({
- mutationFn: () =>
- apiFetch<{ url: string }>("/api/billing/checkout", { method: "POST" }),
+ mutationFn: (input?: { offerToken: string } | void) =>
+ apiFetch<{ url: string }>("/api/billing/checkout", {
+ method: "POST",
+ ...(input ? { body: JSON.stringify(input) } : {}),
+ }),
});
}
diff --git a/site/src/queries/credits.ts b/site/src/queries/credits.ts
index 72e689ed..a07d9eb2 100644
--- a/site/src/queries/credits.ts
+++ b/site/src/queries/credits.ts
@@ -47,11 +47,17 @@ export function useCreditBalance() {
}
export type SubscribeBonus = {
+ // Where the offer reached the person: the app opened the bonus on its own,
+ // a promotion came by email.
+ origin: "app" | "email";
// USD, as a credit string.
dollars: string;
openedAt: string;
closesAt: string;
+ // The credit's life once it lands: a fixed last moment, or a span from the
+ // claim as people read it ("a month"). Both null keeps it forever.
creditsExpireAt: string | null;
+ creditsLifetime: string | null;
status: "open" | "closed" | "claimed";
};
@@ -137,6 +143,9 @@ export function useOfferCredits() {
export const creditOfferQueryKey = (token: string) => ["credits", "offer", token] as const;
export type CreditOffer = {
+ // What lands the credit: the Claim button, or a Pro subscription started
+ // inside the window.
+ claim: "link" | "subscribe";
claimed: boolean;
// The last moment the offer can be claimed; null keeps it open.
closesAt: string | null;
@@ -150,7 +159,8 @@ export type CreditOffer = {
};
// The offer a claim link names. 404 is a link that no longer opens anything;
-// 403 is an offer made to another account; 410 is a claim window that closed.
+// 403 is an offer made to another account; 410 is a claim window that closed;
+// 409 is a subscribe offer read by an account that already holds Pro.
export function useCreditOffer(token: string, options: { enabled?: boolean } = {}) {
return useQuery({
enabled: options.enabled ?? true,