Files
Project_Velocity/app/src/components/modules/Comms.tsx
Sagnik 3623bacbac
Some checks failed
Production Readiness / backend-contracts (push) Failing after 1m58s
Production Readiness / webos-typecheck (push) Successful in 1m37s
Production Readiness / ipad-parse (push) Successful in 2m17s
feat: Whatsapp Integration
2026-04-28 13:41:14 +05:30

729 lines
30 KiB
TypeScript

import { useEffect, useRef, useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
MessageCircle,
Search,
Send,
Phone,
PhoneCall,
Paperclip,
MoreVertical,
Link as LinkIcon,
User,
Settings,
Bot,
AlertCircle,
CheckCheck,
Clock,
ChevronLeft,
Inbox,
Voicemail,
Plus,
Hash,
} from 'lucide-react';
import { useStore } from '@/store/useStore';
import {
fetchCommsThreads,
fetchCommsMessages,
sendCommsMessage,
linkCommsThreadToPerson,
fetchCommsSettings,
} from '@/lib/commsApi';
import type {
CommsThread,
CommsMessage,
CommsSettings,
SendMessagePayload,
} from '@/types/commsTypes';
/* ── Mock generators for demo / offline mode ─────────────────────────────── */
function generateMockThreads(): CommsThread[] {
const now = new Date().toISOString();
return [
{
threadId: 'mock-1',
phoneE164: '+919876543210',
displayName: 'Rahul Sharma',
channel: 'whatsapp',
status: 'open',
unreadCount: 2,
lastMessageAt: now,
lastMessagePreview: 'Is the 3BHK still available?',
provider: 'mock',
createdAt: now,
updatedAt: now,
crmPerson: {
id: 'p1',
fullName: 'Rahul Sharma',
primaryPhone: '+919876543210',
leadStatus: 'hot',
projectName: 'Atri Aqua',
},
},
{
threadId: 'mock-2',
phoneE164: '+919988776655',
displayName: 'Unknown Number',
channel: 'whatsapp',
status: 'open',
unreadCount: 1,
lastMessageAt: now,
lastMessagePreview: 'Send me the brochure please',
provider: 'mock',
createdAt: now,
updatedAt: now,
},
{
threadId: 'mock-3',
phoneE164: '+911122334455',
displayName: 'Priya Patel',
channel: 'call',
status: 'resolved',
unreadCount: 0,
lastMessageAt: now,
provider: 'mock',
createdAt: now,
updatedAt: now,
crmPerson: {
id: 'p2',
fullName: 'Priya Patel',
primaryPhone: '+911122334455',
leadStatus: 'qualified',
projectName: 'Godrej Elevate',
},
},
];
}
function generateMockMessages(threadId: string): CommsMessage[] {
const now = new Date();
const t1 = new Date(now.getTime() - 1000 * 60 * 60 * 2).toISOString();
const t2 = new Date(now.getTime() - 1000 * 60 * 30).toISOString();
const t3 = new Date(now.getTime() - 1000 * 60 * 5).toISOString();
if (threadId === 'mock-1') {
return [
{
messageId: 'm1',
threadId,
direction: 'inbound',
messageType: 'text',
body: 'Hi, I saw your listing for Atri Aqua. Is the 3BHK still available?',
deliveryStatus: 'read',
createdAt: t1,
provider: 'mock',
senderName: 'Rahul Sharma',
},
{
messageId: 'm2',
threadId,
direction: 'outbound',
messageType: 'text',
body: 'Yes sir, absolutely. We have a premium corner unit on the 12th floor with marina view.',
deliveryStatus: 'read',
createdAt: t2,
provider: 'mock',
},
{
messageId: 'm3',
threadId,
direction: 'inbound',
messageType: 'text',
body: 'What is the final price and can I schedule a visit this weekend?',
deliveryStatus: 'delivered',
createdAt: t3,
provider: 'mock',
senderName: 'Rahul Sharma',
},
];
}
if (threadId === 'mock-2') {
return [
{
messageId: 'm4',
threadId,
direction: 'inbound',
messageType: 'text',
body: 'Send me the brochure please',
deliveryStatus: 'delivered',
createdAt: t3,
provider: 'mock',
senderName: 'Unknown',
},
];
}
return [];
}
/* ── Component ───────────────────────────────────────────────────────────── */
export function Comms() {
useStore();
const [threads, setThreads] = useState<CommsThread[]>([]);
const [activeThreadId, setActiveThreadId] = useState<string | null>(null);
const [messages, setMessages] = useState<CommsMessage[]>([]);
const [settings, setSettings] = useState<CommsSettings | null>(null);
const [loading, setLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState('');
const [composerText, setComposerText] = useState('');
const [sending, setSending] = useState(false);
const [mockMode, setMockMode] = useState(false);
const [showCrmRail, setShowCrmRail] = useState(true);
const messagesEndRef = useRef<HTMLDivElement>(null);
const activeThread = threads.find((t) => t.threadId === activeThreadId) || null;
useEffect(() => { loadInitial(); }, []);
useEffect(() => { if (activeThreadId) loadMessages(activeThreadId); }, [activeThreadId]);
useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [messages]);
async function loadInitial() {
try {
setLoading(true);
const [threadsRes, settingsRes] = await Promise.all([
fetchCommsThreads({ limit: 50 }),
fetchCommsSettings().catch(() => null),
]);
setThreads(threadsRes.threads || []);
setSettings(settingsRes);
setMockMode(false);
} catch (e) {
console.warn('Comms backend unavailable, switching to mock mode', e);
setMockMode(true);
setThreads(generateMockThreads());
setSettings({
provider: 'mock',
webhookSecretSet: false,
autoLinkByPhone: false,
createCrmInteractionOnInbound: false,
defaultCountryCode: '91',
});
} finally {
setLoading(false);
}
}
async function loadMessages(threadId: string) {
try {
if (mockMode) {
setMessages(generateMockMessages(threadId));
return;
}
const res = await fetchCommsMessages(threadId, { limit: 100 });
setMessages(res.messages || []);
} catch (e) {
setMessages([]);
}
}
async function handleSend(e?: React.FormEvent) {
e?.preventDefault();
if (!composerText.trim() || !activeThreadId) return;
const payload: SendMessagePayload = {
messageType: 'text',
body: composerText.trim(),
};
const optimistic: CommsMessage = {
messageId: `opt-${Date.now()}`,
threadId: activeThreadId,
direction: 'outbound',
messageType: 'text',
body: payload.body,
deliveryStatus: 'pending',
createdAt: new Date().toISOString(),
provider: activeThread?.provider || 'mock',
};
setMessages((prev) => [...prev, optimistic]);
setComposerText('');
setSending(true);
try {
if (mockMode) {
await new Promise((r) => setTimeout(r, 800));
setMessages((prev) =>
prev.map((m) =>
m.messageId === optimistic.messageId
? { ...m, deliveryStatus: 'sent', messageId: `mock-${Date.now()}` }
: m
)
);
} else {
await sendCommsMessage(activeThreadId, payload);
await loadMessages(activeThreadId);
}
} catch (err) {
setMessages((prev) =>
prev.map((m) =>
m.messageId === optimistic.messageId ? { ...m, deliveryStatus: 'failed' } : m
)
);
} finally {
setSending(false);
}
}
async function handleLinkPerson(personId: string) {
if (!activeThreadId || mockMode) return;
try {
await linkCommsThreadToPerson(activeThreadId, { personId });
await loadInitial();
if (activeThreadId) await loadMessages(activeThreadId);
} catch (e) {
console.error(e);
}
}
const filteredThreads = threads.filter((t) => {
const q = searchQuery.toLowerCase();
return (
(t.displayName || '').toLowerCase().includes(q) ||
t.phoneE164.includes(q) ||
(t.lastMessagePreview || '').toLowerCase().includes(q)
);
});
if (loading) {
return (
<div className="h-full flex items-center justify-center text-zinc-400">
<div className="flex items-center gap-3">
<div className="w-5 h-5 border-2 border-blue-500 border-t-transparent rounded-full animate-spin" />
Loading conversations
</div>
</div>
);
}
/* ── Empty state: provider not configured ──────────────────────────────── */
if (!mockMode && (!settings || settings.provider === 'mock')) {
return (
<div className="h-full flex items-center justify-center">
<div
className="max-w-md w-full p-8 rounded-2xl text-center"
style={{
background: 'hsl(var(--surface))',
border: '1px solid hsl(var(--border-subtle))',
}}
>
<div
className="w-14 h-14 rounded-2xl flex items-center justify-center mx-auto mb-5"
style={{ background: 'hsl(var(--accent) / 0.1)' }}
>
<MessageCircle className="w-7 h-7 text-blue-400" />
</div>
<h2 className="text-lg font-semibold text-white mb-2">Conversations</h2>
<p className="text-sm text-zinc-400 mb-6">
Connect a WhatsApp provider to start receiving and sending messages.
Until then, preview the interface with mock data.
</p>
<div className="flex gap-3 justify-center">
<button
onClick={() => setMockMode(true)}
className="px-4 py-2 rounded-xl text-sm font-medium text-white transition-colors"
style={{ background: 'hsl(var(--surface-2))', border: '1px solid hsl(var(--border-subtle))' }}
>
<Bot className="w-4 h-4 inline mr-2" />
Preview Mock Data
</button>
<button
onClick={() => { /* router push to settings */ }}
className="px-4 py-2 rounded-xl text-sm font-medium text-white transition-colors"
style={{ background: 'hsl(var(--accent))' }}
>
<Settings className="w-4 h-4 inline mr-2" />
Configure Provider
</button>
</div>
</div>
</div>
);
}
return (
<div className="h-full flex gap-4" style={{ minHeight: 0 }}>
{/* ════════════════════════════════════════════════════════════════════
LEFT: Inbox
════════════════════════════════════════════════════════════════════ */}
<aside
className="flex-none flex flex-col rounded-2xl overflow-hidden"
style={{
width: 320,
background: 'hsl(var(--surface))',
border: '1px solid hsl(var(--border-subtle))',
}}
>
<div className="p-4 border-b" style={{ borderColor: 'hsl(var(--border-subtle))' }}>
<div className="flex items-center justify-between mb-3">
<h2 className="text-sm font-semibold text-white">Inbox</h2>
{mockMode && (
<span className="tag text-amber-400 border-amber-500/20 bg-amber-500/10">
Mock Mode
</span>
)}
</div>
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-zinc-500" />
<input
type="text"
placeholder="Search threads…"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full pl-9 pr-3 py-2 rounded-xl text-sm text-white placeholder-zinc-500 outline-none"
style={{
background: 'hsl(var(--surface-2))',
border: '1px solid hsl(var(--border-subtle))',
}}
/>
</div>
</div>
<div className="flex-1 overflow-y-auto custom-scrollbar">
{filteredThreads.length === 0 ? (
<div className="p-8 text-center text-zinc-500 text-sm">No threads found</div>
) : (
filteredThreads.map((thread) => (
<button
key={thread.threadId}
onClick={() => setActiveThreadId(thread.threadId)}
className="w-full text-left px-4 py-3 transition-colors relative"
style={{
background: activeThreadId === thread.threadId ? 'hsl(var(--accent) / 0.08)' : 'transparent',
borderLeft: activeThreadId === thread.threadId ? '2px solid hsl(var(--accent))' : '2px solid transparent',
}}
>
<div className="flex items-start gap-3">
<div
className="w-10 h-10 rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0"
style={{
background: thread.crmPerson ? 'hsl(var(--accent) / 0.15)' : 'hsl(var(--surface-3))',
color: thread.crmPerson ? 'hsl(var(--accent))' : 'hsl(var(--muted-fg))',
}}
>
{thread.displayName?.[0]?.toUpperCase() || <User className="w-4 h-4" />}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-white truncate">
{thread.displayName || thread.phoneE164}
</span>
{thread.unreadCount > 0 && (
<span className="ml-2 px-1.5 py-0.5 rounded-md text-[10px] font-bold bg-blue-500 text-white">
{thread.unreadCount}
</span>
)}
</div>
<p className="text-xs text-zinc-400 truncate mt-0.5">{thread.lastMessagePreview || 'No messages'}</p>
<div className="flex items-center gap-2 mt-1">
<span className="text-[10px] text-zinc-500">{thread.phoneE164}</span>
{!thread.personId && (
<span className="text-[10px] px-1.5 rounded bg-amber-500/10 text-amber-400 border border-amber-500/20">
Unresolved
</span>
)}
{thread.channel === 'call' && <Phone className="w-3 h-3 text-zinc-500" />}
</div>
</div>
</div>
</button>
))
)}
</div>
</aside>
{/* ════════════════════════════════════════════════════════════════════
CENTER: Conversation Timeline
════════════════════════════════════════════════════════════════════ */}
<section
className="flex-1 flex flex-col rounded-2xl overflow-hidden"
style={{
background: 'hsl(var(--surface))',
border: '1px solid hsl(var(--border-subtle))',
}}
>
{activeThread ? (
<>
{/* ── Client Identity Strip ── */}
<div
className="flex-none px-5 py-3 flex items-center justify-between border-b"
style={{ borderColor: 'hsl(var(--border-subtle))' }}
>
<div className="flex items-center gap-3">
<div
className="w-10 h-10 rounded-full flex items-center justify-center text-sm font-semibold"
style={{
background: activeThread.crmPerson ? 'hsl(var(--accent) / 0.15)' : 'hsl(var(--surface-3))',
color: activeThread.crmPerson ? 'hsl(var(--accent))' : 'hsl(var(--muted-fg))',
}}
>
{activeThread.displayName?.[0]?.toUpperCase() || <User className="w-4 h-4" />}
</div>
<div>
<div className="flex items-center gap-2">
<h3 className="text-sm font-semibold text-white">
{activeThread.displayName || activeThread.phoneE164}
</h3>
{activeThread.channel === 'whatsapp' && (
<span className="tag text-emerald-400 border-emerald-500/20 bg-emerald-500/10 text-[10px]">
WhatsApp
</span>
)}
{activeThread.channel === 'call' && (
<span className="tag text-blue-300 border-blue-400/20 bg-blue-400/10 text-[10px]">
Call
</span>
)}
</div>
<p className="text-xs text-zinc-400">{activeThread.phoneE164}</p>
</div>
</div>
<div className="flex items-center gap-2">
<button className="p-2 rounded-lg hover:bg-white/5 text-zinc-400 hover:text-white transition-colors">
<PhoneCall className="w-4 h-4" />
</button>
<button className="p-2 rounded-lg hover:bg-white/5 text-zinc-400 hover:text-white transition-colors">
<MoreVertical className="w-4 h-4" />
</button>
<button
onClick={() => setShowCrmRail((v) => !v)}
className="p-2 rounded-lg hover:bg-white/5 text-zinc-400 hover:text-white transition-colors"
title="Toggle CRM rail"
>
<ChevronLeft className={`w-4 h-4 transition-transform ${showCrmRail ? '' : 'rotate-180'}`} />
</button>
</div>
</div>
{/* ── Messages ── */}
<div className="flex-1 overflow-y-auto custom-scrollbar px-5 py-4 space-y-4">
<AnimatePresence initial={false}>
{messages.map((msg) => (
<motion.div
key={msg.messageId}
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
className={`flex ${msg.direction === 'outbound' ? 'justify-end' : 'justify-start'}`}
>
<div
className={`max-w-[70%] px-4 py-2.5 rounded-2xl text-sm ${
msg.direction === 'outbound' ? 'rounded-br-md' : 'rounded-bl-md'
}`}
style={{
background:
msg.direction === 'outbound'
? 'hsl(var(--accent) / 0.9)'
: 'hsl(var(--surface-3))',
color: msg.direction === 'outbound' ? '#fff' : 'hsl(var(--foreground))',
}}
>
{msg.messageType === 'text' && <p className="leading-relaxed">{msg.body}</p>}
{msg.mediaUrl && (
<div className="mt-2 rounded-lg overflow-hidden">
<img src={msg.mediaUrl} alt="media" className="max-w-full max-h-48 object-cover" />
</div>
)}
<div className="flex items-center justify-end gap-1.5 mt-1.5">
<span className="text-[10px] opacity-60">
{new Date(msg.createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
</span>
{msg.direction === 'outbound' && (
<>
{msg.deliveryStatus === 'pending' && <Clock className="w-3 h-3 opacity-60" />}
{msg.deliveryStatus === 'sent' && <CheckCheck className="w-3 h-3 opacity-60" />}
{msg.deliveryStatus === 'delivered' && <CheckCheck className="w-3 h-3 text-blue-200" />}
{msg.deliveryStatus === 'read' && <CheckCheck className="w-3 h-3 text-emerald-300" />}
{msg.deliveryStatus === 'failed' && <AlertCircle className="w-3 h-3 text-red-300" />}
</>
)}
</div>
</div>
</motion.div>
))}
</AnimatePresence>
<div ref={messagesEndRef} />
</div>
{/* ── Composer ── */}
<div
className="flex-none px-4 py-3 border-t"
style={{ borderColor: 'hsl(var(--border-subtle))' }}
>
{!activeThread.personId && (
<div
className="mb-3 px-3 py-2 rounded-xl flex items-center gap-2 text-xs"
style={{
background: 'hsl(38 92% 50% / 0.08)',
border: '1px solid hsl(38 92% 50% / 0.2)',
color: 'hsl(38 92% 65%)',
}}
>
<AlertCircle className="w-4 h-4 flex-shrink-0" />
<span className="flex-1">This number is not linked to a CRM contact.</span>
<button
onClick={() => handleLinkPerson('demo-person-id')}
className="px-2 py-1 rounded-md bg-amber-500/10 hover:bg-amber-500/20 transition-colors font-medium"
>
Link
</button>
</div>
)}
<form onSubmit={handleSend} className="flex items-end gap-2">
<button
type="button"
className="p-2.5 rounded-xl text-zinc-400 hover:text-white hover:bg-white/5 transition-colors"
>
<Paperclip className="w-5 h-5" />
</button>
<div className="flex-1 relative">
<textarea
rows={1}
value={composerText}
onChange={(e) => setComposerText(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSend();
}
}}
placeholder="Type a message…"
className="w-full px-4 py-2.5 rounded-xl text-sm text-white placeholder-zinc-500 outline-none resize-none max-h-32"
style={{
background: 'hsl(var(--surface-2))',
border: '1px solid hsl(var(--border-subtle))',
}}
/>
</div>
<button
type="submit"
disabled={!composerText.trim() || sending}
className="p-2.5 rounded-xl text-white transition-all disabled:opacity-40 disabled:cursor-not-allowed"
style={{ background: 'hsl(var(--accent))' }}
>
<Send className="w-5 h-5" />
</button>
</form>
</div>
</>
) : (
<div className="flex-1 flex flex-col items-center justify-center text-zinc-500">
<Inbox className="w-12 h-12 mb-4 opacity-20" />
<p className="text-sm">Select a conversation to start</p>
</div>
)}
</section>
{/* ════════════════════════════════════════════════════════════════════
RIGHT: CRM Intelligence Rail
════════════════════════════════════════════════════════════════════ */}
<AnimatePresence>
{showCrmRail && activeThread && (
<motion.aside
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: 20 }}
className="flex-none flex flex-col rounded-2xl overflow-hidden"
style={{
width: 300,
background: 'hsl(var(--surface))',
border: '1px solid hsl(var(--border-subtle))',
}}
>
<div className="p-4 border-b" style={{ borderColor: 'hsl(var(--border-subtle))' }}>
<h3 className="text-sm font-semibold text-white">CRM Intelligence</h3>
<p className="text-xs text-zinc-500 mt-0.5">Velocity Lens · {activeThread.phoneE164}</p>
</div>
<div className="flex-1 overflow-y-auto custom-scrollbar p-4 space-y-4">
{activeThread.crmPerson ? (
<>
<div
className="p-4 rounded-xl"
style={{ background: 'hsl(var(--surface-2))', border: '1px solid hsl(var(--border-subtle))' }}
>
<div className="flex items-center gap-3 mb-3">
<div
className="w-10 h-10 rounded-full flex items-center justify-center text-sm font-semibold"
style={{ background: 'hsl(var(--accent) / 0.15)', color: 'hsl(var(--accent))' }}
>
{activeThread.crmPerson.fullName?.[0] || 'C'}
</div>
<div>
<p className="text-sm font-medium text-white">{activeThread.crmPerson.fullName || 'Unknown'}</p>
<p className="text-xs text-zinc-400">{activeThread.crmPerson.primaryEmail || 'No email'}</p>
</div>
</div>
<div className="space-y-2">
<div className="flex justify-between text-xs">
<span className="text-zinc-500">Status</span>
<span className="text-white capitalize">{activeThread.crmPerson.leadStatus || 'New'}</span>
</div>
<div className="flex justify-between text-xs">
<span className="text-zinc-500">Project</span>
<span className="text-white">{activeThread.crmPerson.projectName || '-'}</span>
</div>
<div className="flex justify-between text-xs">
<span className="text-zinc-500">Buyer Type</span>
<span className="text-white">{activeThread.crmPerson.buyerType || '-'}</span>
</div>
</div>
</div>
<div
className="p-4 rounded-xl"
style={{ background: 'hsl(var(--surface-2))', border: '1px solid hsl(var(--border-subtle))' }}
>
<h4 className="text-xs font-semibold text-zinc-300 uppercase tracking-wider mb-3">Next Best Action</h4>
<p className="text-sm text-white font-medium">Schedule site visit</p>
<p className="text-xs text-zinc-400 mt-1">High intent signal detected</p>
</div>
<div
className="p-4 rounded-xl"
style={{ background: 'hsl(var(--surface-2))', border: '1px solid hsl(var(--border-subtle))' }}
>
<h4 className="text-xs font-semibold text-zinc-300 uppercase tracking-wider mb-3">Quick Actions</h4>
<div className="space-y-2">
<button className="w-full text-left px-3 py-2 rounded-lg text-xs text-white hover:bg-white/5 transition-colors flex items-center gap-2">
<Phone className="w-3.5 h-3.5 text-zinc-400" />
Log Call
</button>
<button className="w-full text-left px-3 py-2 rounded-lg text-xs text-white hover:bg-white/5 transition-colors flex items-center gap-2">
<Voicemail className="w-3.5 h-3.5 text-zinc-400" />
Add Recording
</button>
<button className="w-full text-left px-3 py-2 rounded-lg text-xs text-white hover:bg-white/5 transition-colors flex items-center gap-2">
<Plus className="w-3.5 h-3.5 text-zinc-400" />
Create Task
</button>
</div>
</div>
</>
) : (
<div
className="p-4 rounded-xl text-center"
style={{ background: 'hsl(var(--surface-2))', border: '1px solid hsl(var(--border-subtle))' }}
>
<Hash className="w-8 h-8 text-amber-500/60 mx-auto mb-3" />
<p className="text-sm text-white font-medium mb-1">Unresolved Number</p>
<p className="text-xs text-zinc-400 mb-4">
No CRM match found for {activeThread.phoneE164}
</p>
<button
onClick={() => handleLinkPerson('demo-person-id')}
className="w-full px-3 py-2 rounded-lg text-xs font-medium text-white transition-colors"
style={{ background: 'hsl(var(--accent))' }}
>
<LinkIcon className="w-3.5 h-3.5 inline mr-1.5" />
Link to Contact
</button>
</div>
)}
</div>
</motion.aside>
)}
</AnimatePresence>
</div>
);
}