ifixkart-admin/app/(admin)/integrations/whatsapp/page.tsx

571 lines
26 KiB
TypeScript

'use client';
import React, { useState, useEffect, useRef } from 'react';
import { useSearchParams } from 'next/navigation';
import {
MessageSquare,
QrCode,
RefreshCw,
Send,
CheckCircle2,
AlertCircle,
ShieldCheck,
Server,
Lock,
ExternalLink,
Smartphone,
Layers,
Radio,
FileText
} from 'lucide-react';
import { toast } from 'sonner';
import { IntegrationsHeaderNav } from '@/components/integrations/IntegrationsHeaderNav';
import { integrationService } from '@/services/api/integrationService';
export default function WhatsAppIntegrationsPage() {
const searchParams = useSearchParams();
const initialTab = searchParams.get('tab') === 'wati' ? 'wati' : 'openwa';
const [activeSubTab, setActiveSubTab] = useState<'openwa' | 'wati'>(initialTab);
// -------------------------------------------------------------
// OpenWA State
// -------------------------------------------------------------
const [openwaStatus, setOpenwaStatus] = useState<any>({
status: 'LOADING',
qr_code: null,
phone: null,
push_name: null,
});
const [openwaLoading, setOpenwaLoading] = useState(true);
const [restarting, setRestarting] = useState(false);
const [testPhone, setTestPhone] = useState('');
const [testMessage, setTestMessage] = useState('Test verification message from iFixKart ERP WhatsApp Gateway');
const [sendingTest, setSendingTest] = useState(false);
const pollTimerRef = useRef<NodeJS.Timeout | null>(null);
// -------------------------------------------------------------
// WATI State
// -------------------------------------------------------------
const [watiCreds, setWatiCreds] = useState<any>({
api_endpoint: 'https://live-mt-server.wati.io',
api_token: '',
source: 'unconfigured',
is_locked_by_config: false,
});
const [watiLoading, setWatiLoading] = useState(true);
const [watiTesting, setWatiTesting] = useState(false);
const [watiSaving, setWatiSaving] = useState(false);
const [watiTemplates, setWatiTemplates] = useState<any[]>([]);
const [templatesLoading, setTemplatesLoading] = useState(false);
const [selectedTemplate, setSelectedTemplate] = useState('');
const [watiRecipientPhone, setWatiRecipientPhone] = useState('');
const [sendingWatiTemplate, setSendingWatiTemplate] = useState(false);
// Fetch OpenWA QR status
const fetchOpenWaStatus = async (showToast = false) => {
try {
const res = await integrationService.getWhatsappQr();
setOpenwaStatus(res);
if (showToast) {
toast.success(`OpenWA Gateway: ${res.status}`);
}
} catch (err: any) {
setOpenwaStatus({ status: 'OFFLINE', message: err.message || 'Cannot reach OpenWA service' });
} finally {
setOpenwaLoading(false);
}
};
// Poll QR code if in QR_READY or INITIALIZING
useEffect(() => {
if (activeSubTab === 'openwa') {
fetchOpenWaStatus();
if (pollTimerRef.current) clearInterval(pollTimerRef.current);
pollTimerRef.current = setInterval(() => {
fetchOpenWaStatus();
}, 4500);
} else {
if (pollTimerRef.current) clearInterval(pollTimerRef.current);
}
return () => {
if (pollTimerRef.current) clearInterval(pollTimerRef.current);
};
}, [activeSubTab]);
// Fetch WATI credentials and templates
const fetchWatiData = async () => {
setWatiLoading(true);
try {
const creds = await integrationService.getWatiCredentials();
setWatiCreds(creds);
if (creds.api_token) {
loadTemplates();
}
} catch (err: any) {
toast.error('Failed to load WATI configuration');
} finally {
setWatiLoading(false);
}
};
const loadTemplates = async () => {
setTemplatesLoading(true);
try {
const res = await integrationService.getWatiTemplates();
setWatiTemplates(res.templates || []);
} catch (err) {
console.warn('WATI templates error:', err);
} finally {
setTemplatesLoading(false);
}
};
useEffect(() => {
if (activeSubTab === 'wati') {
fetchWatiData();
}
}, [activeSubTab]);
// Restart OpenWA session
const handleRestartOpenWa = async () => {
setRestarting(true);
try {
await integrationService.restartWhatsappSession();
toast.info('Session restart initiated. Generating fresh QR code...');
setTimeout(() => fetchOpenWaStatus(), 2000);
} catch (err: any) {
toast.error(err.message || 'Failed to restart WhatsApp session');
} finally {
setRestarting(false);
}
};
// Send OpenWA Test Message
const handleSendOpenWaTest = async (e: React.FormEvent) => {
e.preventDefault();
if (!testPhone.trim()) {
toast.error('Please enter a valid phone number');
return;
}
setSendingTest(true);
try {
const res = await integrationService.sendWhatsappTest(testPhone.trim(), testMessage.trim());
if (res.status === 'SUCCESS') {
toast.success(`Message sent successfully to ${testPhone}!`);
} else {
toast.error(`Send failed: ${res.detail || JSON.stringify(res)}`);
}
} catch (err: any) {
toast.error(err.message || 'Failed to send WhatsApp message');
} finally {
setSendingTest(false);
}
};
// Test WATI Connection
const handleTestWati = async () => {
setWatiTesting(true);
try {
const res = await integrationService.testWatiConnection({
api_endpoint: watiCreds.api_endpoint,
api_token: watiCreds.api_token,
});
if (res.status === 'SUCCESS') {
toast.success(`Connected! ${res.templates_count || 0} approved templates discovered.`);
setWatiTemplates(res.templates || []);
} else {
toast.error(`Connection failed: ${res.detail || 'Invalid token or endpoint'}`);
}
} catch (err: any) {
toast.error(err.message || 'WATI test connection failed');
} finally {
setWatiTesting(false);
}
};
// Save WATI Credentials
const handleSaveWati = async (e: React.FormEvent) => {
e.preventDefault();
setWatiSaving(true);
try {
await integrationService.saveWatiCredentials({
api_endpoint: watiCreds.api_endpoint,
api_token: watiCreds.api_token,
});
toast.success('WATI credentials saved successfully');
loadTemplates();
} catch (err: any) {
toast.error(err.message || 'Failed to save WATI credentials');
} finally {
setWatiSaving(false);
}
};
// Send WATI template message
const handleSendWatiTemplate = async (e: React.FormEvent) => {
e.preventDefault();
if (!watiRecipientPhone.trim() || !selectedTemplate) {
toast.error('Select a template and enter a valid recipient phone number');
return;
}
setSendingWatiTemplate(true);
try {
const res = await integrationService.sendWatiTemplate({
phone: watiRecipientPhone.trim(),
template_name: selectedTemplate,
broadcast_name: `test_${Date.now()}`,
});
if (res.status === 'SUCCESS') {
toast.success('WATI template message dispatched successfully!');
} else {
toast.error(`Dispatch failed: ${res.detail || JSON.stringify(res)}`);
}
} catch (err: any) {
toast.error(err.message || 'Failed to send WATI template');
} finally {
setSendingWatiTemplate(false);
}
};
return (
<div className="p-6 max-w-7xl mx-auto space-y-6">
<IntegrationsHeaderNav activeTab="whatsapp" />
{/* Sub-Tabs: Internal OpenWA vs Customer WATI */}
<div className="flex border-b border-gray-200 dark:border-gray-800">
<button
onClick={() => setActiveSubTab('openwa')}
className={`pb-3 px-4 text-sm font-semibold border-b-2 flex items-center gap-2 transition ${
activeSubTab === 'openwa'
? 'border-emerald-600 text-emerald-600 dark:text-emerald-400'
: 'border-transparent text-gray-500 hover:text-gray-700 dark:text-gray-400'
}`}
>
<Smartphone className="w-4 h-4" />
Internal Staff Gateway (OpenWA Live QR)
</button>
<button
onClick={() => setActiveSubTab('wati')}
className={`pb-3 px-4 text-sm font-semibold border-b-2 flex items-center gap-2 transition ${
activeSubTab === 'wati'
? 'border-blue-600 text-blue-600 dark:text-blue-400'
: 'border-transparent text-gray-500 hover:text-gray-700 dark:text-gray-400'
}`}
>
<MessageSquare className="w-4 h-4" />
Customer Communication (WATI Cloud API)
</button>
</div>
{/* ========================================================================= */}
{/* TAB A: OPENWA (INTERNAL LIVE QR SCANNER) */}
{/* ========================================================================= */}
{activeSubTab === 'openwa' && (
<div className="space-y-6">
{/* Top Banner */}
<div className="p-4 rounded-xl bg-emerald-50 dark:bg-emerald-950/30 border border-emerald-200 dark:border-emerald-900/50 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
<div>
<h2 className="text-base font-semibold text-emerald-900 dark:text-emerald-100 flex items-center gap-2">
<Radio className="w-4 h-4 text-emerald-600 animate-pulse" />
Live Embedded WhatsApp QR Scanner
</h2>
<p className="text-xs text-emerald-700 dark:text-emerald-300 mt-0.5">
Connecting directly to local OpenWA microservice on port 8088. Scan using WhatsApp on your phone (Linked Devices).
</p>
</div>
<div className="flex items-center gap-2">
<button
onClick={() => fetchOpenWaStatus(true)}
disabled={openwaLoading}
className="px-3 py-1.5 text-xs font-medium rounded-lg bg-white dark:bg-gray-800 border border-emerald-200 dark:border-emerald-800 text-gray-700 dark:text-gray-200 hover:bg-emerald-50 transition flex items-center gap-1.5"
>
<RefreshCw className={`w-3.5 h-3.5 ${openwaLoading ? 'animate-spin' : ''}`} />
Refresh QR
</button>
<button
onClick={handleRestartOpenWa}
disabled={restarting}
className="px-3 py-1.5 text-xs font-medium rounded-lg bg-emerald-600 text-white hover:bg-emerald-700 transition flex items-center gap-1.5"
>
<RefreshCw className={`w-3.5 h-3.5 ${restarting ? 'animate-spin' : ''}`} />
Restart Session
</button>
</div>
</div>
<div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
{/* QR Scanner Card (Cols 1-7) */}
<div className="lg:col-span-7 rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-6 shadow-sm">
<h3 className="font-semibold text-gray-900 dark:text-white flex items-center gap-2 mb-4">
<QrCode className="w-5 h-5 text-emerald-600" />
Session Connection State
</h3>
{openwaLoading ? (
<div className="flex flex-col items-center justify-center p-12 space-y-4">
<div className="w-12 h-12 border-4 border-emerald-600 border-t-transparent rounded-full animate-spin" />
<p className="text-sm text-gray-500">Checking OpenWA gateway status...</p>
</div>
) : openwaStatus.status === 'CONNECTED' ? (
<div className="flex flex-col items-center justify-center p-8 border-2 border-dashed border-emerald-200 dark:border-emerald-800 rounded-xl bg-emerald-50/50 dark:bg-emerald-950/20 text-center space-y-3">
<div className="p-4 rounded-full bg-emerald-100 dark:bg-emerald-900/50 text-emerald-600">
<CheckCircle2 className="w-12 h-12" />
</div>
<div>
<h4 className="text-lg font-bold text-gray-900 dark:text-white">WhatsApp Session Authenticated</h4>
<p className="text-sm font-mono text-emerald-700 dark:text-emerald-300 mt-1">
Phone: +{openwaStatus.phone || 'Connected'} ({openwaStatus.push_name || 'Staff'})
</p>
<p className="text-xs text-gray-500 mt-2">
Gateway is actively listening and transmitting automated order, dispatch, and internal alert messages.
</p>
</div>
</div>
) : openwaStatus.qr_code ? (
<div className="flex flex-col items-center justify-center p-6 border-2 border-emerald-500/30 rounded-xl bg-gray-50 dark:bg-gray-800/50 text-center space-y-4">
<div className="p-3 bg-white rounded-xl shadow-md border border-gray-200">
<img
src={
openwaStatus.qr_code.startsWith('data:image')
? openwaStatus.qr_code
: `data:image/png;base64,${openwaStatus.qr_code}`
}
alt="WhatsApp Scan QR"
className="w-64 h-64 object-contain"
/>
</div>
<div>
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-emerald-100 dark:bg-emerald-900/60 text-emerald-800 dark:text-emerald-200 text-xs font-semibold">
<span className="w-2 h-2 rounded-full bg-emerald-500 animate-ping" />
QR Ready — Scan Now
</span>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-2">
1. Open WhatsApp on your phone &gt; Settings &gt; Linked Devices &gt; Link a Device.
<br />
2. Point camera at this QR code. The page will automatically synchronize once linked.
</p>
</div>
</div>
) : (
<div className="flex flex-col items-center justify-center p-12 text-center space-y-3 border-2 border-dashed border-gray-200 dark:border-gray-800 rounded-xl">
<AlertCircle className="w-10 h-10 text-amber-500" />
<p className="font-semibold text-gray-800 dark:text-gray-200">
Status: {openwaStatus.status || 'OFFLINE'}
</p>
<p className="text-xs text-gray-500 max-w-sm">
{openwaStatus.message || 'Session is initializing or waiting for gateway response.'}
</p>
<button
onClick={handleRestartOpenWa}
className="mt-2 px-4 py-2 text-xs font-medium rounded-lg bg-emerald-600 text-white hover:bg-emerald-700"
>
Force Restart Session
</button>
</div>
)}
</div>
{/* Test Send Form (Cols 8-12) */}
<div className="lg:col-span-5 rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-6 shadow-sm flex flex-col justify-between">
<div>
<h3 className="font-semibold text-gray-900 dark:text-white flex items-center gap-2 mb-2">
<Send className="w-4 h-4 text-emerald-600" />
Direct Test Dispatch
</h3>
<p className="text-xs text-gray-500 dark:text-gray-400 mb-4">
Send a live verification message through the active OpenWA gateway to any WhatsApp mobile number.
</p>
<form onSubmit={handleSendOpenWaTest} className="space-y-4">
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Recipient Mobile Number
</label>
<input
type="text"
placeholder="e.g. 919876543210 or 9876543210"
value={testPhone}
onChange={(e) => setTestPhone(e.target.value)}
className="w-full px-3 py-2 text-sm rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:ring-2 focus:ring-emerald-500 focus:outline-none"
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Message Content
</label>
<textarea
rows={4}
value={testMessage}
onChange={(e) => setTestMessage(e.target.value)}
className="w-full px-3 py-2 text-sm rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:ring-2 focus:ring-emerald-500 focus:outline-none"
/>
</div>
<button
type="submit"
disabled={sendingTest}
className="w-full py-2.5 px-4 rounded-lg bg-emerald-600 hover:bg-emerald-700 text-white text-sm font-semibold shadow-sm transition flex items-center justify-center gap-2"
>
<Send className={`w-4 h-4 ${sendingTest ? 'animate-pulse' : ''}`} />
{sendingTest ? 'Dispatching Message...' : 'Send WhatsApp Test'}
</button>
</form>
</div>
<div className="mt-6 pt-4 border-t border-gray-100 dark:border-gray-800 text-xs text-gray-500">
<span className="font-medium text-gray-700 dark:text-gray-300">Gateway URL:</span> http://localhost:8088
</div>
</div>
</div>
</div>
)}
{/* ========================================================================= */}
{/* TAB B: WATI (CUSTOMER COMMUNICATION & BROADCASTS) */}
{/* ========================================================================= */}
{activeSubTab === 'wati' && (
<div className="space-y-6">
{/* Top Banner */}
<div className="p-4 rounded-xl bg-blue-50 dark:bg-blue-950/30 border border-blue-200 dark:border-blue-900/50 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
<div>
<h2 className="text-base font-semibold text-blue-900 dark:text-blue-100 flex items-center gap-2">
<MessageSquare className="w-4 h-4 text-blue-600" />
Customer WhatsApp Integration (WATI Cloud API)
</h2>
<p className="text-xs text-blue-700 dark:text-blue-300 mt-0.5">
Purely dedicated to customer notifications, verified Meta template delivery, and external broadcasts.
</p>
</div>
{watiCreds.is_locked_by_config ? (
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 text-xs font-semibold">
<ShieldCheck className="w-3.5 h-3.5 text-blue-600" />
Configured via Config.py
</span>
) : (
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-purple-100 dark:bg-purple-900 text-purple-800 dark:text-purple-200 text-xs font-semibold">
<Server className="w-3.5 h-3.5 text-purple-600" />
Database Configuration
</span>
)}
</div>
<div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
{/* Credentials Card (Cols 1-6) */}
<div className="lg:col-span-6 rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-6 shadow-sm">
<h3 className="font-semibold text-gray-900 dark:text-white flex items-center gap-2 mb-4">
<Lock className="w-4 h-4 text-blue-600" />
WATI Cloud API Credentials
</h3>
<form onSubmit={handleSaveWati} className="space-y-4">
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
API Endpoint Base URL
</label>
<input
type="text"
disabled={watiCreds.is_locked_by_config}
value={watiCreds.api_endpoint}
onChange={(e) => setWatiCreds({ ...watiCreds, api_endpoint: e.target.value })}
className="w-full px-3 py-2 text-sm rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-900 dark:text-white disabled:opacity-60 disabled:cursor-not-allowed focus:ring-2 focus:ring-blue-500 focus:outline-none"
/>
<p className="text-[11px] text-gray-400 mt-1">Default: https://live-mt-server.wati.io</p>
</div>
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
API Access Token / Bearer Key
</label>
<input
type="password"
disabled={watiCreds.is_locked_by_config}
placeholder="Enter WATI token..."
value={watiCreds.api_token}
onChange={(e) => setWatiCreds({ ...watiCreds, api_token: e.target.value })}
className="w-full px-3 py-2 text-sm rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-900 dark:text-white disabled:opacity-60 disabled:cursor-not-allowed focus:ring-2 focus:ring-blue-500 focus:outline-none"
/>
</div>
<div className="flex items-center gap-3 pt-2">
<button
type="button"
onClick={handleTestWati}
disabled={watiTesting || !watiCreds.api_token}
className="flex-1 py-2 px-4 rounded-lg bg-gray-100 hover:bg-gray-200 dark:bg-gray-800 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-200 text-xs font-semibold transition flex items-center justify-center gap-1.5"
>
<RefreshCw className={`w-3.5 h-3.5 ${watiTesting ? 'animate-spin' : ''}`} />
{watiTesting ? 'Testing...' : 'Test Connection'}
</button>
{!watiCreds.is_locked_by_config && (
<button
type="submit"
disabled={watiSaving}
className="flex-1 py-2 px-4 rounded-lg bg-blue-600 hover:bg-blue-700 text-white text-xs font-semibold shadow-sm transition"
>
{watiSaving ? 'Saving...' : 'Save Settings'}
</button>
)}
</div>
</form>
</div>
{/* Test Template Send (Cols 7-12) */}
<div className="lg:col-span-6 rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-6 shadow-sm">
<h3 className="font-semibold text-gray-900 dark:text-white flex items-center gap-2 mb-2">
<Send className="w-4 h-4 text-blue-600" />
Customer Template Broadcast Test
</h3>
<p className="text-xs text-gray-500 dark:text-gray-400 mb-4">
Select an approved Meta/WATI template to send customer notifications.
</p>
<form onSubmit={handleSendWatiTemplate} className="space-y-4">
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Select Approved Template ({watiTemplates.length} Available)
</label>
<select
value={selectedTemplate}
onChange={(e) => setSelectedTemplate(e.target.value)}
className="w-full px-3 py-2 text-sm rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:outline-none"
>
<option value="">-- Choose a template --</option>
{watiTemplates.map((t, idx) => (
<option key={t.elementName || t.templateName || idx} value={t.elementName || t.templateName}>
{t.elementName || t.templateName} ({t.category || 'MARKETING'})
</option>
))}
</select>
</div>
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Customer WhatsApp Number
</label>
<input
type="text"
placeholder="e.g. 919876543210"
value={watiRecipientPhone}
onChange={(e) => setWatiRecipientPhone(e.target.value)}
className="w-full px-3 py-2 text-sm rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:outline-none"
/>
</div>
<button
type="submit"
disabled={sendingWatiTemplate || !selectedTemplate || !watiRecipientPhone}
className="w-full py-2.5 px-4 rounded-lg bg-blue-600 hover:bg-blue-700 text-white text-xs font-semibold shadow-sm transition flex items-center justify-center gap-2"
>
<Send className={`w-3.5 h-3.5 ${sendingWatiTemplate ? 'animate-pulse' : ''}`} />
{sendingWatiTemplate ? 'Sending Template...' : 'Send Customer Template'}
</button>
</form>
</div>
</div>
</div>
)}
</div>
);
}