feat(admin): add enterprise integrations hub and swarm prediction lab UI

This commit is contained in:
adithiyan 2026-10-26 12:26:17 +05:30
parent ae5dc76076
commit 9b2b0b0a7c
13 changed files with 4238 additions and 1 deletions

View file

@ -0,0 +1,374 @@
'use client';
import React, { useState, useEffect } from 'react';
import {
PhoneCall,
ShieldCheck,
Server,
Lock,
RefreshCw,
CheckCircle2,
AlertCircle,
PhoneForwarded,
Clock,
History,
Play,
Key,
} from 'lucide-react';
import { toast } from 'sonner';
import { IntegrationsHeaderNav } from '@/components/integrations/IntegrationsHeaderNav';
import { integrationService } from '@/services/api/integrationService';
export default function KnowlarityCallIntegrationPage() {
const [creds, setCreds] = useState<any>({
api_key: '',
authorization: '',
virtual_number: '',
call_url: 'https://kpi.knowlarity.com/Basic/v1/account/call/makecall',
log_url: 'https://kpi.knowlarity.com/Basic/v1/account/calllog',
source: 'unconfigured',
is_locked_by_config: false,
});
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
// Click to call form state
const [agentNumber, setAgentNumber] = useState('');
const [customerNumber, setCustomerNumber] = useState('');
const [calling, setCalling] = useState(false);
// Call logs table
const [logs, setLogs] = useState<any[]>([]);
const [logsLoading, setLogsLoading] = useState(false);
const [page, setPage] = useState(1);
const fetchKnowlarityConfig = async () => {
setLoading(true);
try {
const data = await integrationService.getKnowlarityCredentials();
setCreds(data);
if (data.api_key || data.authorization) {
fetchLogs();
}
} catch (err: any) {
toast.error('Failed to load Knowlarity settings');
} finally {
setLoading(false);
}
};
const fetchLogs = async () => {
setLogsLoading(true);
try {
const res = await integrationService.getKnowlarityCallLogs(page, 20);
const callData = res.data?.call_logs || res.data?.objects || res.call_logs || [];
setLogs(callData);
} catch (err) {
console.warn('Call logs error:', err);
} finally {
setLogsLoading(false);
}
};
useEffect(() => {
fetchKnowlarityConfig();
}, []);
const handleSave = async (e: React.FormEvent) => {
e.preventDefault();
setSaving(true);
try {
await integrationService.saveKnowlarityCredentials(creds);
toast.success('Knowlarity credentials saved successfully');
fetchLogs();
} catch (err: any) {
toast.error(err.message || 'Failed to save Knowlarity credentials');
} finally {
setSaving(false);
}
};
const handleMakeCall = async (e: React.FormEvent) => {
e.preventDefault();
if (!agentNumber.trim() || !customerNumber.trim()) {
toast.error('Both Agent number and Customer number are required for bridging');
return;
}
setCalling(true);
try {
const res = await integrationService.makeKnowlarityCall({
agent_number: agentNumber.trim(),
customer_number: customerNumber.trim(),
});
if (res.status === 'SUCCESS') {
toast.success('Call initiated! Knowlarity is ringing the agent first, then connecting customer.');
fetchLogs();
} else {
toast.error(`Call failed: ${res.detail || JSON.stringify(res)}`);
}
} catch (err: any) {
toast.error(err.message || 'Call initiation failed');
} finally {
setCalling(false);
}
};
return (
<div className="p-6 max-w-7xl mx-auto space-y-6">
<IntegrationsHeaderNav activeTab="call" />
{/* Top Banner */}
<div className="p-4 rounded-xl bg-rose-50 dark:bg-rose-950/30 border border-rose-200 dark:border-rose-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-rose-900 dark:text-rose-100 flex items-center gap-2">
<PhoneCall className="w-4 h-4 text-rose-600" />
Knowlarity Cloud Telephony & SuperReceptionist IVR
</h2>
<p className="text-xs text-rose-700 dark:text-rose-300 mt-0.5">
Cloud IVR call routing, technician click-to-call bridging, customer service recordings, and live call logs.
</p>
</div>
{creds.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 Form (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">
<div className="flex items-center justify-between mb-4">
<h3 className="font-semibold text-gray-900 dark:text-white flex items-center gap-2">
<Key className="w-4 h-4 text-rose-600" />
SuperReceptionist Credentials
</h3>
</div>
<form onSubmit={handleSave} className="space-y-4">
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Virtual SR Number (Caller ID)
</label>
<input
type="text"
disabled={creds.is_locked_by_config}
value={creds.virtual_number || ''}
onChange={(e) => setCreds({ ...creds, virtual_number: e.target.value })}
placeholder="e.g. +91XXXXXXXXXX"
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 focus:ring-2 focus:ring-rose-500 focus:outline-none"
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
x-api-key
</label>
<input
type="password"
disabled={creds.is_locked_by_config}
value={creds.api_key || ''}
onChange={(e) => setCreds({ ...creds, api_key: e.target.value })}
placeholder="Knowlarity x-api-key"
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 focus:ring-2 focus:ring-rose-500 focus:outline-none"
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Authorization Token
</label>
<input
type="password"
disabled={creds.is_locked_by_config}
value={creds.authorization || ''}
onChange={(e) => setCreds({ ...creds, authorization: e.target.value })}
placeholder="Knowlarity Authorization"
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 focus:ring-2 focus:ring-rose-500 focus:outline-none"
/>
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
MakeCall API Endpoint
</label>
<input
type="text"
disabled={creds.is_locked_by_config}
value={creds.call_url || 'https://kpi.knowlarity.com/Basic/v1/account/call/makecall'}
onChange={(e) => setCreds({ ...creds, call_url: 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"
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
CallLog API Endpoint
</label>
<input
type="text"
disabled={creds.is_locked_by_config}
value={creds.log_url || 'https://kpi.knowlarity.com/Basic/v1/account/calllog'}
onChange={(e) => setCreds({ ...creds, log_url: 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"
/>
</div>
</div>
{!creds.is_locked_by_config && (
<button
type="submit"
disabled={saving}
className="w-full py-2.5 px-4 rounded-lg bg-rose-600 hover:bg-rose-700 text-white text-xs font-semibold shadow-sm transition"
>
{saving ? 'Saving...' : 'Save Knowlarity Settings'}
</button>
)}
</form>
</div>
{/* Live Click-to-Call Dialer (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">
<PhoneForwarded className="w-4 h-4 text-rose-600" />
Agent Click-to-Call Bridge
</h3>
<p className="text-xs text-gray-500 dark:text-gray-400 mb-4">
Connect a technician or sales rep with a customer through Knowlarity without revealing personal numbers.
</p>
<form onSubmit={handleMakeCall} className="space-y-4">
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Agent Mobile Number (Rings First)
</label>
<input
type="text"
placeholder="e.g. 919876543210"
value={agentNumber}
onChange={(e) => setAgentNumber(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-rose-500 focus:outline-none"
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Customer Mobile Number (Rings Second)
</label>
<input
type="text"
placeholder="e.g. 919123456789"
value={customerNumber}
onChange={(e) => setCustomerNumber(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-rose-500 focus:outline-none"
/>
</div>
<button
type="submit"
disabled={calling}
className="w-full py-2.5 px-4 rounded-lg bg-rose-600 hover:bg-rose-700 text-white text-xs font-semibold shadow-sm transition flex items-center justify-center gap-2"
>
<PhoneCall className={`w-3.5 h-3.5 ${calling ? 'animate-bounce' : ''}`} />
{calling ? 'Bridging Call...' : 'Initiate Call Bridge'}
</button>
</form>
</div>
<div className="mt-6 pt-4 border-t border-gray-100 dark:border-gray-800 text-xs text-gray-500 flex items-center justify-between">
<span>Virtual Number:</span>
<span className="font-mono text-rose-600 font-semibold">{creds.virtual_number || 'SR Number'}</span>
</div>
</div>
</div>
{/* Call Logs Table */}
<div className="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-6 shadow-sm">
<div className="flex items-center justify-between mb-4">
<h3 className="font-semibold text-gray-900 dark:text-white flex items-center gap-2">
<History className="w-4 h-4 text-rose-600" />
Telephony Call Logs & Recordings
</h3>
<button
onClick={fetchLogs}
disabled={logsLoading}
className="px-3 py-1.5 text-xs font-medium rounded-lg bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-200 transition flex items-center gap-1.5"
>
<RefreshCw className={`w-3.5 h-3.5 ${logsLoading ? 'animate-spin' : ''}`} />
Refresh Logs
</button>
</div>
<div className="overflow-x-auto">
<table className="w-full text-left text-xs">
<thead className="bg-gray-50 dark:bg-gray-800/50 text-gray-500 uppercase font-medium border-y border-gray-100 dark:border-gray-800">
<tr>
<th className="py-2.5 px-3">Date / Time</th>
<th className="py-2.5 px-3">Customer</th>
<th className="py-2.5 px-3">Agent</th>
<th className="py-2.5 px-3">Status</th>
<th className="py-2.5 px-3">Duration</th>
<th className="py-2.5 px-3">Recording</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100 dark:divide-gray-800">
{logs.length === 0 ? (
<tr>
<td colSpan={6} className="py-8 text-center text-gray-400">
{logsLoading ? 'Fetching call logs from Knowlarity...' : 'No call logs recorded yet.'}
</td>
</tr>
) : (
logs.map((log: any, idx: number) => (
<tr key={idx} className="hover:bg-gray-50 dark:hover:bg-gray-800/50">
<td className="py-2.5 px-3 font-mono text-gray-600 dark:text-gray-400">
{log.start_time || log.call_date || 'Recent'}
</td>
<td className="py-2.5 px-3 font-medium text-gray-900 dark:text-white">
{log.customer_number || log.caller_id || '-'}
</td>
<td className="py-2.5 px-3 text-gray-600 dark:text-gray-300">
{log.agent_number || log.destination || '-'}
</td>
<td className="py-2.5 px-3">
<span className="inline-flex px-2 py-0.5 rounded-full text-[10px] font-semibold bg-emerald-100 dark:bg-emerald-950 text-emerald-800 dark:text-emerald-300">
{log.status || log.call_type || 'COMPLETED'}
</span>
</td>
<td className="py-2.5 px-3 font-mono text-gray-600 dark:text-gray-400">
{log.duration ? `${log.duration}s` : '0s'}
</td>
<td className="py-2.5 px-3">
{log.recording_url ? (
<a
href={log.recording_url}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1 text-rose-600 hover:text-rose-700 font-semibold"
>
<Play className="w-3 h-3" /> Audio
</a>
) : (
<span className="text-gray-400">-</span>
)}
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
</div>
);
}

View file

@ -0,0 +1,331 @@
'use client';
import React, { useState, useEffect } from 'react';
import {
Mail,
Send,
ShieldCheck,
Server,
Lock,
RefreshCw,
CheckCircle2,
AlertCircle,
Key,
} from 'lucide-react';
import { toast } from 'sonner';
import { IntegrationsHeaderNav } from '@/components/integrations/IntegrationsHeaderNav';
import { integrationService } from '@/services/api/integrationService';
export default function EmailIntegrationsPage() {
const [creds, setCreds] = useState<any>({
active_provider: 'ZeptoMail',
sender_email: '',
sender_name: 'iFixKart',
smtp_server: '',
smtp_port: 587,
smtp_username: '',
smtp_password: '',
use_tls: true,
source: 'unconfigured',
is_locked_by_config: false,
});
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
// Test send state
const [testRecipient, setTestRecipient] = useState('');
const [testSubject, setTestSubject] = useState('iFixKart ERP Email Verification Test');
const [testBody, setTestBody] = useState('This is a verified test email sent from iFixKart ERP Email Gateway.');
const [sendingTest, setSendingTest] = useState(false);
const fetchEmailConfig = async () => {
setLoading(true);
try {
const data = await integrationService.getEmailCredentials();
setCreds(data);
} catch (err: any) {
toast.error('Failed to load email settings');
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchEmailConfig();
}, []);
const handleSaveCredentials = async (e: React.FormEvent) => {
e.preventDefault();
setSaving(true);
try {
await integrationService.saveEmailCredentials(creds);
toast.success('Email settings saved successfully');
} catch (err: any) {
toast.error(err.message || 'Failed to save email settings');
} finally {
setSaving(false);
}
};
const handleSendTest = async (e: React.FormEvent) => {
e.preventDefault();
if (!testRecipient.trim() || !testRecipient.includes('@')) {
toast.error('Please enter a valid recipient email address');
return;
}
setSendingTest(true);
try {
const res = await integrationService.sendTestEmail({
recipient: testRecipient.trim(),
subject: testSubject.trim(),
body: testBody.trim(),
});
if (res.status === 'SUCCESS') {
toast.success(`Verification email dispatched to ${testRecipient}!`);
} else {
toast.error(`Email send failed: ${res.detail || JSON.stringify(res)}`);
}
} catch (err: any) {
toast.error(err.message || 'Failed to send test email');
} finally {
setSendingTest(false);
}
};
return (
<div className="p-6 max-w-7xl mx-auto space-y-6">
<IntegrationsHeaderNav activeTab="email" />
{/* Top Banner */}
<div className="p-4 rounded-xl bg-sky-50 dark:bg-sky-950/30 border border-sky-200 dark:border-sky-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-sky-900 dark:text-sky-100 flex items-center gap-2">
<Mail className="w-4 h-4 text-sky-600" />
Transactional Email Gateway (ZeptoMail & SMTP)
</h2>
<p className="text-xs text-sky-700 dark:text-sky-300 mt-0.5">
Manages automated order confirmations, password reset links, quotation invoices, and staff alerts.
</p>
</div>
{creds.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" />
Active via Config.py ({creds.active_provider})
</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" />
Custom Database SMTP
</span>
)}
</div>
<div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
{/* Credentials Form (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">
<div className="flex items-center justify-between mb-4">
<h3 className="font-semibold text-gray-900 dark:text-white flex items-center gap-2">
<Key className="w-4 h-4 text-sky-600" />
Provider Configuration
</h3>
<span className="text-xs font-mono px-2 py-0.5 rounded bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300">
Provider: {creds.active_provider}
</span>
</div>
<form onSubmit={handleSaveCredentials} className="space-y-4">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Active Provider
</label>
<input
type="text"
disabled={creds.is_locked_by_config}
value={creds.active_provider}
onChange={(e) => setCreds({ ...creds, active_provider: 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-sky-500 focus:outline-none"
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Sender Display Name
</label>
<input
type="text"
disabled={creds.is_locked_by_config}
value={creds.sender_name || 'iFixKart ERP'}
onChange={(e) => setCreds({ ...creds, sender_name: 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-sky-500 focus:outline-none"
/>
</div>
</div>
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Sender Email Address
</label>
<input
type="email"
disabled={creds.is_locked_by_config}
value={creds.sender_email || ''}
onChange={(e) => setCreds({ ...creds, sender_email: 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-sky-500 focus:outline-none"
/>
</div>
{creds.active_provider === 'ZeptoMail' ? (
<div className="p-4 rounded-lg bg-sky-50/50 dark:bg-sky-950/20 border border-sky-100 dark:border-sky-900/30 space-y-2">
<div className="flex items-center gap-2 text-xs font-semibold text-sky-800 dark:text-sky-200">
<CheckCircle2 className="w-4 h-4 text-sky-600" />
Zoho ZeptoMail CPaaS Active
</div>
<p className="text-xs text-gray-600 dark:text-gray-400">
ZeptoMail API Token is loaded from production environment variable <code className="font-mono text-sky-600">ZEPTOMAIL_API_KEY</code>.
High delivery inbox rate with SSL/TLS encryption.
</p>
<div className="text-[11px] font-mono text-gray-500">
Endpoint: {creds.endpoint || 'https://api.zeptomail.in/v1.1/email'}
</div>
</div>
) : (
<div className="space-y-4 pt-2 border-t border-gray-100 dark:border-gray-800">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
SMTP Host Server
</label>
<input
type="text"
disabled={creds.is_locked_by_config}
value={creds.smtp_server || ''}
onChange={(e) => setCreds({ ...creds, smtp_server: e.target.value })}
placeholder="e.g. smtp.gmail.com"
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"
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
SMTP Port
</label>
<input
type="number"
disabled={creds.is_locked_by_config}
value={creds.smtp_port || 587}
onChange={(e) => setCreds({ ...creds, smtp_port: parseInt(e.target.value) || 587 })}
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"
/>
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
SMTP Username
</label>
<input
type="text"
disabled={creds.is_locked_by_config}
value={creds.smtp_username || ''}
onChange={(e) => setCreds({ ...creds, smtp_username: 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"
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
SMTP Password
</label>
<input
type="password"
disabled={creds.is_locked_by_config}
value={creds.smtp_password || ''}
onChange={(e) => setCreds({ ...creds, smtp_password: e.target.value })}
placeholder="••••••••••••"
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"
/>
</div>
</div>
</div>
)}
{!creds.is_locked_by_config && (
<button
type="submit"
disabled={saving}
className="w-full py-2.5 px-4 rounded-lg bg-sky-600 hover:bg-sky-700 text-white text-xs font-semibold shadow-sm transition"
>
{saving ? 'Saving...' : 'Save Email Configuration'}
</button>
)}
</form>
</div>
{/* Live Test Email Sender (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-sky-600" />
Live Test Email Dispatch
</h3>
<p className="text-xs text-gray-500 dark:text-gray-400 mb-4">
Sends an immediate verification email to verify SMTP handshake or ZeptoMail CPaaS API delivery.
</p>
<form onSubmit={handleSendTest} className="space-y-4">
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Recipient Email Address
</label>
<input
type="email"
placeholder="admin@ifixkart.com"
value={testRecipient}
onChange={(e) => setTestRecipient(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-sky-500 focus:outline-none"
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Subject Line
</label>
<input
type="text"
value={testSubject}
onChange={(e) => setTestSubject(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-sky-500 focus:outline-none"
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Email Message Body
</label>
<textarea
rows={4}
value={testBody}
onChange={(e) => setTestBody(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-sky-500 focus:outline-none"
/>
</div>
<button
type="submit"
disabled={sendingTest}
className="w-full py-2.5 px-4 rounded-lg bg-sky-600 hover:bg-sky-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 ${sendingTest ? 'animate-pulse' : ''}`} />
{sendingTest ? 'Dispatching Test Email...' : 'Send Test Email'}
</button>
</form>
</div>
<div className="mt-6 pt-4 border-t border-gray-100 dark:border-gray-800 text-xs text-gray-500">
TLS Enabled: <span className="font-semibold text-emerald-600">Yes (Strict Port 587/465)</span>
</div>
</div>
</div>
</div>
);
}

View file

@ -0,0 +1,163 @@
'use client';
import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import {
BarChart3,
TrendingUp,
Users,
Eye,
Clock,
ExternalLink,
ShieldCheck,
CheckCircle2,
RefreshCw,
Radio,
ArrowUpRight,
} from 'lucide-react';
import { toast } from 'sonner';
import { IntegrationsHeaderNav } from '@/components/integrations/IntegrationsHeaderNav';
import { apiFetch } from '@/services/api/client';
import { API_ENDPOINTS } from '@/services/api/config';
export default function GoogleAnalyticsIntegrationPage() {
const [status, setStatus] = useState<any>(null);
const [overview, setOverview] = useState<any>(null);
const [loading, setLoading] = useState(true);
const fetchGA4 = async () => {
setLoading(true);
try {
const [statusRes, overviewRes] = await Promise.all([
apiFetch<any>(API_ENDPOINTS.GOOGLE_ANALYTICS_STATUS),
apiFetch<any>(`${API_ENDPOINTS.GOOGLE_ANALYTICS_OVERVIEW}?days=30`),
]);
setStatus(statusRes);
if (overviewRes && overviewRes.data) {
setOverview(overviewRes.data);
}
} catch (err: any) {
toast.error('Failed to fetch GA4 integration status');
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchGA4();
}, []);
return (
<div className="p-6 max-w-7xl mx-auto space-y-6">
<IntegrationsHeaderNav activeTab="google-analytics" />
{/* Top Banner */}
<div className="p-4 rounded-xl bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-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-amber-900 dark:text-amber-100 flex items-center gap-2">
<BarChart3 className="w-4 h-4 text-amber-600" />
Google Analytics 4 (GA4) Telemetry Integration
</h2>
<p className="text-xs text-amber-700 dark:text-amber-300 mt-0.5">
Real-time analytics tracking, visitor acquisition, engagement rates, and Google Data API synchronization.
</p>
</div>
<div className="flex items-center gap-2">
<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>
<Link
href="/analytics/google"
className="px-3 py-1.5 rounded-lg bg-amber-600 hover:bg-amber-700 text-white text-xs font-semibold flex items-center gap-1.5 shadow-sm transition"
>
Open Full GA4 Board <ArrowUpRight className="w-3.5 h-3.5" />
</Link>
</div>
</div>
{loading ? (
<div className="grid grid-cols-1 md:grid-cols-4 gap-4 animate-pulse">
{[1, 2, 3, 4].map((i) => (
<div key={i} className="h-28 rounded-xl bg-gray-100 dark:bg-gray-800" />
))}
</div>
) : (
<>
{/* Connection Overview */}
<div className="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-6 shadow-sm">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-gray-100 dark:border-gray-800 pb-4">
<div>
<span className="text-xs font-bold uppercase tracking-wider text-amber-600 dark:text-amber-400">
Active Property
</span>
<h3 className="text-xl font-bold text-gray-900 dark:text-white mt-0.5">
Property ID: {status?.property_id || '521198579'}
</h3>
</div>
<div className="flex items-center gap-2">
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-emerald-50 dark:bg-emerald-950/50 text-emerald-700 dark:text-emerald-300 text-xs font-semibold border border-emerald-200 dark:border-emerald-800">
<CheckCircle2 className="w-3.5 h-3.5 text-emerald-500" />
Service Account Connected
</span>
</div>
</div>
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 mt-6">
<div className="p-4 rounded-xl bg-gray-50 dark:bg-gray-800/50 border border-gray-100 dark:border-gray-800">
<div className="flex items-center gap-2 text-xs text-gray-500 mb-1">
<Radio className="w-3.5 h-3.5 text-emerald-500 animate-pulse" />
Realtime Users (Last 30m)
</div>
<div className="text-2xl font-bold text-gray-900 dark:text-white">
{overview?.realtime_active_users ?? 0}
</div>
</div>
<div className="p-4 rounded-xl bg-gray-50 dark:bg-gray-800/50 border border-gray-100 dark:border-gray-800">
<div className="flex items-center gap-2 text-xs text-gray-500 mb-1">
<Users className="w-3.5 h-3.5 text-blue-500" />
30-Day Active Users
</div>
<div className="text-2xl font-bold text-gray-900 dark:text-white">
{overview?.metrics?.active_users?.toLocaleString() ?? 0}
</div>
</div>
<div className="p-4 rounded-xl bg-gray-50 dark:bg-gray-800/50 border border-gray-100 dark:border-gray-800">
<div className="flex items-center gap-2 text-xs text-gray-500 mb-1">
<Eye className="w-3.5 h-3.5 text-purple-500" />
Screen / Page Views
</div>
<div className="text-2xl font-bold text-gray-900 dark:text-white">
{overview?.metrics?.screen_page_views?.toLocaleString() ?? 0}
</div>
</div>
<div className="p-4 rounded-xl bg-gray-50 dark:bg-gray-800/50 border border-gray-100 dark:border-gray-800">
<div className="flex items-center gap-2 text-xs text-gray-500 mb-1">
<Clock className="w-3.5 h-3.5 text-amber-500" />
Avg Session Duration
</div>
<div className="text-2xl font-bold text-gray-900 dark:text-white">
{overview?.metrics?.average_session_duration
? `${Math.round(overview.metrics.average_session_duration)}s`
: '0s'}
</div>
</div>
</div>
<div className="mt-6 flex justify-end">
<Link
href="/analytics/google"
className="inline-flex items-center gap-2 px-4 py-2 text-sm font-semibold rounded-lg bg-amber-600 hover:bg-amber-700 text-white shadow-sm transition"
>
Launch Deep Telemetry Dashboard <ArrowUpRight className="w-4 h-4" />
</Link>
</div>
</div>
</>
)}
</div>
);
}

View file

@ -0,0 +1,279 @@
'use client';
import React, { useState, useEffect } from 'react';
import {
Share2,
ShieldCheck,
Server,
Lock,
RefreshCw,
CheckCircle2,
AlertCircle,
TrendingUp,
DollarSign,
Key,
} from 'lucide-react';
import { toast } from 'sonner';
import { IntegrationsHeaderNav } from '@/components/integrations/IntegrationsHeaderNav';
import { integrationService } from '@/services/api/integrationService';
export default function MetaAdsIntegrationPage() {
const [creds, setCreds] = useState<any>({
app_id: '',
ad_account_id: '',
page_id: '',
instagram_id: '',
access_token: '',
source: 'unconfigured',
is_locked_by_config: false,
});
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [testing, setTesting] = useState(false);
const [testResult, setTestResult] = useState<any>(null);
const fetchMetaConfig = async () => {
setLoading(true);
try {
const data = await integrationService.getMetaCredentials();
setCreds(data);
} catch (err: any) {
toast.error('Failed to load Meta credentials');
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchMetaConfig();
}, []);
const handleSave = async (e: React.FormEvent) => {
e.preventDefault();
setSaving(true);
try {
await integrationService.saveMetaCredentials(creds);
toast.success('Meta credentials saved successfully');
} catch (err: any) {
toast.error(err.message || 'Failed to save Meta credentials');
} finally {
setSaving(false);
}
};
const handleTestToken = async () => {
if (!creds.access_token) {
toast.error('No Meta access token configured to test');
return;
}
setTesting(true);
try {
const res = await integrationService.testMetaConnection({
access_token: creds.access_token,
ad_account_id: creds.ad_account_id,
});
if (res.status === 'SUCCESS') {
toast.success(`Meta API Validated! Connected as: ${res.user?.name || 'Verified User'}`);
setTestResult(res);
} else {
toast.error(`Token verification failed: ${res.detail || 'Invalid token'}`);
}
} catch (err: any) {
toast.error(err.message || 'Meta API verification failed');
} finally {
setTesting(false);
}
};
return (
<div className="p-6 max-w-7xl mx-auto space-y-6">
<IntegrationsHeaderNav activeTab="meta-ads" />
{/* Top Banner */}
<div className="p-4 rounded-xl bg-indigo-50 dark:bg-indigo-950/30 border border-indigo-200 dark:border-indigo-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-indigo-900 dark:text-indigo-100 flex items-center gap-2">
<Share2 className="w-4 h-4 text-indigo-600" />
Meta Graph API & Social Ads Integration (v22.0)
</h2>
<p className="text-xs text-indigo-700 dark:text-indigo-300 mt-0.5">
Connects Facebook Ads Manager, Instagram Business Graph, lead generation webhooks, and catalog synchronization.
</p>
</div>
{creds.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 Form (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">
<div className="flex items-center justify-between mb-4">
<h3 className="font-semibold text-gray-900 dark:text-white flex items-center gap-2">
<Key className="w-4 h-4 text-indigo-600" />
Meta App & Ad Account Coordinates
</h3>
</div>
<form onSubmit={handleSave} className="space-y-4">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Meta App ID
</label>
<input
type="text"
disabled={creds.is_locked_by_config}
value={creds.app_id || ''}
onChange={(e) => setCreds({ ...creds, app_id: e.target.value })}
placeholder="1208251298791396"
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 focus:ring-2 focus:ring-indigo-500 focus:outline-none"
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Meta Ad Account ID
</label>
<input
type="text"
disabled={creds.is_locked_by_config}
value={creds.ad_account_id || ''}
onChange={(e) => setCreds({ ...creds, ad_account_id: e.target.value })}
placeholder="1307493795455160"
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 focus:ring-2 focus:ring-indigo-500 focus:outline-none"
/>
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Facebook Page ID
</label>
<input
type="text"
disabled={creds.is_locked_by_config}
value={creds.page_id || ''}
onChange={(e) => setCreds({ ...creds, page_id: 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 focus:ring-2 focus:ring-indigo-500 focus:outline-none"
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Instagram Account ID
</label>
<input
type="text"
disabled={creds.is_locked_by_config}
value={creds.instagram_id || ''}
onChange={(e) => setCreds({ ...creds, instagram_id: 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 focus:ring-2 focus:ring-indigo-500 focus:outline-none"
/>
</div>
</div>
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Graph API System Access Token (v22.0)
</label>
<input
type="password"
disabled={creds.is_locked_by_config}
value={creds.access_token || ''}
onChange={(e) => setCreds({ ...creds, access_token: e.target.value })}
placeholder="EAAR..."
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 focus:ring-2 focus:ring-indigo-500 focus:outline-none"
/>
</div>
<div className="flex items-center gap-3 pt-2">
<button
type="button"
onClick={handleTestToken}
disabled={testing || !creds.access_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 ${testing ? 'animate-spin' : ''}`} />
{testing ? 'Validating Token...' : 'Test Graph API Token'}
</button>
{!creds.is_locked_by_config && (
<button
type="submit"
disabled={saving}
className="flex-1 py-2 px-4 rounded-lg bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-semibold shadow-sm transition"
>
{saving ? 'Saving...' : 'Save Meta Credentials'}
</button>
)}
</div>
</form>
</div>
{/* Live Token Inspection Result (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">
<CheckCircle2 className="w-4 h-4 text-indigo-600" />
Meta Token Validation Status
</h3>
<p className="text-xs text-gray-500 dark:text-gray-400 mb-4">
Real-time inspection of token permissions, authenticated user profile, and linked Ad Account.
</p>
{testResult ? (
<div className="space-y-3">
<div className="p-3 rounded-lg bg-indigo-50 dark:bg-indigo-950/40 border border-indigo-100 dark:border-indigo-900/30">
<span className="text-[11px] font-semibold text-indigo-800 dark:text-indigo-300 uppercase">
Authenticated User
</span>
<p className="text-sm font-bold text-gray-900 dark:text-white mt-0.5">
{testResult.user?.name || 'Verified App User'}
</p>
<p className="text-xs font-mono text-gray-500">ID: {testResult.user?.id}</p>
</div>
{testResult.ad_account && (
<div className="p-3 rounded-lg bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 space-y-1 text-xs">
<span className="font-semibold text-gray-700 dark:text-gray-300 uppercase">
Ad Account Details
</span>
<p className="font-medium text-gray-900 dark:text-white">{testResult.ad_account.name}</p>
<div className="flex justify-between text-gray-600 dark:text-gray-400">
<span>Status:</span>
<span className="font-semibold text-emerald-600">Active</span>
</div>
<div className="flex justify-between text-gray-600 dark:text-gray-400">
<span>Currency:</span>
<span className="font-mono">{testResult.ad_account.currency || 'INR'}</span>
</div>
</div>
)}
</div>
) : (
<div className="p-6 border-2 border-dashed border-gray-200 dark:border-gray-800 rounded-xl text-center space-y-2">
<Share2 className="w-8 h-8 text-indigo-400 mx-auto" />
<p className="text-xs text-gray-500">
Click &quot;Test Graph API Token&quot; to perform live handshake with Meta Graph API v22.0.
</p>
</div>
)}
</div>
<div className="mt-6 pt-4 border-t border-gray-100 dark:border-gray-800 text-xs text-gray-500">
Graph Base: <code className="font-mono text-indigo-600">https://graph.facebook.com/v22.0</code>
</div>
</div>
</div>
</div>
);
}

View file

@ -0,0 +1,350 @@
'use client';
import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import {
MessageSquare,
Mail,
BarChart3,
Share2,
PhoneCall,
Truck,
CheckCircle2,
AlertCircle,
RefreshCw,
ExternalLink,
ShieldCheck,
ArrowRight,
Server,
Zap,
} from 'lucide-react';
import { toast } from 'sonner';
import { IntegrationsHeaderNav } from '@/components/integrations/IntegrationsHeaderNav';
import { integrationService, IntegrationOverview } from '@/services/api/integrationService';
export default function IntegrationsOverviewPage() {
const [data, setData] = useState<IntegrationOverview | null>(null);
const [loading, setLoading] = useState<boolean>(true);
const [refreshing, setRefreshing] = useState<boolean>(false);
const fetchOverview = async (showToast = false) => {
try {
if (showToast) setRefreshing(true);
const res = await integrationService.getOverview();
setData(res);
if (showToast) toast.success('Integration states refreshed successfully');
} catch (err: any) {
toast.error(err.message || 'Failed to fetch integrations overview');
} finally {
setLoading(false);
setRefreshing(false);
}
};
useEffect(() => {
fetchOverview();
}, []);
const getSourceBadge = (source?: string) => {
if (source === 'config.py') {
return (
<span className="inline-flex items-center gap-1 rounded-full bg-blue-50 dark:bg-blue-950/50 px-2.5 py-0.5 text-xs font-semibold text-blue-700 dark:text-blue-300 border border-blue-200 dark:border-blue-800">
<ShieldCheck className="w-3 h-3 text-blue-600 dark:text-blue-400" />
Primary (Config.py)
</span>
);
}
if (source === 'database') {
return (
<span className="inline-flex items-center gap-1 rounded-full bg-purple-50 dark:bg-purple-950/50 px-2.5 py-0.5 text-xs font-semibold text-purple-700 dark:text-purple-300 border border-purple-200 dark:border-purple-800">
<Server className="w-3 h-3 text-purple-600 dark:text-purple-400" />
Database Fallback
</span>
);
}
return (
<span className="inline-flex items-center gap-1 rounded-full bg-gray-100 dark:bg-gray-800 px-2.5 py-0.5 text-xs font-medium text-gray-600 dark:text-gray-400">
Unconfigured
</span>
);
};
const getStatusBadge = (status: string) => {
const s = status.toUpperCase();
if (s === 'CONNECTED' || s === 'QR_READY' || s === 'AUTHENTICATED') {
return (
<span className="inline-flex items-center gap-1.5 rounded-full bg-emerald-50 dark:bg-emerald-950/50 px-2.5 py-0.5 text-xs font-semibold text-emerald-700 dark:text-emerald-300 border border-emerald-200 dark:border-emerald-800">
<span className="h-1.5 w-1.5 rounded-full bg-emerald-500 animate-pulse" />
{status === 'QR_READY' ? 'Ready for QR Scan' : status}
</span>
);
}
return (
<span className="inline-flex items-center gap-1.5 rounded-full bg-amber-50 dark:bg-amber-950/50 px-2.5 py-0.5 text-xs font-semibold text-amber-700 dark:text-amber-300 border border-amber-200 dark:border-amber-800">
<span className="h-1.5 w-1.5 rounded-full bg-amber-500" />
{status}
</span>
);
};
return (
<div className="p-6 max-w-7xl mx-auto space-y-6">
<IntegrationsHeaderNav activeTab="overview" />
{/* Summary Banner */}
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 p-5 rounded-xl bg-gradient-to-r from-blue-900/10 via-indigo-900/10 to-transparent border border-blue-100 dark:border-blue-900/30">
<div>
<h2 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2">
<Zap className="w-5 h-5 text-blue-600 dark:text-blue-400" />
Configured Microservices & Gateways
</h2>
<p className="text-sm text-gray-600 dark:text-gray-400 mt-0.5">
Real-time status of production telephony, customer communication channels, email providers, and logistics.
</p>
</div>
<button
onClick={() => fetchOverview(true)}
disabled={refreshing}
className="inline-flex items-center gap-2 px-3.5 py-2 text-sm font-medium rounded-lg bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700 shadow-sm transition"
>
<RefreshCw className={`w-4 h-4 ${refreshing ? 'animate-spin' : ''}`} />
Refresh Status
</button>
</div>
{loading ? (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{[1, 2, 3, 4, 5, 6].map((i) => (
<div key={i} className="h-48 rounded-xl bg-gray-100 dark:bg-gray-800 animate-pulse border border-gray-200 dark:border-gray-700" />
))}
</div>
) : !data ? (
<div className="p-8 text-center text-gray-500">No integration data available.</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{/* 1. Internal WhatsApp (OpenWA) */}
<div className="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-5 shadow-sm hover:shadow-md transition flex flex-col justify-between">
<div>
<div className="flex items-start justify-between">
<div className="p-2.5 rounded-lg bg-emerald-50 dark:bg-emerald-950/50 text-emerald-600 dark:text-emerald-400 border border-emerald-100 dark:border-emerald-900/30">
<MessageSquare className="w-6 h-6" />
</div>
{getStatusBadge(data.whatsapp_internal.status)}
</div>
<div className="mt-4">
<h3 className="font-semibold text-gray-900 dark:text-white">Internal WhatsApp (OpenWA)</h3>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
Local Gateway on port 8088. Embedded real-time QR scanner for internal staff.
</p>
{data.whatsapp_internal.phone && (
<p className="text-xs font-mono text-emerald-600 dark:text-emerald-400 mt-2">
+{data.whatsapp_internal.phone} ({data.whatsapp_internal.push_name || 'Staff'})
</p>
)}
</div>
</div>
<div className="mt-5 pt-4 border-t border-gray-100 dark:border-gray-800 flex items-center justify-between">
{getSourceBadge(data.whatsapp_internal.source)}
<Link
href="/integrations/whatsapp"
className="inline-flex items-center gap-1 text-xs font-semibold text-blue-600 hover:text-blue-700 dark:text-blue-400"
>
Open Scanner <ArrowRight className="w-3.5 h-3.5" />
</Link>
</div>
</div>
{/* 2. External WhatsApp (WATI) */}
<div className="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-5 shadow-sm hover:shadow-md transition flex flex-col justify-between">
<div>
<div className="flex items-start justify-between">
<div className="p-2.5 rounded-lg bg-green-50 dark:bg-green-950/50 text-green-600 dark:text-green-400 border border-green-100 dark:border-green-900/30">
<MessageSquare className="w-6 h-6" />
</div>
{getStatusBadge(data.whatsapp_customer.status)}
</div>
<div className="mt-4">
<h3 className="font-semibold text-gray-900 dark:text-white">Customer WhatsApp (WATI)</h3>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
External customer communications, verified template delivery, and broadcast sync.
</p>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-2 truncate">
Endpoint: {data.whatsapp_customer.endpoint || 'https://live-mt-server.wati.io'}
</p>
</div>
</div>
<div className="mt-5 pt-4 border-t border-gray-100 dark:border-gray-800 flex items-center justify-between">
{getSourceBadge(data.whatsapp_customer.source)}
<Link
href="/integrations/whatsapp?tab=wati"
className="inline-flex items-center gap-1 text-xs font-semibold text-blue-600 hover:text-blue-700 dark:text-blue-400"
>
Configure WATI <ArrowRight className="w-3.5 h-3.5" />
</Link>
</div>
</div>
{/* 3. Email (ZeptoMail / SMTP) */}
<div className="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-5 shadow-sm hover:shadow-md transition flex flex-col justify-between">
<div>
<div className="flex items-start justify-between">
<div className="p-2.5 rounded-lg bg-sky-50 dark:bg-sky-950/50 text-sky-600 dark:text-sky-400 border border-sky-100 dark:border-sky-900/30">
<Mail className="w-6 h-6" />
</div>
{getStatusBadge(data.email.status)}
</div>
<div className="mt-4">
<h3 className="font-semibold text-gray-900 dark:text-white">Transactional Email</h3>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
Active Provider: <span className="font-medium text-gray-800 dark:text-gray-200">{data.email.provider}</span>
</p>
{data.email.sender && (
<p className="text-xs font-mono text-gray-600 dark:text-gray-300 mt-2 truncate">
Sender: {data.email.sender}
</p>
)}
</div>
</div>
<div className="mt-5 pt-4 border-t border-gray-100 dark:border-gray-800 flex items-center justify-between">
{getSourceBadge(data.email.source)}
<Link
href="/integrations/email"
className="inline-flex items-center gap-1 text-xs font-semibold text-blue-600 hover:text-blue-700 dark:text-blue-400"
>
Manage Email <ArrowRight className="w-3.5 h-3.5" />
</Link>
</div>
</div>
{/* 4. Google Analytics GA4 */}
<div className="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-5 shadow-sm hover:shadow-md transition flex flex-col justify-between">
<div>
<div className="flex items-start justify-between">
<div className="p-2.5 rounded-lg bg-amber-50 dark:bg-amber-950/50 text-amber-600 dark:text-amber-400 border border-amber-100 dark:border-amber-900/30">
<BarChart3 className="w-6 h-6" />
</div>
{getStatusBadge(data.google_analytics.status)}
</div>
<div className="mt-4">
<h3 className="font-semibold text-gray-900 dark:text-white">Google Analytics GA4</h3>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
Real-time storefront telemetry, visitor channels, and Google Data API synchronization.
</p>
{data.google_analytics.property_id && (
<p className="text-xs font-mono text-amber-700 dark:text-amber-300 mt-2">
Property: {data.google_analytics.property_id}
</p>
)}
</div>
</div>
<div className="mt-5 pt-4 border-t border-gray-100 dark:border-gray-800 flex items-center justify-between">
{getSourceBadge(data.google_analytics.source)}
<Link
href="/integrations/google-analytics"
className="inline-flex items-center gap-1 text-xs font-semibold text-blue-600 hover:text-blue-700 dark:text-blue-400"
>
View Telemetry <ArrowRight className="w-3.5 h-3.5" />
</Link>
</div>
</div>
{/* 5. Meta Ads & Graph API */}
<div className="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-5 shadow-sm hover:shadow-md transition flex flex-col justify-between">
<div>
<div className="flex items-start justify-between">
<div className="p-2.5 rounded-lg bg-indigo-50 dark:bg-indigo-950/50 text-indigo-600 dark:text-indigo-400 border border-indigo-100 dark:border-indigo-900/30">
<Share2 className="w-6 h-6" />
</div>
{getStatusBadge(data.meta_ads.status)}
</div>
<div className="mt-4">
<h3 className="font-semibold text-gray-900 dark:text-white">Meta Ads & Graph API</h3>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
Facebook & Instagram Graph v22.0, Ad Account sync, and lead ingestion.
</p>
{data.meta_ads.ad_account_id && (
<p className="text-xs font-mono text-indigo-600 dark:text-indigo-400 mt-2 truncate">
Ad Account: {data.meta_ads.ad_account_id}
</p>
)}
</div>
</div>
<div className="mt-5 pt-4 border-t border-gray-100 dark:border-gray-800 flex items-center justify-between">
{getSourceBadge(data.meta_ads.source)}
<Link
href="/integrations/meta-ads"
className="inline-flex items-center gap-1 text-xs font-semibold text-blue-600 hover:text-blue-700 dark:text-blue-400"
>
Configure Meta <ArrowRight className="w-3.5 h-3.5" />
</Link>
</div>
</div>
{/* 6. Knowlarity Cloud Telephony */}
<div className="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-5 shadow-sm hover:shadow-md transition flex flex-col justify-between">
<div>
<div className="flex items-start justify-between">
<div className="p-2.5 rounded-lg bg-rose-50 dark:bg-rose-950/50 text-rose-600 dark:text-rose-400 border border-rose-100 dark:border-rose-900/30">
<PhoneCall className="w-6 h-6" />
</div>
{getStatusBadge(data.knowlarity.status)}
</div>
<div className="mt-4">
<h3 className="font-semibold text-gray-900 dark:text-white">Knowlarity Telephony</h3>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
SuperReceptionist virtual IVR numbers, agent click-to-call, and call audit logs.
</p>
{data.knowlarity.virtual_number && (
<p className="text-xs font-mono text-rose-600 dark:text-rose-400 mt-2">
SR Number: {data.knowlarity.virtual_number}
</p>
)}
</div>
</div>
<div className="mt-5 pt-4 border-t border-gray-100 dark:border-gray-800 flex items-center justify-between">
{getSourceBadge(data.knowlarity.source)}
<Link
href="/integrations/call"
className="inline-flex items-center gap-1 text-xs font-semibold text-blue-600 hover:text-blue-700 dark:text-blue-400"
>
Open Dialer & Logs <ArrowRight className="w-3.5 h-3.5" />
</Link>
</div>
</div>
{/* 7. Shiprocket Logistics */}
<div className="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-5 shadow-sm hover:shadow-md transition flex flex-col justify-between">
<div>
<div className="flex items-start justify-between">
<div className="p-2.5 rounded-lg bg-purple-50 dark:bg-purple-950/50 text-purple-600 dark:text-purple-400 border border-purple-100 dark:border-purple-900/30">
<Truck className="w-6 h-6" />
</div>
{getStatusBadge(data.shiprocket.status)}
</div>
<div className="mt-4">
<h3 className="font-semibold text-gray-900 dark:text-white">Shiprocket Logistics</h3>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
Multi-courier shipping, automated label generation, and pincode serviceability calculator.
</p>
{data.shiprocket.pickup_location && (
<p className="text-xs font-mono text-purple-600 dark:text-purple-400 mt-2 truncate">
Hub: {data.shiprocket.pickup_location}
</p>
)}
</div>
</div>
<div className="mt-5 pt-4 border-t border-gray-100 dark:border-gray-800 flex items-center justify-between">
{getSourceBadge(data.shiprocket.source)}
<Link
href="/integrations/shipping"
className="inline-flex items-center gap-1 text-xs font-semibold text-blue-600 hover:text-blue-700 dark:text-blue-400"
>
Logistics & Pincode <ArrowRight className="w-3.5 h-3.5" />
</Link>
</div>
</div>
</div>
)}
</div>
);
}

View file

@ -0,0 +1,396 @@
'use client';
import React, { useState, useEffect } from 'react';
import {
Truck,
ShieldCheck,
Server,
Lock,
RefreshCw,
CheckCircle2,
AlertCircle,
MapPin,
Package,
DollarSign,
Key,
Calendar,
} from 'lucide-react';
import { toast } from 'sonner';
import { IntegrationsHeaderNav } from '@/components/integrations/IntegrationsHeaderNav';
import { integrationService } from '@/services/api/integrationService';
export default function ShippingIntegrationsPage() {
const [creds, setCreds] = useState<any>({
email: '',
pickup_location: 'Primary',
pickup_pin: '',
api_url: 'https://apiv2.shiprocket.in/v1/external',
source: 'unconfigured',
is_locked_by_config: false,
});
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
// Auth test
const [authEmail, setAuthEmail] = useState('');
const [authPassword, setAuthPassword] = useState('');
const [authing, setAuthing] = useState(false);
// Serviceability check
const [pickupPin, setPickupPin] = useState('');
const [deliveryPin, setDeliveryPin] = useState('');
const [weight, setWeight] = useState(0.5);
const [isCod, setIsCod] = useState(false);
const [checkingService, setCheckingService] = useState(false);
const [serviceResults, setServiceResults] = useState<any[]>([]);
const fetchShippingConfig = async () => {
setLoading(true);
try {
const data = await integrationService.getShiprocketCredentials();
setCreds(data);
if (data.pickup_pin) setPickupPin(data.pickup_pin);
if (data.email) setAuthEmail(data.email);
} catch (err: any) {
toast.error('Failed to load Shiprocket credentials');
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchShippingConfig();
}, []);
const handleSave = async (e: React.FormEvent) => {
e.preventDefault();
setSaving(true);
try {
await integrationService.saveShiprocketCredentials(creds);
toast.success('Shiprocket credentials saved successfully');
} catch (err: any) {
toast.error(err.message || 'Failed to save Shiprocket credentials');
} finally {
setSaving(false);
}
};
const handleAuthTest = async (e: React.FormEvent) => {
e.preventDefault();
if (!authEmail.trim() || !authPassword.trim()) {
toast.error('Email and password are required for Shiprocket login');
return;
}
setAuthing(true);
try {
const res = await integrationService.authShiprocket({
email: authEmail.trim(),
password: authPassword.trim(),
});
if (res.status === 'SUCCESS') {
toast.success('Shiprocket Authentication Successful! Session token generated.');
} else {
toast.error(`Auth failed: ${res.detail || JSON.stringify(res)}`);
}
} catch (err: any) {
toast.error(err.message || 'Shiprocket authentication failed');
} finally {
setAuthing(false);
}
};
const handleCheckServiceability = async (e: React.FormEvent) => {
e.preventDefault();
if (!pickupPin.trim() || !deliveryPin.trim()) {
toast.error('Both Pickup and Delivery Pincodes are required');
return;
}
setCheckingService(true);
try {
const res = await integrationService.checkShiprocketServiceability({
pickup_pin: pickupPin.trim(),
delivery_pin: deliveryPin.trim(),
weight,
cod: isCod,
});
if (res.status === 'SUCCESS') {
const couriers = res.data?.data?.available_courier_companies || [];
setServiceResults(couriers);
toast.success(`Serviceability confirmed! ${couriers.length} couriers available.`);
} else {
toast.error(`Serviceability check failed: ${res.detail || 'Pincode not serviceable'}`);
}
} catch (err: any) {
toast.error(err.message || 'Courier serviceability check failed');
} finally {
setCheckingService(false);
}
};
return (
<div className="p-6 max-w-7xl mx-auto space-y-6">
<IntegrationsHeaderNav activeTab="shipping" />
{/* Top Banner */}
<div className="p-4 rounded-xl bg-purple-50 dark:bg-purple-950/30 border border-purple-200 dark:border-purple-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-purple-900 dark:text-purple-100 flex items-center gap-2">
<Truck className="w-4 h-4 text-purple-600" />
Shiprocket Logistics & Courier Partner Integration
</h2>
<p className="text-xs text-purple-700 dark:text-purple-300 mt-0.5">
Automated courier rate comparison, pickup dispatch, label printing, and real-time pincode serviceability calculator.
</p>
</div>
{creds.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 Form (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">
<div className="flex items-center justify-between mb-4">
<h3 className="font-semibold text-gray-900 dark:text-white flex items-center gap-2">
<Key className="w-4 h-4 text-purple-600" />
Shiprocket Logistics Settings
</h3>
</div>
<form onSubmit={handleSave} className="space-y-4">
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Shiprocket Account Email
</label>
<input
type="email"
disabled={creds.is_locked_by_config}
value={creds.email || ''}
onChange={(e) => setCreds({ ...creds, email: 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 focus:ring-2 focus:ring-purple-500 focus:outline-none"
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Primary Pickup Hub
</label>
<input
type="text"
disabled={creds.is_locked_by_config}
value={creds.pickup_location || 'Primary'}
onChange={(e) => setCreds({ ...creds, pickup_location: 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 focus:ring-2 focus:ring-purple-500 focus:outline-none"
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Warehouse Pincode
</label>
<input
type="text"
disabled={creds.is_locked_by_config}
value={creds.pickup_pin || ''}
onChange={(e) => setCreds({ ...creds, pickup_pin: e.target.value })}
placeholder="e.g. 600001"
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 focus:ring-2 focus:ring-purple-500 focus:outline-none"
/>
</div>
</div>
{!creds.is_locked_by_config && (
<button
type="submit"
disabled={saving}
className="w-full py-2.5 px-4 rounded-lg bg-purple-600 hover:bg-purple-700 text-white text-xs font-semibold shadow-sm transition"
>
{saving ? 'Saving...' : 'Save Shiprocket Settings'}
</button>
)}
</form>
{/* Quick Login Authenticator */}
<div className="mt-6 pt-5 border-t border-gray-100 dark:border-gray-800">
<h4 className="text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-2">
Refresh Authentication Token
</h4>
<form onSubmit={handleAuthTest} className="space-y-3">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<input
type="email"
placeholder="Account email"
value={authEmail}
onChange={(e) => setAuthEmail(e.target.value)}
className="w-full px-3 py-1.5 text-xs rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
/>
<input
type="password"
placeholder="Account password"
value={authPassword}
onChange={(e) => setAuthPassword(e.target.value)}
className="w-full px-3 py-1.5 text-xs rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
/>
</div>
<button
type="submit"
disabled={authing}
className="w-full py-2 px-3 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 ${authing ? 'animate-spin' : ''}`} />
{authing ? 'Authenticating...' : 'Authenticate & Generate Token'}
</button>
</form>
</div>
</div>
{/* Real-time Courier Serviceability Checker (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 flex flex-col justify-between">
<div>
<h3 className="font-semibold text-gray-900 dark:text-white flex items-center gap-2 mb-2">
<MapPin className="w-4 h-4 text-purple-600" />
Pincode Serviceability & Rate Calculator
</h3>
<p className="text-xs text-gray-500 dark:text-gray-400 mb-4">
Check real-time courier partner availability, estimated delivery days, and freight tariffs.
</p>
<form onSubmit={handleCheckServiceability} className="space-y-4">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Pickup Pincode
</label>
<input
type="text"
value={pickupPin}
onChange={(e) => setPickupPin(e.target.value)}
placeholder="e.g. 600001"
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-purple-500 focus:outline-none"
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Destination Pincode
</label>
<input
type="text"
value={deliveryPin}
onChange={(e) => setDeliveryPin(e.target.value)}
placeholder="e.g. 560001"
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-purple-500 focus:outline-none"
/>
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 items-center">
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Weight (kg)
</label>
<input
type="number"
step="0.1"
value={weight}
onChange={(e) => setWeight(parseFloat(e.target.value) || 0.5)}
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-purple-500 focus:outline-none"
/>
</div>
<div className="pt-4">
<label className="flex items-center gap-2 cursor-pointer text-xs font-medium text-gray-700 dark:text-gray-300">
<input
type="checkbox"
checked={isCod}
onChange={(e) => setIsCod(e.target.checked)}
className="rounded border-gray-300 text-purple-600 focus:ring-purple-500 w-4 h-4"
/>
Cash On Delivery (COD)
</label>
</div>
</div>
<button
type="submit"
disabled={checkingService}
className="w-full py-2.5 px-4 rounded-lg bg-purple-600 hover:bg-purple-700 text-white text-xs font-semibold shadow-sm transition flex items-center justify-center gap-2"
>
<Truck className={`w-3.5 h-3.5 ${checkingService ? 'animate-bounce' : ''}`} />
{checkingService ? 'Checking Couriers...' : 'Calculate Serviceability'}
</button>
</form>
</div>
<div className="mt-6 pt-4 border-t border-gray-100 dark:border-gray-800 text-xs text-gray-500">
Couriers: Bluedart, Delhivery, Ekart, DTDC, Shadowfax
</div>
</div>
</div>
{/* Available Couriers Table */}
{serviceResults.length > 0 && (
<div className="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">
<CheckCircle2 className="w-4 h-4 text-emerald-600" />
Available Courier Partners ({serviceResults.length})
</h3>
<div className="overflow-x-auto">
<table className="w-full text-left text-xs">
<thead className="bg-gray-50 dark:bg-gray-800/50 text-gray-500 uppercase font-medium border-y border-gray-100 dark:border-gray-800">
<tr>
<th className="py-2.5 px-3">Courier Name</th>
<th className="py-2.5 px-3">Estimated Delivery</th>
<th className="py-2.5 px-3">Rating</th>
<th className="py-2.5 px-3">Freight Charge</th>
<th className="py-2.5 px-3">COD Eligible</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100 dark:divide-gray-800">
{serviceResults.map((c: any, idx: number) => (
<tr key={idx} className="hover:bg-gray-50 dark:hover:bg-gray-800/50">
<td className="py-2.5 px-3 font-semibold text-gray-900 dark:text-white">
{c.courier_name || 'Standard Courier'}
</td>
<td className="py-2.5 px-3 text-gray-600 dark:text-gray-300">
{c.estimated_delivery_days ? `${c.estimated_delivery_days} Days` : '2-4 Days'}
</td>
<td className="py-2.5 px-3">
<span className="inline-flex px-2 py-0.5 rounded text-[10px] font-semibold bg-amber-100 dark:bg-amber-950 text-amber-800 dark:text-amber-300">
★ {c.rating || '4.5'}
</span>
</td>
<td className="py-2.5 px-3 font-mono font-medium text-emerald-600 dark:text-emerald-400">
₹{c.rate || c.freight_charge || '60'}
</td>
<td className="py-2.5 px-3">
<span
className={`inline-flex px-2 py-0.5 rounded-full text-[10px] font-semibold ${
c.cod === 1 || c.is_cod
? 'bg-emerald-100 dark:bg-emerald-950 text-emerald-800 dark:text-emerald-300'
: 'bg-gray-100 dark:bg-gray-800 text-gray-500'
}`}
>
{c.cod === 1 || c.is_cod ? 'Yes' : 'Prepaid Only'}
</span>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
</div>
);
}

View file

@ -0,0 +1,571 @@
'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>
);
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,126 @@
'use client';
import React from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import {
Layers,
MessageSquare,
Mail,
BarChart3,
Share2,
PhoneCall,
Truck,
CheckCircle2,
AlertCircle
} from 'lucide-react';
interface IntegrationsHeaderNavProps {
activeTab?: string;
badgeCounts?: Record<string, string>;
}
export const IntegrationsHeaderNav: React.FC<IntegrationsHeaderNavProps> = ({ activeTab }) => {
const pathname = usePathname();
const tabs = [
{
id: 'overview',
name: 'All Integrations',
href: '/integrations',
icon: Layers,
match: pathname === '/integrations',
},
{
id: 'whatsapp',
name: 'WhatsApp Hub',
description: 'OpenWA QR & WATI',
href: '/integrations/whatsapp',
icon: MessageSquare,
match: pathname.startsWith('/integrations/whatsapp'),
},
{
id: 'email',
name: 'Email Dispatcher',
description: 'ZeptoMail & SMTP',
href: '/integrations/email',
icon: Mail,
match: pathname.startsWith('/integrations/email'),
},
{
id: 'google-analytics',
name: 'Google Analytics GA4',
description: 'Live Telemetry',
href: '/integrations/google-analytics',
icon: BarChart3,
match: pathname.startsWith('/integrations/google-analytics') || pathname.startsWith('/analytics/google'),
},
{
id: 'meta-ads',
name: 'Meta Ads & Graph',
description: 'FB / IG Graph API',
href: '/integrations/meta-ads',
icon: Share2,
match: pathname.startsWith('/integrations/meta-ads'),
},
{
id: 'call',
name: 'Knowlarity Telephony',
description: 'Virtual IVR & Calls',
href: '/integrations/call',
icon: PhoneCall,
match: pathname.startsWith('/integrations/call'),
},
{
id: 'shipping',
name: 'Shiprocket Logistics',
description: 'Courier & Serviceability',
href: '/integrations/shipping',
icon: Truck,
match: pathname.startsWith('/integrations/shipping'),
},
];
return (
<div className="mb-6 space-y-4">
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4 border-b border-gray-200 dark:border-gray-800 pb-4">
<div>
<div className="flex items-center gap-2">
<h1 className="text-2xl font-bold tracking-tight text-gray-900 dark:text-white">
Enterprise Integrations Hub
</h1>
<span className="inline-flex items-center gap-1 rounded-full bg-emerald-50 px-2 py-0.5 text-xs font-medium text-emerald-700 dark:bg-emerald-950 dark:text-emerald-300 border border-emerald-200 dark:border-emerald-800">
<CheckCircle2 className="w-3 h-3 text-emerald-500" />
Live Active
</span>
</div>
<p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
Centralized microservice connections, credential synchronization, and direct gateway actions.
</p>
</div>
</div>
{/* Tabs navigation */}
<div className="flex items-center gap-2 overflow-x-auto pb-2 scrollbar-none border-b border-gray-100 dark:border-gray-800">
{tabs.map((tab) => {
const Icon = tab.icon;
const isActive = tab.match || activeTab === tab.id;
return (
<Link
key={tab.id}
href={tab.href}
className={`flex items-center gap-2.5 px-4 py-2.5 rounded-lg text-sm font-medium transition-all whitespace-nowrap ${
isActive
? 'bg-blue-600 text-white shadow-sm shadow-blue-500/20'
: 'text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white hover:bg-gray-100 dark:hover:bg-gray-800'
}`}
>
<Icon className={`w-4 h-4 ${isActive ? 'text-white' : 'text-gray-500 dark:text-gray-400'}`} />
<span>{tab.name}</span>
</Link>
);
})}
</div>
</div>
);
};

View file

@ -18,6 +18,7 @@ import {
Receipt, Receipt,
BarChart3, BarChart3,
FileSpreadsheet, FileSpreadsheet,
Layers,
} from 'lucide-react'; } from 'lucide-react';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
@ -132,6 +133,7 @@ const NAV_GROUPS: NavGroup[] = [
name: 'Reports & Intelligence', name: 'Reports & Intelligence',
icon: FileSpreadsheet, icon: FileSpreadsheet,
children: [ children: [
{ name: 'AI Prediction Lab (Swarm)', href: '/simulation' },
{ name: 'Reporting Hub (Export)', href: '/reports' }, { name: 'Reporting Hub (Export)', href: '/reports' },
{ name: 'Google Analytics 4', href: '/analytics/google' }, { name: 'Google Analytics 4', href: '/analytics/google' },
{ name: 'Razorpay Ledger', href: '/razorpay-dashboard' }, { name: 'Razorpay Ledger', href: '/razorpay-dashboard' },
@ -149,6 +151,19 @@ const NAV_GROUPS: NavGroup[] = [
{ name: 'User Activity Logs', href: '/activity-logs' }, { name: 'User Activity Logs', href: '/activity-logs' },
], ],
}, },
{
name: 'Integrations Hub',
icon: Layers,
children: [
{ name: 'All Integrations', href: '/integrations' },
{ name: 'WhatsApp Hub (OpenWA & WATI)', href: '/integrations/whatsapp' },
{ name: 'Transactional Email', href: '/integrations/email' },
{ name: 'Google Analytics GA4', href: '/integrations/google-analytics' },
{ name: 'Meta Ads & Graph API', href: '/integrations/meta-ads' },
{ name: 'Knowlarity Telephony', href: '/integrations/call' },
{ name: 'Shiprocket Logistics', href: '/integrations/shipping' },
],
},
{ {
name: 'System Infrastructure', name: 'System Infrastructure',
icon: Shield, icon: Shield,
@ -164,6 +179,8 @@ const NAV_GROUPS: NavGroup[] = [
function pathMatches(href: string, pathname: string) { function pathMatches(href: string, pathname: string) {
if (pathname === href) return true; if (pathname === href) return true;
if (href === '/integrations' && pathname === '/integrations') return true;
if (href.startsWith('/integrations/') && pathname.startsWith(href)) return true;
if (href === '/products' && pathname.startsWith('/products/') && pathname !== '/products/dashboard') { if (href === '/products' && pathname.startsWith('/products/') && pathname !== '/products/dashboard') {
return true; return true;
} }

View file

@ -66,7 +66,7 @@ export function isRouteAllowed(pathname: string, userRole?: string | null): bool
pathname.startsWith('/razorpay-dashboard') || pathname.startsWith('/razorpay-dashboard') ||
pathname.startsWith('/logistics') pathname.startsWith('/logistics')
) return true; ) return true;
if (pathname.startsWith('/reports')) return true; if (pathname.startsWith('/reports') || pathname.startsWith('/simulation')) return true;
return false; return false;
} }

View file

@ -0,0 +1,257 @@
import { apiFetch } from './client';
export interface IntegrationOverview {
whatsapp_internal: {
name: string;
channel: string;
status: string;
phone?: string | null;
push_name?: string | null;
gateway_url: string;
source: string;
};
whatsapp_customer: {
name: string;
channel: string;
status: string;
source: string;
endpoint?: string;
};
email: {
name: string;
provider: string;
status: string;
sender?: string;
source: string;
};
meta_ads: {
name: string;
status: string;
app_id?: string;
ad_account_id?: string;
page_id?: string;
source: string;
};
google_analytics: {
name: string;
status: string;
property_id?: string;
source: string;
};
knowlarity: {
name: string;
status: string;
virtual_number?: string;
source: string;
};
shiprocket: {
name: string;
status: string;
source: string;
pickup_location?: string;
};
}
export const integrationService = {
// Overview
getOverview: async (): Promise<IntegrationOverview> => {
return apiFetch<IntegrationOverview>('/api/v1/integrations/overview');
},
// 1. WhatsApp Internal (OpenWA)
getWhatsappQr: async () => {
return apiFetch<{
status: string;
session_id?: string;
qr_code?: string | null;
phone?: string | null;
push_name?: string | null;
connected_at?: string | null;
message?: string;
}>('/api/v1/integrations/whatsapp/qr');
},
sendWhatsappTest: async (phone: string, message: string) => {
return apiFetch<any>('/api/v1/integrations/whatsapp/test-send', {
method: 'POST',
body: JSON.stringify({ phone, message }),
});
},
restartWhatsappSession: async () => {
return apiFetch<any>('/api/v1/integrations/whatsapp/restart', {
method: 'POST',
});
},
// 2. Customer WhatsApp (WATI)
getWatiCredentials: async () => {
return apiFetch<{
api_endpoint: string;
api_token: string;
source: string;
is_locked_by_config: boolean;
}>('/api/v1/integrations/wati/credentials');
},
saveWatiCredentials: async (payload: { api_endpoint: string; api_token: string }) => {
return apiFetch<any>('/api/v1/integrations/wati/credentials', {
method: 'PUT',
body: JSON.stringify(payload),
});
},
testWatiConnection: async (payload: { api_endpoint: string; api_token: string }) => {
return apiFetch<{
status: string;
templates_count?: number;
templates?: any[];
detail?: string;
status_code?: number;
}>('/api/v1/integrations/wati/test', {
method: 'POST',
body: JSON.stringify(payload),
});
},
getWatiTemplates: async () => {
return apiFetch<{ status: string; templates: any[] }>('/api/v1/integrations/wati/templates');
},
sendWatiTemplate: async (payload: {
phone: string;
template_name: string;
broadcast_name?: string;
parameters?: any[];
}) => {
return apiFetch<any>('/api/v1/integrations/wati/send-template', {
method: 'POST',
body: JSON.stringify(payload),
});
},
// 3. Email (ZeptoMail / SMTP)
getEmailCredentials: async () => {
return apiFetch<{
active_provider: string;
sender_email?: string;
sender_name?: string;
smtp_server?: string;
smtp_port?: number;
smtp_username?: string;
use_tls?: boolean;
source: string;
is_locked_by_config: boolean;
}>('/api/v1/integrations/email/credentials');
},
saveEmailCredentials: async (payload: any) => {
return apiFetch<any>('/api/v1/integrations/email/credentials', {
method: 'PUT',
body: JSON.stringify(payload),
});
},
sendTestEmail: async (payload: { recipient: string; subject?: string; body?: string }) => {
return apiFetch<any>('/api/v1/integrations/email/test', {
method: 'POST',
body: JSON.stringify(payload),
});
},
// 4. Meta Ads
getMetaCredentials: async () => {
return apiFetch<{
app_id?: string;
ad_account_id?: string;
page_id?: string;
instagram_id?: string;
access_token?: string;
source: string;
is_locked_by_config: boolean;
}>('/api/v1/integrations/meta/credentials');
},
saveMetaCredentials: async (payload: any) => {
return apiFetch<any>('/api/v1/integrations/meta/credentials', {
method: 'PUT',
body: JSON.stringify(payload),
});
},
testMetaConnection: async (payload: { access_token: string; ad_account_id?: string }) => {
return apiFetch<any>('/api/v1/integrations/meta/test', {
method: 'POST',
body: JSON.stringify(payload),
});
},
// 5. Knowlarity Telephony
getKnowlarityCredentials: async () => {
return apiFetch<{
api_key?: string;
authorization?: string;
virtual_number?: string;
call_url?: string;
log_url?: string;
source: string;
is_locked_by_config: boolean;
}>('/api/v1/integrations/call/credentials');
},
saveKnowlarityCredentials: async (payload: any) => {
return apiFetch<any>('/api/v1/integrations/call/credentials', {
method: 'PUT',
body: JSON.stringify(payload),
});
},
makeKnowlarityCall: async (payload: { agent_number: string; customer_number: string }) => {
return apiFetch<any>('/api/v1/integrations/call/make-call', {
method: 'POST',
body: JSON.stringify(payload),
});
},
getKnowlarityCallLogs: async (page = 1, limit = 20) => {
return apiFetch<any>(`/api/v1/integrations/call/logs?page=${page}&limit=${limit}`);
},
// 6. Shiprocket Logistics
getShiprocketCredentials: async () => {
return apiFetch<{
email?: string;
pickup_location?: string;
pickup_pin?: string;
api_url?: string;
source: string;
is_locked_by_config: boolean;
}>('/api/v1/integrations/shipping/credentials');
},
saveShiprocketCredentials: async (payload: any) => {
return apiFetch<any>('/api/v1/integrations/shipping/credentials', {
method: 'PUT',
body: JSON.stringify(payload),
});
},
authShiprocket: async (payload: { email: string; password: string }) => {
return apiFetch<any>('/api/v1/integrations/shipping/auth', {
method: 'POST',
body: JSON.stringify(payload),
});
},
checkShiprocketServiceability: async (payload: {
pickup_pin: string;
delivery_pin: string;
weight?: number;
cod?: boolean;
}) => {
return apiFetch<any>('/api/v1/integrations/shipping/serviceability', {
method: 'POST',
body: JSON.stringify(payload),
});
},
};

127
services/api/simulation.ts Normal file
View file

@ -0,0 +1,127 @@
import { apiFetch } from './client';
export interface ScenarioMeta {
title: string;
description: string;
default_params: Record<string, any>;
}
export interface ScenariosResponse {
available_scenarios: string[];
scenarios: Record<string, ScenarioMeta>;
max_concurrent_simulations: number;
job_timeout_seconds: number;
}
export interface SimulationJobSummary {
job_id: string;
scenario_type: string;
status: string;
store_id: number;
created_at: string;
execution_time_ms?: number;
total_cost_usd?: number;
}
export interface HistoricalBaseline {
historical_sample_size: number;
historical_mean: number;
historical_std: number;
empirical_95_ci_lower: number;
empirical_95_ci_upper: number;
baseline_source: string;
sampling_notice: string;
}
export interface SimulationDispersion {
agent_sample_count: number;
simulation_mean: number;
simulation_std: number;
agent_disagreement_index: number;
hypothesis_spread_label: string;
}
export interface CalibratedProjection {
point_estimate: number;
credible_range_lower: number;
credible_range_upper: number;
historical_weight: number;
simulation_weight: number;
epistemic_notice: string;
}
export interface AgentLog {
agent_id: string;
archetype: string;
device?: string;
price_sensitivity?: number;
simulated_purchase_prob?: number;
decision?: string;
reasoning?: string;
[key: string]: any;
}
export interface SimulationJobDetail {
id: string;
store_id: number;
user_id: number;
scenario_type: string;
status: 'QUEUED' | 'CLAIMED' | 'RUNNING' | 'COMPLETED' | 'FAILED' | 'FAILED_INTERRUPTED' | 'TIMED_OUT' | 'CANCELLED';
input_params: Record<string, any>;
historical_baseline?: HistoricalBaseline;
simulation_dispersion?: SimulationDispersion;
calibrated_projection?: CalibratedProjection;
summary_metrics?: Record<string, any>;
report_markdown?: string;
agent_logs?: AgentLog[];
error_message?: string;
execution_time_ms?: number;
prompt_tokens?: number;
completion_tokens?: number;
total_cost_usd?: number;
last_heartbeat_at?: string;
created_at: string;
started_at?: string;
completed_at?: string;
}
export interface PersonaInterviewResponse {
agent_id: string;
question: string;
response: string;
latency_ms: number;
}
export const simulationService = {
async getScenarios(): Promise<ScenariosResponse> {
return apiFetch<ScenariosResponse>('/api/v1/simulation/scenarios');
},
async runSimulation(scenario_type: string, input_params: Record<string, any>, store_id: number = 1): Promise<{ message: string; job_id: string; status: string; poll_url: string }> {
return apiFetch('/api/v1/simulation/scenarios/run', {
method: 'POST',
body: JSON.stringify({ scenario_type, input_params, store_id }),
});
},
async getJobDetail(job_id: string): Promise<SimulationJobDetail> {
return apiFetch<SimulationJobDetail>(`/api/v1/simulation/jobs/${job_id}`);
},
async listJobs(limit: number = 20): Promise<SimulationJobSummary[]> {
return apiFetch<SimulationJobSummary[]>(`/api/v1/simulation/jobs?limit=${limit}`);
},
async cancelJob(job_id: string): Promise<{ message: string; job_id: string; cancelled: boolean }> {
return apiFetch(`/api/v1/simulation/jobs/${job_id}/cancel`, {
method: 'POST',
});
},
async interviewPersona(job_id: string, agent_id: string, question: string): Promise<PersonaInterviewResponse> {
return apiFetch<PersonaInterviewResponse>(`/api/v1/simulation/jobs/${job_id}/interview`, {
method: 'POST',
body: JSON.stringify({ agent_id, question }),
});
},
};