Skip to content

Open source CapCut alternative.

TypeScript

feat(site): render claim buttons in outreach notes

David Le6c3d751af86a
diff --git a/docs/guides/backend-apis.md b/docs/guides/backend-apis.md
index f6bc06d3..8e40e9fa 100644
--- a/docs/guides/backend-apis.md
+++ b/docs/guides/backend-apis.md
@@ -157,6 +157,13 @@ 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.
+Outreach notes can place `{{button}}` in its own paragraph when a credit offer
+is enabled. The offer supplies the recipient's claim URL and the button label:
+“Subscribe to Pro” for a subscription offer, or “Claim my AI credits” for a
+direct claim. Validation, test sends, and recipient sends share the same copy
+renderer. Button notes carry HTML and a plain-text version with the link;
+`{{claimUrl}}` remains available as a URL in the text.
+
Known OpenAI, Gemini, and ElevenLabs models fall back to backend-owned prices
unless a database rate overrides them. The fallbacks mirror current public
provider prices, mark them up by the supported margin, and round up to the
diff --git a/site/src/app/api/marketing/outreach/route.ts b/site/src/app/api/marketing/outreach/route.ts
index 545093e9..5aa8b83f 100644
--- a/site/src/app/api/marketing/outreach/route.ts
+++ b/site/src/app/api/marketing/outreach/route.ts
@@ -3,7 +3,7 @@ import { z } from "zod";
import { formatBytes } from "@/lib/bytes";
import { creditMicrosToString, zeroCreditMicros } from "@/lib/credits/amounts";
-import { CLAIM_URL_PLACEHOLDER, creditOfferTermsSchema } from "@/lib/credits/offerTerms";
+import { creditOfferTermsSchema, type CreditOfferTerms } from "@/lib/credits/offerTerms";
import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";
import {
CREDIT_SPENDERS_CAMPAIGN,
@@ -14,7 +14,6 @@ import {
import { deliverEmail } from "@/lib/email/outbox";
import { lastActiveByUser } from "@/lib/marketing/lastActive";
import {
- fillOutreachText,
firstNameOf,
isOfferPlaceholder,
UnknownPlaceholderError,
@@ -23,6 +22,7 @@ import {
import { promotionIdempotencyKey } from "@/lib/marketing/promotions";
import { sendIssue } from "@/lib/marketing/promotionSave";
import { outreachIdempotencyKey } from "@/lib/marketing/send-outreach";
+import { OutreachCopyError, renderOutreachCopy } from "@/lib/marketing/outreachCopy";
import { prisma } from "@/lib/prisma";
const listQuerySchema = z.object({
@@ -201,15 +201,12 @@ export const GET = withSuperUser(async (request) => {
// placeholder, or an offer placeholder in a note that carries no offer, is
// refused before anything is queued; so is an offer the words never link to,
// since the link is the only way the person reaches it.
-function wordsIssue(subject: string, body: string, vars: OutreachVars, offered: boolean): string | null {
- if (offered && !subject.includes(CLAIM_URL_PLACEHOLDER) && !body.includes(CLAIM_URL_PLACEHOLDER)) {
- return `A note with a credit offer needs ${CLAIM_URL_PLACEHOLDER} in it.`;
- }
+function wordsIssue(subject: string, body: string, vars: OutreachVars, offer: CreditOfferTerms | null): string | null {
try {
- fillOutreachText(subject, vars);
- fillOutreachText(body, vars);
+ renderOutreachCopy(subject, body, vars, offer);
return null;
} catch (error) {
+ if (error instanceof OutreachCopyError) return error.message;
if (!(error instanceof UnknownPlaceholderError)) throw error;
return isOfferPlaceholder(error.placeholder)
? `Turn on the credit offer to use {{${error.placeholder}}}.`
@@ -296,7 +293,7 @@ export const POST = withSuperUser(async (request) => {
parsed.data.subject,
parsed.data.body,
parsed.data.creditOffer ? { ...vars, claimUrl: "", claimBy: "" } : vars,
- parsed.data.creditOffer !== null,
+ parsed.data.creditOffer,
);
if (issue) {
return NextResponse.json({ error: "Invalid request", issues: [{ message: issue, path: "body" }] }, { status: 400 });
diff --git a/site/src/app/su/outreach/ComposeDialog.tsx b/site/src/app/su/outreach/ComposeDialog.tsx
index e2e6d5c8..b5e372da 100644
--- a/site/src/app/su/outreach/ComposeDialog.tsx
+++ b/site/src/app/su/outreach/ComposeDialog.tsx
@@ -37,6 +37,7 @@ import {
OUTREACH_PLACEHOLDERS,
} from "@/lib/marketing/placeholders";
import { cn } from "@/lib/utils";
+import { BUTTON_MARK } from "@/lib/marketing/promotionCopy";
import { ApiError } from "@/queries/apiClient";
import {
useBusyOutreachIds,
@@ -551,13 +552,29 @@ export function OutreachComposeDialog({
{`{{${name}}}`}
</Button>
))}
+ {creditOffer ? (
+ <Button
+ onClick={() => {
+ const field = bodyField.current;
+ const start = field?.selectionStart ?? body.length;
+ const end = field?.selectionEnd ?? start;
+ const before = body.slice(0, start).trimEnd();
+ const after = body.slice(end).trimStart();
+ setBody(`${before ? `${before}\n\n` : ""}${BUTTON_MARK}${after ? `\n\n${after}` : ""}`);
+ }}
+ size="xs"
+ variant="outline"
+ >
+ {BUTTON_MARK}
+ </Button>
+ ) : null}
</div>
<CreditOfferFields
idPrefix="outreach-offer"
value={creditOffer}
defaults={offerDefaults}
onChange={setCreditOffer}
- hint="The note carries a link for AI credits; {{claimUrl}} is the link and {{claimBy}} the last day to claim."
+ hint="Put {{button}} in its own paragraph for a claim button. {{claimUrl}} inserts the URL; {{claimBy}} is the last day to claim."
/>
{sendFailed ? (
<p className="text-sm text-destructive">
diff --git a/site/src/emails/outreach.tsx b/site/src/emails/outreach.tsx
new file mode 100644
index 00000000..58698196
--- /dev/null
+++ b/site/src/emails/outreach.tsx
@@ -0,0 +1,34 @@
+import { Fragment } from "react";
+import { Body, Button, Head, Html, Link, Text } from "react-email";
+
+type Props = {
+ blocks: ({ kind: "text"; text: string } | { kind: "button" })[];
+ cta: { label: string; url: string };
+ unsubscribeUrl: string | null;
+};
+
+export default function OutreachEmail({ blocks, cta, unsubscribeUrl }: Props) {
+ return (
+ <Html>
+ <Head />
+ <Body style={{ fontFamily: "Arial, sans-serif", color: "#0F0E0D", backgroundColor: "#ffffff" }}>
+ {blocks.map((block, index) => block.kind === "button" ? (
+ <Button key={index} href={cta.url} style={{ backgroundColor: "#0F0E0D", color: "#ffffff", padding: "12px 24px", borderRadius: 8, fontSize: 15, fontWeight: 600 }}>
+ {cta.label}
+ </Button>
+ ) : (
+ <Text key={index} style={{ fontSize: 15, lineHeight: "24px", margin: "0 0 16px" }}>
+ {block.text.split("\n").map((line, lineIndex) => (
+ <Fragment key={lineIndex}>{lineIndex > 0 ? <br /> : null}{line}</Fragment>
+ ))}
+ </Text>
+ ))}
+ {unsubscribeUrl ? (
+ <Text style={{ marginTop: 24, fontSize: 12, color: "#666666" }}>
+ <Link href={unsubscribeUrl} style={{ color: "#666666" }}>Unsubscribe from product emails</Link>
+ </Text>
+ ) : null}
+ </Body>
+ </Html>
+ );
+}
diff --git a/site/src/lib/marketing/outreachCopy.test.tsx b/site/src/lib/marketing/outreachCopy.test.tsx
new file mode 100644
index 00000000..e00713bd
--- /dev/null
+++ b/site/src/lib/marketing/outreachCopy.test.tsx
@@ -0,0 +1,58 @@
+import { describe, expect, test } from "bun:test";
+import { render } from "react-email";
+
+import OutreachEmail from "@/emails/outreach";
+import { type CreditOfferTerms } from "@/lib/credits/offerTerms";
+import { renderOutreachCopy } from "@/lib/marketing/outreachCopy";
+
+const vars = {
+ balance: "0", email: "[email protected]", firstName: "Ada", name: "Ada Lovelace",
+ spent: "2.4", storage: "120 MB", claimUrl: "https://example.com/app?claim=test&source=email", claimBy: "September 30",
+};
+const offer: CreditOfferTerms = { dollars: 60, claim: "subscribe", claimWindowDays: 3, expiresAfterDays: 30 };
+
+describe("outreach claim button", () => {
+ test("accepts the note's button without a separate claimUrl placeholder", async () => {
+ const copy = renderOutreachCopy("Low on credits?", "Hey {{firstName}},\n\nSubscribe for $60 in credits.\n\n{{button}}", vars, offer);
+ expect(copy.cta).toEqual({ label: "Subscribe to Pro", url: vars.claimUrl });
+ expect(copy.blocks.at(-1)).toEqual({ kind: "button" });
+ expect(copy.text).toContain(`Subscribe to Pro: ${vars.claimUrl}`);
+ expect(copy.text).not.toContain("{{");
+ const html = await render(<OutreachEmail blocks={copy.blocks} cta={copy.cta!} unsubscribeUrl="https://example.com/unsubscribe" />);
+ expect(html).toContain("Subscribe to Pro");
+ expect(html).toContain('href="https://example.com/app?claim=test&amp;source=email"');
+ expect(html).toContain("background-color:#0F0E0D");
+ expect(html).toContain("Unsubscribe from product emails");
+ });
+
+ test("direct claims use their own label and repeated markers place one button", () => {
+ const copy = renderOutreachCopy("Credits", "{{button}}\r\n\r\nThanks!\r\n\r\n{{button}}", vars, { ...offer, claim: "link" });
+ expect(copy.cta?.label).toBe("Claim my AI credits");
+ expect(copy.blocks.filter((block) => block.kind === "button")).toHaveLength(1);
+ });
+
+ test("requires an offer, a claim URL, and a standalone marker", () => {
+ expect(() => renderOutreachCopy("Credits", "{{button}}", vars, null)).toThrow("Turn on the credit offer");
+ expect(() => renderOutreachCopy("Credits", "{{button}}", { ...vars, claimUrl: undefined }, offer)).toThrow("Turn on the credit offer");
+ expect(() => renderOutreachCopy("Credits", "Click {{button}}", vars, offer)).toThrow("own paragraph");
+ expect(() => renderOutreachCopy("Credits", "Hello", vars, offer)).toThrow("needs {{button}} or {{claimUrl}}");
+ expect(() => renderOutreachCopy("{{button}}", "{{claimUrl}}", vars, offer)).toThrow("Unknown placeholder");
+ });
+
+ test("keeps plain notes and URL placeholders as text", () => {
+ const body = "Hey {{firstName}},\n\n\nClaim here: {{ claimUrl }}";
+ const copy = renderOutreachCopy("Credits", body, vars, offer);
+ expect(copy.cta).toBeNull();
+ expect(copy.text).toBe(`Hey Ada,\n\n\nClaim here: ${vars.claimUrl}`);
+ expect(renderOutreachCopy("Hello", "Plain note", vars, null).text).toBe("Plain note");
+ });
+
+ test("escapes recipient text and omits the disabled unsubscribe footer", async () => {
+ const copy = renderOutreachCopy("Credits", "Hey {{name}},\nA second line.\n\n{{button}}", { ...vars, name: '<img src="x"> {{button}}' }, offer);
+ const html = await render(<OutreachEmail blocks={copy.blocks} cta={copy.cta!} unsubscribeUrl={null} />);
+ expect(html).toContain("&lt;img");
+ expect(html).not.toContain('<img src="x">');
+ expect(html).toContain("<br");
+ expect(html).not.toContain("Unsubscribe");
+ });
+});
diff --git a/site/src/lib/marketing/outreachCopy.ts b/site/src/lib/marketing/outreachCopy.ts
new file mode 100644
index 00000000..b2994f27
--- /dev/null
+++ b/site/src/lib/marketing/outreachCopy.ts
@@ -0,0 +1,43 @@
+import { OFFER_BUTTON_LABELS, type CreditOfferTerms } from "@/lib/credits/offerTerms";
+import { fillOutreachText, type OutreachVars } from "@/lib/marketing/placeholders";
+import { BUTTON_MARK, type PromotionBlock } from "@/lib/marketing/promotionCopy";
+
+export class OutreachCopyError extends Error {}
+
+/** Parse template syntax before inserting recipient values. */
+export function renderOutreachCopy(
+ subject: string,
+ body: string,
+ vars: OutreachVars,
+ offer: CreditOfferTerms | null,
+) {
+ const blocks: PromotionBlock[] = [];
+ let hasButton = false;
+ for (const paragraph of body.replace(/\r\n/g, "\n").split(/\n[ \t]*\n/)) {
+ const text = paragraph.trim();
+ if (!text) continue;
+ if (text === BUTTON_MARK) {
+ if (!offer || typeof vars.claimUrl !== "string") {
+ throw new OutreachCopyError("Turn on the credit offer to use {{button}}.");
+ }
+ if (!hasButton) blocks.push({ kind: "button" });
+ hasButton = true;
+ } else {
+ if (text.includes(BUTTON_MARK)) {
+ throw new OutreachCopyError("Put {{button}} in its own paragraph, with a blank line before and after it.");
+ }
+ blocks.push({ kind: "text", text: fillOutreachText(text, vars) });
+ }
+ }
+ const filledSubject = fillOutreachText(subject, vars);
+ if (offer && !hasButton && !/\{\{\s*claimUrl\s*\}\}/.test(`${subject}\n${body}`)) {
+ throw new OutreachCopyError("A note with a credit offer needs {{button}} or {{claimUrl}} in it.");
+ }
+ const cta = hasButton && offer && typeof vars.claimUrl === "string"
+ ? { label: OFFER_BUTTON_LABELS[offer.claim], url: vars.claimUrl }
+ : null;
+ const text = cta
+ ? blocks.map((block) => block.kind === "text" ? block.text : `${cta.label}: ${cta.url}`).join("\n\n")
+ : fillOutreachText(body, vars);
+ return { subject: filledSubject, text, blocks, cta };
+}
diff --git a/site/src/lib/marketing/send-outreach.ts b/site/src/lib/marketing/send-outreach.ts
index 6459371a..1ae4f5cc 100644
--- a/site/src/lib/marketing/send-outreach.ts
+++ b/site/src/lib/marketing/send-outreach.ts
@@ -1,12 +1,14 @@
import { z } from "zod";
+import OutreachEmail from "@/emails/outreach";
import { createTermsCreditOffer } from "@/lib/credits/offers";
import { creditOfferTermsSchema } from "@/lib/credits/offerTerms";
import { PermanentSendError } from "@/lib/email/errors";
import { emailFrom, type EmailMessage, type EmailUser } from "@/lib/email/resend";
import { isMarketingUnsubscribed, unsubscribePageUrl } from "@/lib/email/unsubscribe";
import { outreachReplyAddress } from "@/lib/marketing/replyAddress";
-import { fillOutreachText, type OutreachVars, UnknownPlaceholderError } from "@/lib/marketing/placeholders";
+import { type OutreachVars, UnknownPlaceholderError } from "@/lib/marketing/placeholders";
+import { OutreachCopyError, renderOutreachCopy } from "@/lib/marketing/outreachCopy";
import { prisma } from "@/lib/prisma";
export const outreachPayloadSchema = z
@@ -44,11 +46,7 @@ export function outreachIdempotencyKey(outreachId: string, attempt: number): str
return `outreach:${outreachId}:${attempt}`;
}
-// One person writing to one person, so the message goes out as text/plain with
-// no markup, no template shell, and no bulk-mail headers. A mail provider reads
-// an HTML body or a `List-Unsubscribe` header as a mailing list and files the
-// note under promotions. When the operator turns the opt-out footer on, it
-// rides along as a line of text.
+// Every note carries a plain-text version, including its optional opt-out footer.
function outreachText(body: string, unsubscribeUrl: string | null): string {
const trimmed = body.trim();
if (!unsubscribeUrl) return `${trimmed}\n`;
@@ -87,21 +85,21 @@ export async function buildOutreachEmail(
})
: null;
const vars: OutreachVars = { ...payload.vars, ...offer?.vars };
- let subject: string;
- let body: string;
+ let copy: ReturnType<typeof renderOutreachCopy>;
try {
- subject = fillOutreachText(payload.subject, vars);
- body = fillOutreachText(payload.body, vars);
+ copy = renderOutreachCopy(payload.subject, payload.body, vars, payload.creditOffer);
} catch (error) {
- if (error instanceof UnknownPlaceholderError) throw new PermanentSendError(error.message);
+ if (error instanceof UnknownPlaceholderError || error instanceof OutreachCopyError) throw new PermanentSendError(error.message);
throw error;
}
+ const unsubscribeUrl = payload.unsubscribeLink ? unsubscribePageUrl(user.id) : null;
return {
from,
to: user.email,
replyTo: payload.trackReplies ? outreachReplyAddress(payload.outreachId) : undefined,
- subject,
- text: outreachText(body, payload.unsubscribeLink ? unsubscribePageUrl(user.id) : null),
+ subject: copy.subject,
+ text: outreachText(copy.text, unsubscribeUrl),
+ ...(copy.cta ? { react: OutreachEmail({ blocks: copy.blocks, cta: copy.cta, unsubscribeUrl }) } : {}),
};
}