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

539 lines
21 KiB
TypeScript

'use client';
import React, { useState, useEffect, useRef } from 'react';
import { useSearchParams } from 'next/navigation';
import {
MessageSquare,
QrCode,
RefreshCw,
Send,
CheckCircle2,
AlertCircle,
Lock,
Smartphone,
} from 'lucide-react';
import { toast } from 'sonner';
import { IntegrationsHeaderNav } from '@/components/integrations/IntegrationsHeaderNav';
import { CustomSelect } from '@/components/ui/CustomSelect';
import { integrationService } from '@/services/api/integrationService';
const fieldClass =
'w-full h-9 px-3 bg-card border border-border crm-radius-control text-[13px] text-foreground focus:outline-none focus:border-primary disabled:opacity-60';
const areaClass =
'w-full px-3 py-2 bg-card border border-border crm-radius-control text-[13px] text-foreground focus:outline-none focus:border-primary disabled:opacity-60';
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 labelClass = 'block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5';
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="flex flex-col gap-5 min-w-0">
<h1 className="text-lg font-semibold text-foreground">WhatsApp</h1>
<IntegrationsHeaderNav activeTab="whatsapp" />
<div className="flex flex-wrap items-center gap-2">
<button
type="button"
onClick={() => setActiveSubTab('openwa')}
className={`inline-flex items-center gap-1.5 h-9 px-3 crm-radius-control text-[13px] font-semibold whitespace-nowrap ${
activeSubTab === 'openwa'
? 'bg-primary text-white'
: 'border border-border bg-card text-foreground hover:bg-muted'
}`}
>
<Smartphone className="w-3.5 h-3.5" />
Internal Staff Gateway (OpenWA Live QR)
</button>
<button
type="button"
onClick={() => setActiveSubTab('wati')}
className={`inline-flex items-center gap-1.5 h-9 px-3 crm-radius-control text-[13px] font-semibold whitespace-nowrap ${
activeSubTab === 'wati'
? 'bg-primary text-white'
: 'border border-border bg-card text-foreground hover:bg-muted'
}`}
>
<MessageSquare className="w-3.5 h-3.5" />
Customer Communication (WATI Cloud API)
</button>
</div>
{/* ========================================================================= */}
{/* TAB A: OPENWA (INTERNAL LIVE QR SCANNER) */}
{/* ========================================================================= */}
{activeSubTab === 'openwa' && (
<div className="space-y-6">
<div className="flex flex-wrap items-center justify-between gap-3">
<h2 className="text-[13px] font-semibold text-foreground">Internal Staff Gateway (OpenWA Live QR)</h2>
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => fetchOpenWaStatus(true)}
disabled={openwaLoading}
className={secondaryButton}
>
<RefreshCw className={`w-3.5 h-3.5 ${openwaLoading ? 'animate-spin' : ''}`} />
Refresh
</button>
<button
onClick={handleRestartOpenWa}
disabled={restarting}
className={primaryButton}
>
<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={`${shell} p-4 lg:col-span-7`}>
<h3 className="font-semibold text-foreground flex items-center gap-2 mb-4">
<QrCode className="w-4 h-4 text-primary" />
Session Connection State
</h3>
{openwaLoading ? (
<div className="flex flex-col items-center justify-center p-12 space-y-4">
<RefreshCw className="w-5 h-5 text-primary animate-spin" />
<p className="text-[13px] text-muted-foreground">Checking session</p>
</div>
) : openwaStatus.status === 'CONNECTED' ? (
<div className="flex flex-col items-center justify-center p-8 border border-border crm-radius-control bg-muted/40 text-center gap-2">
<CheckCircle2 className="w-8 h-8 text-success" />
<h4 className="text-[15px] font-semibold text-foreground">Connected</h4>
<p className="text-[13px] text-foreground">
{openwaStatus.phone ? `+${openwaStatus.phone}` : '—'}
{openwaStatus.push_name ? ` · ${openwaStatus.push_name}` : ''}
</p>
</div>
) : openwaStatus.qr_code ? (
<div className="flex flex-col items-center justify-center p-6 border border-border crm-radius-control bg-muted/40 text-center gap-4">
<div className="p-3 bg-white crm-radius-control border border-border">
<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 px-2.5 py-1 crm-radius-badge text-[11px] font-semibold bg-success/15 text-success">
QR ready
</span>
<p className="text-[12px] text-muted-foreground mt-2">
WhatsApp → Settings → Linked devices → Link a device
</p>
</div>
</div>
) : (
<div className="flex flex-col items-center justify-center p-12 text-center gap-3 border border-dashed border-border crm-radius-control">
<AlertCircle className="w-8 h-8 text-warning" />
<p className="font-semibold text-foreground">
Status: {openwaStatus.status || 'OFFLINE'}
</p>
<p className="text-xs text-muted-foreground max-w-sm">
{openwaStatus.message || 'Session is initializing or waiting for gateway response.'}
</p>
<button
onClick={handleRestartOpenWa}
className={primaryButton}
>
Force Restart Session
</button>
</div>
)}
</div>
{/* Test Send Form (Cols 8-12) */}
<div className={`${shell} p-4 lg:col-span-5 flex flex-col justify-between`}>
<div>
<h3 className="font-semibold text-foreground flex items-center gap-2 mb-4">
<Send className="w-4 h-4 text-primary" />
Direct Test Dispatch
</h3>
<form onSubmit={handleSendOpenWaTest} className="space-y-4">
<div>
<label className={labelClass}>
Recipient Mobile Number
</label>
<input
type="text"
placeholder="Phone"
value={testPhone}
onChange={(e) => setTestPhone(e.target.value)}
className={fieldClass}
/>
</div>
<div>
<label className={labelClass}>
Message Content
</label>
<textarea
rows={4}
value={testMessage}
onChange={(e) => setTestMessage(e.target.value)}
className={areaClass}
/>
</div>
<button
type="submit"
disabled={sendingTest}
className={`${primaryButton} w-full`}
>
<Send className={`w-4 h-4 ${sendingTest ? 'animate-pulse' : ''}`} />
{sendingTest ? 'Dispatching Message...' : 'Send WhatsApp Test'}
</button>
</form>
</div>
</div>
</div>
</div>
)}
{/* ========================================================================= */}
{/* TAB B: WATI (CUSTOMER COMMUNICATION & BROADCASTS) */}
{/* ========================================================================= */}
{activeSubTab === 'wati' && (
<div className="space-y-6">
<div className="flex flex-wrap items-center justify-between gap-3">
<h2 className="text-[13px] font-semibold text-foreground">Customer Communication (WATI Cloud API)</h2>
<span className={`inline-flex items-center px-2.5 py-1 crm-radius-badge text-[11px] font-semibold ${watiCreds.is_locked_by_config ? 'bg-primary/10 text-primary' : 'bg-muted text-foreground'}`}>
{watiCreds.is_locked_by_config ? 'Config' : 'Database'}
</span>
</div>
<div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
{/* Credentials Card (Cols 1-6) */}
<div className={`${shell} p-4 lg:col-span-6`}>
<h3 className="font-semibold text-foreground flex items-center gap-2 mb-4">
<Lock className="w-4 h-4 text-primary" />
WATI Cloud API Credentials
</h3>
<form onSubmit={handleSaveWati} className="space-y-4">
<div>
<label className={labelClass}>
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={fieldClass}
/>
</div>
<div>
<label className={labelClass}>
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={fieldClass}
/>
</div>
<div className="flex items-center gap-3 pt-2">
<button
type="button"
onClick={handleTestWati}
disabled={watiTesting || !watiCreds.api_token}
className={`${secondaryButton} flex-1`}
>
<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={`${primaryButton} flex-1`}
>
{watiSaving ? 'Saving...' : 'Save Settings'}
</button>
)}
</div>
</form>
</div>
{/* Test Template Send (Cols 7-12) */}
<div className={`${shell} p-4 lg:col-span-6`}>
<h3 className="font-semibold text-foreground flex items-center gap-2 mb-4">
<Send className="w-4 h-4 text-primary" />
Customer Template Broadcast Test
</h3>
<form onSubmit={handleSendWatiTemplate} className="space-y-4">
<div>
<label className={labelClass}>
Select Approved Template ({watiTemplates.length} Available)
</label>
<CustomSelect
value={selectedTemplate}
onChange={setSelectedTemplate}
placeholder="Choose a template"
options={[
{ value: '', label: 'Choose a template' },
...watiTemplates.map((t) => {
const name = t.elementName || t.templateName || '';
return {
value: name,
label: `${name}${t.category ? ` (${t.category})` : ''}`,
};
}),
]}
/>
</div>
<div>
<label className={labelClass}>
Customer WhatsApp Number
</label>
<input
type="text"
placeholder="Phone"
value={watiRecipientPhone}
onChange={(e) => setWatiRecipientPhone(e.target.value)}
className={fieldClass}
/>
</div>
<button
type="submit"
disabled={sendingWatiTemplate || !selectedTemplate || !watiRecipientPhone}
className={`${primaryButton} w-full`}
>
<Send className={`w-3.5 h-3.5 ${sendingWatiTemplate ? 'animate-pulse' : ''}`} />
{sendingWatiTemplate ? 'Sending Template...' : 'Send Customer Template'}
</button>
</form>
</div>
</div>
</div>
)}
</div>
);
}