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

375 lines
14 KiB
TypeScript

'use client';
import React, { useState, useEffect } from 'react';
import {
PhoneCall,
RefreshCw,
PhoneForwarded,
History,
Play,
Key,
} from 'lucide-react';
import { toast } from 'sonner';
import { IntegrationsHeaderNav } from '@/components/integrations/IntegrationsHeaderNav';
import { integrationService } from '@/services/api/integrationService';
const fieldClass =
'w-full h-9 px-3 bg-card border border-border crm-radius-control text-[13px] text-foreground focus:outline-none focus:border-primary disabled:opacity-60';
const areaClass =
'w-full px-3 py-2 bg-card border border-border crm-radius-control text-[13px] text-foreground focus:outline-none focus:border-primary disabled:opacity-60';
const primaryButton =
'inline-flex items-center justify-center gap-1.5 h-9 px-3 crm-radius-control bg-primary hover:bg-primary/90 text-white text-[13px] font-semibold cursor-pointer disabled:opacity-50';
const secondaryButton =
'inline-flex items-center justify-center gap-1.5 h-9 px-3 crm-radius-control border border-border bg-card text-foreground text-[13px] font-medium hover:bg-muted cursor-pointer disabled:opacity-50';
const shell =
'crm-radius-section border border-border bg-card shadow-[0_1px_3px_rgba(16,24,40,0.06)] min-w-0';
const labelClass = 'block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5';
export default function 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 [logsError, setLogsError] = 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);
setLogsError(false);
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);
setLogsError(true);
} 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="flex flex-col gap-5 min-w-0">
<div className="flex flex-wrap items-center justify-between gap-3">
<h1 className="text-lg font-semibold text-foreground">Knowlarity</h1>
<span className={`inline-flex items-center px-2.5 py-1 crm-radius-badge text-[11px] font-semibold ${creds.is_locked_by_config ? 'bg-primary/10 text-primary' : 'bg-muted text-foreground'}`}>
{creds.is_locked_by_config ? 'Config' : 'Database'}
</span>
</div>
<IntegrationsHeaderNav activeTab="call" />
<div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
{/* Credentials Form (Cols 1-7) */}
<div className={`${shell} p-4 lg:col-span-7`}>
<div className="flex items-center justify-between mb-4">
<h3 className="font-semibold text-foreground flex items-center gap-2">
<Key className="w-4 h-4 text-primary" />
SuperReceptionist Credentials
</h3>
</div>
<form onSubmit={handleSave} className="space-y-4">
<div>
<label className={labelClass}>
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="Number"
className={fieldClass}
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label className={labelClass}>
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={fieldClass}
/>
</div>
<div>
<label className={labelClass}>
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={fieldClass}
/>
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label className={labelClass}>
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={fieldClass}
/>
</div>
<div>
<label className={labelClass}>
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={fieldClass}
/>
</div>
</div>
{!creds.is_locked_by_config && (
<button
type="submit"
disabled={saving}
className={`${primaryButton} w-full`}
>
{saving ? 'Saving...' : 'Save Knowlarity Settings'}
</button>
)}
</form>
</div>
{/* Live Click-to-Call Dialer (Cols 8-12) */}
<div className={`${shell} p-4 lg:col-span-5 flex flex-col justify-between`}>
<div>
<h3 className="font-semibold text-foreground flex items-center gap-2 mb-4">
<PhoneForwarded className="w-4 h-4 text-primary" />
Agent Click-to-Call Bridge
</h3>
<form onSubmit={handleMakeCall} className="space-y-4">
<div>
<label className={labelClass}>
Agent Mobile Number (Rings First)
</label>
<input
type="text"
placeholder="Phone"
value={agentNumber}
onChange={(e) => setAgentNumber(e.target.value)}
className={fieldClass}
/>
</div>
<div>
<label className={labelClass}>
Customer Mobile Number (Rings Second)
</label>
<input
type="text"
placeholder="Phone"
value={customerNumber}
onChange={(e) => setCustomerNumber(e.target.value)}
className={fieldClass}
/>
</div>
<button
type="submit"
disabled={calling}
className={`${primaryButton} w-full`}
>
<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-border text-xs text-muted-foreground flex items-center justify-between">
<span>Virtual Number:</span>
<span className="font-mono text-primary font-semibold">{creds.virtual_number || '—'}</span>
</div>
</div>
</div>
{/* Call Logs Table */}
<div className={`${shell} p-4`}>
<div className="flex items-center justify-between mb-4">
<h3 className="font-semibold text-foreground flex items-center gap-2">
<History className="w-4 h-4 text-primary" />
Telephony Call Logs & Recordings
</h3>
<button
onClick={fetchLogs}
disabled={logsLoading}
className={secondaryButton}
>
<RefreshCw className={`w-3.5 h-3.5 ${logsLoading ? 'animate-spin' : ''}`} />
Refresh Logs
</button>
</div>
<div className="overflow-x-auto">
<table className="crm-data-table w-full text-left">
<thead className="bg-muted/40 text-muted-foreground uppercase font-medium border-y border-border">
<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-border">
{logsLoading ? (
<tr>
<td colSpan={6} className="py-8 text-center text-muted-foreground">
<RefreshCw className="w-4 h-4 animate-spin text-primary inline-block" />
</td>
</tr>
) : logsError ? (
<tr>
<td colSpan={6} className="py-8 text-center text-[13px] text-muted-foreground whitespace-normal">
Call logs could not be loaded.{' '}
<button type="button" onClick={fetchLogs} className="text-primary font-semibold cursor-pointer">Retry</button>
</td>
</tr>
) : logs.length === 0 ? (
<tr>
<td colSpan={6} className="py-8 text-center text-[13px] text-muted-foreground whitespace-normal">
No call logs recorded yet.
</td>
</tr>
) : (
logs.map((log: any, idx: number) => (
<tr key={idx} className="hover:bg-muted/40">
<td className="py-2.5 px-3 font-mono text-muted-foreground">
{log.start_time || log.call_date || '—'}
</td>
<td className="py-2.5 px-3 font-medium text-foreground">
{log.customer_number || log.caller_id || '-'}
</td>
<td className="py-2.5 px-3 text-muted-foreground">
{log.agent_number || log.destination || '-'}
</td>
<td className="py-2.5 px-3">
<span className="inline-flex px-2.5 py-1 crm-radius-badge text-[11px] font-semibold bg-muted text-foreground">
{log.status || log.call_type || '—'}
</span>
</td>
<td className="py-2.5 px-3 font-mono text-muted-foreground">
{log.duration ? `${log.duration}s` : '—'}
</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-primary font-semibold"
>
<Play className="w-3 h-3" /> Audio
</a>
) : (
<span className="text-muted-foreground">-</span>
)}
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
</div>
);
}