Files
govoplan-campaign/webui/src/features/campaigns/utils/templatePreviewDraft.ts
2026-06-25 19:58:20 +02:00

86 lines
2.7 KiB
TypeScript

const addressArrayKeys = [
"from",
"to",
"cc",
"bcc",
"reply_to",
"bounce_to",
"disposition_notification_to"
];
export function campaignJsonForAttachmentPreview(draft: Record<string, unknown>): Record<string, unknown> {
const next = cloneJson(draft);
const entries = asRecord(next.entries);
if (Array.isArray(entries.inline)) {
entries.inline = entries.inline.map((entry) => normalizePreviewEntry(entry));
}
if (isRecord(entries.defaults)) {
entries.defaults = normalizePreviewEntry(entries.defaults);
}
next.entries = entries;
if (isRecord(next.recipients)) {
next.recipients = normalizeAddressContainer(next.recipients);
}
return next;
}
function normalizePreviewEntry(value: unknown): Record<string, unknown> {
const entry = { ...asRecord(value) };
if (typeof entry.email === "string" && !entry.email.trim()) delete entry.email;
if (typeof entry.name === "string" && !entry.name.trim()) delete entry.name;
for (const key of addressArrayKeys) {
const current = entry[key];
if (Array.isArray(current)) {
const filtered = current.map(normalizeRecipient).filter((item): item is Record<string, unknown> => Boolean(item));
entry[key] = filtered;
continue;
}
if (isRecord(current)) {
const normalized = normalizeRecipient(current);
if (normalized) entry[key] = normalized;
else delete entry[key];
}
}
return entry;
}
function normalizeAddressContainer(value: Record<string, unknown>): Record<string, unknown> {
const container = { ...value };
for (const key of addressArrayKeys) {
const current = container[key];
if (Array.isArray(current)) {
container[key] = current.map(normalizeRecipient).filter((item): item is Record<string, unknown> => Boolean(item));
continue;
}
if (isRecord(current)) {
const normalized = normalizeRecipient(current);
if (normalized) container[key] = normalized;
else delete container[key];
}
}
return container;
}
function normalizeRecipient(value: unknown): Record<string, unknown> | null {
const recipient = { ...asRecord(value) };
const email = typeof recipient.email === "string" ? recipient.email.trim() : "";
if (!email) return null;
recipient.email = email;
if (typeof recipient.name === "string" && !recipient.name.trim()) delete recipient.name;
return recipient;
}
function cloneJson<T>(value: T): T {
return JSON.parse(JSON.stringify(value ?? {})) as T;
}
function asRecord(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}