Implement modular email template system with preview and testing

- Create modular EmailTemplateRenderer with master shell and content separation
- Build reusable email components library (buttons, alerts, OTP boxes, etc.)
- Add EmailTemplatePreview component with master/content preview modes
- Implement test email functionality for each notification template
- Update NotifikasiTab to use new preview system with shortcode processing
- Add dummy shortcode data for testing (nama, email, order_id, etc.)
- Maintain design consistency between web and email

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
dwindown
2025-12-22 19:56:23 +07:00
parent 6e7b8eea1c
commit efc085e231
4 changed files with 967 additions and 46 deletions

View File

@@ -0,0 +1,164 @@
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { toast } from '@/hooks/use-toast';
import { Eye, Send, Mail } from 'lucide-react';
import { EmailTemplateRenderer, ShortcodeProcessor } from '@/lib/email-templates/master-template';
interface NotificationTemplate {
id: string;
key: string;
name: string;
is_active: boolean;
email_subject: string;
email_body_html: string;
webhook_url: string;
last_payload_example?: Record<string, unknown> | null;
}
interface EmailTemplatePreviewProps {
template: NotificationTemplate;
onTest?: (template: NotificationTemplate) => void;
isTestSending?: boolean;
}
export function EmailTemplatePreview({ template, onTest, isTestSending = false }: EmailTemplatePreviewProps) {
const [previewMode, setPreviewMode] = useState<'master' | 'content'>('master');
const [testEmail, setTestEmail] = useState('');
const [showTestForm, setShowTestForm] = useState(false);
// Generate preview with dummy shortcode data
const generatePreview = () => {
const processedSubject = ShortcodeProcessor.process(template.email_subject);
const processedContent = ShortcodeProcessor.process(template.email_body_html);
if (previewMode === 'master') {
const fullHtml = EmailTemplateRenderer.render({
subject: processedSubject,
content: processedContent,
brandName: 'ACCESS HUB'
});
return fullHtml;
} else {
return processedContent;
}
};
const handleTestEmail = async () => {
if (!testEmail) {
toast({ title: 'Error', description: 'Masukkan email tujuan', variant: 'destructive' });
return;
}
if (onTest) {
await onTest({ ...template, test_email: testEmail });
}
};
const previewHtml = generatePreview();
return (
<div className="space-y-4">
{/* Preview Controls */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<Label>Preview Mode:</Label>
<select
value={previewMode}
onChange={(e) => setPreviewMode(e.target.value as 'master' | 'content')}
className="border-2 px-3 py-1 rounded"
>
<option value="master">Master Template</option>
<option value="content">Content Only</option>
</select>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
onClick={() => setShowTestForm(!showTestForm)}
>
<Send className="w-4 h-4 mr-2" />
{showTestForm ? 'Cancel' : 'Test Email'}
</Button>
</div>
</div>
{/* Test Email Form */}
{showTestForm && (
<div className="p-4 border-2 border-gray-300 rounded-lg bg-gray-50">
<div className="space-y-3">
<Label htmlFor="test-email">Test Email Address:</Label>
<div className="flex gap-2">
<Input
id="test-email"
type="email"
value={testEmail}
onChange={(e) => setTestEmail(e.target.value)}
placeholder="test@example.com"
className="flex-1"
/>
<Button
onClick={handleTestEmail}
disabled={!testEmail || isTestSending}
>
<Mail className="w-4 h-4 mr-2" />
{isTestSending ? 'Sending...' : 'Send Test'}
</Button>
</div>
<p className="text-sm text-muted-foreground">
This will send a test email with dummy data for all available shortcodes.
</p>
</div>
</div>
)}
{/* Preview Info */}
<Alert>
<Eye className="w-4 h-4" />
<AlertDescription>
{previewMode === 'master'
? 'Showing complete email template with header, footer, and styling applied.'
: 'Showing only the content section without master template styling.'
}
</AlertDescription>
</Alert>
{/* Email Preview */}
<div className="border-2 border-gray-300 rounded-lg overflow-hidden">
<div className="bg-gray-100 px-4 py-2 border-b border-gray-300">
<span className="text-sm font-mono text-gray-600">
{previewMode === 'master' ? 'Full Email Preview' : 'Content Preview'}
</span>
</div>
<div className="max-h-96 overflow-auto bg-white">
<iframe
srcDoc={previewHtml}
className="w-full border-0"
style={{ height: '500px' }}
sandbox="allow-same-origin"
/>
</div>
</div>
{/* Shortcodes Used */}
<div className="p-3 bg-blue-50 border border-blue-200 rounded">
<h4 className="font-semibold text-sm mb-2">Shortcodes Used in This Template:</h4>
<div className="grid grid-cols-2 gap-2 text-sm">
{['{nama}', '{email}', '{order_id}', '{tanggal_pesanan}', '{total}', '{metode_pembayaran}',
'{produk}', '{link_akses}', '{tanggal_konsultasi}', '{jam_konsultasi}', '{link_meet}',
'{judul_event}', '{tanggal_event}', '{jam_event}', '{link_event}'].filter(shortcode =>
template.email_subject.includes(shortcode) || template.email_body_html.includes(shortcode)
).map(shortcode => (
<code key={shortcode} className="bg-blue-100 px-2 py-1 rounded text-xs">
{shortcode}
</code>
))}
</div>
</div>
</div>
);
}

View File

@@ -11,6 +11,7 @@ import { RichTextEditor } from '@/components/RichTextEditor';
import { toast } from '@/hooks/use-toast';
import { Mail, ChevronDown, ChevronUp, Webhook } from 'lucide-react';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { EmailTemplatePreview } from '@/components/admin/EmailTemplatePreview';
interface NotificationTemplate {
id: string;
@@ -79,6 +80,7 @@ export function NotifikasiTab() {
const [templates, setTemplates] = useState<NotificationTemplate[]>([]);
const [loading, setLoading] = useState(true);
const [expandedTemplates, setExpandedTemplates] = useState<Set<string>>(new Set());
const [testingTemplate, setTestingTemplate] = useState<string | null>(null);
useEffect(() => {
fetchData();
@@ -117,6 +119,55 @@ export function NotifikasiTab() {
else toast({ title: 'Berhasil', description: `Template "${name}" disimpan` });
};
const sendTestEmail = async (template: NotificationTemplate & { test_email?: string }) => {
if (!template.test_email) {
toast({ title: 'Error', description: 'Masukkan email tujuan', variant: 'destructive' });
return;
}
setTestingTemplate(template.id);
try {
// Fetch email settings from notification_settings
const { data: emailData } = await supabase
.from('notification_settings')
.select('*')
.single();
if (!emailData || !emailData.api_token || !emailData.from_email) {
throw new Error('Konfigurasi email provider belum lengkap');
}
// Send test email using send-email-v2
const { data, error } = await supabase.functions.invoke('send-email-v2', {
body: {
to: template.test_email,
api_token: emailData.api_token,
from_name: emailData.from_name,
from_email: emailData.from_email,
subject: template.email_subject,
html_body: template.email_body_html,
},
});
if (error) throw error;
if (data?.success) {
toast({ title: 'Berhasil', description: `Email test "${template.name}" dikirim ke ${template.test_email}` });
} else {
throw new Error(data?.message || 'Failed to send test email');
}
} catch (error: any) {
console.error('Test template email error:', error);
toast({
title: 'Error',
description: error.message || 'Gagal mengirim email test template',
variant: 'destructive'
});
} finally {
setTestingTemplate(null);
}
};
const toggleExpand = (id: string) => {
setExpandedTemplates(prev => {
const next = new Set(prev);
@@ -218,48 +269,60 @@ export function NotifikasiTab() {
</CollapsibleTrigger>
<CollapsibleContent>
<div className="p-4 pt-0 space-y-4 border-t">
<div className="space-y-2">
<Label>Subjek Email</Label>
<Input
value={template.email_subject}
onChange={(e) => {
setTemplates(templates.map(t =>
t.id === template.id ? { ...t, email_subject: e.target.value } : t
));
}}
placeholder="Subjek email..."
className="border-2"
/>
<div className="p-4 pt-0 space-y-6 border-t">
<div className="space-y-4">
<div className="space-y-2">
<Label>Subjek Email</Label>
<Input
value={template.email_subject}
onChange={(e) => {
setTemplates(templates.map(t =>
t.id === template.id ? { ...t, email_subject: e.target.value } : t
));
}}
placeholder="Subjek email..."
className="border-2"
/>
</div>
<div className="space-y-2">
<Label>Isi Email (HTML)</Label>
<RichTextEditor
content={template.email_body_html}
onChange={(html) => {
setTemplates(templates.map(t =>
t.id === template.id ? { ...t, email_body_html: html } : t
));
}}
placeholder="Tulis isi email..."
/>
</div>
<div className="space-y-2">
<Label className="flex items-center gap-2">
<Webhook className="w-4 h-4" />
Webhook URL (opsional, untuk n8n/Zapier)
</Label>
<Input
value={template.webhook_url}
onChange={(e) => {
setTemplates(templates.map(t =>
t.id === template.id ? { ...t, webhook_url: e.target.value } : t
));
}}
placeholder="https://n8n.example.com/webhook/..."
className="border-2"
/>
</div>
</div>
<div className="space-y-2">
<Label>Isi Email (HTML)</Label>
<RichTextEditor
content={template.email_body_html}
onChange={(html) => {
setTemplates(templates.map(t =>
t.id === template.id ? { ...t, email_body_html: html } : t
));
}}
placeholder="Tulis isi email..."
/>
</div>
<div className="space-y-2">
<Label className="flex items-center gap-2">
<Webhook className="w-4 h-4" />
Webhook URL (opsional, untuk n8n/Zapier)
</Label>
<Input
value={template.webhook_url}
onChange={(e) => {
setTemplates(templates.map(t =>
t.id === template.id ? { ...t, webhook_url: e.target.value } : t
));
}}
placeholder="https://n8n.example.com/webhook/..."
className="border-2"
{/* Email Preview */}
<div className="space-y-4">
<h4 className="font-semibold">Email Preview</h4>
<EmailTemplatePreview
template={template}
onTest={sendTestEmail}
isTestSending={testingTemplate === template.id}
/>
</div>
@@ -272,12 +335,14 @@ export function NotifikasiTab() {
</div>
)}
<Button
onClick={() => updateTemplate(template)}
className="shadow-sm"
>
Simpan Template
</Button>
<div className="flex gap-2">
<Button
onClick={() => updateTemplate(template)}
className="shadow-sm flex-1"
>
Simpan Template
</Button>
</div>
</div>
</CollapsibleContent>
</div>

View File

@@ -0,0 +1,382 @@
interface EmailTemplateData {
subject: string;
content: string;
brandName?: string;
brandLogo?: string;
}
export class EmailTemplateRenderer {
private static readonly MASTER_TEMPLATE = `
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{subject}}</title>
<style>
/* =========================================
1. CLIENT RESETS (The Boring Stuff)
========================================= */
body, table, td, a { -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; }
table, td { mso-table-lspace: 0pt; mso-table-rspace: 0pt; }
img { -ms-interpolation-mode: bicubic; border: 0; height: auto; line-height: 100%; outline: none; text-decoration: none; }
table { border-collapse: collapse !important; }
body { height: 100% !important; margin: 0 !important; padding: 0 !important; width: 100% !important; background-color: #FFFFFF; }
/* =========================================
2. MASTER TYPOGRAPHY & VARS
========================================= */
:root {
--color-black: #000000;
--color-white: #FFFFFF;
--color-gray: #F4F4F5;
--color-success: #00A651;
--color-danger: #E11D48;
--border-thick: 2px solid #000000;
--border-thin: 1px solid #000000;
--shadow-hard: 4px 4px 0px 0px #000000;
}
body {
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
color: #000000;
-webkit-font-smoothing: antialiased;
}
/* =========================================
3. DYNAMIC CONTENT POLISH
========================================= */
/* Headings */
.email-content h1 {
font-size: 28px;
font-weight: 800;
margin: 0 0 20px 0;
letter-spacing: -1px;
line-height: 1.1;
}
.email-content h2 {
font-size: 20px;
font-weight: 700;
margin: 25px 0 15px 0;
text-transform: uppercase;
letter-spacing: 0.5px;
border-bottom: 2px solid #000;
padding-bottom: 5px;
display: inline-block;
}
.email-content h3 {
font-size: 18px;
font-weight: 700;
margin: 20px 0 10px 0;
color: #333;
}
.email-content p {
font-size: 16px;
line-height: 1.6;
margin: 0 0 20px 0;
color: #333;
}
/* Standard Links */
.email-content a {
color: #000000;
text-decoration: underline;
font-weight: 700;
text-underline-offset: 3px;
}
/* Lists */
.email-content ul, .email-content ol {
margin: 0 0 20px 0;
padding-left: 20px;
}
.email-content li {
margin-bottom: 8px;
font-size: 16px;
padding-left: 5px;
}
/* TABLES (Brutalist Style) */
.email-content table {
width: 100%;
border: 2px solid #000;
margin-bottom: 25px;
border-collapse: collapse;
}
.email-content th {
background-color: #000;
color: #FFF;
padding: 12px;
text-align: left;
font-size: 14px;
text-transform: uppercase;
font-weight: 700;
border: 1px solid #000;
}
.email-content td {
padding: 12px;
border: 1px solid #000;
font-size: 15px;
vertical-align: top;
}
/* Zebra Striping */
.email-content tr:nth-child(even) td {
background-color: #F8F8F8;
}
/* BUTTONS (Class: .btn) */
.btn {
display: inline-block;
background-color: #000;
color: #FFF !important;
padding: 14px 28px;
font-weight: 700;
text-transform: uppercase;
text-decoration: none !important;
font-size: 16px;
border: 2px solid #000;
box-shadow: 4px 4px 0px 0px #000000; /* Hard Shadow */
margin: 10px 0;
transition: all 0.1s;
}
.btn:hover {
transform: translate(2px, 2px);
box-shadow: 2px 2px 0px 0px #000000;
}
.btn-full { width: 100%; text-align: center; box-sizing: border-box; }
/* CODE BLOCKS */
.email-content pre {
background-color: #F4F4F5;
border: 2px solid #000;
padding: 15px;
overflow-x: auto;
margin-bottom: 20px;
}
.email-content code {
font-family: 'Courier New', Courier, monospace;
font-size: 14px;
color: #E11D48;
background-color: #F4F4F5;
padding: 2px 4px;
}
/* Special OTP Style */
.otp-box {
background-color: #F4F4F5;
border: 2px dashed #000;
padding: 20px;
text-align: center;
margin: 20px 0;
letter-spacing: 5px;
font-family: 'Courier New', Courier, monospace;
font-size: 32px;
font-weight: 700;
color: #000;
}
/* BLOCKQUOTES / ALERTS */
.email-content blockquote {
margin: 0 0 20px 0;
padding: 15px 20px;
border-left: 6px solid #000;
background-color: #F9F9F9;
font-style: italic;
font-weight: 500;
}
/* Contextual Alerts */
.alert-success { background-color: #E6F4EA; border-left-color: #00A651; color: #005A2B; }
.alert-danger { background-color: #FFE4E6; border-left-color: #E11D48; color: #881337; }
.alert-info { background-color: #E3F2FD; border-left-color: #1976D2; color: #0D47A1; }
/* =========================================
4. RESPONSIVE
========================================= */
@media screen and (max-width: 600px) {
.email-container { width: 100% !important; border-left: 0 !important; border-right: 0 !important; }
.content-padding { padding: 30px 20px !important; }
.stack-mobile { display: block !important; width: 100% !important; }
}
</style>
</head>
<body style="margin: 0; padding: 0; background-color: #FFFFFF;">
<!-- 100% WRAPPER -->
<table border="0" cellpadding="0" cellspacing="0" width="100%" style="background-color: #FFFFFF;">
<tr>
<td align="center" style="padding: 40px 0;">
<!-- MAIN CONTAINER (600px) -->
<table border="0" cellpadding="0" cellspacing="0" width="600" class="email-container" style="background-color: #FFFFFF; border: 2px solid #000000; width: 600px; min-width: 320px;">
<!-- HEADER -->
<tr>
<td align="left" style="background-color: #000000; padding: 25px 40px; border-bottom: 2px solid #000000;">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left">
<!-- LOGO (White text) -->
<div style="font-family: 'Helvetica Neue', sans-serif; font-size: 24px; font-weight: 900; color: #FFFFFF; letter-spacing: -1px; text-transform: uppercase;">
{{brandName}}
</div>
</td>
<td align="right">
<!-- Optional: Small Date or Tag -->
<div style="font-family: monospace; font-size: 12px; color: #888;">
NOTIF #{{timestamp}}
</div>
</td>
</tr>
</table>
</td>
</tr>
<!-- BODY CONTENT -->
<tr>
<td class="content-padding" style="padding: 40px 40px 60px 40px;">
<!-- DYNAMIC CONTENT -->
<div class="email-content">
{{content}}
</div>
</td>
</tr>
<!-- FOOTER -->
<tr>
<td style="padding: 30px 40px; border-top: 2px solid #000000; background-color: #F4F4F5; color: #000;">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left" style="font-size: 12px; line-height: 18px; font-family: monospace; color: #555;">
<p style="margin: 0 0 10px 0; font-weight: bold;">{{brandName}}</p>
<p style="margin: 0 0 15px 0;">Email ini dikirim otomatis. Jangan membalas email ini.</p>
<p style="margin: 0;">
<a href="#" style="color: #000; text-decoration: underline;">Ubah Preferensi</a> &nbsp;|&nbsp;
<a href="#" style="color: #000; text-decoration: underline;">Unsubscribe</a>
</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
<!-- END MAIN CONTAINER -->
</td>
</tr>
</table>
</body>
</html>
`;
static render(data: EmailTemplateData): string {
let html = this.MASTER_TEMPLATE;
// Replace placeholders
html = html.replace(/{{subject}}/g, data.subject || 'Notification');
html = html.replace(/{{brandName}}/g, data.brandName || 'ACCESS HUB');
html = html.replace(/{{brandLogo}}/g, data.brandLogo || '');
html = html.replace(/{{timestamp}}/g, Date.now().toString().slice(-6));
html = html.replace(/{{content}}/g, data.content);
return html;
}
}
// Reusable Email Components
export const EmailComponents = {
// Buttons
button: (text: string, url: string, fullwidth = false) =>
`<p style="margin-top: 20px; text-align: ${fullwidth ? 'center' : 'left'};">
<a href="${url}" class="${fullwidth ? 'btn-full' : 'btn'}">${text}</a>
</p>`,
// Alert boxes
alert: (type: 'success' | 'danger' | 'info', content: string) =>
`<blockquote class="alert-${type}">
${content}
</blockquote>`,
// Code blocks
codeBlock: (code: string, language = '') =>
`<pre><code>${code}</code></pre>`,
// OTP boxes
otpBox: (code: string) =>
`<div class="otp-box">${code}</div>`,
// Info card
infoCard: (title: string, items: Array<{label: string; value: string}>) => {
const rows = items.map(item =>
`<tr>
<td>${item.label}</td>
<td>${item.value}</td>
</tr>`
).join('');
return `
<h2>${title}</h2>
<table>
<thead>
<tr>
<th>Parameter</th>
<th>Value</th>
</tr>
</thead>
<tbody>
${rows}
</tbody>
</table>
`;
},
// Divider
divider: () => '<hr style="border: 1px solid #000; margin: 30px 0;">',
// Spacing
spacing: (size: 'small' | 'medium' | 'large' = 'medium') => {
const sizes = { small: '15px', medium: '25px', large: '40px' };
return `<div style="height: ${sizes[size]};"></div>`;
}
};
// Shortcode processor
export class ShortcodeProcessor {
private static readonly DEFAULT_DATA = {
nama: 'John Doe',
email: 'john@example.com',
order_id: 'ORD-123456',
tanggal_pesanan: '22 Desember 2025',
total: 'Rp 1.500.000',
metode_pembayaran: 'Transfer Bank',
produk: 'Product Name',
link_akses: 'https://example.com/access',
tanggal_konsultasi: '22 Desember 2025',
jam_konsultasi: '14:00',
link_meet: 'https://meet.google.com/example',
judul_event: 'Workshop Digital Marketing',
tanggal_event: '25 Desember 2025',
jam_event: '19:00',
link_event: 'https://event.example.com'
};
static process(content: string, customData: Record<string, string> = {}): string {
const data = { ...this.DEFAULT_DATA, ...customData };
let processed = content;
for (const [key, value] of Object.entries(data)) {
const regex = new RegExp(`\\{${key}\\}`, 'g');
processed = processed.replace(regex, value);
}
return processed;
}
static getDummyData(): Record<string, string> {
return this.DEFAULT_DATA;
}
}