Improve bulk email compose with full template list and free-form HTML modes.

Load all active email templates for the send composer, fix API parsing/pagination, and add template preview with scheduled-job template labels.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Yared Yemane 2026-07-02 05:31:17 -07:00
parent 5df5a7f742
commit 2e59a446e5
5 changed files with 406 additions and 158 deletions

View File

@ -12,9 +12,16 @@ import type {
UpdateEmailTemplateResponse,
} from "../types/emailTemplate.types"
/** GET /admin/email-templates — list all email templates. */
export const getEmailTemplates = () =>
http.get<GetEmailTemplatesResponse>("/admin/email-templates")
export interface GetEmailTemplatesParams {
status?: string
limit?: number
offset?: number
query?: string
}
/** GET /admin/email-templates — list email templates (paginated). */
export const getEmailTemplates = (params?: GetEmailTemplatesParams) =>
http.get<GetEmailTemplatesResponse>("/admin/email-templates", { params })
/** GET /admin/email-templates/slug/:slug — single template by slug. */
export const getEmailTemplateBySlug = (slug: string) =>
@ -23,28 +30,55 @@ export const getEmailTemplateBySlug = (slug: string) =>
)
function normalizeEmailTemplate(row: unknown): EmailTemplate | null {
if (!row || typeof row !== "object" || !("slug" in row)) return null
const t = row as EmailTemplate
if (!row || typeof row !== "object") return null
const o = row as Record<string, unknown>
const slug = String(o.slug ?? o.Slug ?? "").trim()
if (!slug) return null
const id = Number(o.id ?? o.ID ?? o.Id)
const variablesRaw = o.variables ?? o.Variables
const variables = Array.isArray(variablesRaw)
? variablesRaw.map((v) => String(v).trim()).filter(Boolean)
: []
return {
...t,
variables: Array.isArray(t.variables) ? t.variables : [],
status: t.status ?? "ACTIVE",
updated_at: t.updated_at ?? t.created_at ?? "",
id: Number.isFinite(id) && id > 0 ? id : 0,
slug,
name: String(o.name ?? o.Name ?? slug),
subject: String(o.subject ?? o.Subject ?? ""),
body_text: String(o.body_text ?? o.BodyText ?? o.bodyText ?? ""),
body_html: String(o.body_html ?? o.BodyHtml ?? o.bodyHTML ?? ""),
variables,
is_system: Boolean(o.is_system ?? o.IsSystem ?? false),
status: String(o.status ?? o.Status ?? "ACTIVE"),
created_at: String(o.created_at ?? o.CreatedAt ?? ""),
updated_at: String(o.updated_at ?? o.UpdatedAt ?? o.created_at ?? o.CreatedAt ?? ""),
}
}
function extractTemplateRows(data: unknown): unknown[] {
if (Array.isArray(data)) return data
if (!data || typeof data !== "object") return []
const record = data as Record<string, unknown>
const candidates = [
record.templates,
record.Templates,
record.email_templates,
record.EmailTemplates,
]
for (const candidate of candidates) {
if (Array.isArray(candidate)) return candidate
}
return []
}
export function parseEmailTemplatesResponse(
response: Awaited<ReturnType<typeof getEmailTemplates>>,
): EmailTemplate[] {
const data = response.data?.data
const rows = Array.isArray(data)
? data
: Array.isArray(data?.templates)
? data.templates
: []
return rows
return extractTemplateRows(data)
.map(normalizeEmailTemplate)
.filter((row): row is EmailTemplate => row != null)
.filter((row): row is EmailTemplate => row != null && row.id > 0)
}
/** PUT /admin/email-templates/:id — update subject and bodies. */

View File

