Skip to content

Open source CapCut alternative.

TypeScript

feat(site): a promotion draft saves however it stands

David Lef38dd7e53661
diff --git a/site/src/app/api/su/promotions/[id]/route.ts b/site/src/app/api/su/promotions/[id]/route.ts
index a3be2930..883802e0 100644
--- a/site/src/app/api/su/promotions/[id]/route.ts
+++ b/site/src/app/api/su/promotions/[id]/route.ts
@@ -3,23 +3,21 @@ import { z } from "zod";
import { invalidResponse } from "@/lib/config/experimentList";
import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";
-import { promotionInputSchema } from "@/lib/marketing/promotionInput";
+import { promotionDraftSchema } from "@/lib/marketing/promotionInput";
import { listPromotions } from "@/lib/marketing/promotions";
-import { copyIssue, promotionData } from "@/lib/marketing/promotionSave";
+import { promotionData } from "@/lib/marketing/promotionSave";
import { prisma } from "@/lib/prisma";
type Params = { params: Promise<{ id: string }> };
const idSchema = z.string().trim().min(1);
-// A draft is edited in place; anything that has started sending is history
-// and stays as it went out.
+// A draft is edited in place and saves as it stands, blanks and all;
+// anything that has started sending is history and stays as it went out.
export const PUT = withSuperUser(async (request, { params }: Params) => {
const id = idSchema.safeParse((await params).id);
if (!id.success) return notFoundResponse();
- const parsed = promotionInputSchema.safeParse(await request.json());
+ const parsed = promotionDraftSchema.safeParse(await request.json());
if (!parsed.success) return invalidResponse(parsed.error.issues);
- const refused = copyIssue(parsed.data);
- if (refused) return refused;
const existing = await prisma.promotion.findUnique({ select: { status: true }, where: { id: id.data } });
if (!existing) return notFoundResponse();
diff --git a/site/src/app/api/su/promotions/[id]/send/route.ts b/site/src/app/api/su/promotions/[id]/send/route.ts
index cb7a8e4f..555b099e 100644
--- a/site/src/app/api/su/promotions/[id]/send/route.ts
+++ b/site/src/app/api/su/promotions/[id]/send/route.ts
@@ -5,6 +5,7 @@ import { invalidResponse } from "@/lib/config/experimentList";
import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";
import { enqueueJob } from "@/lib/jobs/queue";
import { listPromotions } from "@/lib/marketing/promotions";
+import { sendIssue } from "@/lib/marketing/promotionSave";
import { prisma } from "@/lib/prisma";
// Without a queue (local dev) the job's first run happens inside this
@@ -14,7 +15,7 @@ export const maxDuration = 300;
type Params = { params: Promise<{ id: string }> };
const idSchema = z.string().trim().min(1);
-// Starts a send: a job reads the segment a page at a time into outbox rows
+// Starts a send, once the draft reads as a complete promotion: a job reads the segment a page at a time into outbox rows
// while the promotion is queuing, moves it to sending once every recipient
// is a row, and the outbox drainer mails the rows under the budget. The rows
// are the send's memory — a later promotion that excludes this one reads
@@ -27,6 +28,8 @@ export const POST = withSuperUser(async (request, { params }: Params) => {
if (promotion.status !== "draft" && promotion.status !== "paused") {
return invalidResponse([{ path: ["status"], message: "This promotion has already been sent." }]);
}
+ const refused = sendIssue(promotion);
+ if (refused) return refused;
await prisma.promotion.update({
data: { startedAt: promotion.startedAt ?? new Date(), status: "queuing" },
diff --git a/site/src/app/api/su/promotions/[id]/test/route.ts b/site/src/app/api/su/promotions/[id]/test/route.ts
index 300754ac..6e6a8df0 100644
--- a/site/src/app/api/su/promotions/[id]/test/route.ts
+++ b/site/src/app/api/su/promotions/[id]/test/route.ts
@@ -4,21 +4,25 @@ import { z } from "zod";
import { invalidResponse } from "@/lib/config/experimentList";
import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";
import { deliverEmail } from "@/lib/email/outbox";
+import { sendIssue } from "@/lib/marketing/promotionSave";
import { prisma } from "@/lib/prisma";
type Params = { params: Promise<{ id: string }> };
const idSchema = z.string().trim().min(1);
// Mails the saved copy to the operator, placeholders filled with their own
-// account. A copy error comes back on the body field.
+// account, once the draft reads as a complete promotion. A copy error comes
+// back on the body field.
export const POST = withSuperUser(async (request, { params }: Params) => {
const id = idSchema.safeParse((await params).id);
if (!id.success) return notFoundResponse();
const [promotion, operator] = await Promise.all([
- prisma.promotion.findUnique({ select: { id: true }, where: { id: id.data } }),
+ prisma.promotion.findUnique({ where: { id: id.data } }),
prisma.user.findUnique({ select: { email: true, id: true }, where: { id: request.donkey.userId } }),
]);
if (!promotion || !operator) return notFoundResponse();
+ const refused = sendIssue(promotion);
+ if (refused) return refused;
const delivery = await deliverEmail({
idempotencyKey: `promotion-test:${promotion.id}:${Date.now()}`,
diff --git a/site/src/app/api/su/promotions/route.ts b/site/src/app/api/su/promotions/route.ts
index 7b26ef27..20c50801 100644
--- a/site/src/app/api/su/promotions/route.ts
+++ b/site/src/app/api/su/promotions/route.ts
@@ -2,9 +2,9 @@ import { NextResponse } from "next/server";
import { invalidResponse } from "@/lib/config/experimentList";
import { withSuperUser } from "@/lib/donkey-api-auth";
-import { promotionInputSchema } from "@/lib/marketing/promotionInput";
+import { promotionDraftSchema } from "@/lib/marketing/promotionInput";
import { listPromotions, promotionSenders } from "@/lib/marketing/promotions";
-import { copyIssue, promotionData } from "@/lib/marketing/promotionSave";
+import { promotionData } from "@/lib/marketing/promotionSave";
import { prisma } from "@/lib/prisma";
// Promotions: the list with the addresses the senders stand for, and a new
@@ -15,10 +15,8 @@ export const GET = withSuperUser(async () => {
});
export const POST = withSuperUser(async (request) => {
- const parsed = promotionInputSchema.safeParse(await request.json());
+ const parsed = promotionDraftSchema.safeParse(await request.json());
if (!parsed.success) return invalidResponse(parsed.error.issues);
- const refused = copyIssue(parsed.data);
- if (refused) return refused;
const promotion = await prisma.promotion.create({
data: promotionData(parsed.data, request.donkey.userId),
select: { id: true },
diff --git a/site/src/app/su/promotions/PromotionDialog.tsx b/site/src/app/su/promotions/PromotionDialog.tsx
index 8ed75493..ab8e7db6 100644
--- a/site/src/app/su/promotions/PromotionDialog.tsx
+++ b/site/src/app/su/promotions/PromotionDialog.tsx
@@ -2,6 +2,7 @@
import { ChevronRight } from "lucide-react";
import { useState } from "react";
+import type { z } from "zod";
import { CreditOfferFields } from "@/app/su/CreditOfferFields";
import {
@@ -32,7 +33,9 @@ import { cn } from "@/lib/utils";
import { isOfferPlaceholder, PROMOTION_PLACEHOLDERS } from "@/lib/marketing/placeholders";
import { BUTTON_MARK } from "@/lib/marketing/promotionCopy";
import {
+ promotionDraftSchema,
promotionInputSchema,
+ type PromotionDraftInput,
type PromotionInput,
type PromotionSender,
type SegmentCount,
@@ -54,7 +57,8 @@ import { useOutreachTemplates, useSaveOutreachTemplate } from "@/queries/outreac
// 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.
+// are left out. A draft saves however it stands; a test or a send checks the
+// whole form first. A sent promotion opens read-only.
type OfferDefaults = Settings["promotionCreditOffer"];
@@ -186,9 +190,9 @@ export function PromotionDialog({
const readOnly = existing !== null && existing.status !== "draft";
const dirty = !readOnly && JSON.stringify(draft) !== savedDraft;
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");
+ // Earlier promotions that reached anyone, by segment or by hand; the one
+ // being edited is not a choice against itself.
+ const earlier = promotions.filter((p) => p.id !== existing?.id && p.counts.recipients > 0);
const setAudience = (patch: Partial<AudienceDraft>) =>
setDraft((d) => ({ ...d, audience: { ...d.audience, ...patch } }));
@@ -209,8 +213,8 @@ export function PromotionDialog({
});
};
- const parse = (): PromotionInput | null => {
- const parsed = promotionInputSchema.safeParse(toInput(draft));
+ const parseWith = <T,>(schema: { safeParse: (v: unknown) => z.ZodSafeParseResult<T> }): T | null => {
+ const parsed = schema.safeParse(toInput(draft));
if (!parsed.success) {
setIssues(parsed.error.issues.map((i) => `${i.path.join(".") || "form"}: ${i.message}`));
return null;
@@ -218,13 +222,15 @@ export function PromotionDialog({
setIssues([]);
return parsed.data;
};
+ const parseDraft = (): PromotionDraftInput | null => parseWith(promotionDraftSchema);
+ const parse = (): PromotionInput | null => parseWith(promotionInputSchema);
const fail = (e: Error) => setIssues([e.message]);
// Every action past a plain save goes through the saved row, so the test
// and the send read exactly what is stored.
const ensureSaved = async (): Promise<string | null> => {
- const input = parse();
+ const input = parseDraft();
if (!input) return null;
try {
const result = await save.mutateAsync({ id: savedId, ...input });
@@ -268,6 +274,7 @@ export function PromotionDialog({
const onTest = async () => {
setNotice(null);
setIssues([]);
+ if (!readOnly && !parse()) return;
const id = readOnly ? existing.id : await ensureSaved();
if (!id) return;
test.mutate(id, {
@@ -278,10 +285,10 @@ export function PromotionDialog({
const onSend = async () => {
setNotice(null);
- const id = await ensureSaved();
- if (!id) return;
const input = parse();
if (!input) return;
+ const id = await ensureSaved();
+ if (!id) return;
count.mutate(
{ audience: input.audience, excludePromotionIds: input.excludePromotionIds },
{ onSuccess: (c) => setConfirm({ id, count: c }), onError: fail },
@@ -306,7 +313,7 @@ export function PromotionDialog({
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-6xl">
<DialogHeader>
- <DialogTitle>{readOnly ? draft.name : existing ? "Edit promotion" : "New promotion"}</DialogTitle>
+ <DialogTitle>{readOnly ? draft.name || "Untitled" : existing ? "Edit promotion" : "New promotion"}</DialogTitle>
<DialogDescription>
{readOnly
? "Sent as it reads here."
diff --git a/site/src/lib/credits/offerTerms.ts b/site/src/lib/credits/offerTerms.ts
index dae25e20..f87ffa36 100644
--- a/site/src/lib/credits/offerTerms.ts
+++ b/site/src/lib/credits/offerTerms.ts
@@ -33,11 +33,27 @@ export const creditOfferTermsSchema = z
export type CreditOfferTerms = z.infer<typeof creditOfferTermsSchema>;
+// The terms as a draft holds them: the same fields, with a number still to be
+// typed allowed at 0. A send parses the strict terms.
+export const creditOfferDraftSchema = z
+ .object({
+ dollars: z.number().int().min(0).max(10000),
+ claimWindowDays: z.number().int().min(0).max(365),
+ expiresAfterDays: z.number().int().min(0).max(3650),
+ claim: z.enum(OFFER_CLAIMS).default("link"),
+ })
+ .strict();
+
/** 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 draft terms, or null for none: what a saved draft reads back as. */
+export function creditOfferDraftOf(value: unknown): CreditOfferTerms | null {
+ return value == null ? null : creditOfferDraftSchema.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;
diff --git a/site/src/lib/marketing/promotionInput.ts b/site/src/lib/marketing/promotionInput.ts
index 0badbab2..d4346423 100644
--- a/site/src/lib/marketing/promotionInput.ts
+++ b/site/src/lib/marketing/promotionInput.ts
@@ -1,9 +1,16 @@
import { audienceSchema, type Audience } from "@donkeycut/abexp";
import { z } from "zod";
-import { CLAIM_URL_PLACEHOLDER, creditOfferTermsSchema, type CreditOfferTerms } from "@/lib/credits/offerTerms";
+import {
+ CLAIM_URL_PLACEHOLDER,
+ creditOfferDraftSchema,
+ 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.
+// The shape of a promotion as su writes it and the routes validate it. A
+// draft saves whatever the row can hold, so work in progress is never lost;
+// a test or a send parses the strict shape first. Client-safe: zod only, so
+// the dialog parses the same schemas the server does.
export const PROMOTION_SENDERS = ["bulk", "personal"] as const;
export type PromotionSender = (typeof PROMOTION_SENDERS)[number];
@@ -14,6 +21,22 @@ export const PROMOTION_STATUSES = ["draft", "queuing", "sending", "paused", "sen
export type PromotionStatus = (typeof PROMOTION_STATUSES)[number];
+export const promotionDraftSchema = z
+ .object({
+ name: z.string().trim().max(80),
+ subject: z.string().trim().max(200),
+ body: z.string().trim().max(10_000),
+ ctaLabel: z.string().trim().max(80).nullable(),
+ ctaUrl: z.string().trim().max(2000).nullable(),
+ creditOffer: creditOfferDraftSchema.nullable().default(null),
+ sender: z.enum(PROMOTION_SENDERS),
+ audience: audienceSchema,
+ excludePromotionIds: z.array(z.string().min(1)).max(100),
+ })
+ .strict();
+
+export type PromotionDraftInput = z.output<typeof promotionDraftSchema>;
+
export const promotionInputSchema = z
.object({
name: z.string().trim().min(1).max(80),
diff --git a/site/src/lib/marketing/promotionSave.ts b/site/src/lib/marketing/promotionSave.ts
index 26d4b630..78dfb9cc 100644
--- a/site/src/lib/marketing/promotionSave.ts
+++ b/site/src/lib/marketing/promotionSave.ts
@@ -2,13 +2,18 @@ import { Prisma } from "@/generated/prisma/client";
import { invalidResponse } from "@/lib/config/experimentList";
import { UnknownPlaceholderError } from "@/lib/marketing/placeholders";
import { renderPromotion, SAMPLE_RECIPIENT } from "@/lib/marketing/promotionCopy";
-import type { PromotionInput } from "@/lib/marketing/promotionInput";
+import {
+ promotionInputSchema,
+ type PromotionDraftInput,
+ 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 and its last day are minted per person at the send, so the
-// check fills them blank.
+// What a save of a promotion shares between create and edit: the row data a
+// draft maps to. What a test or a send checks first: the stored row parsed as
+// a complete promotion, and its copy rendered for a stand-in recipient, so a
+// blank field or a placeholder typo comes back to the form and never reaches
+// a mailbox. The 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 {
@@ -22,7 +27,33 @@ export function copyIssue(input: PromotionInput): Response | null {
}
}
-export function promotionData(input: PromotionInput, actorUserId: string) {
+export function sendIssue(row: {
+ name: string;
+ subject: string;
+ body: string;
+ ctaLabel: string | null;
+ ctaUrl: string | null;
+ creditOffer: Prisma.JsonValue;
+ sender: string;
+ audience: Prisma.JsonValue;
+ excludePromotionIds: string[];
+}): Response | null {
+ const parsed = promotionInputSchema.safeParse({
+ name: row.name,
+ subject: row.subject,
+ body: row.body,
+ ctaLabel: row.ctaLabel,
+ ctaUrl: row.ctaUrl,
+ creditOffer: row.creditOffer,
+ sender: row.sender,
+ audience: row.audience,
+ excludePromotionIds: row.excludePromotionIds,
+ });
+ if (!parsed.success) return invalidResponse(parsed.error.issues);
+ return copyIssue(parsed.data);
+}
+
+export function promotionData(input: PromotionDraftInput, actorUserId: string) {
return {
actorUserId,
creditOffer: input.creditOffer ? (input.creditOffer as Prisma.InputJsonValue) : Prisma.DbNull,
diff --git a/site/src/queries/promotions.ts b/site/src/queries/promotions.ts
index e8f6962f..90ff48c2 100644
--- a/site/src/queries/promotions.ts
+++ b/site/src/queries/promotions.ts
@@ -4,7 +4,7 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { Audience } from "@donkeycut/abexp";
import type {
- PromotionInput,
+ PromotionDraftInput,
PromotionSender,
PromotionSummary,
SegmentCount,
@@ -44,7 +44,7 @@ export function usePromotions() {
export function useSavePromotion() {
const takeList = useTakeList();
return useMutation({
- mutationFn: ({ id, ...input }: PromotionInput & { id: string | null }) =>
+ mutationFn: ({ id, ...input }: PromotionDraftInput & { id: string | null }) =>
apiFetch<{ id: string; promotions: PromotionSummary[] }>(
id ? `/api/su/promotions/${encodeURIComponent(id)}` : "/api/su/promotions",
{ body: JSON.stringify(input), method: id ? "PUT" : "POST" },