feat: Whatsapp Integration
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

This commit is contained in:
Sagnik
2026-04-28 13:41:14 +05:30
parent 7ee51543d9
commit 3623bacbac
15 changed files with 2549 additions and 3 deletions

View File

@@ -11,6 +11,7 @@ import { Inventory } from '@/components/modules/Inventory';
import { Settings } from '@/components/modules/Settings';
import { Catalyst } from '@/components/modules/Catalyst';
import { CRM } from '@/components/modules/CRM';
import { Comms } from '@/components/modules/Comms';
import { NotificationCenter } from '@/components/layout/NotificationCenter';
import { useCrmBootstrap } from '@/hooks/useCrmBootstrap';
import type { ModuleId } from '@/types';
@@ -53,6 +54,7 @@ export const MODULE_ROUTES: Array<{
{ id: 'inventory', path: '/inventory', title: 'Inventory', component: Inventory },
{ id: 'catalyst', path: '/catalyst', title: 'The Catalyst', component: Catalyst },
{ id: 'crm', path: '/crm', title: 'CRM', component: CRM },
{ id: 'comms', path: '/comms', title: 'Conversations', component: Comms },
{ id: 'settings', path: '/settings', title: 'Settings', component: Settings },
{ id: 'admin', path: '/admin', title: 'Admin', component: AdminPage, adminOnly: true },
];

View File