@ -1,5 +1,6 @@
import { useEffect, useMemo, useState } from "react"
import { Eye, RefreshCw } from "lucide-react"
import { Link } from "react-router-dom"
import { Eye, ExternalLink, RefreshCw } from "lucide-react"
import { toast } from "sonner"
import {
parseEmailTemplatePreviewResponse,
@ -10,12 +11,17 @@ import { Input } from "../ui/input"
import { SpinnerIcon } from "../ui/spinner-icon"
import { Textarea } from "../ui/textarea"
import { Select } from "../ui/select"
import { cn } from "../../lib/utils"
import {
buildEmailTemplateVariablesForSend,
defaultOutboundEmailTemplateSlug,
isAutomatedEmailTemplateSlug,
isCustomMessageTemplate,
} from "../../lib/notificationEmailCompose"
import type { EmailTemplate, PreviewEmailTemplateResult } from "../../types/emailTemplate.types"
type EmailContentMode = "freeform" | "template"
type EmailComposeFieldsProps = {
templates: EmailTemplate[]
templatesLoading: boolean
@ -47,20 +53,48 @@ export function EmailComposeFields({
}: EmailComposeFieldsProps) {
const [previewLoading, setPreviewLoading] = useState(false)
const [preview, setPreview] = useState<PreviewEmailTemplateResult | null>(null)
const [contentMode, setContentMode] = useState<EmailContentMode>(
templateSlug ? "template" : "freeform",
)
const selectedTemplate = useMemo(
() => templates.find((t) => t.slug === templateSlug) ?? null,
[templates, templateSlug],
)
const isFreeForm = !templateSlug
const isFreeForm = contentMode === "freeform"
const isCustomMessage = isCustomMessageTemplate(templateSlug)
const usesTemplateVariables =
Boolean(templateSlug) && !isCustomMessage && (selectedTemplate?.variables.length ?? 0) > 0
contentMode === "template" &&
Boolean(templateSlug) &&
!isCustomMessage &&
(selectedTemplate?.variables.length ?? 0) > 0
useEffect(() => {
setContentMode(templateSlug ? "template" : "freeform")
}, [templateSlug])
useEffect(() => {
setPreview(null)
}, [templateSlug, subject, message, htmlBody, templateVariables])
}, [templateSlug, subject, message, htmlBody, templateVariables, contentMode])
const switchToFreeForm = () => {
setContentMode("freeform")
onTemplateSlugChange("")
onTemplateVariablesChange({})
setPreview(null)
}
const switchToTemplate = () => {
setContentMode("template")
const slug = templateSlug || defaultOutboundEmailTemplateSlug(templates)
onTemplateSlugChange(slug)
onTemplateVariablesChange({})
if (slug && !isCustomMessageTemplate(slug)) {
onHtmlBodyChange("")
}
setPreview(null)
}
const handleTemplateChange = (slug: string) => {
onTemplateSlugChange(slug)
@ -68,6 +102,7 @@ export function EmailComposeFields({
if (slug && !isCustomMessageTemplate(slug)) {
onHtmlBodyChange("")
}
setPreview(null)
}
const handlePreview = async () => {
@ -98,133 +133,229 @@ export function EmailComposeFields({
}
return (
<div className="space-y-3">
<div>
<label className="mb-1 block text-xs font-medium text-grayScale-500">
Email content mode
</label>
<Select
value={templateSlug}
onChange={(e) => handleTemplateChange(e.target.value)}
disabled={templatesLoading}
>
<option value="">Free-form (subject + message/HTML)</option>
{templates.map((template) => (
<option key={template.slug} value={template.slug}>
{template.name} ({template.slug})
</option>
))}
</Select>
<p className="mt-1 text-[10px] text-grayScale-400">
{templatesLoading
? "Loading templates…"
: "System templates (OTP, welcome, etc.) are excluded from outbound campaigns."}
</p>
<div className="space-y-4">
<div className="flex flex-wrap items-start justify-between gap-2">
<div>
<p className="text-xs font-semibold uppercase tracking-[0.14em] text-grayScale-400">
Email content
</p>
<p className="mt-0.5 text-[11px] text-grayScale-500">
Send free-form HTML or render a stored email template on the server.
</p>
</div>
<Button type="button" variant="ghost" size="sm" className="h-8 text-xs" asChild>
<Link to="/notifications/email-templates">
<ExternalLink className="mr-1.5 h-3.5 w-3.5" />
Manage templates
</Link>
</Button>
</div>
{(isFreeForm || isCustomMessage) && (
<div>
<label className="mb-1 block text-xs font-medium text-grayScale-500">Subject</label>
<Input
placeholder="Email subject line"
value={subject}
onChange={(e) => onSubjectChange(e.target.value)}
/>
</div>
)}
{(isFreeForm || isCustomMessage) && (
<div>
<label className="mb-1 block text-xs font-medium text-grayScale-500">Message</label>
<Textarea
rows={4}
placeholder="Plain-text email body"
value={message}
onChange={(e) => onMessageChange(e.target.value)}
/>
</div>
)}
{isFreeForm && (
<div>
<label className="mb-1 block text-xs font-medium text-grayScale-500">
HTML body (optional)
</label>
<Textarea
rows={3}
placeholder="<p>Rich HTML content</p>"
value={htmlBody}
onChange={(e) => onHtmlBodyChange(e.target.value)}
/>
</div>
)}
{usesTemplateVariables && selectedTemplate && (
<div className="space-y-2 rounded-lg border border-grayScale-100 bg-grayScale-50/50 p-3">
<p className="text-xs font-semibold text-grayScale-600">Template variables</p>
{selectedTemplate.variables.map((variable) => (
<div key={variable}>
<label className="mb-1 block text-[11px] font-medium text-grayScale-500">
{variable}
</label>
<Input
value={templateVariables[variable] ?? ""}
onChange={(e) =>
onTemplateVariablesChange({
...templateVariables,
[variable]: e.target.value,
})
}
placeholder={`Value for {{.${variable}}}`}
/>
</div>
))}
</div>
)}
{templateSlug && (
<div className="flex flex-wrap items-center gap-2">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => void handlePreview()}
disabled={previewLoading}
>
{previewLoading ? (
<SpinnerIcon className="mr-2 h-3.5 w-3.5" alt="" />
) : (
<Eye className="mr-2 h-3.5 w-3.5" />
)}
Preview rendered email
</Button>
{preview && (
<Button type="button" variant="ghost" size="sm" onClick={() => setPreview(null)}>
<RefreshCw className="mr-2 h-3.5 w-3.5" />
Hide preview
</Button>
<div className="inline-flex rounded-full border border-grayScale-200 bg-grayScale-50 p-0.5 text-xs font-medium">
<button
type="button"
onClick={switchToFreeForm}
className={cn(
"rounded-full px-3 py-1.5 transition-colors",
isFreeForm
? "bg-brand-500 text-white shadow-sm"
: "text-grayScale-500 hover:text-grayScale-700",
)}
</div>
)}
>
Free-form HTML
</button>
<button
type="button"
onClick={switchToTemplate}
disabled={templatesLoading || templates.length === 0}
className={cn(
"rounded-full px-3 py-1.5 transition-colors disabled:cursor-not-allowed disabled:opacity-50",
!isFreeForm
? "bg-brand-500 text-white shadow-sm"
: "text-grayScale-500 hover:text-grayScale-700",
)}
>
Email template
</button>
</div>
{preview && (
<div className="space-y-2 rounded-lg border border-grayScale-200 bg-white p-3">
<p className="text-xs font-semibold text-grayScale-600">Server preview</p>
<p className="rounded-md border border-grayScale-100 bg-grayScale-50 px-2 py-1.5 text-xs font-medium text-grayScale-800">
{preview.subject || "(no subject)"}
</p>
{preview.html ? (
<iframe
title="Email preview"
sandbox=""
srcDoc={preview.html}
className="h-48 w-full rounded-md border border-grayScale-200 bg-white"
{isFreeForm ? (
<div className="space-y-3 rounded-lg border border-grayScale-100 bg-grayScale-50/40 p-3">
<div>
<label className="mb-1 block text-xs font-medium text-grayScale-500">Subject</label>
<Input
placeholder="Email subject line"
value={subject}
onChange={(e) => onSubjectChange(e.target.value)}
/>
) : (
<pre className="max-h-40 overflow-auto whitespace-pre-wrap rounded-md border border-grayScale-100 bg-grayScale-50 p-2 text-xs text-grayScale-700">
{preview.text || "(empty body)"}
</pre>
</div>
<div>
<label className="mb-1 block text-xs font-medium text-grayScale-500">Message</label>
<Textarea
rows={4}
placeholder="Plain-text email body"
value={message}
onChange={(e) => onMessageChange(e.target.value)}
/>
</div>
<div>
<label className="mb-1 block text-xs font-medium text-grayScale-500">
HTML body (optional)
</label>
<Textarea
rows={4}
placeholder="<p>Rich HTML content</p>"
value={htmlBody}
onChange={(e) => onHtmlBodyChange(e.target.value)}
/>
<p className="mt-1 text-[10px] text-grayScale-400">
Provide message, HTML, or both. Sent as-is without a template wrapper.
</p>
</div>
</div>
) : (
<div className="space-y-3 rounded-lg border border-grayScale-100 bg-grayScale-50/40 p-3">
<div>
<label className="mb-1 block text-xs font-medium text-grayScale-500">
Email template
</label>
<Select
value={templateSlug}
onChange={(e) => handleTemplateChange(e.target.value)}
disabled={templatesLoading || templates.length === 0}
>
{templates.length === 0 ? (
<option value="">No templates available</option>
) : (
templates.map((template) => (
<option key={template.slug} value={template.slug}>
{template.name} ({template.slug})
{isAutomatedEmailTemplateSlug(template.slug) ? " · system" : ""}
</option>
))
)}
</Select>
<p className="mt-1 text-[10px] text-grayScale-400">
{templatesLoading
? "Loading templates…"
: `${templates.length} active template${templates.length === 1 ? "" : "s"} from the template store.`}
</p>
</div>
{selectedTemplate && selectedTemplate.variables.length === 0 && !isCustomMessage ? (
<p className="rounded-md border border-grayScale-100 bg-white px-2.5 py-2 text-[11px] text-grayScale-500">
This template has no placeholders — subject and HTML are taken from the template
body when sent.
</p>
) : null}
{isAutomatedEmailTemplateSlug(templateSlug) ? (
<p className="rounded-md border border-amber-200 bg-amber-50 px-2.5 py-2 text-[11px] text-amber-900">
This template is normally used by automated flows (OTP, invites, etc.). Fill all
variables below before sending.
</p>
) : null}
{isCustomMessage && (
<>
<div>
<label className="mb-1 block text-xs font-medium text-grayScale-500">Subject</label>
<Input
placeholder="Email subject line"
value={subject}
onChange={(e) => onSubjectChange(e.target.value)}
/>
</div>
<div>
<label className="mb-1 block text-xs font-medium text-grayScale-500">Message</label>
<Textarea
rows={4}
placeholder="Body text rendered inside the branded custom_message template"
value={message}
onChange={(e) => onMessageChange(e.target.value)}
/>
</div>
</>
)}
{usesTemplateVariables && selectedTemplate && (
<div className="space-y-2 rounded-lg border border-grayScale-100 bg-white p-3">
<p className="text-xs font-semibold text-grayScale-600">Template variables</p>
{selectedTemplate.variables.map((variable) => (
<div key={variable}>
<label className="mb-1 block text-[11px] font-medium text-grayScale-500">
{variable}
</label>
<Input
value={templateVariables[variable] ?? ""}
onChange={(e) =>
onTemplateVariablesChange({
...templateVariables,
[variable]: e.target.value,
})
}
placeholder={`Value for {{.${variable}}}`}
/>
</div>
))}
</div>
)}
{!templatesLoading && templates.length === 0 ? (
<p className="text-xs text-amber-800">
No outbound templates found. Use free-form HTML or{" "}
<Link to="/notifications/email-templates/new" className="font-semibold underline">
create a template
</Link>
.
</p>
) : null}
{templateSlug ? (
<div className="flex flex-wrap items-center gap-2">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => void handlePreview()}
disabled={previewLoading}
>
{previewLoading ? (
<SpinnerIcon className="mr-2 h-3.5 w-3.5" alt="" />
) : (
<Eye className="mr-2 h-3.5 w-3.5" />
)}
Preview rendered email
</Button>
{preview ? (
<Button type="button" variant="ghost" size="sm" onClick={() => setPreview(null)}>
<RefreshCw className="mr-2 h-3.5 w-3.5" />
Hide preview
</Button>
) : null}
</div>
) : null}
{preview ? (
<div className="space-y-2 rounded-lg border border-grayScale-200 bg-white p-3">
<p className="text-xs font-semibold text-grayScale-600">Server preview</p>
<p className="rounded-md border border-grayScale-100 bg-grayScale-50 px-2 py-1.5 text-xs font-medium text-grayScale-800">
{preview.subject || "(no subject)"}
</p>
{preview.html ? (
<iframe
title="Email preview"
sandbox=""
srcDoc={preview.html}
className="h-48 w-full rounded-md border border-grayScale-200 bg-white"
/>
) : (
<pre className="max-h-40 overflow-auto whitespace-pre-wrap rounded-md border border-grayScale-100 bg-grayScale-50 p-2 text-xs text-grayScale-700">
{preview.text || "(empty body)"}
</pre>
)}
</div>
) : null}
</div>
)}
</div>

View File

@ -1,6 +1,9 @@
import { getEmailTemplates, parseEmailTemplatesResponse } from "../api/emailTemplates.api"
import type { EmailTemplate } from "../types/emailTemplate.types"
/** Reserved for automated learner/team flows — not for admin outbound campaigns. */
const TEMPLATE_LIST_PAGE_SIZE = 100
/** Slugs reserved for automated learner/team flows — shown with a label in the compose UI. */
export const AUTOMATED_EMAIL_TEMPLATE_SLUGS = new Set([
"otp",
"invitation",
@ -8,14 +11,71 @@ export const AUTOMATED_EMAIL_TEMPLATE_SLUGS = new Set([
"welcome",
])
export function isOutboundEmailTemplate(template: EmailTemplate): boolean {
if (String(template.status ?? "").toUpperCase() !== "ACTIVE") return false
if (AUTOMATED_EMAIL_TEMPLATE_SLUGS.has(template.slug)) return false
return template.slug === "custom_message" || !template.is_system
export function isAutomatedEmailTemplateSlug(slug: string): boolean {
return AUTOMATED_EMAIL_TEMPLATE_SLUGS.has(slug)
}
/** ACTIVE templates available in bulk-email compose. */
export function isComposeEmailTemplate(template: EmailTemplate): boolean {
return String(template.status ?? "").toUpperCase() === "ACTIVE"
}
/** @deprecated Use isComposeEmailTemplate */
export function isOutboundEmailTemplate(template: EmailTemplate): boolean {
return isComposeEmailTemplate(template)
}
export function filterComposeEmailTemplates(templates: EmailTemplate[]): EmailTemplate[] {
return templates.filter(isComposeEmailTemplate)
}
/** @deprecated Use filterComposeEmailTemplates */
export function filterOutboundEmailTemplates(templates: EmailTemplate[]): EmailTemplate[] {
return templates.filter(isOutboundEmailTemplate)
return filterComposeEmailTemplates(templates)
}
function sortOutboundEmailTemplates(templates: EmailTemplate[]): EmailTemplate[] {
return [...templates].sort((a, b) => {
if (a.slug === "custom_message") return -1
if (b.slug === "custom_message") return 1
return a.name.localeCompare(b.name)
})
}
/** Loads all ACTIVE email templates for bulk-email compose. */
export async function fetchActiveOutboundEmailTemplates(): Promise<EmailTemplate[]> {
const all: EmailTemplate[] = []
let offset = 0
while (true) {
const response = await getEmailTemplates({
limit: TEMPLATE_LIST_PAGE_SIZE,
offset,
})
const rawPage = parseEmailTemplatesResponse(response)
if (rawPage.length === 0) break
all.push(...rawPage)
const data = response.data?.data
const totalRaw =
data && typeof data === "object" && !Array.isArray(data)
? (data as Record<string, unknown>).total_count ??
(data as Record<string, unknown>).TotalCount
: undefined
const total = totalRaw != null ? Number(totalRaw) : undefined
offset += rawPage.length
if (total != null && Number.isFinite(total) && offset >= total) break
if (rawPage.length < TEMPLATE_LIST_PAGE_SIZE) break
}
return sortOutboundEmailTemplates(filterComposeEmailTemplates(all))
}
export function defaultOutboundEmailTemplateSlug(templates: EmailTemplate[]): string {
const custom = templates.find((t) => t.slug === "custom_message")
return custom?.slug ?? templates[0]?.slug ?? ""
}
export function isCustomMessageTemplate(slug: string): boolean {

View File

@ -12,10 +12,6 @@ import { SpinnerIcon } from "../../components/ui/spinner-icon"
import { NotificationSchedulePicker } from "../../components/notifications/NotificationSchedulePicker"
import { EmailComposeFields } from "../../components/notifications/EmailComposeFields"
import { cn } from "../../lib/utils"
import {
getEmailTemplates,
parseEmailTemplatesResponse,
} from "../../api/emailTemplates.api"
import {
sendBulkEmail,
sendBulkInApp,
@ -24,7 +20,7 @@ import {
} from "../../api/notifications.api"
import {
appendBulkEmailContentToForm,
filterOutboundEmailTemplates,
fetchActiveOutboundEmailTemplates,
validateEmailComposeInput,
} from "../../lib/notificationEmailCompose"
import {
@ -102,6 +98,7 @@ function buildContentPreview(
title: string,
message: string,
emailTemplateSlug: string,
htmlBody: string,
): { titlePreview: string; messagePreview: string } {
if (channel === "email" && emailTemplateSlug) {
return {
@ -109,6 +106,15 @@ function buildContentPreview(
messagePreview: message.trim() || `Using template "${emailTemplateSlug}"`,
}
}
if (channel === "email") {
return {
titlePreview: title.trim() || "Email",
messagePreview:
htmlBody.trim() ||
message.trim() ||
"Free-form email (no template)",
}
}
if (channel === "sms") {
return {
titlePreview: title.trim() || "SMS",
@ -190,10 +196,9 @@ export function CreateNotificationPage() {
}
let cancelled = false
setEmailTemplatesLoading(true)
getEmailTemplates()
.then((response) => {
if (cancelled) return
setEmailTemplates(filterOutboundEmailTemplates(parseEmailTemplatesResponse(response)))
fetchActiveOutboundEmailTemplates()
.then((templates) => {
if (!cancelled) setEmailTemplates(templates)
})
.catch(() => {
if (!cancelled) setEmailTemplates([])
@ -384,7 +389,13 @@ export function CreateNotificationPage() {
directRecipients,
channel,
)
const contentPreview = buildContentPreview(channel, title, message, emailTemplateSlug)
const contentPreview = buildContentPreview(
channel,
title,
message,
emailTemplateSlug,
htmlBody,
)
try {
setSending(true)
@ -1190,13 +1201,20 @@ export function CreateNotificationPage() {
: "Notification title")}
</p>
<p className="truncate text-[11px] text-grayScale-500">
{message || "Message preview will appear here."}
{channel === "email" && !emailTemplateSlug && htmlBody.trim()
? "HTML email body"
: message || "Message preview will appear here."}
</p>
</div>
</div>
</div>
<p className="text-[10px] text-grayScale-400">
Channel: {channel.toUpperCase().replace("_", "-")}
{channel === "email" && emailTemplateSlug
? ` · Template: ${emailTemplateSlug}`
: channel === "email" && htmlBody.trim()
? " · Free-form HTML"
: ""}
{isScheduling && scheduledAt
? ` · Scheduled ${formatScheduledAtLabel(scheduledAt)}`
: ""}

View File

@ -263,6 +263,11 @@ export function ScheduledNotificationsPage() {
{job.title || "—"}
</p>
<p className="truncate text-xs text-grayScale-400">{job.message}</p>
{job.channel === "email" && job.email_template_slug ? (
<p className="mt-0.5 truncate text-[10px] text-grayScale-400">
Template: {job.email_template_slug}
</p>
) : null}
</TableCell>
<TableCell className="text-xs text-grayScale-500">
{targetingSummary(job)}