ifixkart-admin/app/(admin)/notifications-gateway/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

564 lines
26 KiB
TypeScript

'use client';
import { useEffect, useState, useCallback } from 'react';
import { openwaService, type OWASession } from '@/services/api/openwaService';
import { roleNotificationSettingsService, type RoleNotificationSetting } from '@/services/api/roleNotificationSettingsService';
import { rolePermissionService } from '@/services/api/rolePermissionService';
import {
QrCode,
Wifi,
WifiOff,
RefreshCw,
Send,
MessageSquare,
Loader2,
CheckCircle2,
AlertTriangle,
Phone,
Activity,
User,
Clock,
Shield,
Settings,
Plus,
Trash2,
} from 'lucide-react';
import { toast } from 'sonner';
export default function NotificationsGatewayPage() {
const [activeTab, setActiveTab] = useState<'gateway' | 'rules'>('gateway');
// Gateway State
const [sessions, setSessions] = useState<OWASession[]>([]);
const [health, setHealth] = useState<{ status: string; version: string; timestamp: string } | null>(null);
const [loading, setLoading] = useState(true);
// Send message form
const [recipient, setRecipient] = useState('');
const [message, setMessage] = useState('');
const [sending, setSending] = useState(false);
const [confirming, setConfirming] = useState(false);
// Rules State
const [rules, setRules] = useState<RoleNotificationSetting[]>([]);
const [roles, setRoles] = useState<{ role_id: string; role_name: string }[]>([]);
const [loadingRules, setLoadingRules] = useState(false);
const [showAddForm, setShowAddForm] = useState(false);
const [newRule, setNewRule] = useState({ role_name: '', event_type: 'ORDER_STATUS_CHANGED', channel_email: true, channel_whatsapp: false });
const loadGatewayData = useCallback(async () => {
try {
setLoading(true);
const [sessionsRes, healthRes] = await Promise.all([
openwaService.getSessions().catch(() => [] as OWASession[]),
openwaService.getHealth().catch(() => null),
]);
setSessions(sessionsRes);
setHealth(healthRes);
} finally {
setLoading(false);
}
}, []);
const loadRulesData = useCallback(async () => {
try {
setLoadingRules(true);
const [rulesRes, rolesRes] = await Promise.all([
roleNotificationSettingsService.getSettings().catch(() => []),
rolePermissionService.getRoles().catch(() => [])
]);
setRules(rulesRes);
setRoles(rolesRes);
} catch (error) {
toast.error('Failed to load notification rules');
} finally {
setLoadingRules(false);
}
}, []);
useEffect(() => {
if (activeTab === 'gateway') {
loadGatewayData();
} else {
loadRulesData();
}
}, [activeTab, loadGatewayData, loadRulesData]);
const handleCreateRule = async (e: React.FormEvent) => {
e.preventDefault();
if (!newRule.role_name) return toast.error('Please select a role');
try {
await roleNotificationSettingsService.createSetting(newRule);
toast.success('Rule created');
setShowAddForm(false);
loadRulesData();
} catch (err: any) {
toast.error(err.message || 'Failed to create rule');
}
};
const handleToggleChannel = async (settingId: string, channel: 'email' | 'whatsapp', currentValue: boolean) => {
try {
await roleNotificationSettingsService.updateSetting(settingId, {
[channel === 'email' ? 'channel_email' : 'channel_whatsapp']: !currentValue
});
loadRulesData();
} catch (err: any) {
toast.error(err.message || 'Failed to update rule');
}
};
const handleDeleteRule = async (settingId: string) => {
if (!confirm('Are you sure you want to delete this rule?')) return;
try {
await roleNotificationSettingsService.deleteSetting(settingId);
toast.success('Rule deleted');
loadRulesData();
} catch (err: any) {
toast.error(err.message || 'Failed to delete rule');
}
};
const handleSendMessage = async (e: React.FormEvent) => {
e.preventDefault();
const readySession = sessions.find((s) => s.status === 'ready');
if (!readySession) {
toast.error('No active WhatsApp session. Please pair your device first.');
return;
}
if (!recipient.trim() || !message.trim()) {
toast.error('Please enter a recipient and message.');
return;
}
// First click: show confirmation
if (!confirming) {
setConfirming(true);
return;
}
// Second click: actually send
try {
setSending(true);
setConfirming(false);
const cleaned = recipient.replace(/\D/g, '');
const chatId = cleaned.endsWith('@c.us') ? cleaned : `${cleaned}@c.us`;
await openwaService.sendText(readySession.id, chatId, message);
toast.success(`Message sent to +${cleaned} via OpenWA!`);
setRecipient('');
setMessage('');
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : 'Failed to send message';
toast.error(msg);
} finally {
setSending(false);
}
};
const primarySession = sessions.find((s) => s.status === 'ready') || sessions[0] || null;
const isConnected = primarySession?.status === 'ready';
return (
<div className="p-6 space-y-6 max-w-5xl mx-auto">
{/* Header */}
<div className="flex flex-col gap-4">
<div className="flex items-center justify-between flex-wrap gap-3">
<div>
<h1 className="text-2xl font-bold tracking-tight text-foreground flex items-center gap-2">
<Shield className="w-6 h-6 text-primary" />
Notifications Configuration
</h1>
<p className="text-sm text-muted-foreground mt-0.5">
Manage WhatsApp API gateway and automated internal notification rules
</p>
</div>
<button
onClick={activeTab === 'gateway' ? loadGatewayData : loadRulesData}
disabled={activeTab === 'gateway' ? loading : loadingRules}
className="flex items-center gap-2 bg-card border border-border px-3 py-2 rounded-lg text-xs font-semibold hover:bg-muted transition-colors cursor-pointer disabled:opacity-50"
>
<RefreshCw className={`w-3.5 h-3.5 ${(activeTab === 'gateway' ? loading : loadingRules) ? 'animate-spin' : ''}`} />
Refresh
</button>
</div>
{/* Tabs */}
<div className="flex items-center gap-1 border-b border-border">
<button
onClick={() => setActiveTab('gateway')}
className={`px-4 py-2 text-sm font-semibold border-b-2 transition-colors ${
activeTab === 'gateway' ? 'border-primary text-primary' : 'border-transparent text-muted-foreground hover:text-foreground hover:border-muted-foreground/30'
}`}
>
OpenWA Gateway Settings
</button>
<button
onClick={() => setActiveTab('rules')}
className={`px-4 py-2 text-sm font-semibold border-b-2 transition-colors ${
activeTab === 'rules' ? 'border-primary text-primary' : 'border-transparent text-muted-foreground hover:text-foreground hover:border-muted-foreground/30'
}`}
>
Internal Notification Rules
</button>
</div>
</div>
{activeTab === 'gateway' && (
<>
{/* Health + Status Cards */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
{/* Gateway Health */}
<div className="bg-card border border-border rounded-xl p-4 space-y-2">
<div className="flex items-center gap-2 text-xs font-bold text-muted-foreground uppercase">
<Activity className="w-3.5 h-3.5" /> Gateway Health
</div>
{loading ? (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="w-4 h-4 animate-spin" /> Checking…
</div>
) : health ? (
<div className="space-y-1">
<div className="flex items-center gap-2">
<span className={`w-2.5 h-2.5 rounded-full ${health.status === 'ok' ? 'bg-emerald-500' : 'bg-red-500'}`} />
<span className={`text-sm font-bold ${health.status === 'ok' ? 'text-emerald-600' : 'text-red-600'}`}>
{health.status === 'ok' ? 'Healthy' : 'Unhealthy'}
</span>
</div>
<p className="text-xs text-muted-foreground">Version: {health.version}</p>
<p className="text-xs text-muted-foreground">Port: 8088</p>
</div>
) : (
<div className="flex items-center gap-2 text-sm text-red-500">
<WifiOff className="w-4 h-4" /> Unreachable
</div>
)}
</div>
{/* WhatsApp Session Status */}
<div className="bg-card border border-border rounded-xl p-4 space-y-2">
<div className="flex items-center gap-2 text-xs font-bold text-muted-foreground uppercase">
<MessageSquare className="w-3.5 h-3.5" /> WhatsApp Session
</div>
{loading ? (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="w-4 h-4 animate-spin" /> Loading…
</div>
) : primarySession ? (
<div className="space-y-1">
<div className="flex items-center gap-2">
{isConnected ? (
<span className="flex items-center gap-1.5 text-emerald-600 font-bold text-sm">
<span className="w-2.5 h-2.5 rounded-full bg-emerald-500 animate-ping" />
Connected
</span>
) : (
<span className="flex items-center gap-1.5 text-amber-600 font-bold text-sm">
<span className="w-2.5 h-2.5 rounded-full bg-amber-500" />
{primarySession.status}
</span>
)}
</div>
{primarySession.pushName && (
<p className="text-xs text-muted-foreground flex items-center gap-1">
<User className="w-3 h-3" /> {primarySession.pushName}
</p>
)}
{primarySession.phone && (
<p className="text-xs text-muted-foreground flex items-center gap-1">
<Phone className="w-3 h-3" /> {primarySession.phone}
</p>
)}
<p className="text-xs text-muted-foreground">Session: {primarySession.name}</p>
</div>
) : (
<div className="space-y-2">
<div className="flex items-center gap-2 text-sm text-amber-600">
<WifiOff className="w-4 h-4" /> Not Connected
</div>
<p className="text-xs text-muted-foreground">No sessions found. OpenWA gateway may be offline.</p>
</div>
)}
</div>
{/* Engine Info */}
<div className="bg-card border border-border rounded-xl p-4 space-y-2">
<div className="flex items-center gap-2 text-xs font-bold text-muted-foreground uppercase">
<Shield className="w-3.5 h-3.5" /> Engine
</div>
<div className="space-y-1">
<p className="text-sm font-bold text-foreground">Baileys</p>
<p className="text-xs text-muted-foreground">Multi-device WhatsApp Web API</p>
<p className="text-xs text-muted-foreground">DB: SQLite</p>
{primarySession?.connectedAt && (
<p className="text-xs text-muted-foreground flex items-center gap-1">
<Clock className="w-3 h-3" />
Since {new Date(primarySession.connectedAt).toLocaleString()}
</p>
)}
</div>
</div>
</div>
{/* Sessions Table */}
{sessions.length > 0 && (
<div className="bg-card border border-border rounded-xl overflow-hidden">
<div className="px-4 py-3 border-b border-border">
<h2 className="text-sm font-bold text-foreground">Active Sessions ({sessions.length})</h2>
</div>
<div className="overflow-x-auto">
<table className="w-full text-xs">
<thead className="bg-muted/40 border-b border-border">
<tr>
<th className="text-left px-4 py-2.5 text-muted-foreground font-bold uppercase text-[10px]">Name</th>
<th className="text-left px-4 py-2.5 text-muted-foreground font-bold uppercase text-[10px]">Status</th>
<th className="text-left px-4 py-2.5 text-muted-foreground font-bold uppercase text-[10px]">Phone</th>
<th className="text-left px-4 py-2.5 text-muted-foreground font-bold uppercase text-[10px]">Push Name</th>
<th className="text-left px-4 py-2.5 text-muted-foreground font-bold uppercase text-[10px]">Last Active</th>
</tr>
</thead>
<tbody className="divide-y divide-border">
{sessions.map((sess) => (
<tr key={sess.id} className="hover:bg-muted/20 transition-colors">
<td className="px-4 py-2.5 font-semibold text-foreground">{sess.name}</td>
<td className="px-4 py-2.5">
<span className={`px-2 py-0.5 rounded-full font-bold text-[10px] uppercase ${
sess.status === 'ready'
? 'bg-emerald-500/10 text-emerald-600'
: sess.status === 'qr'
? 'bg-amber-500/10 text-amber-600'
: 'bg-red-500/10 text-red-600'
}`}>
{sess.status}
</span>
</td>
<td className="px-4 py-2.5 font-mono text-muted-foreground">{sess.phone || '—'}</td>
<td className="px-4 py-2.5 text-muted-foreground">{sess.pushName || '—'}</td>
<td className="px-4 py-2.5 text-muted-foreground">
{sess.lastActive ? new Date(sess.lastActive).toLocaleString() : '—'}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
{/* Send Test Message */}
<div className="bg-card border border-border rounded-xl p-5">
<h2 className="text-sm font-bold text-foreground flex items-center gap-2 mb-4">
<Send className="w-4 h-4 text-primary" />
Send WhatsApp Message
{!isConnected && (
<span className="text-[10px] text-amber-600 bg-amber-500/10 px-2 py-0.5 rounded-full font-bold">
No active session
</span>
)}
</h2>
<form onSubmit={handleSendMessage} className="space-y-3">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div>
<label className="block text-xs font-semibold text-muted-foreground mb-1">
Recipient Phone Number
</label>
<input
type="text"
value={recipient}
onChange={(e) => setRecipient(e.target.value)}
placeholder="e.g. 919876543210"
className="w-full bg-background border border-border rounded-lg px-3 py-2 text-xs text-foreground focus:outline-hidden focus:ring-1 focus:ring-primary/50 font-mono"
/>
<p className="text-[10px] text-muted-foreground mt-1">Enter full number with country code (no + or spaces)</p>
</div>
<div>
<label className="block text-xs font-semibold text-muted-foreground mb-1">
Session
</label>
<div className="w-full bg-muted border border-border rounded-lg px-3 py-2 text-xs text-muted-foreground">
{primarySession
? `${primarySession.name} (${primarySession.phone || 'no phone'})`
: 'No session available'}
</div>
</div>
</div>
<div>
<label className="block text-xs font-semibold text-muted-foreground mb-1">Message</label>
<textarea
value={message}
onChange={(e) => setMessage(e.target.value)}
rows={3}
placeholder="Type your WhatsApp message here..."
className="w-full bg-background border border-border rounded-lg px-3 py-2 text-xs text-foreground focus:outline-hidden focus:ring-1 focus:ring-primary/50 resize-none"
/>
</div>
<div className="flex items-center gap-2 flex-wrap">
<button
type="submit"
disabled={sending || !isConnected || !recipient.trim() || !message.trim()}
className={`inline-flex items-center gap-2 font-bold px-4 py-2 rounded-lg text-xs transition-all shadow-sm cursor-pointer disabled:opacity-50 ${
confirming
? 'bg-red-600 hover:bg-red-700 text-white ring-2 ring-red-400 ring-offset-2 ring-offset-background'
: 'bg-emerald-600 hover:bg-emerald-700 text-white'
}`}
>
{sending ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Send className="w-3.5 h-3.5" />}
{sending
? 'Sending…'
: confirming
? `⚠️ Confirm Send to +${recipient.replace(/\D/g, '')}?`
: 'Send via OpenWA'}
</button>
{confirming && (
<button
type="button"
onClick={() => setConfirming(false)}
className="px-3 py-2 rounded-lg border border-border text-xs font-semibold text-muted-foreground hover:bg-muted cursor-pointer"
>
Cancel
</button>
)}
</div>
</form>
</div>
{/* Info Panel */}
<div className="bg-muted/30 border border-border rounded-xl p-4 text-xs text-muted-foreground space-y-2">
<p className="font-bold text-foreground">About OpenWA Gateway</p>
<ul className="space-y-1 list-disc list-inside">
<li>Self-hosted WhatsApp Web gateway running on <strong>port 8088</strong></li>
<li>Powered by <strong>Baileys</strong> multi-device engine</li>
<li>Uses <strong>SQLite</strong> for session and message persistence</li>
<li>Sessions are stored in <code>/Backend/OpenWA/data/sessions/</code></li>
<li>Access the built-in OpenWA dashboard at <a href="http://localhost:8088" target="_blank" className="text-primary underline">http://localhost:8088</a></li>
</ul>
</div>
</>
)}
{activeTab === 'rules' && (
<div className="space-y-4">
<div className="flex items-center justify-between">
<h2 className="text-lg font-bold text-foreground flex items-center gap-2">
<Settings className="w-5 h-5 text-primary" />
Role Notification Rules
</h2>
<button
onClick={() => setShowAddForm(!showAddForm)}
className="flex items-center gap-2 bg-primary text-primary-foreground px-4 py-2 rounded-lg text-xs font-semibold hover:bg-primary/90 transition-colors"
>
<Plus className="w-4 h-4" /> Add Rule
</button>
</div>
{showAddForm && (
<form onSubmit={handleCreateRule} className="bg-muted/30 border border-border rounded-xl p-4 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 items-end">
<div>
<label className="block text-xs font-semibold text-muted-foreground mb-1">Target Role</label>
<select
value={newRule.role_name}
onChange={(e) => setNewRule({ ...newRule, role_name: e.target.value })}
className="w-full bg-background border border-border rounded-lg px-3 py-2 text-xs text-foreground focus:outline-hidden focus:ring-1 focus:ring-primary/50"
required
>
<option value="">Select Role...</option>
{roles.map(r => (
<option key={r.role_id} value={r.role_name}>{r.role_name}</option>
))}
</select>
</div>
<div>
<label className="block text-xs font-semibold text-muted-foreground mb-1">Trigger Event</label>
<select
value={newRule.event_type}
onChange={(e) => setNewRule({ ...newRule, event_type: e.target.value })}
className="w-full bg-background border border-border rounded-lg px-3 py-2 text-xs text-foreground focus:outline-hidden focus:ring-1 focus:ring-primary/50"
>
<option value="ORDER_STATUS_CHANGED">Order Status Changed</option>
<option value="NEW_ORDER_ALERT">New Order Alert</option>
<option value="SERVICE_BOOKED_INTERNAL">Service Booked Internal</option>
<option value="SERVICE_STATUS_CHANGED">Service Status Changed</option>
<option value="INVENTORY_LOW_STOCK">Inventory Low Stock</option>
<option value="REFUND_TRIGGERED">Refund Triggered</option>
<option value="END_OF_DAY_REPORT">End of Day Report</option>
<option value="REPAIR_SLA_BREACH">Repair SLA Breach</option>
</select>
</div>
<div className="flex items-center gap-4 py-2">
<label className="flex items-center gap-2 cursor-pointer">
<input type="checkbox" checked={newRule.channel_email} onChange={(e) => setNewRule({ ...newRule, channel_email: e.target.checked })} className="rounded border-border" />
<span className="text-xs font-semibold">Email</span>
</label>
<label className="flex items-center gap-2 cursor-pointer">
<input type="checkbox" checked={newRule.channel_whatsapp} onChange={(e) => setNewRule({ ...newRule, channel_whatsapp: e.target.checked })} className="rounded border-border" />
<span className="text-xs font-semibold">WhatsApp</span>
</label>
</div>
<div>
<button type="submit" className="w-full bg-primary text-primary-foreground px-4 py-2 rounded-lg text-xs font-semibold hover:bg-primary/90 transition-colors">
Save Rule
</button>
</div>
</form>
)}
<div className="bg-card border border-border rounded-xl overflow-hidden">
<table className="w-full text-xs text-left">
<thead className="bg-muted/40 border-b border-border">
<tr>
<th className="px-4 py-3 font-bold text-muted-foreground uppercase">Role</th>
<th className="px-4 py-3 font-bold text-muted-foreground uppercase">Event Type</th>
<th className="px-4 py-3 font-bold text-muted-foreground uppercase text-center">Email</th>
<th className="px-4 py-3 font-bold text-muted-foreground uppercase text-center">WhatsApp</th>
<th className="px-4 py-3 font-bold text-muted-foreground uppercase text-right">Actions</th>
</tr>
</thead>
<tbody className="divide-y divide-border">
{loadingRules ? (
<tr>
<td colSpan={5} className="px-4 py-8 text-center text-muted-foreground">
<Loader2 className="w-5 h-5 animate-spin mx-auto mb-2" />
Loading rules...
</td>
</tr>
) : rules.length === 0 ? (
<tr>
<td colSpan={5} className="px-4 py-8 text-center text-muted-foreground">
No notification rules found. Add one above.
</td>
</tr>
) : (
rules.map((rule) => (
<tr key={rule.setting_id} className="hover:bg-muted/20 transition-colors">
<td className="px-4 py-3 font-semibold text-foreground">{rule.role_name}</td>
<td className="px-4 py-3 font-mono text-muted-foreground">{rule.event_type}</td>
<td className="px-4 py-3 text-center">
<button onClick={() => handleToggleChannel(rule.setting_id, 'email', rule.channel_email)} className={`px-2 py-1 rounded text-[10px] font-bold uppercase transition-colors ${rule.channel_email ? 'bg-emerald-500/10 text-emerald-600' : 'bg-muted text-muted-foreground'}`}>
{rule.channel_email ? 'Enabled' : 'Disabled'}
</button>
</td>
<td className="px-4 py-3 text-center">
<button onClick={() => handleToggleChannel(rule.setting_id, 'whatsapp', rule.channel_whatsapp)} className={`px-2 py-1 rounded text-[10px] font-bold uppercase transition-colors ${rule.channel_whatsapp ? 'bg-emerald-500/10 text-emerald-600' : 'bg-muted text-muted-foreground'}`}>
{rule.channel_whatsapp ? 'Enabled' : 'Disabled'}
</button>
</td>
<td className="px-4 py-3 text-right">
<button onClick={() => handleDeleteRule(rule.setting_id)} className="text-red-500 hover:bg-red-50 p-1.5 rounded transition-colors" title="Delete Rule">
<Trash2 className="w-4 h-4" />
</button>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
)}
</div>
);
}