ifixkart-admin/app/(admin)/notification-templates/page.tsx

435 lines
20 KiB
TypeScript

'use client';
import { useEffect, useState, useCallback } from 'react';
import { notificationTemplateService, type NotificationTemplate, type EventRegistry } from '@/services/api/notificationTemplateService';
import { Plus, Edit2, Eye, LayoutTemplate, MessageSquare, Mail, CheckCircle2, X, RefreshCw, Loader2 } from 'lucide-react';
import { toast } from 'sonner';
import { CustomSelect } from '@/components/ui/CustomSelect';
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<NotificationTemplate[]>([]);
const [events, setEvents] = useState<EventRegistry[]>([]);
const [loading, setLoading] = useState(true);
const [isModalOpen, setIsModalOpen] = useState(false);
const [editingTemplate, setEditingTemplate] = useState<NotificationTemplate | null>(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: `<p>Dear <strong>{{ customer_name }}</strong>,</p><p><br></p><p>Thank you for your order! Your Tax Invoice <strong>#{{ invoice_no }}</strong> (Order Ref: <strong>{{ order_no }}</strong>) is attached as a PDF to this email.</p>`
});
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);
const fieldClass =
'w-full h-9 px-3 bg-card border border-border crm-radius-control text-[13px] text-foreground focus:outline-none focus:border-primary disabled:opacity-60';
const areaClass =
'w-full px-3 py-2 bg-card border border-border crm-radius-control text-[13px] text-foreground focus:outline-none focus:border-primary';
const primaryButton =
'inline-flex items-center justify-center gap-1.5 h-9 px-3 crm-radius-control bg-primary hover:bg-primary/90 text-white text-[13px] font-semibold cursor-pointer disabled:opacity-50';
const secondaryButton =
'inline-flex items-center justify-center gap-1.5 h-9 px-3 crm-radius-control border border-border bg-card text-foreground text-[13px] font-medium hover:bg-muted cursor-pointer';
const shell =
'crm-radius-section border border-border bg-card shadow-[0_1px_3px_rgba(16,24,40,0.06)] min-w-0';
const labelClass = 'block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5';
return (
<div className="flex flex-col gap-5 min-w-0">
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex items-center gap-2 min-w-0">
<h1 className="text-lg font-semibold text-foreground">Notification Templates</h1>
<span className="inline-flex items-center justify-center min-w-5 h-5 px-1.5 crm-radius-toggle bg-primary/10 text-primary text-[11px] font-semibold leading-none">
{templates.length}
</span>
</div>
<div className="flex items-center gap-2">
<button
type="button"
onClick={loadData}
className="w-8 h-8 crm-radius-control border border-border bg-card text-muted-foreground hover:text-foreground hover:bg-muted cursor-pointer flex items-center justify-center"
title="Reload"
>
<RefreshCw className={`w-3.5 h-3.5 ${loading ? 'animate-spin' : ''}`} />
</button>
<button type="button" onClick={handleOpenCreate} className={primaryButton}>
<Plus className="w-3.5 h-3.5" /> Create template
</button>
</div>
</div>
<div className={`${shell} overflow-hidden`}>
<div className="overflow-x-auto">
<table className="crm-data-table w-full text-left">
<thead>
<tr className="border-b border-border">
<th className="px-4 py-2.5 font-medium text-muted-foreground">Template Name</th>
<th className="px-4 py-2.5 font-medium text-muted-foreground">Event Key</th>
<th className="px-4 py-2.5 font-medium text-muted-foreground">Channel</th>
<th className="px-4 py-2.5 font-medium text-muted-foreground text-center">Variables</th>
<th className="px-4 py-2.5 font-medium text-muted-foreground text-center">Status</th>
<th className="px-4 py-2.5 font-medium text-muted-foreground text-right">Actions</th>
</tr>
</thead>
<tbody className="divide-y divide-border">
{loading ? (
<tr><td colSpan={6} className="px-4 py-16 text-center"><Loader2 className="w-5 h-5 text-primary animate-spin inline-block" /></td></tr>
) : templates.length === 0 ? (
<tr><td colSpan={6} className="px-4 py-16 text-center text-[13px] text-muted-foreground">No templates yet</td></tr>
) : (
templates.map((tpl) => (
<tr key={tpl.template_id} className="hover:bg-muted/30 transition-colors">
<td className="px-4 py-3 font-medium">{tpl.name}</td>
<td className="px-4 py-3 text-muted-foreground font-mono text-xs">{tpl.event_key}</td>
<td className="px-4 py-3">
<span className={`inline-flex items-center gap-1.5 px-2.5 py-1 crm-radius-badge text-[11px] font-semibold ${
tpl.channel === 'EMAIL' ? 'bg-primary/10 text-primary' : 'bg-success/15 text-success'
}`}>
{tpl.channel === 'EMAIL' ? <Mail className="w-3.5 h-3.5" /> : <MessageSquare className="w-3.5 h-3.5" />}
{tpl.channel}
</span>
</td>
<td className="px-4 py-3 text-center">
<span className="inline-flex items-center px-2.5 py-1 crm-radius-badge text-[11px] font-semibold bg-muted text-foreground font-mono">
{tpl.variables?.length || 0} vars
</span>
</td>
<td className="px-4 py-3 text-center">
<button type="button" onClick={() => handleToggle(tpl.template_id, tpl.is_active)} className={`inline-flex items-center px-2.5 py-1 crm-radius-badge text-[11px] font-semibold cursor-pointer ${
tpl.is_active ? 'bg-success/15 text-success' : 'bg-muted text-muted-foreground'
}`}>
{tpl.is_active ? 'Active' : 'Inactive'}
</button>
</td>
<td className="px-4 py-3 text-right">
<button onClick={() => handleOpenEdit(tpl)} className="p-1.5 text-muted-foreground hover:text-primary transition-colors">
<Edit2 className="w-4 h-4" />
</button>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
{/* Modal */}
{isModalOpen && (
<div className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4">
<div className="bg-card border border-border crm-radius-section shadow-lg w-full max-w-6xl max-h-[90vh] flex flex-col">
<div className="border-b border-border px-4 py-3 flex items-center justify-between shrink-0">
<h2 className="text-lg font-semibold text-foreground">
{editingTemplate ? 'Edit template' : 'Create template'}
</h2>
<button type="button" onClick={() => setIsModalOpen(false)} className="w-8 h-8 crm-radius-control border border-border bg-card text-muted-foreground hover:bg-muted flex items-center justify-center cursor-pointer">
<X className="w-4 h-4" />
</button>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-5 p-4 min-h-0 flex-1 items-stretch">
<form id="notification-template-form" onSubmit={handleSubmit} className="space-y-4 min-w-0">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="min-w-0">
<label className={labelClass}>Template name</label>
<input
type="text"
required
value={form.name}
onChange={e => setForm({...form, name: e.target.value})}
className={fieldClass}
placeholder="Name"
/>
</div>
<div className="min-w-0">
<label className={labelClass}>Channel</label>
<CustomSelect
className="w-full"
value={form.channel}
onChange={(value) => setForm({...form, channel: value})}
disabled={!!editingTemplate}
options={[
{ value: 'EMAIL', label: 'Email' },
{ value: 'WHATSAPP', label: 'WhatsApp' },
]}
/>
</div>
</div>
<div>
<label className={labelClass}>Event</label>
<CustomSelect
className="w-full"
value={form.event_key}
onChange={(value) => setForm({...form, event_key: value})}
disabled={!!editingTemplate}
placeholder="Select event"
options={[
{ value: '', label: 'Select event' },
...events.map((ev) => ({ value: ev.event_key, label: ev.event_key })),
]}
/>
</div>
{form.channel === 'EMAIL' && (
<div>
<label className={labelClass}>Subject</label>
<input
type="text"
value={form.subject}
onChange={e => setForm({...form, subject: e.target.value})}
className={`${fieldClass} font-mono`}
placeholder="Subject"
/>
</div>
)}
<div>
<div className="flex items-center justify-between gap-3 mb-1.5">
<span className="text-[11px] font-semibold text-muted-foreground uppercase">Body</span>
<div className="flex items-center gap-2 shrink-0">
<button type="button" onClick={loadDefaultTemplate} className={secondaryButton}>
<LayoutTemplate className="w-3.5 h-3.5" /> Load standard
</button>
<button type="button" onClick={handlePreview} className={secondaryButton}>
<Eye className="w-3.5 h-3.5" /> Preview
</button>
</div>
</div>
{form.channel === 'EMAIL' ? (
<div className="crm-radius-control overflow-hidden border border-border bg-card [&_.ql-toolbar]:bg-muted/40 [&_.ql-toolbar]:border-border [&_.ql-container]:border-border [&_.ql-container]:border-t-0 [&_.ql-container]:min-h-[200px] [&_.ql-editor]:min-h-[200px] [&_.ql-editor]:text-[13px]">
<ReactQuill
theme="snow"
value={form.body_content}
onChange={(content) => 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']
]
}}
/>
</div>
) : (
<textarea
required
value={form.body_content}
onChange={e => setForm({...form, body_content: e.target.value})}
rows={10}
className={`${areaClass} font-mono`}
placeholder="Message"
/>
)}
</div>
</form>
<div className="min-w-0 h-full max-h-[70vh] lg:max-h-full overflow-y-auto border border-border crm-radius-control bg-muted/40 p-4 space-y-3">
<div>
<h3 className="text-[11px] font-semibold text-muted-foreground uppercase">Variables</h3>
{selectedEvent?.description && (
<p className="text-[12px] text-muted-foreground mt-1">{selectedEvent.description}</p>
)}
</div>
{selectedEvent ? (
<div className="space-y-2">
{selectedEvent.variables.map(v => (
<div key={v.name} className="bg-card border border-border crm-radius-control p-3">
<p className="font-mono text-[13px] font-semibold text-primary">{`{{ ${v.name} }}`}</p>
{v.description && <p className="text-[12px] text-muted-foreground mt-1">{v.description}</p>}
{v.example && (
<p className="text-[12px] text-muted-foreground mt-1 break-all">
Example: <span className="font-mono text-foreground">{v.example}</span>
</p>
)}
</div>
))}
</div>
) : (
<p className="py-8 text-center text-[13px] text-muted-foreground">Select an event to view variables</p>
)}
{previewObj && (
<div className="pt-3 border-t border-border space-y-3">
<h3 className="text-[11px] font-semibold text-muted-foreground uppercase flex items-center gap-1.5">
<CheckCircle2 className="w-3.5 h-3.5 text-success" /> Preview
</h3>
{form.channel === 'EMAIL' && (
<div className="border border-border crm-radius-control overflow-hidden bg-card">
<div className="px-3 py-2 border-b border-border text-[11px] font-semibold text-muted-foreground uppercase">Subject</div>
<div className="px-3 py-2 text-[13px] font-mono text-foreground">{previewObj.subject || '—'}</div>
</div>
)}
<div className="border border-border crm-radius-control overflow-hidden bg-card">
<div className="px-3 py-2 border-b border-border text-[11px] font-semibold text-muted-foreground uppercase">Body</div>
{form.channel === 'EMAIL' ? (
<iframe
srcDoc={previewObj.body}
className="w-full h-[280px] border-none bg-white"
title="Email Preview"
/>
) : (
<pre className="p-3 text-[13px] whitespace-pre-wrap font-sans text-foreground">{previewObj.body}</pre>
)}
</div>
</div>
)}
</div>
</div>
<div className="border-t border-border px-4 py-3 flex flex-wrap items-center justify-between gap-3 shrink-0">
<label htmlFor="is_active" className="inline-flex items-center gap-2 text-[13px] font-medium text-foreground cursor-pointer">
<input
type="checkbox"
id="is_active"
checked={form.is_active}
onChange={e => setForm({...form, is_active: e.target.checked})}
className="rounded border-border text-primary focus:ring-primary"
/>
Active template
</label>
<div className="flex items-center gap-2">
<button type="button" onClick={() => setIsModalOpen(false)} className={secondaryButton}>
Cancel
</button>
<button type="submit" form="notification-template-form" className={primaryButton}>
{editingTemplate ? 'Update template' : 'Create template'}
</button>
</div>
</div>
</div>
</div>
)}
</div>
);
}