Backend modules from tastefully 8bd93d15: core-libs, core-session, api-gateway, mobile-api, services-auth, services-system, services-counter, services-member, services-log, services-email. solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal from tastefully 8bd93d15. Copied as tracked files only. Literal secrets replaced with environment placeholders: - services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY, MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default) - services-system: JUMIO_TOKEN, JUMIO_SECRET (optional) - services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed - core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default removed, ipgeolocation key read from IPGEOLOCATION_API_KEY - services-system EkycAppConfig: commented Jumio credentials removed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
425 lines
16 KiB
TypeScript
425 lines
16 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useMemo, useRef, useState } from "react";
|
|
import { Plus } from "lucide-react";
|
|
import { Alert, AlertDescription, AlertTitle } from "@/app/components/ui/alert";
|
|
import { Button } from "@/app/components/ui/button";
|
|
import { Input } from "@/app/components/ui/input";
|
|
import { Label } from "@/app/components/ui/label";
|
|
import {
|
|
Select,
|
|
SelectContent,
|
|
SelectItem,
|
|
SelectTrigger,
|
|
SelectValue,
|
|
} from "@/app/components/ui/select";
|
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/app/components/ui/tabs";
|
|
import { Textarea } from "@/app/components/ui/textarea";
|
|
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
|
import {
|
|
createEmailTemplate,
|
|
EMAIL_LANG_OPTIONS,
|
|
previewEmailTemplate,
|
|
updateEmailTemplate,
|
|
uploadEmailAttachment,
|
|
} from "@/app/lib/services/emailTemplates";
|
|
import type {
|
|
AttachmentRef,
|
|
EmailTemplate,
|
|
EmailTemplateLang,
|
|
EmailTemplateStatus,
|
|
} from "@/app/lib/types";
|
|
import { TemplatePreviewPane } from "./TemplatePreviewPane";
|
|
|
|
// Shared editor for create (app/email-templates/new) and edit
|
|
// (app/email-templates/[name]). One tab per language row; the active tab's row
|
|
// is what Save persists (the BFF create/edit operate on exactly one (name, lang)
|
|
// row). The template `name` is a code-referenced key: read-only on edit, and on
|
|
// create the caveat is shown — a new name sends nothing until backend trigger
|
|
// code references it (design §3.1). Attachments: save always sends the current
|
|
// tab's attachment ids as a non-null array ([] when none) — Task 13 adds the
|
|
// upload UI; the payload contract is already enforced here.
|
|
|
|
interface LanguageDraft {
|
|
id?: number;
|
|
lang: EmailTemplateLang;
|
|
subject: string;
|
|
description: string;
|
|
body: string;
|
|
status: EmailTemplateStatus;
|
|
attachments: AttachmentRef[];
|
|
}
|
|
|
|
const PREVIEW_DEBOUNCE_MS = 300;
|
|
|
|
/** Handlebars tokens in a body: {{fieldName}} / {{ field.name }} (spec G3 — parsed, never claimed as runtime data). */
|
|
function extractTokens(body: string): string[] {
|
|
const tokens = new Set<string>();
|
|
const re = /\{\{\s*([\w.]+)\s*\}\}/g;
|
|
let m: RegExpExecArray | null;
|
|
while ((m = re.exec(body)) !== null) tokens.add(m[1]);
|
|
return Array.from(tokens);
|
|
}
|
|
|
|
function draftFromRow(row: EmailTemplate): LanguageDraft {
|
|
return {
|
|
id: row.id,
|
|
lang: row.lang,
|
|
subject: row.subject ?? "",
|
|
description: row.description ?? "",
|
|
body: row.body ?? "",
|
|
status: row.status,
|
|
attachments: row.attachments ?? [],
|
|
};
|
|
}
|
|
|
|
function emptyDraft(lang: EmailTemplateLang): LanguageDraft {
|
|
return { lang, subject: "", description: "", body: "", status: "Y", attachments: [] };
|
|
}
|
|
|
|
export function EmailTemplateEditor({
|
|
mode,
|
|
initialName,
|
|
initialRows,
|
|
onSaved,
|
|
}: {
|
|
mode: "create" | "edit";
|
|
initialName?: string;
|
|
initialRows?: EmailTemplate[];
|
|
onSaved?: () => void;
|
|
}) {
|
|
const t = useT();
|
|
const [name, setName] = useState(initialName ?? "");
|
|
const [drafts, setDrafts] = useState<LanguageDraft[]>(() =>
|
|
initialRows && initialRows.length > 0
|
|
? initialRows.map(draftFromRow)
|
|
: [emptyDraft("EN")],
|
|
);
|
|
const [activeLang, setActiveLang] = useState<EmailTemplateLang>(
|
|
() => initialRows?.[0]?.lang ?? "EN",
|
|
);
|
|
const [sampleValues, setSampleValues] = useState<Record<string, string>>({});
|
|
const [renderedHtml, setRenderedHtml] = useState("");
|
|
const [saving, setSaving] = useState(false);
|
|
const [saveError, setSaveError] = useState<string | null>(null);
|
|
const [saved, setSaved] = useState(false);
|
|
const [uploading, setUploading] = useState(false);
|
|
const [uploadError, setUploadError] = useState<string | null>(null);
|
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
|
|
|
const activeDraft = drafts.find((d) => d.lang === activeLang) ?? drafts[0];
|
|
const activeBody = activeDraft?.body ?? "";
|
|
const tokens = useMemo(() => extractTokens(activeBody), [activeBody]);
|
|
const availableLangs = EMAIL_LANG_OPTIONS.filter(
|
|
(o) => !drafts.some((d) => d.lang === o.value),
|
|
);
|
|
|
|
// Debounced live preview of the ACTIVE tab's unsaved body. Upstream's
|
|
// /retriveTemplateAndMapping renders the STORED body, so the BFF substitutes
|
|
// the sample values in-process (spec G3); a failed render shows an empty pane.
|
|
// The empty-body case is handled in render (TemplatePreviewPane gets ""), so
|
|
// this effect never calls setState synchronously.
|
|
useEffect(() => {
|
|
if (!activeBody.trim()) return;
|
|
const handle = setTimeout(() => {
|
|
previewEmailTemplate(activeBody, sampleValues)
|
|
.then((res) => setRenderedHtml(res.renderedHtml))
|
|
.catch(() => setRenderedHtml(""));
|
|
}, PREVIEW_DEBOUNCE_MS);
|
|
return () => clearTimeout(handle);
|
|
}, [activeBody, sampleValues, activeLang]);
|
|
|
|
function patchDraft(patch: Partial<LanguageDraft>, lang: EmailTemplateLang = activeLang) {
|
|
setDrafts((prev) => prev.map((d) => (d.lang === lang ? { ...d, ...patch } : d)));
|
|
}
|
|
|
|
function addLanguage(lang: EmailTemplateLang) {
|
|
setDrafts((prev) => [...prev, emptyDraft(lang)]);
|
|
setActiveLang(lang);
|
|
setSampleValues({});
|
|
setRenderedHtml("");
|
|
}
|
|
|
|
/**
|
|
* Attachment upload — SERVER-INITIATED: reads the file as a base64 data URL, strips the
|
|
* {@code data:...;base64,} prefix and uploads through the BFF attachment route, which proxies
|
|
* services-email's auto-committing {@code /email/attachment/updateAttachment}. No
|
|
* {@code /storage/upload} or {@code /storage/commit} is ever called from the portal (design §6).
|
|
* The tab active when the file was picked receives the returned attachment.
|
|
*/
|
|
function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
|
|
const file = e.target.files?.[0];
|
|
e.target.value = ""; // allow re-picking the same file
|
|
if (!file) return;
|
|
const targetLang = activeLang;
|
|
setUploading(true);
|
|
setUploadError(null);
|
|
const reader = new FileReader();
|
|
reader.onload = () => {
|
|
const dataUrl = String(reader.result ?? "");
|
|
const base = dataUrl.split(",")[1] ?? "";
|
|
uploadEmailAttachment({
|
|
fileName: file.name,
|
|
fileType: file.type || "application/octet-stream",
|
|
base,
|
|
})
|
|
.then((ref) => {
|
|
const current = drafts.find((d) => d.lang === targetLang);
|
|
patchDraft({ attachments: [...(current?.attachments ?? []), ref] }, targetLang);
|
|
})
|
|
.catch((err: unknown) =>
|
|
setUploadError(err instanceof Error ? err.message : "Upload failed"),
|
|
)
|
|
.finally(() => setUploading(false));
|
|
};
|
|
reader.onerror = () => {
|
|
setUploading(false);
|
|
setUploadError("Could not read the file.");
|
|
};
|
|
reader.readAsDataURL(file);
|
|
}
|
|
|
|
function removeAttachment(id: number, lang: EmailTemplateLang) {
|
|
const current = drafts.find((d) => d.lang === lang);
|
|
if (!current) return;
|
|
// Removing = omitting the id from attachmentId on the next edit; upstream unlinks it.
|
|
patchDraft({ attachments: current.attachments.filter((a) => a.id !== id) }, lang);
|
|
}
|
|
|
|
async function handleSave() {
|
|
if (!activeDraft) return;
|
|
setSaving(true);
|
|
setSaveError(null);
|
|
setSaved(false);
|
|
const payload = {
|
|
name: name.trim(),
|
|
lang: activeDraft.lang,
|
|
subject: activeDraft.subject.trim(),
|
|
description: activeDraft.description.trim() || undefined,
|
|
body: activeDraft.body,
|
|
status: activeDraft.status,
|
|
// NEVER null upstream: [] when the tab has no attachments.
|
|
attachmentId: activeDraft.attachments.map((a) => a.id),
|
|
};
|
|
try {
|
|
if (mode === "edit" && activeDraft.id != null) {
|
|
await updateEmailTemplate(activeDraft.id, payload);
|
|
} else {
|
|
await createEmailTemplate(payload);
|
|
}
|
|
setSaved(true);
|
|
onSaved?.();
|
|
} catch (err) {
|
|
setSaveError(err instanceof Error ? err.message : t("EmailTemplateSaveFailed"));
|
|
} finally {
|
|
setSaving(false);
|
|
}
|
|
}
|
|
|
|
const canSave =
|
|
name.trim().length > 0 &&
|
|
Boolean(activeDraft) &&
|
|
activeDraft.subject.trim().length > 0 &&
|
|
activeDraft.body.trim().length > 0;
|
|
|
|
return (
|
|
<div className="space-y-4">
|
|
{saveError && (
|
|
<Alert variant="destructive">
|
|
<AlertTitle>{t("EmailTemplateSaveFailed")}</AlertTitle>
|
|
<AlertDescription>{saveError}</AlertDescription>
|
|
</Alert>
|
|
)}
|
|
{saved && !saveError && (
|
|
<Alert>
|
|
<AlertTitle>{t("EmailTemplateSaved")}</AlertTitle>
|
|
</Alert>
|
|
)}
|
|
|
|
<div className="space-y-1.5">
|
|
<Label htmlFor="email-template-name">{t("EmailTemplateName")}</Label>
|
|
<Input
|
|
id="email-template-name"
|
|
value={name}
|
|
readOnly={mode === "edit"}
|
|
onChange={(e) => mode === "create" && setName(e.target.value)}
|
|
aria-label={t("EmailTemplateName")}
|
|
className={mode === "edit" ? "bg-muted text-muted-foreground" : undefined}
|
|
/>
|
|
{mode === "create" && (
|
|
<p className="text-sm text-muted-foreground">{t("EmailTemplateNameCaveat")}</p>
|
|
)}
|
|
{mode === "edit" && (
|
|
<p className="text-sm text-muted-foreground">{t("EmailTemplateEditNote")}</p>
|
|
)}
|
|
</div>
|
|
|
|
<Tabs
|
|
value={activeLang}
|
|
onValueChange={(v) => {
|
|
setActiveLang(v as EmailTemplateLang);
|
|
setSampleValues({});
|
|
setRenderedHtml("");
|
|
}}
|
|
>
|
|
<div className="flex flex-wrap items-center gap-2">
|
|
<TabsList className="flex-wrap">
|
|
{drafts.map((d) => (
|
|
<TabsTrigger key={d.lang} value={d.lang}>
|
|
{d.lang}
|
|
</TabsTrigger>
|
|
))}
|
|
</TabsList>
|
|
{availableLangs.length > 0 && (
|
|
<Select value="" onValueChange={(v) => addLanguage(v as EmailTemplateLang)}>
|
|
<SelectTrigger
|
|
aria-label={t("EmailTemplateAddLanguage")}
|
|
className="h-9 w-fit gap-2 [&>svg:last-child]:hidden"
|
|
>
|
|
<Plus aria-hidden="true" className="size-4" />
|
|
<span>{t("EmailTemplateAddLanguage")}</span>
|
|
</SelectTrigger>
|
|
<SelectContent>
|
|
{availableLangs.map((o) => (
|
|
<SelectItem key={o.value} value={o.value}>
|
|
{o.label} ({o.value})
|
|
</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
)}
|
|
</div>
|
|
|
|
{drafts.map((d) => (
|
|
<TabsContent key={d.lang} value={d.lang}>
|
|
<div className="grid gap-4 lg:grid-cols-2">
|
|
<div className="space-y-4">
|
|
<div className="space-y-1.5">
|
|
<Label htmlFor={`subject-${d.lang}`}>{t("EmailTemplateSubject")}</Label>
|
|
<Input
|
|
id={`subject-${d.lang}`}
|
|
value={d.subject}
|
|
onChange={(e) => patchDraft({ subject: e.target.value })}
|
|
/>
|
|
</div>
|
|
<div className="space-y-1.5">
|
|
<Label htmlFor={`description-${d.lang}`}>{t("Description")}</Label>
|
|
<Input
|
|
id={`description-${d.lang}`}
|
|
value={d.description}
|
|
onChange={(e) => patchDraft({ description: e.target.value })}
|
|
/>
|
|
</div>
|
|
<div className="space-y-1.5">
|
|
<Label htmlFor={`status-${d.lang}`}>{t("Status")}</Label>
|
|
<Select
|
|
value={d.status}
|
|
onValueChange={(v) => patchDraft({ status: v as EmailTemplateStatus })}
|
|
>
|
|
<SelectTrigger id={`status-${d.lang}`} className="h-9 w-[160px]">
|
|
<SelectValue />
|
|
</SelectTrigger>
|
|
<SelectContent>
|
|
<SelectItem value="Y">{t("Active")}</SelectItem>
|
|
<SelectItem value="N">{t("Inactive")}</SelectItem>
|
|
</SelectContent>
|
|
</Select>
|
|
</div>
|
|
<div className="space-y-1.5">
|
|
<Label htmlFor={`body-${d.lang}`}>{t("EmailTemplateBody")}</Label>
|
|
<Textarea
|
|
id={`body-${d.lang}`}
|
|
value={d.body}
|
|
onChange={(e) => patchDraft({ body: e.target.value })}
|
|
className="min-h-40 font-mono text-xs"
|
|
/>
|
|
</div>
|
|
|
|
<div className="space-y-1.5">
|
|
<Label>{t("EmailTemplateAttachments")}</Label>
|
|
{d.attachments.length > 0 && (
|
|
<ul className="space-y-1">
|
|
{d.attachments.map((a) => (
|
|
<li
|
|
key={a.id}
|
|
className="flex items-center justify-between gap-2 rounded-md border px-2 py-1 text-sm"
|
|
>
|
|
<span className="truncate" title={a.fileName}>
|
|
{a.fileName ?? `#${a.id}`}
|
|
</span>
|
|
<Button
|
|
variant="ghost"
|
|
size="sm"
|
|
onClick={() => removeAttachment(a.id, d.lang)}
|
|
>
|
|
{t("EmailTemplateRemoveAttachment")}
|
|
</Button>
|
|
</li>
|
|
))}
|
|
</ul>
|
|
)}
|
|
{uploadError && <p className="text-sm text-destructive">{uploadError}</p>}
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
onClick={() => fileInputRef.current?.click()}
|
|
disabled={uploading}
|
|
>
|
|
<Plus aria-hidden="true" className="size-4" />
|
|
{uploading ? t("EmailTemplateUploading") : t("EmailTemplateAddAttachment")}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="space-y-3">
|
|
<div className="space-y-1.5">
|
|
<Label>{t("EmailTemplateSampleValues")}</Label>
|
|
{tokens.length === 0 ? (
|
|
<p className="text-sm text-muted-foreground">—</p>
|
|
) : (
|
|
<div className="space-y-3">
|
|
{tokens.map((token) => (
|
|
<div key={token} className="space-y-1.5">
|
|
<Label htmlFor={`sample-${token}`}>{token}</Label>
|
|
<Input
|
|
id={`sample-${token}`}
|
|
aria-label={token}
|
|
value={sampleValues[token] ?? ""}
|
|
onChange={(e) =>
|
|
setSampleValues((prev) => ({ ...prev, [token]: e.target.value }))
|
|
}
|
|
className="h-9 font-mono text-xs"
|
|
/>
|
|
</div>
|
|
))}
|
|
</div>
|
|
)}
|
|
</div>
|
|
<div className="space-y-1.5">
|
|
<Label>{t("EmailTemplatePreview")}</Label>
|
|
<TemplatePreviewPane html={activeBody.trim() ? renderedHtml : ""} title={t("EmailTemplatePreview")} />
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</TabsContent>
|
|
))}
|
|
</Tabs>
|
|
|
|
<div className="flex justify-end gap-2">
|
|
<Button onClick={handleSave} disabled={saving || !canSave}>
|
|
{saving ? t("EmailTemplateSaving") : t("EmailTemplateSave")}
|
|
</Button>
|
|
</div>
|
|
|
|
{/* Shared hidden file input for attachment uploads (opened by each tab's Add button). */}
|
|
<input
|
|
ref={fileInputRef}
|
|
type="file"
|
|
className="hidden"
|
|
aria-label={t("EmailTemplateAddAttachmentFile")}
|
|
onChange={handleFileChange}
|
|
/>
|
|
</div>
|
|
);
|
|
}
|