Skip to content

Open source CapCut alternative.

TypeScript

feat(site): outreach notes carry the credit offer and reach anyone by email

David Lee2509822ab1d
diff --git a/site/src/app/api/marketing/outreach/route.ts b/site/src/app/api/marketing/outreach/route.ts
index 4717f3d5..32b66b54 100644
--- a/site/src/app/api/marketing/outreach/route.ts
+++ b/site/src/app/api/marketing/outreach/route.ts
@@ -2,15 +2,24 @@ import { NextResponse } from "next/server";
import { z } from "zod";
import { formatBytes } from "@/lib/bytes";
-import { creditMicrosToString } from "@/lib/credits/amounts";
+import { creditMicrosToString, zeroCreditMicros } from "@/lib/credits/amounts";
+import { CLAIM_URL_PLACEHOLDER, creditOfferTermsSchema } from "@/lib/credits/offerTerms";
import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";
import {
CREDIT_SPENDERS_CAMPAIGN,
OUTREACH_REASONS,
OUTREACH_STATUSES,
+ PICKED_REASON,
} from "@/lib/marketing/campaigns";
import { deliverEmail } from "@/lib/email/outbox";
-import { firstNameOf } from "@/lib/marketing/placeholders";
+import { lastActiveByUser } from "@/lib/marketing/lastActive";
+import {
+ fillOutreachText,
+ firstNameOf,
+ isOfferPlaceholder,
+ UnknownPlaceholderError,
+ type OutreachVars,
+} from "@/lib/marketing/placeholders";
import { outreachIdempotencyKey } from "@/lib/marketing/send-outreach";
import { prisma } from "@/lib/prisma";
@@ -20,8 +29,8 @@ const listQuerySchema = z.object({
status: z.enum(OUTREACH_STATUSES).optional(),
});
-// Two shapes: start a conversation with a user who is on the list, or file a
-// row that is already on it.
+// Three shapes: start a conversation with a user who is on the list, file a
+// row that is already on it, or put an account on the list by its address.
const actionSchema = z.union([
z
.object({
@@ -31,8 +40,10 @@ const actionSchema = z.union([
subject: z.string().trim().min(1).max(200),
trackReplies: z.boolean(),
unsubscribeLink: z.boolean(),
+ creditOffer: creditOfferTermsSchema.nullable().default(null),
})
.strict(),
+ z.object({ action: z.literal("add"), email: z.string().trim().min(1).max(320) }).strict(),
z
.object({
action: z.enum(["ignore", "unignore", "replied"]),
@@ -177,6 +188,59 @@ export const GET = withSuperUser(async (request) => {
return NextResponse.json({ rows: rows.map(serialize) });
});
+// The words are filled once here with the row's own values, so a typo in a
+// 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.`;
+ }
+ try {
+ fillOutreachText(subject, vars);
+ fillOutreachText(body, vars);
+ return null;
+ } catch (error) {
+ if (!(error instanceof UnknownPlaceholderError)) throw error;
+ return isOfferPlaceholder(error.placeholder)
+ ? `Turn on the credit offer to use {{${error.placeholder}}}.`
+ : error.message;
+ }
+}
+
+/** Puts an account on the list by hand, with the numbers the list shows read
+ * now. An account already on it comes back as it is, whatever its status. */
+async function addByEmail(email: string) {
+ const user = await prisma.user.findFirst({
+ select: { id: true },
+ where: { email: { equals: email, mode: "insensitive" } },
+ });
+ if (!user) return null;
+ const [account, storage, lastActiveBy] = await Promise.all([
+ prisma.userCreditAccount.findUnique({
+ select: { balanceMicros: true, lifetimeChargedMicros: true },
+ where: { userId: user.id },
+ }),
+ prisma.cutStorageUsage.findUnique({ select: { bytes: true }, where: { userId: user.id } }),
+ lastActiveByUser([user.id]),
+ ]);
+ return prisma.userOutreach.upsert({
+ create: {
+ balanceMicros: account?.balanceMicros ?? zeroCreditMicros,
+ campaign: CREDIT_SPENDERS_CAMPAIGN,
+ lastActiveAt: lastActiveBy.get(user.id) ?? null,
+ reasons: [PICKED_REASON],
+ spentMicros: account?.lifetimeChargedMicros ?? zeroCreditMicros,
+ status: "todo",
+ storageBytes: storage?.bytes ?? BigInt(0),
+ userId: user.id,
+ },
+ select: rowSelect,
+ update: {},
+ where: { userId_campaign: { campaign: CREDIT_SPENDERS_CAMPAIGN, userId: user.id } },
+ });
+}
+
export const POST = withSuperUser(async (request) => {
const parsed = actionSchema.safeParse(await request.json());
if (!parsed.success) {
@@ -192,6 +256,12 @@ export const POST = withSuperUser(async (request) => {
);
}
+ if (parsed.data.action === "add") {
+ const row = await addByEmail(parsed.data.email);
+ if (!row) return notFoundResponse();
+ return NextResponse.json({ row: serialize(row) });
+ }
+
const outreach = await prisma.userOutreach.findUnique({
select: rowSelect,
where: { id: parsed.data.outreachId },
@@ -205,6 +275,23 @@ export const POST = withSuperUser(async (request) => {
if (parsed.data.action === "send") {
const attempt = outreach.sentCount + 1;
+ const vars = {
+ balance: creditMicrosToString(outreach.balanceMicros),
+ email: outreach.user.email,
+ firstName: firstNameOf(outreach.user.name),
+ name: outreach.user.name,
+ spent: creditMicrosToString(outreach.spentMicros),
+ storage: formatBytes(Number(outreach.storageBytes)),
+ };
+ const issue = wordsIssue(
+ parsed.data.subject,
+ parsed.data.body,
+ parsed.data.creditOffer ? { ...vars, claimUrl: "", claimBy: "" } : vars,
+ parsed.data.creditOffer !== null,
+ );
+ if (issue) {
+ return NextResponse.json({ error: "Invalid request", issues: [{ message: issue, path: "body" }] }, { status: 400 });
+ }
const delivery = await deliverEmail({
idempotencyKey: outreachIdempotencyKey(outreach.id, attempt),
kind: "outreach",
@@ -212,18 +299,12 @@ export const POST = withSuperUser(async (request) => {
actorUserId,
attempt,
body: parsed.data.body,
+ creditOffer: parsed.data.creditOffer,
outreachId: outreach.id,
subject: parsed.data.subject,
trackReplies: parsed.data.trackReplies,
unsubscribeLink: parsed.data.unsubscribeLink,
- vars: {
- balance: creditMicrosToString(outreach.balanceMicros),
- email: outreach.user.email,
- firstName: firstNameOf(outreach.user.name),
- name: outreach.user.name,
- spent: creditMicrosToString(outreach.spentMicros),
- storage: formatBytes(Number(outreach.storageBytes)),
- },
+ vars,
},
userId: outreach.user.id,
});
diff --git a/site/src/app/api/marketing/templates/route.ts b/site/src/app/api/marketing/templates/route.ts
index e9ba6090..8fd8532a 100644
--- a/site/src/app/api/marketing/templates/route.ts
+++ b/site/src/app/api/marketing/templates/route.ts
@@ -2,6 +2,7 @@ import { NextResponse } from "next/server";
import { z } from "zod";
import { Prisma } from "@/generated/prisma/client";
+import { creditOfferTermsSchema } from "@/lib/credits/offerTerms";
import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";
import { prisma } from "@/lib/prisma";
@@ -15,7 +16,8 @@ const saveSchema = z
subject: z.string().trim().min(1).max(200),
trackReplies: z.boolean(),
unsubscribeLink: z.boolean(),
- promotion: z.record(z.string(), z.unknown()).nullable().optional(),
+ // The credit offer the template starts a note with, if any.
+ promotion: creditOfferTermsSchema.nullable().optional(),
})
.strict();
diff --git a/site/src/app/su/outreach/drafts.ts b/site/src/app/su/outreach/drafts.ts
index f3104e9f..250f2dd4 100644
--- a/site/src/app/su/outreach/drafts.ts
+++ b/site/src/app/su/outreach/drafts.ts
@@ -3,6 +3,7 @@
import { useCallback } from "react";
import { useLocalPref } from "@/cut/lib/uiState";
+import { creditOfferTermsIfValid, type CreditOfferTerms } from "@/lib/credits/offerTerms";
// What was sent last, kept in this browser so the next note can start from it
// and be edited. It stays here on purpose: the server keeps status and
@@ -14,6 +15,7 @@ export type OutreachDraft = {
body: string;
unsubscribeLink: boolean;
trackReplies: boolean;
+ creditOffer: CreditOfferTerms | null;
savedAt: string;
};
@@ -27,6 +29,9 @@ type StoredDraft = {
body: string;
unsubscribeLink?: boolean;
trackReplies?: boolean;
+ // Terms as stored; read through the schema, so an entry from before a
+ // field existed loads as no offer.
+ creditOffer?: unknown;
savedAt: string;
};
@@ -71,17 +76,20 @@ export function useOutreachDrafts(): {
id: draft.id ?? draft.savedAt,
trackReplies: draft.trackReplies ?? true,
unsubscribeLink: draft.unsubscribeLink ?? true,
+ creditOffer: creditOfferTermsIfValid(draft.creditOffer),
}));
const remember = useCallback(
({
body,
+ creditOffer,
subject,
trackReplies,
unsubscribeLink,
}: Omit<OutreachDraft, "id" | "savedAt">) => {
const id = crypto.randomUUID();
const savedAt = new Date().toISOString();
+ const offerKey = JSON.stringify(creditOffer);
setStored((current) => {
// Sending the same note twice moves the entry up rather than doubling it.
const rest = current.filter(
@@ -89,10 +97,11 @@ export function useOutreachDrafts(): {
draft.subject !== subject ||
draft.body !== body ||
(draft.unsubscribeLink ?? true) !== unsubscribeLink ||
- (draft.trackReplies ?? true) !== trackReplies,
+ (draft.trackReplies ?? true) !== trackReplies ||
+ JSON.stringify(creditOfferTermsIfValid(draft.creditOffer)) !== offerKey,
);
return [
- { body, id, savedAt, subject, trackReplies, unsubscribeLink },
+ { body, creditOffer, id, savedAt, subject, trackReplies, unsubscribeLink },
...rest,
].slice(0, LIMIT);
});
diff --git a/site/src/app/su/outreach/page.tsx b/site/src/app/su/outreach/page.tsx
index bb99bf92..70d7044c 100644
--- a/site/src/app/su/outreach/page.tsx
+++ b/site/src/app/su/outreach/page.tsx
@@ -3,6 +3,7 @@
import { XIcon } from "lucide-react";
import { useEffect, useRef, useState } from "react";
+import { CreditOfferFields, useCreditOfferDefaults } from "@/app/su/CreditOfferFields";
import {
useLastOutreachStart,
useOutreachDrafts,
@@ -23,6 +24,7 @@ import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { formatBytes } from "@/lib/bytes";
+import { creditOfferTermsIfValid, type CreditOfferTerms } from "@/lib/credits/offerTerms";
import { cn } from "@/lib/utils";
import {
OUTREACH_REASON_LABELS,
@@ -31,7 +33,8 @@ import {
type OutreachReason,
type OutreachStatus,
} from "@/lib/marketing/campaigns";
-import { OUTREACH_PLACEHOLDERS } from "@/lib/marketing/placeholders";
+import { isOfferPlaceholder, OUTREACH_PLACEHOLDERS } from "@/lib/marketing/placeholders";
+import { ApiError } from "@/queries/apiClient";
import {
useBusyOutreachIds,
useOutreach,
@@ -57,7 +60,7 @@ const BLANK = "blank";
// A place a note can start from: a saved template, or something this browser
// already sent. Both are starting points; whatever ends up in the dialog —
-// words and send toggles alike — is what goes out.
+// words, send toggles and the credit offer alike — is what goes out.
type StartPoint = {
id: string;
title: string;
@@ -66,6 +69,7 @@ type StartPoint = {
body: string;
unsubscribeLink: boolean;
trackReplies: boolean;
+ creditOffer: CreditOfferTerms | null;
at: number;
remove?: () => void;
busy?: boolean;
@@ -163,6 +167,8 @@ export default function SuOutreachPage() {
const [lastStart, setLastStart] = useLastOutreachStart();
const [unsubscribeLink, setUnsubscribeLink] = useState(true);
const [trackReplies, setTrackReplies] = useState(true);
+ const [creditOffer, setCreditOffer] = useState<CreditOfferTerms | null>(null);
+ const offerDefaults = useCreditOfferDefaults();
const saved = templates.data?.templates ?? [];
@@ -187,10 +193,12 @@ export default function SuOutreachPage() {
title: template.name,
trackReplies: template.trackReplies,
unsubscribeLink: template.unsubscribeLink,
+ creditOffer: creditOfferTermsIfValid(template.promotion),
})),
...drafts.map((draft) => ({
at: new Date(draft.savedAt).getTime(),
body: draft.body,
+ creditOffer: draft.creditOffer,
id: `draft:${draft.id}`,
meta: `Sent ${ago(draft.savedAt)}`,
remove: () => {
@@ -214,6 +222,7 @@ export default function SuOutreachPage() {
title: "Blank",
trackReplies: true,
unsubscribeLink: true,
+ creditOffer: null,
},
...starts,
];
@@ -231,6 +240,7 @@ export default function SuOutreachPage() {
setBody(picked.body);
setUnsubscribeLink(picked.unsubscribeLink);
setTrackReplies(picked.trackReplies);
+ setCreditOffer(picked.creditOffer);
setNaming(false);
};
@@ -245,15 +255,20 @@ export default function SuOutreachPage() {
setBody(start.body);
setUnsubscribeLink(start.unsubscribeLink);
setTrackReplies(start.trackReplies);
+ setCreditOffer(start.creditOffer);
setNaming(false);
setSendTarget(row);
};
+ // An address that is not on the list is put there, then opened for a note.
+ const addByEmail = () =>
+ act.mutate({ action: "add", email: needle }, { onSuccess: (result) => openSend(result.row) });
+
const submitTemplate = () => {
const name = templateName.trim();
if (name === "" || !sendable) return;
saveTemplate.mutate(
- { body, name, subject, trackReplies, unsubscribeLink },
+ { body, name, subject, trackReplies, unsubscribeLink, promotion: creditOffer },
{
onSuccess: (result) => {
// The note now lives in a template, so the sent copy of the same
@@ -298,11 +313,13 @@ export default function SuOutreachPage() {
from?.subject !== subject ||
from.body !== body ||
from.unsubscribeLink !== unsubscribeLink ||
- from.trackReplies !== trackReplies;
+ from.trackReplies !== trackReplies ||
+ JSON.stringify(from.creditOffer) !== JSON.stringify(creditOffer);
act.mutate(
{
action: "send",
body,
+ creditOffer,
outreachId: target.id,
subject,
trackReplies,
@@ -312,7 +329,7 @@ export default function SuOutreachPage() {
onSuccess: () => {
setLastStart(
edited
- ? `draft:${remember({ body, subject, trackReplies, unsubscribeLink })}`
+ ? `draft:${remember({ body, creditOffer, subject, trackReplies, unsubscribeLink })}`
: source,
);
// A send in flight leaves the dialog free for the next row, so only
@@ -340,8 +357,13 @@ export default function SuOutreachPage() {
const truncated = searching && matchTotal > rows.length;
const sending = sendTarget !== null && busy.has(sendTarget.id);
// A failed send keeps its dialog open, so the reason belongs in there with
- // the words that still need fixing.
+ // the words that still need fixing; the server names a bad placeholder.
const sendFailed = act.isError && act.variables?.action === "send";
+ const sendIssue = sendFailed && act.error instanceof ApiError ? act.error.issues[0]?.message : undefined;
+ const addFailed = act.isError && act.variables?.action === "add";
+ const adding = act.isPending && act.variables?.action === "add";
+ // The offer's placeholders are offered only while the note carries one.
+ const placeholders = OUTREACH_PLACEHOLDERS.filter((name) => creditOffer !== null || !isOfferPlaceholder(name));
return (
<div className="space-y-4 pb-9">
@@ -481,13 +503,22 @@ export default function SuOutreachPage() {
))}
</ul>
) : (
- <p className="p-5 text-sm text-muted-foreground">
- {loading
- ? "Loading…"
- : searching
- ? "No matches."
- : "Nothing here. Run a scan to refresh."}
- </p>
+ <div className="flex flex-wrap items-center justify-between gap-3 p-5">
+ <p className="text-sm text-muted-foreground">
+ {loading
+ ? "Loading…"
+ : searching
+ ? addFailed
+ ? `No account has the address ${needle}.`
+ : "No matches."
+ : "Nothing here. Run a scan to refresh."}
+ </p>
+ {searching && !loading ? (
+ <Button disabled={adding} onClick={addByEmail} size="sm" variant="outline">
+ {adding ? "Adding…" : `Add ${needle} to the list`}
+ </Button>
+ ) : null}
+ </div>
)}
</div>
@@ -498,7 +529,7 @@ export default function SuOutreachPage() {
</p>
) : null}
- {act.isError && !sendFailed ? (
+ {act.isError && !sendFailed && !addFailed ? (
<p className="text-sm text-destructive">
That didn&apos;t go through. Run a scan and try again.
</p>
@@ -638,7 +669,7 @@ export default function SuOutreachPage() {
<span className="text-xs text-muted-foreground">
Blank line starts a paragraph. Insert:
</span>
- {OUTREACH_PLACEHOLDERS.map((name) => (
+ {placeholders.map((name) => (
<Button
key={name}
onClick={() => insertPlaceholder(name)}
@@ -649,11 +680,17 @@ export default function SuOutreachPage() {
</Button>
))}
</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."
+ />
{sendFailed ? (
<p className="text-sm text-destructive">
- That didn&apos;t go through. The account may have unsubscribed
- since the last scan, or the text may name a placeholder that
- doesn&apos;t exist.
+ {sendIssue ??
+ "That didn’t go through. The account may have unsubscribed since the last scan, or the text may name a placeholder that doesn’t exist."}
</p>
) : null}
</div>
diff --git a/site/src/lib/jobs/outreach-scan.ts b/site/src/lib/jobs/outreach-scan.ts
index be874a1e..464ae165 100644
--- a/site/src/lib/jobs/outreach-scan.ts
+++ b/site/src/lib/jobs/outreach-scan.ts
@@ -24,6 +24,7 @@ import {
OUTREACH_RECONTACT_DAYS,
OUTREACH_STORAGE_FULL_SHARE,
type OutreachReason,
+ PICKED_REASON,
} from "@/lib/marketing/campaigns";
import { lastActiveByUser } from "@/lib/marketing/lastActive";
import { prisma } from "@/lib/prisma";
@@ -155,9 +156,10 @@ async function scan() {
const retire = async () => {
// Anything this run did not touch no longer qualifies — unsubscribed,
// went cold, cleared the wall, or never came back. Only untouched
- // candidates go; a contacted row is history and stays.
+ // candidates go; a contacted row is history and stays, and so does a
+ // row a person added by hand.
const { count } = await prisma.userOutreach.deleteMany({
- where: { campaign, scannedAt: { lt: startedAt }, status: "todo" },
+ where: { campaign, scannedAt: { lt: startedAt }, status: "todo", NOT: { reasons: { has: PICKED_REASON } } },
});
return count;
};
diff --git a/site/src/lib/marketing/campaigns.ts b/site/src/lib/marketing/campaigns.ts
index 9674ff49..c0d0dbbc 100644
--- a/site/src/lib/marketing/campaigns.ts
+++ b/site/src/lib/marketing/campaigns.ts
@@ -32,9 +32,14 @@ export const OUTREACH_PAYMENT_WINDOW_DAYS = 60;
/** The share of the storage quota at which an account counts as full. */
export const OUTREACH_STORAGE_FULL_SHARE = 0.9;
+/** The reason on a row a person added by email. The scan never retires such
+ * a row; the next scan that lists the account replaces the reason with its own. */
+export const PICKED_REASON = "picked";
+
/** Why an account is on the list. The first two are people using the product
- * well; the rest are walls they hit — the moment a note can turn into a
- * top-up, an upgrade, or a saved subscription. An account can carry several. */
+ * well; the next are walls they hit — the moment a note can turn into a
+ * top-up, an upgrade, or a saved subscription; the last is a person the
+ * operator added by hand. An account can carry several. */
export const OUTREACH_REASONS = [
"spent",
"storage",
@@ -44,6 +49,7 @@ export const OUTREACH_REASONS = [
"past_due",
"canceling",
"canceled",
+ PICKED_REASON,
] as const;
export type OutreachReason = (typeof OUTREACH_REASONS)[number];
@@ -54,6 +60,7 @@ export const OUTREACH_REASON_LABELS: Record<OutreachReason, string> = {
no_credits: "Out of credits",
past_due: "Payment past due",
payment_failed: "Payment declined",
+ picked: "Added by hand",
spent: "Spending credits",
storage: "Holding media",
storage_full: "Storage full",
diff --git a/site/src/lib/marketing/placeholders.test.ts b/site/src/lib/marketing/placeholders.test.ts
index 00409950..68f1e9cb 100644
--- a/site/src/lib/marketing/placeholders.test.ts
+++ b/site/src/lib/marketing/placeholders.test.ts
@@ -45,13 +45,20 @@ describe("fillOutreachText", () => {
// The button row offers every name in the list, so every one of them has to
// resolve to a value; a name the send path forgets to supply would mail the
- // word "undefined" to a real person.
+ // word "undefined" to a real person. The offer's names fill once a note
+ // carries an offer, and are refused before that.
test("every offered placeholder fills with the recipient's value", () => {
+ const withOffer = { ...vars, claimBy: "September 30, 2026", claimUrl: "https://donkeycut.com/app?claim=t" };
for (const name of OUTREACH_PLACEHOLDERS) {
- const filled = fillOutreachText(`{{${name}}}`, vars);
+ const filled = fillOutreachText(`{{${name}}}`, withOffer);
expect(filled).not.toBe("");
expect(filled).not.toContain("undefined");
}
});
+
+ test("an offer placeholder in a note without an offer is refused", () => {
+ expect(refusedPlaceholder("{{claimUrl}}")).toBe(true);
+ expect(refusedPlaceholder("{{claimBy}}")).toBe(true);
+ });
});
diff --git a/site/src/lib/marketing/send-outreach.ts b/site/src/lib/marketing/send-outreach.ts
index 15985645..5c18ffd5 100644
--- a/site/src/lib/marketing/send-outreach.ts
+++ b/site/src/lib/marketing/send-outreach.ts
@@ -1,5 +1,7 @@
import { z } from "zod";
+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";
@@ -22,6 +24,9 @@ export const outreachPayloadSchema = z
vars: z
.object({ balance: z.string(), email: z.string(), firstName: z.string(), name: z.string(), spent: z.string(), storage: z.string() })
.strict() satisfies z.ZodType<OutreachVars>,
+ // The credit offer the note carries, if any. The offer row is made when
+ // the note is built, and the words fill in its link and last day.
+ creditOffer: creditOfferTermsSchema.nullable().default(null),
// Whether the note carries the opt-out footer. The operator decides per
// send; the unsubscribed check always runs.
unsubscribeLink: z.boolean(),
@@ -50,6 +55,12 @@ function outreachText(body: string, unsubscribeUrl: string | null): string {
return `${trimmed}\n\n--\nUnsubscribe from product emails: ${unsubscribeUrl}\n`;
}
+/** The scope of the offer one note makes: the row and the attempt, so a
+ * deliberate second note makes a fresh offer and a retry reuses the first. */
+export function outreachOfferScope(outreachId: string, attempt: number): string {
+ return `outreach:${outreachId}:${attempt}`;
+}
+
// Builds one outreach note. The reply target is the operator's call per
// send: the row's own signed alias, or the sending address itself.
export async function buildOutreachEmail(payload: OutreachPayload, user: EmailUser): Promise<EmailMessage> {
@@ -57,11 +68,20 @@ export async function buildOutreachEmail(payload: OutreachPayload, user: EmailUs
if (!from) throw new PermanentSendError("RESEND_FROM_EMAIL is not configured.");
if (await isMarketingUnsubscribed(user.id)) throw new PermanentSendError("That account is unsubscribed.");
+ const offer = payload.creditOffer
+ ? await createTermsCreditOffer({
+ scope: outreachOfferScope(payload.outreachId, payload.attempt),
+ userId: user.id,
+ terms: payload.creditOffer,
+ offeredByUserId: payload.actorUserId,
+ })
+ : null;
+ const vars: OutreachVars = { ...payload.vars, ...offer?.vars };
let subject: string;
let body: string;
try {
- subject = fillOutreachText(payload.subject, payload.vars);
- body = fillOutreachText(payload.body, payload.vars);
+ subject = fillOutreachText(payload.subject, vars);
+ body = fillOutreachText(payload.body, vars);
} catch (error) {
if (error instanceof UnknownPlaceholderError) throw new PermanentSendError(error.message);
throw error;
diff --git a/site/src/queries/outreach.ts b/site/src/queries/outreach.ts
index 3635202a..b94d12d4 100644
--- a/site/src/queries/outreach.ts
+++ b/site/src/queries/outreach.ts
@@ -8,6 +8,7 @@ import {
useQueryClient,
} from "@tanstack/react-query";
+import type { CreditOfferTerms } from "@/lib/credits/offerTerms";
import type { OutreachReason, OutreachStatus } from "@/lib/marketing/campaigns";
import { apiFetch } from "@/queries/apiClient";
import type { AsyncJobStatus } from "@/queries/jobs";
@@ -96,8 +97,11 @@ type OutreachAction =
body: string;
unsubscribeLink: boolean;
trackReplies: boolean;
+ creditOffer: CreditOfferTerms | null;
}
- | { action: "ignore" | "unignore" | "replied"; outreachId: string };
+ | { action: "ignore" | "unignore" | "replied"; outreachId: string }
+ // Puts the account with this address on the list, and answers with its row.
+ | { action: "add"; email: string };
const outreachActionKey = ["outreach", "action"] as const;
@@ -121,8 +125,10 @@ export function useOutreachAction() {
export function useBusyOutreachIds(): Set<string> {
const running = useMutationState({
filters: { mutationKey: outreachActionKey, status: "pending" },
- select: (mutation) =>
- (mutation.state.variables as OutreachAction | undefined)?.outreachId,
+ select: (mutation) => {
+ const variables = mutation.state.variables as OutreachAction | undefined;
+ return variables && "outreachId" in variables ? variables.outreachId : undefined;
+ },
});
return new Set(running.filter((id): id is string => typeof id === "string"));
}
diff --git a/site/src/queries/outreachTemplates.ts b/site/src/queries/outreachTemplates.ts
index 6649f686..14d7e7f6 100644
--- a/site/src/queries/outreachTemplates.ts
+++ b/site/src/queries/outreachTemplates.ts
@@ -2,6 +2,7 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import type { CreditOfferTerms } from "@/lib/credits/offerTerms";
import { apiFetch } from "@/queries/apiClient";
export type SavedTemplate = {
@@ -12,7 +13,9 @@ export type SavedTemplate = {
unsubscribeLink: boolean;
trackReplies: boolean;
updatedAt: string;
- promotion: Record<string, unknown> | null;
+ // The credit offer the template starts a note with, as stored; a form
+ // parses it before use.
+ promotion: unknown;
};
export const outreachTemplatesQueryKey = ["outreach", "templates"] as const;
@@ -36,7 +39,7 @@ export function useSaveOutreachTemplate() {
body: string;
unsubscribeLink: boolean;
trackReplies: boolean;
- promotion?: Record<string, unknown> | null;
+ promotion?: CreditOfferTerms | null;
}) =>
apiFetch<{ template: SavedTemplate }>("/api/marketing/templates", {
body: JSON.stringify(input),