ifixkart-admin/app/(admin)/notifications-gateway/page.tsx

468 lines
21 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 {
RefreshCw,
Send,
Loader2,
Phone,
User,
Plus,
Trash2,
} from 'lucide-react';
import { toast } from 'sonner';
import { CustomSelect } from '@/components/ui/CustomSelect';
const field =
'w-full h-9 px-3 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 disabled:opacity-50';
const shell =
'crm-radius-section border border-border bg-card shadow-[0_1px_3px_rgba(16,24,40,0.06)] min-w-0';
const EVENT_TYPES = [
{ value: 'ORDER_STATUS_CHANGED', label: 'Order status changed' },
{ value: 'NEW_ORDER_ALERT', label: 'New order' },
{ value: 'SERVICE_BOOKED_INTERNAL', label: 'Service booked' },
{ value: 'SERVICE_STATUS_CHANGED', label: 'Service status changed' },
{ value: 'INVENTORY_LOW_STOCK', label: 'Low stock' },
{ value: 'REFUND_TRIGGERED', label: 'Refund' },
{ value: 'END_OF_DAY_REPORT', label: 'End of day report' },
{ value: 'REPAIR_SLA_BREACH', label: 'Repair SLA breach' },
];
function eventLabel(value: string) {
return EVENT_TYPES.find((event) => event.value === value)?.label || value.replaceAll('_', ' ').toLowerCase();
}
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}`);
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="flex flex-col gap-5 min-w-0">
<div className="flex flex-wrap items-center justify-between gap-3">
<h1 className="text-lg font-semibold text-foreground">WhatsApp & Notification Gateway</h1>
<button
type="button"
onClick={activeTab === 'gateway' ? loadGatewayData : loadRulesData}
disabled={activeTab === 'gateway' ? loading : loadingRules}
className="w-9 h-9 crm-radius-control border border-border bg-card text-muted-foreground hover:text-foreground hover:bg-muted flex items-center justify-center cursor-pointer disabled:opacity-50"
title="Reload"
>
<RefreshCw className={`w-3.5 h-3.5 ${(activeTab === 'gateway' ? loading : loadingRules) ? 'animate-spin' : ''}`} />
</button>
</div>
<div className="flex flex-wrap items-center gap-2">
<button
type="button"
onClick={() => setActiveTab('gateway')}
className={`inline-flex items-center h-9 px-3 crm-radius-control text-[13px] font-semibold cursor-pointer ${
activeTab === 'gateway' ? 'bg-primary text-white' : 'border border-border bg-card text-foreground hover:bg-muted'
}`}
>
Gateway
</button>
<button
type="button"
onClick={() => setActiveTab('rules')}
className={`inline-flex items-center h-9 px-3 crm-radius-control text-[13px] font-semibold cursor-pointer ${
activeTab === 'rules' ? 'bg-primary text-white' : 'border border-border bg-card text-foreground hover:bg-muted'
}`}
>
Rules
</button>
</div>
{activeTab === 'gateway' && (
<>
{/* Health + Status Cards */}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className={`${shell} p-4 space-y-2`}>
<p className="text-[11px] font-semibold text-muted-foreground uppercase">Health</p>
{loading ? (
<p className="text-[13px] text-muted-foreground">Loading</p>
) : health ? (
<div className="space-y-1">
<p className={`text-[13px] font-semibold ${health.status === 'ok' ? 'text-success' : 'text-destructive'}`}>
{health.status === 'ok' ? 'Healthy' : 'Unhealthy'}
</p>
{health.version && <p className="text-[12px] text-muted-foreground">Version {health.version}</p>}
</div>
) : (
<p className="text-[13px] text-destructive">Unreachable</p>
)}
</div>
<div className={`${shell} p-4 space-y-2`}>
<p className="text-[11px] font-semibold text-muted-foreground uppercase">WhatsApp</p>
{loading ? (
<p className="text-[13px] text-muted-foreground">Loading</p>
) : primarySession ? (
<div className="space-y-1 text-[13px]">
<p className={`font-semibold ${isConnected ? 'text-success' : 'text-warning'}`}>
{isConnected ? 'Connected' : primarySession.status}
</p>
{primarySession.pushName && (
<p className="text-[12px] text-muted-foreground flex items-center gap-1">
<User className="w-3 h-3" /> {primarySession.pushName}
</p>
)}
{primarySession.phone && (
<p className="text-[12px] text-muted-foreground flex items-center gap-1">
<Phone className="w-3 h-3" /> {primarySession.phone}
</p>
)}
<p className="text-[12px] text-muted-foreground">{primarySession.name}</p>
{primarySession.connectedAt && (
<p className="text-[12px] text-muted-foreground">
Since {new Date(primarySession.connectedAt).toLocaleString()}
</p>
)}
</div>
) : (
<p className="text-[13px] text-muted-foreground">No sessions</p>
)}
</div>
</div>
{/* Sessions Table */}
{sessions.length > 0 && (
<div className={`${shell} overflow-hidden`}>
<div className="px-4 py-3 border-b border-border flex items-center gap-2">
<h2 className="text-[13px] font-semibold text-foreground">Sessions</h2>
<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">
{sessions.length}
</span>
</div>
<div className="overflow-x-auto">
<table className="crm-data-table min-w-[720px]">
<thead>
<tr className="border-b border-border">
<th className="text-left font-medium text-muted-foreground px-4 py-2.5">Name</th>
<th className="text-left font-medium text-muted-foreground px-4 py-2.5">Status</th>
<th className="text-left font-medium text-muted-foreground px-4 py-2.5">Phone</th>
<th className="text-left font-medium text-muted-foreground px-4 py-2.5">Name on WhatsApp</th>
<th className="text-left font-medium text-muted-foreground px-4 py-2.5">Last active</th>
</tr>
</thead>
<tbody>
{sessions.map((sess) => (
<tr key={sess.id} className="border-b border-border last:border-0">
<td className="px-4 py-3 font-semibold text-foreground">{sess.name}</td>
<td className="px-4 py-3">
<span className={`inline-flex items-center px-2.5 py-1 crm-radius-badge text-[11px] font-semibold ${
sess.status === 'ready'
? 'bg-success/15 text-success'
: sess.status === 'qr'
? 'bg-warning/15 text-warning'
: 'bg-destructive/10 text-destructive'
}`}>
{sess.status === 'ready' ? 'Connected' : sess.status}
</span>
</td>
<td className="px-4 py-3 text-muted-foreground">{sess.phone || 'โ€”'}</td>
<td className="px-4 py-3 text-muted-foreground">{sess.pushName || 'โ€”'}</td>
<td className="px-4 py-3 text-muted-foreground">
{sess.lastActive ? new Date(sess.lastActive).toLocaleString() : 'โ€”'}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
<div className={`${shell} p-5`}>
<div className="flex items-center gap-2 mb-4">
<h2 className="text-[13px] font-semibold text-foreground">Send message</h2>
{!isConnected && (
<span className="inline-flex items-center px-2 py-0.5 crm-radius-badge text-[11px] font-semibold bg-warning/15 text-warning">
No active session
</span>
)}
</div>
<form onSubmit={handleSendMessage} className="space-y-3">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<label className="block">
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">Phone</span>
<input
type="text"
value={recipient}
onChange={(e) => setRecipient(e.target.value)}
placeholder="Country code and number"
className={field}
/>
</label>
<label className="block">
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">Session</span>
<div className="h-9 px-3 border border-border crm-radius-control text-[13px] text-muted-foreground flex items-center">
{primarySession
? `${primarySession.name}${primarySession.phone ? ` ยท ${primarySession.phone}` : ''}`
: 'No session'}
</div>
</label>
</div>
<label className="block">
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">Message</span>
<textarea
value={message}
onChange={(e) => setMessage(e.target.value)}
rows={3}
className="w-full px-3 py-2 bg-card border border-border crm-radius-control text-[13px] text-foreground focus:outline-none focus:border-primary resize-none"
/>
</label>
<div className="flex items-center gap-2 flex-wrap">
<button
type="submit"
disabled={sending || !isConnected || !recipient.trim() || !message.trim()}
className={primaryButton}
>
{sending ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Send className="w-3.5 h-3.5" />}
{sending ? 'Sending' : confirming ? 'Confirm send' : 'Send'}
</button>
{confirming && (
<button type="button" onClick={() => setConfirming(false)} className={secondaryButton}>
Cancel
</button>
)}
</div>
</form>
</div>
</>
)}
{activeTab === 'rules' && (
<div className="space-y-4">
<div className="flex items-center justify-end">
<button type="button" onClick={() => setShowAddForm(!showAddForm)} className={primaryButton}>
<Plus className="w-3.5 h-3.5" />
New rule
</button>
</div>
{showAddForm && (
<form onSubmit={handleCreateRule} className={`${shell} p-4 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 items-end`}>
<label className="block">
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">Role</span>
<CustomSelect
value={newRule.role_name}
onChange={(value) => setNewRule({ ...newRule, role_name: value })}
aria-label="Role"
placeholder="Role"
options={roles.map((role) => ({ value: role.role_name, label: role.role_name }))}
/>
</label>
<label className="block">
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">Event</span>
<CustomSelect
value={newRule.event_type}
onChange={(value) => setNewRule({ ...newRule, event_type: value })}
aria-label="Event"
options={EVENT_TYPES.map((event) => ({ value: event.value, label: event.label }))}
/>
</label>
<div className="flex items-center gap-4 h-9">
<label className="flex items-center gap-2 text-[13px] text-foreground cursor-pointer">
<input type="checkbox" checked={newRule.channel_email} onChange={(e) => setNewRule({ ...newRule, channel_email: e.target.checked })} className="accent-primary cursor-pointer" />
Email
</label>
<label className="flex items-center gap-2 text-[13px] text-foreground cursor-pointer">
<input type="checkbox" checked={newRule.channel_whatsapp} onChange={(e) => setNewRule({ ...newRule, channel_whatsapp: e.target.checked })} className="accent-primary cursor-pointer" />
WhatsApp
</label>
</div>
<button type="submit" className={primaryButton}>Save rule</button>
</form>
)}
<div className={`${shell} overflow-x-auto`}>
<table className="crm-data-table min-w-[720px]">
<thead>
<tr className="border-b border-border">
<th className="text-left font-medium text-muted-foreground px-4 py-2.5">Role</th>
<th className="text-left font-medium text-muted-foreground px-4 py-2.5">Event</th>
<th className="text-center font-medium text-muted-foreground px-4 py-2.5">Email</th>
<th className="text-center font-medium text-muted-foreground px-4 py-2.5">WhatsApp</th>
<th className="text-right font-medium text-muted-foreground px-4 py-2.5">Action</th>
</tr>
</thead>
<tbody>
{loadingRules ? (
<tr>
<td colSpan={5} className="px-4 py-16 text-center text-[13px] text-muted-foreground">Loading rules</td>
</tr>
) : rules.length === 0 ? (
<tr>
<td colSpan={5} className="px-4 py-16 text-center text-[13px] text-muted-foreground">No rules</td>
</tr>
) : (
rules.map((rule) => (
<tr key={rule.setting_id} className="border-b border-border last:border-0">
<td className="px-4 py-3 font-semibold text-foreground">{rule.role_name}</td>
<td className="px-4 py-3 text-muted-foreground">{eventLabel(rule.event_type)}</td>
<td className="px-4 py-3 text-center">
<button type="button" onClick={() => handleToggleChannel(rule.setting_id, 'email', rule.channel_email)} className={`px-2.5 py-1 crm-radius-badge text-[11px] font-semibold cursor-pointer ${rule.channel_email ? 'bg-success/15 text-success' : 'bg-muted text-muted-foreground'}`}>
{rule.channel_email ? 'On' : 'Off'}
</button>
</td>
<td className="px-4 py-3 text-center">
<button type="button" onClick={() => handleToggleChannel(rule.setting_id, 'whatsapp', rule.channel_whatsapp)} className={`px-2.5 py-1 crm-radius-badge text-[11px] font-semibold cursor-pointer ${rule.channel_whatsapp ? 'bg-success/15 text-success' : 'bg-muted text-muted-foreground'}`}>
{rule.channel_whatsapp ? 'On' : 'Off'}
</button>
</td>
<td className="px-4 py-3 text-right">
<button type="button" onClick={() => handleDeleteRule(rule.setting_id)} className="w-8 h-8 inline-flex items-center justify-center crm-radius-control text-muted-foreground hover:text-foreground hover:bg-muted cursor-pointer" aria-label="Delete rule">
<Trash2 className="w-3.5 h-3.5" />
</button>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
)}
</div>
);
}