@@ -9,6 +9,7 @@ import {
Megaphone,
Shield,
Users,
MessageCircle,
type LucideIcon,
} from 'lucide-react';
import { useStore } from '@/store/useStore';
@@ -21,6 +22,7 @@ const NAV_ICONS: Record<string, LucideIcon> = {
'/sentinel': ScanFace,
'/inventory': Building2,
'/catalyst': Megaphone,
'/comms': MessageCircle,
'/settings': Sliders,
'/admin': Shield,
'/crm': Users,

View File

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

View File

@@ -1,4 +1,4 @@
import { useRef, useState, type ChangeEvent } from 'react';
import { useEffect, useRef, useState, type ChangeEvent } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
User,
@@ -16,12 +16,15 @@ import {
ChevronDown,
LogOut,
Pencil,
MessageCircle,
type LucideIcon,
} from 'lucide-react';
import { useStore } from '@/store/useStore';
import { useCurrency, CURRENCY_OPTIONS } from '@/store/useCurrencyStore';
import type { CurrencyCode } from '@/store/useCurrencyStore';
import { API_URL } from '@/lib/api';
import { fetchCommsSettings, testCommsProviderConnection, updateCommsSettings } from '@/lib/commsApi';
import type { CommsProvider, CommsSettings } from '@/types/commsTypes';
import {
clearVelocityToken,
getVelocityToken,
@@ -613,6 +616,160 @@ function DisplaySettings() {
}
// ── Data & Privacy ───────────────────────────────────────────────────────────
function CommunicationsSettings() {
const [settings, setSettings] = useState<CommsSettings | null>(null);
const [draft, setDraft] = useState<Partial<CommsSettings>>({});
const [statusText, setStatusText] = useState('Loading provider settings...');
const [saving, setSaving] = useState(false);
const current: CommsSettings = {
provider: 'mock',
providerBaseUrl: '',
providerApiKey: '',
instanceId: '',
phoneNumberId: '',
webhookCallbackUrl: '/api/comms/webhooks/{provider}',
webhookSecretSet: false,
autoLinkByPhone: true,
createCrmInteractionOnInbound: true,
defaultCountryCode: '91',
transcriptionProvider: 'none',
...(settings ?? {}),
...draft,
};
useEffect(() => {
let cancelled = false;
void fetchCommsSettings()
.then((value) => {
if (cancelled) return;
setSettings(value);
setStatusText('Settings loaded from backend.');
})
.catch((error) => {
if (cancelled) return;
setStatusText(error instanceof Error ? error.message : 'Unable to load comms settings.');
});
return () => {
cancelled = true;
};
}, []);
const update = <K extends keyof CommsSettings>(key: K, value: CommsSettings[K]) => {
setDraft((prev) => ({ ...prev, [key]: value }));
};
const save = async () => {
setSaving(true);
try {
await updateCommsSettings(draft);
const latest = await fetchCommsSettings();
setSettings(latest);
setDraft({});
setStatusText('Communications settings saved.');
} catch (error) {
setStatusText(error instanceof Error ? error.message : 'Failed to save communications settings.');
} finally {
setSaving(false);
}
};
const test = async () => {
try {
const result = await testCommsProviderConnection();
setStatusText(result.message || (result.success ? 'Provider connection succeeded.' : 'Provider connection failed.'));
} catch (error) {
setStatusText(error instanceof Error ? error.message : 'Provider test failed.');
}
};
const fieldClass = "w-64 rounded-xl px-3 py-2 text-sm text-white placeholder-zinc-500 outline-none";
return (
<GlassCard delay={0.3}>
<SectionHeader icon={MessageCircle} title="Communications" accent="#22d3ee" />
<div>
<SettingsRow label="Provider" description="Mock is local preview. WAHA and Evolution require a running provider service.">
<DarkSelect
value={current.provider}
onChange={(v) => update('provider', v as CommsProvider)}
options={[
{ value: 'mock', label: 'Mock' },
{ value: 'waha', label: 'WAHA' },
{ value: 'evolution', label: 'Evolution API' },
{ value: 'meta_cloud', label: 'Meta Cloud API' },
]}
/>
</SettingsRow>
<SettingsRow label="Provider Base URL" description="Internal or public base URL for WAHA/Evolution.">
<input
className={fieldClass}
style={INNER_SURFACE}
value={current.providerBaseUrl ?? ''}
onChange={(event) => update('providerBaseUrl', event.target.value)}
placeholder="http://127.0.0.1:3000"
/>
</SettingsRow>
<SettingsRow label="API Key" description="Stored in backend comms settings. Masked when read back.">
<input
className={fieldClass}
style={INNER_SURFACE}
type="password"
value={current.providerApiKey ?? ''}
onChange={(event) => update('providerApiKey', event.target.value)}
placeholder="Provider API key"
/>
</SettingsRow>
<SettingsRow label="Instance / Session" description="WAHA session name or Evolution instance name.">
<input
className={fieldClass}
style={INNER_SURFACE}
value={current.instanceId ?? ''}
onChange={(event) => update('instanceId', event.target.value)}
placeholder="default"
/>
</SettingsRow>
<SettingsRow label="Webhook URL" description="Point provider inbound webhooks here.">
<span className="text-xs font-mono text-zinc-300">{current.webhookCallbackUrl || '/api/comms/webhooks/{provider}'}</span>
</SettingsRow>
<SettingsRow label="Auto-link by Phone" description="Match inbound numbers to crm_people.primary_phone.">
<Toggle enabled={Boolean(current.autoLinkByPhone)} onChange={(v) => update('autoLinkByPhone', v)} />
</SettingsRow>
<SettingsRow label="Create CRM Interaction" description="Mirror inbound messages into canonical intelligence tables.">
<Toggle enabled={Boolean(current.createCrmInteractionOnInbound)} onChange={(v) => update('createCrmInteractionOnInbound', v)} />
</SettingsRow>
<SettingsRow label="Transcription Provider" description="Recording intake is stored now; transcription worker can be added later.">
<DarkSelect
value={current.transcriptionProvider ?? 'none'}
onChange={(v) => update('transcriptionProvider', v as CommsSettings['transcriptionProvider'])}
options={[
{ value: 'none', label: 'None' },
{ value: 'local', label: 'Local Whisper' },
{ value: 'openai', label: 'OpenAI' },
]}
/>
</SettingsRow>
<div className="px-6 py-4 flex items-center justify-between gap-3">
<p className="text-xs text-zinc-400">{statusText}</p>
<div className="flex items-center gap-2">
<GhostButton onClick={test}>Test</GhostButton>
<motion.button
type="button"
onClick={save}
disabled={saving || Object.keys(draft).length === 0}
className="px-4 py-2 rounded-xl text-sm font-semibold disabled:opacity-50 disabled:cursor-not-allowed"
style={{ background: 'hsl(var(--accent))', color: 'hsl(var(--accent-fg))' }}
whileHover={{ scale: saving ? 1 : 1.02 }}
whileTap={{ scale: saving ? 1 : 0.97 }}
>
{saving ? 'Saving...' : 'Save'}
</motion.button>
</div>
</div>
</div>
</GlassCard>
);
}
function DataSettings() {
const [retention, setRetention] = useState('90');
const { leads, messages, units, status } = useStore();
@@ -728,9 +885,14 @@ export function Settings() {
<DisplaySettings />
</div>
{/* Row 4: Data + About */}
{/* Row 4: Communications + Data */}
<div className="grid grid-cols-2 gap-4 relative z-10">
<CommunicationsSettings />
<DataSettings />
</div>
{/* Row 5: About */}
<div className="grid grid-cols-1 gap-4 relative z-0">
<AboutSection />
</div>
</div>

89
app/src/lib/commsApi.ts Normal file
View File

@@ -0,0 +1,89 @@
import { getVelocityToken } from './velocityPlatformClient';
import type {
CommsThread,
CommsSettings,
CommsProviderTestResult,
SendMessagePayload,
CommsThreadListResponse,
CommsMessageListResponse,
ThreadLinkPayload,
} from '@/types/commsTypes';
const API_BASE = import.meta.env.VITE_API_BASE_URL || '';
async function commsFetch(path: string, options?: RequestInit) {
const token = getVelocityToken();
const res = await fetch(`${API_BASE}${path}`, {
...options,
headers: {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
...options?.headers,
},
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err.detail || `HTTP ${res.status}`);
}
return res.json();
}
function toQuery(params?: Record<string, string | number | undefined>) {
const query = new URLSearchParams();
Object.entries(params ?? {}).forEach(([key, value]) => {
if (value !== undefined && value !== '') query.set(key, String(value));
});
const serialized = query.toString();
return serialized ? `?${serialized}` : '';
}
export const fetchCommsThreads = (params?: { status?: string; search?: string; limit?: number; offset?: number }) =>
commsFetch(`/api/comms/threads${toQuery(params)}`) as Promise<CommsThreadListResponse>;
export const fetchCommsThread = (threadId: string) =>
commsFetch(`/api/comms/threads/${threadId}`) as Promise<CommsThread>;
export const fetchCommsMessages = (threadId: string, params?: { limit?: number; offset?: number }) =>
commsFetch(`/api/comms/threads/${threadId}/messages${toQuery(params)}`) as Promise<CommsMessageListResponse>;
export const sendCommsMessage = (threadId: string, payload: SendMessagePayload) =>
commsFetch(`/api/comms/threads/${threadId}/messages`, {
method: 'POST',
body: JSON.stringify(payload),
});
export const linkCommsThreadToPerson = (threadId: string, payload: ThreadLinkPayload) =>
commsFetch(`/api/comms/threads/${threadId}/link-person`, {
method: 'POST',
body: JSON.stringify(payload),
});
export const addCommsThreadNote = (threadId: string, body: { content: string }) =>
commsFetch(`/api/comms/threads/${threadId}/notes`, {
method: 'POST',
body: JSON.stringify(body),
});
export const addCommsThreadTask = (threadId: string, body: { title: string; dueAt?: string }) =>
commsFetch(`/api/comms/threads/${threadId}/tasks`, {
method: 'POST',
body: JSON.stringify(body),
});
export const fetchCommsSettings = () =>
commsFetch(`/api/comms/settings`) as Promise<CommsSettings>;
export const updateCommsSettings = (payload: Partial<CommsSettings>) =>
commsFetch(`/api/comms/settings`, {
method: 'PATCH',
body: JSON.stringify(payload),
});
export const testCommsProviderConnection = () =>
commsFetch(`/api/comms/provider/test`, { method: 'POST' }) as Promise<CommsProviderTestResult>;
export const transcribeCommsRecording = (callId: string) =>
commsFetch(`/api/comms/recordings/transcribe`, {
method: 'POST',
body: JSON.stringify({ callId }),
});

121
app/src/types/commsTypes.ts Normal file
View File

@@ -0,0 +1,121 @@
// Velocity Comms Types
// Native types for the Conversations module
export type CommsChannel = 'whatsapp' | 'sms' | 'call';
export type CommsThreadStatus = 'open' | 'resolved' | 'spam' | 'archived';
export type CommsMessageDirection = 'inbound' | 'outbound' | 'system';
export type CommsMessageType = 'text' | 'image' | 'video' | 'audio' | 'document' | 'location' | 'template';
export type CommsProvider = 'mock' | 'waha' | 'evolution' | 'meta_cloud';
export type CommsDeliveryStatus = 'pending' | 'sent' | 'delivered' | 'read' | 'failed';
export interface CommsThread {
threadId: string;
provider: CommsProvider;
externalThreadId?: string;
personId?: string;
phoneE164: string;
displayName?: string;
channel: CommsChannel;
status: CommsThreadStatus;
assignedUserId?: string;
lastMessageAt?: string;
unreadCount: number;
metadataJson?: Record<string, unknown>;
createdAt: string;
updatedAt: string;
crmPerson?: {
id: string;
fullName?: string;
primaryPhone?: string;
primaryEmail?: string;
buyerType?: string;
leadStatus?: string;
projectName?: string;
};
lastMessagePreview?: string;
}
export interface CommsMessage {
messageId: string;
threadId: string;
provider: CommsProvider;
externalMessageId?: string;
direction: CommsMessageDirection;
messageType: CommsMessageType;
body: string;
mediaUrl?: string;
mediaMimeType?: string;
deliveryStatus: CommsDeliveryStatus;
sentAt?: string;
deliveredAt?: string;
readAt?: string;
rawPayload?: Record<string, unknown>;
createdAt: string;
senderName?: string;
senderAvatar?: string;
}
export interface CommsCallLog {
callId: string;
threadId?: string;
personId?: string;
provider: CommsProvider;
externalCallId?: string;
phoneE164: string;
direction: 'inbound' | 'outbound';
status: 'ringing' | 'answered' | 'missed' | 'voicemail' | 'completed';
startedAt: string;
endedAt?: string;
durationSeconds?: number;
recordingUrl?: string;
transcriptId?: string;
transcriptText?: string;
rawPayload?: Record<string, unknown>;
createdAt: string;
}
export interface CommsSettings {
provider: CommsProvider;
providerBaseUrl?: string;
providerApiKey?: string;
instanceId?: string;
phoneNumberId?: string;
webhookCallbackUrl?: string;
webhookSecretSet: boolean;
defaultAssignmentUserId?: string;
autoLinkByPhone: boolean;
createCrmInteractionOnInbound: boolean;
defaultCountryCode: string;
mediaStorageDir?: string;
transcriptionProvider?: 'none' | 'openai' | 'local';
updatedAt?: string;
}
export interface ThreadLinkPayload {
personId: string;
}
export interface SendMessagePayload {
messageType: CommsMessageType;
body: string;
mediaUrl?: string;
templateName?: string;
templateLanguage?: string;
}
export interface CommsProviderTestResult {
success: boolean;
message: string;
accountInfo?: Record<string, unknown>;
}
export interface CommsThreadListResponse {
threads: CommsThread[];
total: number;
unreadTotal: number;
}
export interface CommsMessageListResponse {
messages: CommsMessage[];
thread: CommsThread;
}

View File

@@ -1,5 +1,5 @@
// Navigation Module Types
export type ModuleId = 'dashboard' | 'oracle' | 'sentinel' | 'inventory' | 'settings' | 'catalyst' | 'admin' | 'crm';
export type ModuleId = 'dashboard' | 'oracle' | 'sentinel' | 'inventory' | 'settings' | 'catalyst' | 'admin' | 'crm' | 'comms';
export type SentinelSubTab = 'overview' | 'live-session';