Files
co-lite/solvway-admin-portal/app/lib/services/emailTemplates.ts
T
ngqileandClaude Opus 5.5 5ee51d1913 chore: copy kept Tastefully modules and portals into Co-Lite
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
2026-11-26 15:55:45 +08:00

181 lines
7.1 KiB
TypeScript

import { apiGet, apiPost, apiPut } from "@/app/lib/clientApi";
import type {
AttachmentRef,
EmailLog,
EmailLogDetail,
EmailTemplate,
EmailTemplateGroup,
EmailTemplateLang,
EmailTemplateStatus,
} from "@/app/lib/types";
// Client-side wrapper for the /email-templates module. Calls only the portal's own
// /api/email-templates/** and /api/email-logs route handlers, which forward the admin JWT —
// never solvway-mobile-api directly.
export interface EmailTemplateListParams {
name?: string;
description?: string;
lang?: EmailTemplateLang;
status?: EmailTemplateStatus;
/** 1-based, matching this portal's other list pages (e.g. Messages). */
page: number;
pageSize: number;
/** Server-side sort: attribute name + direction; sent only when present. */
sortBy?: string;
sortDir?: "asc" | "desc";
}
export interface EmailTemplateListResult {
items: EmailTemplateGroup[];
total: number;
}
export interface EmailLogListParams {
/** 1-based, matching this portal's other list pages. */
page: number;
pageSize: number;
/** Contains-match on any recipient address / on the subject; blank is not sent. */
recipient?: string;
subject?: string;
/** Server-side sort: attribute name + direction; sent only when present. */
sortBy?: string;
sortDir?: "asc" | "desc";
}
export interface EmailLogListResult {
items: EmailLog[];
total: number;
}
/** The email-only Lang set (CN/ZH/EN/MY/ID — spec G4), with display labels. */
export const EMAIL_LANG_OPTIONS: { value: EmailTemplateLang; label: string }[] = [
{ value: "CN", label: "简体中文" },
{ value: "ZH", label: "繁體中文" },
{ value: "EN", label: "English" },
{ value: "MY", label: "Bahasa Melayu" },
{ value: "ID", label: "Bahasa Indonesia" },
];
/**
* Builds the query string for GET /api/email-templates. `page` is 1-based here (this portal's
* list-page convention) but mobile-api's `/api/admin/email-templates` is 0-based, so it is
* translated at the boundary.
*/
export function buildEmailTemplatesQuery(params: EmailTemplateListParams): string {
const qs = new URLSearchParams();
if (params.name) qs.set("name", params.name);
if (params.description) qs.set("description", params.description);
if (params.lang) qs.set("lang", params.lang);
if (params.status) qs.set("status", params.status);
qs.set("page", String(Math.max(0, params.page - 1)));
qs.set("size", String(params.pageSize));
if (params.sortBy) qs.set("sortBy", params.sortBy);
if (params.sortDir && params.sortBy) qs.set("sortDir", params.sortDir);
return qs.toString();
}
/** Normalizes the mobile-api page response ({content, totalElements}) into {items, total}. */
export function normalizeEmailTemplatePage(raw: unknown): EmailTemplateListResult {
if (!raw || typeof raw !== "object") return { items: [], total: 0 };
const obj = raw as Record<string, unknown>;
const items: EmailTemplateGroup[] = Array.isArray(obj.content)
? (obj.content as EmailTemplateGroup[])
: Array.isArray(obj.items)
? (obj.items as EmailTemplateGroup[])
: [];
const total =
typeof obj.totalElements === "number"
? obj.totalElements
: typeof obj.total === "number"
? obj.total
: items.length;
return { items, total };
}
export async function listEmailTemplates(params: EmailTemplateListParams): Promise<EmailTemplateListResult> {
const raw = await apiGet<unknown>(`/api/email-templates?${buildEmailTemplatesQuery(params)}`);
return normalizeEmailTemplatePage(raw);
}
/**
* Every language row for one template name (editor detail). The route lives under by-name/ —
* Next.js cannot host both [name] and [id] dynamic segments at the same path level.
*/
export async function getEmailTemplate(name: string): Promise<EmailTemplate[]> {
return apiGet<EmailTemplate[]>(`/api/email-templates/by-name/${encodeURIComponent(name)}`);
}
/** Create: always POSTs without an id; the body MUST carry a non-null attachmentId array. */
export async function createEmailTemplate(body: Omit<EmailTemplate, "id">): Promise<EmailTemplate> {
return apiPost<EmailTemplate>("/api/email-templates", body);
}
/** Update: PUTs to the record's own URL; the id is in the path, not the body. */
export async function updateEmailTemplate(id: number, body: Omit<EmailTemplate, "id">): Promise<EmailTemplate> {
return apiPut<EmailTemplate>(`/api/email-templates/${id}`, body);
}
/** Activate/deactivate one language row (Y/N). */
export async function setEmailTemplateStatus(id: number, status: EmailTemplateStatus): Promise<EmailTemplate> {
return apiPut<EmailTemplate>(`/api/email-templates/${id}/status`, { status });
}
/** Renders an unsaved body with admin-supplied sample values (spec G3). */
export async function previewEmailTemplate(
body: string,
sampleValues: Record<string, string>,
): Promise<{ renderedHtml: string }> {
return apiPost<{ renderedHtml: string }>("/api/email-templates/preview", { body, sampleValues });
}
/**
* Uploads one template attachment through the BFF route (which proxies the auto-committing
* upstream /email/attachment/updateAttachment). SERVER-INITIATED — no /storage/upload or
* /storage/commit is ever called from the portal.
*/
export async function uploadEmailAttachment(input: {
fileName: string;
fileType: string;
base: string;
}): Promise<AttachmentRef> {
return apiPost<AttachmentRef>("/api/email-templates/attachments", input);
}
/** Read-only send log. */
export async function listEmailLogs(params: EmailLogListParams): Promise<EmailLogListResult> {
const qs = new URLSearchParams();
qs.set("page", String(Math.max(0, params.page - 1)));
qs.set("size", String(params.pageSize));
if (params.recipient?.trim()) qs.set("recipient", params.recipient.trim());
if (params.subject?.trim()) qs.set("subject", params.subject.trim());
if (params.sortBy) qs.set("sortBy", params.sortBy);
if (params.sortDir && params.sortBy) qs.set("sortDir", params.sortDir);
const raw = await apiGet<unknown>(`/api/email-logs?${qs.toString()}`);
if (!raw || typeof raw !== "object") return { items: [], total: 0 };
const obj = raw as Record<string, unknown>;
const items: EmailLog[] = Array.isArray(obj.content) ? (obj.content as EmailLog[]) : [];
const total = typeof obj.totalElements === "number" ? obj.totalElements : items.length;
return { items, total };
}
/** One sent email (read-only detail). */
export async function getEmailLog(id: number): Promise<EmailLogDetail> {
return apiGet<EmailLogDetail>(`/api/email-logs/${id}`);
}
/** Requeues one send-log email (Failed or Success only; the BFF answers 409 while it is Pending). */
export async function resendEmailLog(id: number): Promise<void> {
await apiPost<unknown>(`/api/email-logs/${id}/resend`, {});
}
/** Send-log status codes (EmailEnum.StatusType in services-email): P Pending, Y Success, N Failed. */
const LOG_STATUS: Record<string, { label: string; tone: "positive" | "warning" | "negative" }> = {
P: { label: "Pending", tone: "warning" },
Y: { label: "Success", tone: "positive" },
N: { label: "Failed", tone: "negative" },
};
export const emailLogStatus = (code?: string) =>
(code && LOG_STATUS[code]) || { label: code || "—", tone: "neutral" as const };