'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([]); 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([]); 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 (
{/* Header */}

Notifications Configuration

Manage WhatsApp API gateway and automated internal notification rules

{/* Tabs */}
{activeTab === 'gateway' && ( <> {/* Health + Status Cards */}
{/* Gateway Health */}
Gateway Health
{loading ? (
Checking…
) : health ? (
{health.status === 'ok' ? 'Healthy' : 'Unhealthy'}

Version: {health.version}

Port: 8088

) : (
Unreachable
)}
{/* WhatsApp Session Status */}
WhatsApp Session
{loading ? (
Loading…
) : primarySession ? (
{isConnected ? ( Connected ) : ( {primarySession.status} )}
{primarySession.pushName && (

{primarySession.pushName}

)} {primarySession.phone && (

{primarySession.phone}

)}

Session: {primarySession.name}

) : (
Not Connected

No sessions found. OpenWA gateway may be offline.

)}
{/* Engine Info */}
Engine

Baileys

Multi-device WhatsApp Web API

DB: SQLite

{primarySession?.connectedAt && (

Since {new Date(primarySession.connectedAt).toLocaleString()}

)}
{/* Sessions Table */} {sessions.length > 0 && (

Active Sessions ({sessions.length})

{sessions.map((sess) => ( ))}
Name Status Phone Push Name Last Active
{sess.name} {sess.status} {sess.phone || '—'} {sess.pushName || '—'} {sess.lastActive ? new Date(sess.lastActive).toLocaleString() : '—'}
)} {/* Send Test Message */}

Send WhatsApp Message {!isConnected && ( No active session )}

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" />

Enter full number with country code (no + or spaces)

{primarySession ? `${primarySession.name} (${primarySession.phone || 'no phone'})` : 'No session available'}