Skip to content

Open source CapCut alternative.

TypeScript

feat(site): promotion credit offers, pause and resume, outreach templates

David Lebe67cfb2d75f
diff --git a/site/packages/abexp/src/audience.ts b/site/packages/abexp/src/audience.ts
index 882f1ef4..858c2f69 100644
--- a/site/packages/abexp/src/audience.ts
+++ b/site/packages/abexp/src/audience.ts
@@ -15,6 +15,7 @@ export const audienceSchema = z
// Account creation window; either edge may be open.
createdAfter: z.iso.datetime().nullable().default(null),
createdBefore: z.iso.datetime().nullable().default(null),
+ minimumAccountAgeDays: z.number().int().min(1).max(36500).nullable().default(null),
// Whether the account holds an active Pro subscription.
plan: z.enum(["any", "free", "pro"]).default("any"),
// Whether the account has ever paid for anything.
@@ -50,7 +51,7 @@ export type AudienceFact = keyof AudienceFacts;
export function audienceNeeds(audience: Audience): Set<AudienceFact> {
const needs = new Set<AudienceFact>();
if (audience.countries.length > 0) needs.add("country");
- if (audience.createdAfter || audience.createdBefore) needs.add("createdAt");
+ if (audience.createdAfter || audience.createdBefore || audience.minimumAccountAgeDays != null) needs.add("createdAt");
if (audience.plan !== "any") needs.add("pro");
if (audience.paid !== "any") needs.add("paid");
if (audience.activeWithinDays !== null) needs.add("lastActiveAt");
@@ -60,6 +61,8 @@ export function audienceNeeds(audience: Audience): Set<AudienceFact> {
}
export function matchesAudience(audience: Audience, facts: AudienceFacts, now: Date): boolean {
+ if (audience.minimumAccountAgeDays != null &&
+ facts.createdAt.getTime() > now.getTime() - audience.minimumAccountAgeDays * 86_400_000) return false;
if (audience.countries.length > 0) {
if (!facts.country || !audience.countries.includes(facts.country)) return false;
}
@@ -89,6 +92,7 @@ export function matchesAudience(audience: Audience, facts: AudienceFacts, now: D
/** One line for a list: the rules an audience sets. */
export function describeAudience(audience: Audience): string {
const parts: string[] = [];
+ if (audience.minimumAccountAgeDays != null) parts.push(`signed up at least ${audience.minimumAccountAgeDays} days ago`);
if (audience.countries.length) parts.push(audience.countries.join(", "));
if (audience.createdAfter) parts.push(`created from ${audience.createdAfter.slice(0, 10)}`);
if (audience.createdBefore) parts.push(`created before ${audience.createdBefore.slice(0, 10)}`);
diff --git a/site/prisma/migrations/20260910011638/migration.sql b/site/prisma/migrations/20260910011638/migration.sql
new file mode 100644
index 00000000..bed30676
--- /dev/null
+++ b/site/prisma/migrations/20260910011638/migration.sql
@@ -0,0 +1,16 @@
+-- AlterTable
+ALTER TABLE "OutreachTemplate" ADD COLUMN "promotion" JSONB;
+
+-- AlterTable
+ALTER TABLE "Promotion" ADD COLUMN "creditOffer" JSONB;
+
+-- CreateTable
+CREATE TABLE "EmailDailyQuota" (
+ "day" TEXT NOT NULL,
+ "sent" INTEGER NOT NULL DEFAULT 0,
+ "inFlight" INTEGER NOT NULL DEFAULT 0,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "EmailDailyQuota_pkey" PRIMARY KEY ("day")
+);
diff --git a/site/src/app/api/credits/offers/claim/route.ts b/site/src/app/api/credits/offers/claim/route.ts
index dc813b2f..23785222 100644
--- a/site/src/app/api/credits/offers/claim/route.ts
+++ b/site/src/app/api/credits/offers/claim/route.ts
@@ -39,7 +39,7 @@ export const GET = withDonkeyAuth(async (request) => {
},
where: { id: offerId },
});
- if (!offer || offer.kind !== MANUAL_OFFER_KIND) return notFoundResponse();
+ if (!offer || (offer.kind !== MANUAL_OFFER_KIND && offer.kind !== "promotion_email")) return notFoundResponse();
if (offer.userId !== request.donkey.userId) return forbiddenResponse();
if (!offer.claimedAt && !creditOfferOpen(offer, new Date())) return goneResponse();
return NextResponse.json({
diff --git a/site/src/app/api/marketing/templates/route.ts b/site/src/app/api/marketing/templates/route.ts
index f3675fa3..e9ba6090 100644
--- a/site/src/app/api/marketing/templates/route.ts
+++ b/site/src/app/api/marketing/templates/route.ts
@@ -1,6 +1,7 @@
import { NextResponse } from "next/server";
import { z } from "zod";
+import { Prisma } from "@/generated/prisma/client";
import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";
import { prisma } from "@/lib/prisma";
@@ -14,6 +15,7 @@ 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(),
})
.strict();
@@ -25,6 +27,7 @@ const templateSelect = {
trackReplies: true,
unsubscribeLink: true,
updatedAt: true,
+ promotion: true,
} as const;
type TemplateRow = {
@@ -35,6 +38,7 @@ type TemplateRow = {
trackReplies: boolean;
unsubscribeLink: boolean;
updatedAt: Date;
+ promotion: unknown;
};
function serialize(row: TemplateRow) {
@@ -46,6 +50,7 @@ function serialize(row: TemplateRow) {
trackReplies: row.trackReplies,
unsubscribeLink: row.unsubscribeLink,
updatedAt: row.updatedAt.toISOString(),
+ promotion: row.promotion,
};
}
@@ -75,6 +80,7 @@ export const POST = withSuperUser(async (request) => {
}
const { body, name, subject, trackReplies, unsubscribeLink } = parsed.data;
+ const promotion = parsed.data.promotion ? (parsed.data.promotion as Prisma.InputJsonValue) : Prisma.DbNull;
const template = await prisma.outreachTemplate.upsert({
create: {
actorUserId: request.donkey.userId,
@@ -83,6 +89,7 @@ export const POST = withSuperUser(async (request) => {
subject,
trackReplies,
unsubscribeLink,
+ promotion,
},
select: templateSelect,
update: {
@@ -91,6 +98,7 @@ export const POST = withSuperUser(async (request) => {
subject,
trackReplies,
unsubscribeLink,
+ promotion,
},
where: { name },
});
diff --git a/site/src/app/api/su/promotions/[id]/cancel/route.ts b/site/src/app/api/su/promotions/[id]/cancel/route.ts
new file mode 100644
index 00000000..ce85e9e9
--- /dev/null
+++ b/site/src/app/api/su/promotions/[id]/cancel/route.ts
@@ -0,0 +1,22 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+
+import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";
+import { invalidResponse } from "@/lib/config/experimentList";
+import { listPromotions } from "@/lib/marketing/promotions";
+import { prisma } from "@/lib/prisma";
+
+type Params = { params: Promise<{ id: string }> };
+const idSchema = z.string().trim().min(1);
+
+export const POST = withSuperUser(async (_request, { params }: Params) => {
+ const parsed = idSchema.safeParse((await params).id);
+ if (!parsed.success) return notFoundResponse();
+ const promotion = await prisma.promotion.findUnique({ where: { id: parsed.data } });
+ if (!promotion) return notFoundResponse();
+ if (promotion.status !== "sending") {
+ return invalidResponse([{ path: ["status"], message: "This promotion is not running." }]);
+ }
+ await prisma.promotion.update({ data: { status: "paused" }, where: { id: promotion.id } });
+ return NextResponse.json({ promotions: await listPromotions() });
+});
diff --git a/site/src/app/su/SuSidebar.tsx b/site/src/app/su/SuSidebar.tsx
index bc90886f..029970f7 100644
--- a/site/src/app/su/SuSidebar.tsx
+++ b/site/src/app/su/SuSidebar.tsx
@@ -91,7 +91,7 @@ export function SuSidebar() {
/>
</span>
<span className="text-[17px] font-semibold tracking-tight">
- Super user
+ Super User
</span>
</SidebarHeader>
diff --git a/site/src/app/su/experiments/AudienceFields.tsx b/site/src/app/su/experiments/AudienceFields.tsx
index 98728055..d66b673e 100644
--- a/site/src/app/su/experiments/AudienceFields.tsx
+++ b/site/src/app/su/experiments/AudienceFields.tsx
@@ -12,6 +12,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@
// conversions below move between it and the audience schema.
export type AudienceDraft = {
+ minimumAccountAgeDays: string;
countries: string;
createdAfter: string;
createdBefore: string;
@@ -26,6 +27,7 @@ export const blankAudienceDraft = (): AudienceDraft => ({
countries: "",
createdAfter: "",
createdBefore: "",
+ minimumAccountAgeDays: "",
plan: "any",
paid: "any",
activeWithinDays: "",
@@ -39,6 +41,7 @@ const dayStart = (d: string) => (d ? new Date(`${d}T00:00:00Z`).toISOString() :
const numberOrNull = (s: string) => (s.trim() === "" ? null : Number(s));
export const audienceDraftFrom = (a: Audience): AudienceDraft => ({
+ minimumAccountAgeDays: numberOrBlank(a.minimumAccountAgeDays),
countries: a.countries.join(", "),
createdAfter: day(a.createdAfter),
createdBefore: day(a.createdBefore),
@@ -50,6 +53,7 @@ export const audienceDraftFrom = (a: Audience): AudienceDraft => ({
});
export const audienceInputFrom = (draft: AudienceDraft): AudienceInput => ({
+ minimumAccountAgeDays: draft.minimumAccountAgeDays.trim() ? Number(draft.minimumAccountAgeDays) : null,
countries: draft.countries
.split(",")
.map((s) => s.trim().toUpperCase())
@@ -111,6 +115,17 @@ export function AudienceFields({
onChange={(e) => onChange({ createdBefore: e.target.value })}
/>
</Field>
+ <Field label="Signed up at least (days)" htmlFor="aud-min-age">
+ <Input
+ id="aud-min-age"
+ type="number"
+ min={1}
+ max={36500}
+ disabled={disabled}
+ value={value.minimumAccountAgeDays}
+ onChange={(e) => onChange({ minimumAccountAgeDays: e.target.value })}
+ />
+ </Field>
<Field label="Plan" htmlFor="aud-plan">
<Select
disabled={disabled}
diff --git a/site/src/app/su/layout.tsx b/site/src/app/su/layout.tsx
index 5883b554..63878243 100644
--- a/site/src/app/su/layout.tsx
+++ b/site/src/app/su/layout.tsx
@@ -11,7 +11,7 @@ import { SuShell } from "@/app/su/SuShell";
// exports dock, the welcome sequence — mounts on an admin page.
export const metadata: Metadata = {
robots: { follow: false, index: false },
- title: "Super user",
+ title: "Super User",
};
export default function SuLayout({ children }: { children: ReactNode }) {
diff --git a/site/src/app/su/promotions/PromotionDialog.tsx b/site/src/app/su/promotions/PromotionDialog.tsx
index fccbd924..78fb4f38 100644
--- a/site/src/app/su/promotions/PromotionDialog.tsx
+++ b/site/src/app/su/promotions/PromotionDialog.tsx
@@ -39,12 +39,14 @@ import {
useTestPromotion,
type PromotionSummary,
} from "@/queries/promotions";
+import { useOutreachTemplates, useSaveOutreachTemplate } from "@/queries/outreachTemplates";
// One form writes a promotion and sends it: the words, the button, which
// address it comes from, who gets it, and which earlier promotions' readers
// are left out. A sent promotion opens read-only.
type Draft = {
+ creditOffer: import("@/lib/marketing/promotionOfferInput").PromotionOffer | null;
name: string;
subject: string;
body: string;
@@ -59,8 +61,9 @@ const blank = (): Draft => ({
name: "",
subject: "",
body: "",
- ctaLabel: "",
- ctaUrl: "",
+ ctaLabel: "Claim my AI credits",
+ ctaUrl: "{{claimUrl}}",
+ creditOffer: { dollars: 15, claimWindowDays: 3, expiresAfterDays: 28 },
sender: "bulk",
audience: blankAudienceDraft(),
excludePromotionIds: [],
@@ -70,8 +73,9 @@ const fromSummary = (p: PromotionSummary): Draft => ({
name: p.name,
subject: p.subject,
body: p.body,
- ctaLabel: p.ctaLabel ?? "",
- ctaUrl: p.ctaUrl ?? "",
+ ctaLabel: p.ctaLabel ?? (p.creditOffer ? "Claim my AI credits" : ""),
+ ctaUrl: p.ctaUrl ?? (p.creditOffer ? "{{claimUrl}}" : ""),
+ creditOffer: p.creditOffer ?? { dollars: 15, claimWindowDays: 3, expiresAfterDays: 28 },
sender: p.sender,
audience: audienceDraftFrom(p.audience),
excludePromotionIds: p.excludePromotionIds,
@@ -84,6 +88,7 @@ function toInput(draft: Draft): unknown {
body: draft.body.trim(),
ctaLabel: draft.ctaLabel.trim() || null,
ctaUrl: draft.ctaUrl.trim() || null,
+ creditOffer: draft.creditOffer,
sender: draft.sender,
audience: audienceInputFrom(draft.audience),
excludePromotionIds: draft.excludePromotionIds,
@@ -114,14 +119,17 @@ export function PromotionDialog({
const [savedId, setSavedId] = useState<string | null>(existing?.id ?? null);
const [issues, setIssues] = useState<string[]>([]);
const [notice, setNotice] = useState<string | null>(null);
+ const [templateName, setTemplateName] = useState("");
const [confirm, setConfirm] = useState<{ id: string; count: SegmentCount } | null>(null);
const save = useSavePromotion();
const send = useSendPromotion();
const test = useTestPromotion();
const count = useCountSegment();
+ const saveTemplate = useSaveOutreachTemplate();
+ const templates = useOutreachTemplates();
const readOnly = existing !== null && existing.status !== "draft";
- const busy = save.isPending || send.isPending || test.isPending || count.isPending;
+ const busy = save.isPending || send.isPending || test.isPending || count.isPending || saveTemplate.isPending;
// Earlier promotions that reached anyone; the one being edited is not a
// choice against itself.
const earlier = promotions.filter((p) => p.id !== existing?.id && p.status !== "draft");
@@ -135,6 +143,18 @@ export function PromotionDialog({
? Array.from(new Set([...d.excludePromotionIds, id]))
: d.excludePromotionIds.filter((x) => x !== id),
}));
+ const loadTemplate = (id: string) => {
+ const template = templates.data?.templates.find((item) => item.id === id);
+ if (!template) return;
+ setDraft((current) => ({
+ ...current,
+ subject: template.subject,
+ body: template.body,
+ creditOffer: template.promotion
+ ? (template.promotion as Draft["creditOffer"])
+ : current.creditOffer,
+ }));
+ };
const parse = (): PromotionInput | null => {
const parsed = promotionInputSchema.safeParse(toInput(draft));
@@ -169,6 +189,25 @@ export function PromotionDialog({
if (id) onOpenChange(false);
};
+ const onSaveTemplate = () => {
+ const name = templateName.trim();
+ if (!name) {
+ setIssues(["Enter a template name."]);
+ return;
+ }
+ saveTemplate.mutate({
+ name,
+ subject: draft.subject.trim(),
+ body: draft.body.trim(),
+ unsubscribeLink: true,
+ trackReplies: false,
+ promotion: draft.creditOffer,
+ }, {
+ onSuccess: () => setNotice(`Template ${name} saved.`),
+ onError: fail,
+ });
+ };
+
const onTest = async () => {
setNotice(null);
setIssues([]);
@@ -216,6 +255,16 @@ export function PromotionDialog({
? "Sent as it reads here."
: "One email to everyone in the segment. Unsubscribed accounts are always left out."}
</DialogDescription>
+ {!readOnly && templates.data?.templates.length ? (
+ <Select onValueChange={(id: string | null) => id && loadTemplate(id)}>
+ <SelectTrigger><SelectValue placeholder="Load saved template" /></SelectTrigger>
+ <SelectContent>
+ {templates.data.templates.map((template) => (
+ <SelectItem key={template.id} value={template.id}>{template.name}</SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ ) : null}
</DialogHeader>
<div className="grid gap-5">
@@ -333,6 +382,17 @@ export function PromotionDialog({
</Button>
) : (
<>
+ <Input
+ aria-label="Template name"
+ placeholder="Template name"
+ value={templateName}
+ onChange={(e) => setTemplateName(e.target.value)}
+ disabled={busy}
+ className="w-36"
+ />
+ <Button type="button" variant="outline" disabled={busy} onClick={onSaveTemplate}>
+ {saveTemplate.isPending ? "Saving…" : "Save template"}
+ </Button>
<Button type="button" variant="secondary" disabled={busy} onClick={onSave}>
{save.isPending ? "Saving…" : "Save draft"}
</Button>
diff --git a/site/src/app/su/promotions/page.tsx b/site/src/app/su/promotions/page.tsx
index 71545391..5d3843d9 100644
--- a/site/src/app/su/promotions/page.tsx
+++ b/site/src/app/su/promotions/page.tsx
@@ -18,13 +18,20 @@ import {
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import type { PromotionSender, PromotionStatus } from "@/lib/marketing/promotionInput";
-import { useDeletePromotion, usePromotions, type PromotionSummary } from "@/queries/promotions";
+import {
+ useCancelPromotion,
+ useDeletePromotion,
+ usePromotions,
+ useSendPromotion,
+ type PromotionSummary,
+} from "@/queries/promotions";
type BadgeVariant = "default" | "secondary" | "outline" | "destructive";
const STATUS_VARIANT: Record<PromotionStatus, BadgeVariant> = {
draft: "outline",
sending: "default",
+ paused: "outline",
sent: "secondary",
};
@@ -108,6 +115,8 @@ function PromotionRow({
onDuplicate: () => void;
}) {
const remove = useDeletePromotion();
+ const cancel = useCancelPromotion();
+ const resume = useSendPromotion();
const [confirmDelete, setConfirmDelete] = useState(false);
const skipped = p.excludePromotionIds
.map((id) => all.find((other) => other.id === id)?.name ?? "a deleted promotion")
@@ -142,7 +151,25 @@ function PromotionRow({
<Button size="sm" variant="outline" onClick={onDuplicate}>
Duplicate
</Button>
- {p.status !== "sending" ? (
+ {p.status === "sending" ? (
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={cancel.isPending}
+ onClick={() => cancel.mutate(p.id)}
+ >
+ {cancel.isPending ? "Pausing…" : "Pause"}
+ </Button>
+ ) : p.status === "paused" ? (
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={resume.isPending}
+ onClick={() => resume.mutate(p.id)}
+ >
+ {resume.isPending ? "Resuming…" : "Resume"}
+ </Button>
+ ) : (
<Button
size="sm"
variant="ghost"
@@ -154,7 +181,7 @@ function PromotionRow({
>
Delete
</Button>
- ) : null}
+ )}
</div>
</div>
<AlertDialog open={confirmDelete} onOpenChange={(isOpen) => {
diff --git a/site/src/cut/worker/cf/worker.ts b/site/src/cut/worker/cf/worker.ts
index 060e0237..803c45f4 100644
--- a/site/src/cut/worker/cf/worker.ts
+++ b/site/src/cut/worker/cf/worker.ts
@@ -135,7 +135,12 @@ export default {
body: JSON.stringify({ jobId }),
});
if (res.ok) message.ack();
- else message.retry({ delaySeconds: 30 });
+ else {
+ const retryAfter = Number(res.headers.get("retry-after"));
+ message.retry({
+ delaySeconds: Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : 30,
+ });
+ }
} catch {
message.retry({ delaySeconds: 30 });
}
diff --git a/site/src/lib/marketing/placeholders.ts b/site/src/lib/marketing/placeholders.ts
index 01864cd1..53f2c40f 100644
--- a/site/src/lib/marketing/placeholders.ts
+++ b/site/src/lib/marketing/placeholders.ts
@@ -32,12 +32,14 @@ export type PromotionVars = {
firstName: string;
name: string;
email: string;
+ claimUrl?: string;
};
export const PROMOTION_PLACEHOLDERS = [
"firstName",
"name",
"email",
+ "claimUrl",
] as const satisfies readonly (keyof PromotionVars)[];
const PLACEHOLDER = /\{\{\s*([a-zA-Z]+)\s*\}\}/g;
@@ -54,12 +56,16 @@ export function firstNameOf(name: string): string {
return name.trim().split(/\s+/)[0] || name;
}
-function fill(text: string, vars: Record<string, string>, allowed: readonly string[]): string {
+function fill(text: string, vars: Record<string, unknown>, allowed: readonly string[]): string {
return text.replace(PLACEHOLDER, (_match, key: string) => {
if (!allowed.includes(key)) {
throw new UnknownPlaceholderError(key);
}
- return vars[key];
+ const value = vars[key];
+ if (typeof value !== "string") {
+ throw new UnknownPlaceholderError(key);
+ }
+ return value;
});
}
diff --git a/site/src/lib/marketing/promotionCopy.ts b/site/src/lib/marketing/promotionCopy.ts
index 9c6d4c61..e8000a4b 100644
--- a/site/src/lib/marketing/promotionCopy.ts
+++ b/site/src/lib/marketing/promotionCopy.ts
@@ -59,12 +59,12 @@ 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): RenderedPromotion {
- const vars = promotionVars(user);
+export function renderPromotion(copy: PromotionCopy, user: EmailUser, claimUrl?: string): RenderedPromotion {
+ const vars = { ...promotionVars(user), claimUrl };
const subject = fillPromotionText(copy.subject, vars);
const cta =
copy.ctaLabel !== null && copy.ctaUrl !== null
- ? { label: fillPromotionText(copy.ctaLabel, vars), url: copy.ctaUrl }
+ ? { label: fillPromotionText(copy.ctaLabel, vars), url: fillPromotionText(copy.ctaUrl, vars) }
: null;
const body = fillPromotionText(copy.body.replaceAll(BUTTON_MARK, "\u0000button\u0000"), vars).replaceAll(
"\u0000button\u0000",
diff --git a/site/src/lib/marketing/promotionInput.ts b/site/src/lib/marketing/promotionInput.ts
index fb669f3b..1e6c509a 100644
--- a/site/src/lib/marketing/promotionInput.ts
+++ b/site/src/lib/marketing/promotionInput.ts
@@ -1,5 +1,6 @@
import { audienceSchema, type Audience } from "@donkeycut/abexp";
import { z } from "zod";
+import { CLAIM_URL_PLACEHOLDER, promotionOfferSchema, type PromotionOffer } from "@/lib/marketing/promotionOfferInput";
// 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.
@@ -7,10 +8,8 @@ import { z } from "zod";
export const PROMOTION_SENDERS = ["bulk", "personal"] as const;
export type PromotionSender = (typeof PROMOTION_SENDERS)[number];
-export const PROMOTION_STATUSES = ["draft", "sending", "sent"] as const;
+export const PROMOTION_STATUSES = ["draft", "sending", "paused", "sent"] as const;
-// Sends tried on one recipient before the row is given up.
-export const MAX_SEND_ATTEMPTS = 5;
export type PromotionStatus = (typeof PROMOTION_STATUSES)[number];
export const promotionInputSchema = z
@@ -19,13 +18,18 @@ export const promotionInputSchema = z
subject: z.string().trim().min(1).max(200),
body: z.string().trim().min(1).max(10_000),
ctaLabel: z.string().trim().min(1).max(80).nullable(),
- ctaUrl: z.url().max(2000).nullable(),
+ ctaUrl: z.union([z.url().max(2000).refine((url) => ["https:", "http:"].includes(new URL(url).protocol), "Use an HTTP or HTTPS link."), z.literal(CLAIM_URL_PLACEHOLDER)]).nullable(),
+ creditOffer: promotionOfferSchema.nullable().default(null),
sender: z.enum(PROMOTION_SENDERS),
audience: audienceSchema,
// Earlier promotions whose recipients are left out.
excludePromotionIds: z.array(z.string().min(1)).max(100),
})
.strict()
+ .refine((d) => (d.creditOffer !== null) === (d.ctaUrl === CLAIM_URL_PLACEHOLDER), {
+ message: "A credit offer needs a claim button. Set its link to {{claimUrl}}.",
+ path: ["ctaUrl"],
+ })
.refine((d) => (d.ctaLabel === null) === (d.ctaUrl === null), {
message: "A button needs both a label and a link.",
path: ["ctaLabel"],
@@ -34,6 +38,7 @@ export const promotionInputSchema = z
export type PromotionInput = z.output<typeof promotionInputSchema>;
export type PromotionSummary = {
+ creditOffer: PromotionOffer | null;
id: string;
name: string;
subject: string;
diff --git a/site/src/lib/marketing/promotionOfferInput.ts b/site/src/lib/marketing/promotionOfferInput.ts
new file mode 100644
index 00000000..3c2ae27f
--- /dev/null
+++ b/site/src/lib/marketing/promotionOfferInput.ts
@@ -0,0 +1,15 @@
+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 const SAMPLE_CLAIM_URL = "https://example.com/preview-credit-offer";
+
+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 82fd1082..812c19f0 100644
--- a/site/src/lib/marketing/promotionSave.ts
+++ b/site/src/lib/marketing/promotionSave.ts
@@ -1,4 +1,5 @@
-import type { Prisma } from "@/generated/prisma/client";
+import { Prisma } from "@/generated/prisma/client";
+import { SAMPLE_CLAIM_URL } from "@/lib/marketing/promotionOfferInput";
import { invalidResponse } from "@/lib/config/experimentList";
import { UnknownPlaceholderError } from "@/lib/marketing/placeholders";
import { renderPromotion, SAMPLE_RECIPIENT } from "@/lib/marketing/promotionCopy";
@@ -10,7 +11,7 @@ import type { PromotionInput } from "@/lib/marketing/promotionInput";
export function copyIssue(input: PromotionInput): Response | null {
try {
- renderPromotion(input, SAMPLE_RECIPIENT);
+ renderPromotion(input, SAMPLE_RECIPIENT, input.creditOffer ? SAMPLE_CLAIM_URL : undefined);
return null;
} catch (error) {
if (error instanceof UnknownPlaceholderError) {
@@ -23,6 +24,7 @@ export function copyIssue(input: PromotionInput): Response | null {
export function promotionData(input: PromotionInput, actorUserId: string) {
return {
actorUserId,
+ creditOffer: input.creditOffer ? (input.creditOffer as Prisma.InputJsonValue) : Prisma.DbNull,
audience: input.audience as Prisma.InputJsonValue,
body: input.body,
ctaLabel: input.ctaLabel,
diff --git a/site/src/queries/outreachTemplates.ts b/site/src/queries/outreachTemplates.ts
index b56bd66d..6649f686 100644
--- a/site/src/queries/outreachTemplates.ts
+++ b/site/src/queries/outreachTemplates.ts
@@ -12,6 +12,7 @@ export type SavedTemplate = {
unsubscribeLink: boolean;
trackReplies: boolean;
updatedAt: string;
+ promotion: Record<string, unknown> | null;
};
export const outreachTemplatesQueryKey = ["outreach", "templates"] as const;
@@ -35,6 +36,7 @@ export function useSaveOutreachTemplate() {
body: string;
unsubscribeLink: boolean;
trackReplies: boolean;
+ promotion?: Record<string, unknown> | null;
}) =>
apiFetch<{ template: SavedTemplate }>("/api/marketing/templates", {
body: JSON.stringify(input),