'use client'; import { useEffect, useState, useCallback } from 'react'; import { notificationTemplateService, type NotificationTemplate, type EventRegistry } from '@/services/api/notificationTemplateService'; import { Settings, Plus, Edit2, Trash2, Eye, LayoutTemplate, MessageSquare, Mail, AlertTriangle, CheckCircle2, X } from 'lucide-react'; import { toast } from 'sonner'; import dynamic from 'next/dynamic'; import 'react-quill-new/dist/quill.snow.css'; const ReactQuill = dynamic(() => import('react-quill-new'), { ssr: false }); export default function NotificationTemplatesPage() { const [templates, setTemplates] = useState([]); const [events, setEvents] = useState([]); const [loading, setLoading] = useState(true); const [isModalOpen, setIsModalOpen] = useState(false); const [editingTemplate, setEditingTemplate] = useState(null); // Form State const [form, setForm] = useState({ name: '', event_key: '', channel: 'EMAIL', subject: '', body_content: '', is_active: true }); // Preview State const [previewObj, setPreviewObj] = useState<{subject: string, body: string} | null>(null); const loadData = useCallback(async () => { try { setLoading(true); const [tpls, evts] = await Promise.all([ notificationTemplateService.getTemplates(), notificationTemplateService.getEvents() ]); setTemplates(tpls); setEvents(evts); } catch (err: any) { toast.error('Failed to load templates or events'); } finally { setLoading(false); } }, []); useEffect(() => { loadData(); }, [loadData]); const handleOpenCreate = () => { setEditingTemplate(null); setForm({ name: '', event_key: events[0]?.event_key || '', channel: 'EMAIL', subject: '', body_content: '', is_active: true }); setPreviewObj(null); setIsModalOpen(true); }; const handleOpenEdit = (t: NotificationTemplate) => { setEditingTemplate(t); setForm({ name: t.name, event_key: t.event_key, channel: t.channel, subject: t.subject || '', body_content: t.body_content, is_active: t.is_active }); setPreviewObj(null); setIsModalOpen(true); }; const handleToggle = async (id: string, current: boolean) => { try { await notificationTemplateService.toggleActivation(id, !current); toast.success('Template status updated'); loadData(); } catch (err: any) { toast.error(err.response?.data?.detail || err.message); } }; const handlePreview = async () => { const activeEvent = events.find(e => e.event_key === form.event_key); const mockContext: any = {}; if (activeEvent) { activeEvent.variables.forEach(v => { // Special case for items to render a fake list for the preview if (v.name === 'items') { mockContext[v.name] = [ { product_name: "Apple Camera Lens Guards for iPhone 16 Plus", sku: "IFK-APP-05334-V05", quantity: 1, unit_price: 4187.15 } ]; } else { mockContext[v.name] = v.example || `[${v.name}]`; } }); } try { const res = await notificationTemplateService.previewTemplateRaw(form.body_content, mockContext, form.subject); setPreviewObj(res); toast.success('Preview generated successfully!'); } catch (err: any) { toast.error(err.response?.data?.detail || err.message); } }; const loadDefaultTemplate = () => { if (form.channel === 'EMAIL' && form.event_key === 'ORDER_CREATED') { setForm({ ...form, subject: 'Order Confirmation & Tax Invoice #{{ invoice_no }} - iFixKart', body_content: `

Dear {{ customer_name }},


Thank you for your order! Your Tax Invoice #{{ invoice_no }} (Order Ref: {{ order_no }}) is attached as a PDF to this email.

` }); toast.success("Loaded Standard Template Design"); } else { toast.error("Standard template only available for ORDER_CREATED on EMAIL currently."); } }; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); try { if (editingTemplate) { await notificationTemplateService.updateTemplate(editingTemplate.template_id, { name: form.name, subject: form.subject || undefined, body_content: form.body_content, is_active: form.is_active }); toast.success('Template updated'); } else { await notificationTemplateService.createTemplate(form); toast.success('Template created'); } setIsModalOpen(false); loadData(); } catch (err: any) { toast.error(err.response?.data?.detail || err.message); } }; const selectedEvent = events.find(e => e.event_key === form.event_key); return (
{/* Header */}

Notification Templates

Manage Jinja2 templates for email and WhatsApp notifications

{/* Table */}
{loading ? ( ) : templates.length === 0 ? ( ) : ( templates.map((tpl) => ( )) )}
Template Name Event Key Channel Variables Status Actions
Loading...
No templates found
{tpl.name} {tpl.event_key} {tpl.channel === 'EMAIL' ? : } {tpl.channel} {tpl.variables?.length || 0} vars
{/* Modal */} {isModalOpen && (

{editingTemplate ? 'Edit Template' : 'Create New Template'}

{/* Form Side */}
setForm({...form, name: e.target.value})} className="w-full border border-border rounded-md px-3 py-2 text-sm bg-background" placeholder="e.g. Welcome Email" />
{form.channel === 'EMAIL' && (
setForm({...form, subject: e.target.value})} className="w-full border border-border rounded-md px-3 py-2 text-sm bg-background font-mono" placeholder="e.g. Order {{ order_id }} Confirmed" />
)}
{form.channel === 'EMAIL' ? (
setForm({...form, body_content: content})} modules={{ toolbar: [ [{ 'header': [1, 2, 3, false] }], ['bold', 'italic', 'underline', 'strike'], [{ 'color': [] }, { 'background': [] }], [{ 'list': 'ordered'}, { 'list': 'bullet' }], ['link', 'image'], ['clean'] ] }} />
) : (