ifixkart-admin/app/(admin)/notification-templates/page.tsx
adithiyan b5837073e7 feat: add warranties, refunds, notification templates, user POS analytics, credit & delivery services
New pages:
- app/(admin)/warranties/ — full warranty management with claims
- app/(admin)/refunds/ — refund management
- app/(admin)/notification-templates/ — email/SMS template editor
- app/(admin)/user-pos-analytics/ — per-user POS analytics

New components:
- components/quotations/ — quotation components
- components/ui/PartNumbersModal.tsx — part numbers selection

New services:
- creditService.ts, deliverySettingsService.ts
- notificationTemplateService.ts, roleNotificationSettingsService.ts

Updated:
- Sidebar navigation, dashboard, orders, POS sessions, products
- Bulk quotations, CRM leads/quotations, notifications gateway
- settings, service invoices, quotes, technician, users pages
- adminService, billingFinanceService, catalogService, client
- inventoryPosService, notificationGatewayService, openwaService, userService
- Removed pos-sync page (merged into POS sessions)
2026-10-13 22:05:55 +05:30

423 lines
19 KiB
TypeScript

'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<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);
return (
<div className="p-6 space-y-6 max-w-6xl mx-auto">
{/* Header */}
<div className="flex items-center justify-between flex-wrap gap-4">
<div>
<h1 className="text-2xl font-bold tracking-tight text-foreground flex items-center gap-2">
<LayoutTemplate className="w-6 h-6 text-primary" />
Notification Templates
</h1>
<p className="text-sm text-muted-foreground mt-0.5">
Manage Jinja2 templates for email and WhatsApp notifications
</p>
</div>
<button
onClick={handleOpenCreate}
className="flex items-center gap-2 bg-primary text-primary-foreground px-4 py-2 rounded-lg text-sm font-semibold hover:bg-primary/90 transition-colors"
>
<Plus className="w-4 h-4" /> Create Template
</button>
</div>
{/* Table */}
<div className="bg-card border border-border rounded-xl overflow-hidden shadow-xs">
<table className="w-full text-sm text-left">
<thead className="bg-muted/50 border-b border-border">
<tr>
<th className="px-4 py-3 font-semibold text-muted-foreground">Template Name</th>
<th className="px-4 py-3 font-semibold text-muted-foreground">Event Key</th>
<th className="px-4 py-3 font-semibold text-muted-foreground">Channel</th>
<th className="px-4 py-3 font-semibold text-muted-foreground text-center">Variables</th>
<th className="px-4 py-3 font-semibold text-muted-foreground text-center">Status</th>
<th className="px-4 py-3 font-semibold text-muted-foreground text-right">Actions</th>
</tr>
</thead>
<tbody className="divide-y divide-border">
{loading ? (
<tr><td colSpan={6} className="px-4 py-8 text-center text-muted-foreground">Loading...</td></tr>
) : templates.length === 0 ? (
<tr><td colSpan={6} className="px-4 py-8 text-center text-muted-foreground">No templates found</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 rounded-full text-xs font-semibold ${
tpl.channel === 'EMAIL' ? 'bg-blue-500/10 text-blue-600' : 'bg-green-500/10 text-green-600'
}`}>
{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="bg-muted px-2 py-1 rounded text-xs text-muted-foreground font-mono">
{tpl.variables?.length || 0} vars
</span>
</td>
<td className="px-4 py-3 text-center">
<button onClick={() => handleToggle(tpl.template_id, tpl.is_active)} className={`px-2 py-1 rounded-full text-xs font-semibold uppercase ${
tpl.is_active ? 'bg-emerald-500/10 text-emerald-600' : '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>
{/* Modal */}
{isModalOpen && (
<div className="fixed inset-0 z-50 bg-background/80 backdrop-blur-xs flex items-center justify-center p-4">
<div className="bg-card border border-border rounded-xl shadow-lg w-full max-w-4xl max-h-[90vh] overflow-y-auto flex flex-col">
<div className="sticky top-0 bg-card border-b border-border p-4 flex items-center justify-between z-10">
<h2 className="text-lg font-bold">
{editingTemplate ? 'Edit Template' : 'Create New Template'}
</h2>
<button onClick={() => setIsModalOpen(false)} className="p-1 hover:bg-muted rounded-full">
<X className="w-5 h-5" />
</button>
</div>
<div className="p-4 grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* Form Side */}
<form onSubmit={handleSubmit} className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-xs font-semibold mb-1">Template Name</label>
<input
type="text"
required
value={form.name}
onChange={e => 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"
/>
</div>
<div>
<label className="block text-xs font-semibold mb-1">Channel</label>
<select
value={form.channel}
onChange={e => setForm({...form, channel: e.target.value})}
disabled={!!editingTemplate}
className="w-full border border-border rounded-md px-3 py-2 text-sm bg-background disabled:opacity-50"
>
<option value="EMAIL">Email</option>
<option value="WHATSAPP">WhatsApp</option>
</select>
</div>
</div>
<div>
<label className="block text-xs font-semibold mb-1">Event Key</label>
<select
value={form.event_key}
onChange={e => setForm({...form, event_key: e.target.value})}
disabled={!!editingTemplate}
className="w-full border border-border rounded-md px-3 py-2 text-sm bg-background disabled:opacity-50"
>
<option value="">Select Event...</option>
{events.map(ev => (
<option key={ev.event_key} value={ev.event_key}>{ev.event_key}</option>
))}
</select>
</div>
{form.channel === 'EMAIL' && (
<div>
<label className="block text-xs font-semibold mb-1">Subject (Jinja2 Supported)</label>
<input
type="text"
value={form.subject}
onChange={e => 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"
/>
</div>
)}
<div>
<div className="flex flex-col sm:flex-row sm:items-center justify-between mb-2 gap-2">
<label className="block text-xs font-semibold">Body Content (Jinja2 Supported)</label>
<div className="flex items-center gap-3">
<button
type="button"
onClick={loadDefaultTemplate}
className="text-xs text-emerald-600 bg-emerald-500/10 px-2 py-1.5 rounded hover:bg-emerald-500/20 transition-colors flex items-center gap-1 font-semibold"
>
<LayoutTemplate className="w-3 h-3" /> Load Standard Design
</button>
<button
type="button"
onClick={handlePreview}
className="text-xs text-primary bg-primary/10 px-2 py-1.5 rounded hover:bg-primary/20 transition-colors flex items-center gap-1 font-semibold"
>
<Eye className="w-3 h-3" /> Preview Render
</button>
</div>
</div>
{form.channel === 'EMAIL' ? (
<div className="bg-background rounded-md mb-2 overflow-hidden border border-border [&_.ql-toolbar]:bg-muted/50 [&_.ql-container]:min-h-[250px] [&_.ql-editor]:min-h-[250px] [&_.ql-editor]:text-sm [&_.ql-toolbar]:border-border [&_.ql-container]:border-border [&_.ql-container]:border-t-0">
<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={8}
className="w-full border border-border rounded-md px-3 py-2 text-sm bg-background font-mono"
placeholder="Hi {{ customer_name }},&#10;&#10;Your order..."
/>
)}
</div>
<div className="flex items-center gap-2">
<input
type="checkbox"
id="is_active"
checked={form.is_active}
onChange={e => setForm({...form, is_active: e.target.checked})}
className="rounded border-border"
/>
<label htmlFor="is_active" className="text-sm font-semibold">Active Template</label>
</div>
<div className="pt-2">
<button type="submit" className="w-full bg-primary text-primary-foreground py-2 rounded-lg font-semibold hover:bg-primary/90 transition-colors">
{editingTemplate ? 'Update Template' : 'Create Template'}
</button>
</div>
</form>
{/* Info Side */}
<div className="bg-muted/30 p-4 rounded-xl space-y-4 border border-border">
{selectedEvent ? (
<>
<div>
<h3 className="font-bold text-sm text-foreground">Available Variables</h3>
<p className="text-xs text-muted-foreground mb-3">{selectedEvent.description}</p>
<div className="space-y-2">
{selectedEvent.variables.map(v => (
<div key={v.name} className="bg-background border border-border rounded p-2 text-xs">
<span className="font-mono font-bold text-primary">{`{{ ${v.name} }}`}</span>
<p className="text-muted-foreground mt-1">{v.description}</p>
<p className="text-muted-foreground mt-1">Example: <span className="font-mono text-foreground">{v.example}</span></p>
</div>
))}
</div>
</div>
</>
) : (
<div className="text-center py-8 text-muted-foreground text-sm">
Select an event to view available variables.
</div>
)}
{previewObj && (
<div className="mt-4 pt-4 border-t border-border">
<h3 className="font-bold text-sm text-foreground mb-3 flex items-center gap-2">
<CheckCircle2 className="w-4 h-4 text-emerald-500" /> Preview Result
</h3>
{form.channel === 'EMAIL' && (
<div className="mb-3 border border-border rounded-md overflow-hidden">
<div className="bg-muted px-3 py-1.5 border-b border-border text-xs font-semibold text-muted-foreground">Subject</div>
<div className="p-3 bg-background text-sm font-mono">{previewObj.subject}</div>
</div>
)}
<div className="border border-border rounded-md overflow-hidden">
<div className="bg-muted px-3 py-1.5 border-b border-border text-xs font-semibold text-muted-foreground">Body</div>
{form.channel === 'EMAIL' ? (
<div className="bg-white">
<iframe
srcDoc={previewObj.body}
className="w-full h-[600px] border-none"
title="Email Preview"
/>
</div>
) : (
<pre className="p-3 bg-background text-sm whitespace-pre-wrap font-sans">{previewObj.body}</pre>
)}
</div>
</div>
)}
</div>
</div>
</div>
</div>
)}
</div>
);
}