Spaces:
Sleeping

axeronis commited on
Commit
5b6905f
Β·
1 Parent(s): 37dee8d

feat(chat): real-time WebSocket updates and media display

Browse files
backend/app/api/chats.py CHANGED
@@ -25,6 +25,7 @@ from app.api.webhook import send_telegram_message
25
  # from app.api.meta_webhooks import send_meta_message # DEPRECATED
26
  from app.services.meta_whatsapp import whatsapp_cloud_service
27
  import httpx
 
28
 
29
  logger = get_logger(__name__)
30
 
@@ -116,6 +117,16 @@ async def send_message(
116
 
117
  print(f"πŸ’¬ Human message saved: {human_message.id} for lead {lead.id}")
118
 
 
 
 
 
 
 
 
 
 
 
119
  # 7. SEND TO APPROPRIATE CHANNEL (ROBUST ERROR HANDLING)
120
  send_success = False
121
  send_error_detail = None
 
25
  # from app.api.meta_webhooks import send_meta_message # DEPRECATED
26
  from app.services.meta_whatsapp import whatsapp_cloud_service
27
  import httpx
28
+ from app.api.websocket_chat import notify_new_message
29
 
30
  logger = get_logger(__name__)
31
 
 
117
 
118
  print(f"πŸ’¬ Human message saved: {human_message.id} for lead {lead.id}")
119
 
120
+ # Notify WebSocket clients about new message
121
+ await notify_new_message(str(lead.id), {
122
+ "id": str(human_message.id),
123
+ "content": human_message.content,
124
+ "sender_type": "human",
125
+ "created_at": human_message.created_at.isoformat(),
126
+ "media_url": None,
127
+ "media_type": None
128
+ })
129
+
130
  # 7. SEND TO APPROPRIATE CHANNEL (ROBUST ERROR HANDLING)
131
  send_success = False
132
  send_error_detail = None
backend/app/api/leads.py CHANGED
@@ -40,6 +40,7 @@ class LeadResponse(BaseModel):
40
  last_message_at: datetime
41
  created_at: datetime
42
  current_stage_id: Optional[str] = None
 
43
 
44
 
45
  class ConversationResponse(BaseModel):
@@ -88,6 +89,28 @@ async def get_leads(
88
  result = await session.execute(stmt)
89
  leads = result.scalars().all()
90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  return [
92
  LeadResponse(
93
  id=str(lead.id),
@@ -111,7 +134,8 @@ async def get_leads(
111
  first_message_at=lead.first_message_at,
112
  last_message_at=lead.last_message_at,
113
  created_at=lead.created_at,
114
- current_stage_id=str(lead.current_stage_id) if lead.current_stage_id else None
 
115
  )
116
  for lead in leads
117
  ]
 
40
  last_message_at: datetime
41
  created_at: datetime
42
  current_stage_id: Optional[str] = None
43
+ last_message: Optional[str] = None # Last message content for preview
44
 
45
 
46
  class ConversationResponse(BaseModel):
 
89
  result = await session.execute(stmt)
90
  leads = result.scalars().all()
91
 
92
+ # Fetch last messages for all leads in one query
93
+ lead_ids = [lead.id for lead in leads]
94
+
95
+ # Get conversations for these leads
96
+ from app.models.conversation import Conversation
97
+ conv_stmt = select(Conversation).where(Conversation.lead_id.in_(lead_ids))
98
+ conv_result = await session.execute(conv_stmt)
99
+ conversations = conv_result.scalars().all()
100
+ conv_map = {c.lead_id: c.id for c in conversations}
101
+
102
+ # Get last message for each conversation
103
+ last_messages = {}
104
+ for lead_id, conv_id in conv_map.items():
105
+ msg_stmt = select(Message).where(
106
+ Message.conversation_id == conv_id
107
+ ).order_by(Message.created_at.desc()).limit(1)
108
+ msg_result = await session.execute(msg_stmt)
109
+ msg = msg_result.scalar_one_or_none()
110
+ if msg:
111
+ # Truncate for preview
112
+ last_messages[lead_id] = msg.content[:100] if msg.content else None
113
+
114
  return [
115
  LeadResponse(
116
  id=str(lead.id),
 
134
  first_message_at=lead.first_message_at,
135
  last_message_at=lead.last_message_at,
136
  created_at=lead.created_at,
137
+ current_stage_id=str(lead.current_stage_id) if lead.current_stage_id else None,
138
+ last_message=last_messages.get(lead.id)
139
  )
140
  for lead in leads
141
  ]
backend/app/api/websocket_chat.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ WebSocket Chat - Real-time messaging for chat interface.
3
+
4
+ Provides instant message updates without polling.
5
+ """
6
+
7
+ from fastapi import APIRouter, WebSocket, WebSocketDisconnect, Query
8
+ from app.core.security import decode_access_token
9
+ from app.core.database import get_session
10
+ from app.models.lead import Lead
11
+ from app.models.message import Message
12
+ from app.models.conversation import Conversation
13
+ from sqlalchemy import select
14
+ from uuid import UUID
15
+ from typing import Dict, Set
16
+ import logging
17
+ import json
18
+ import asyncio
19
+
20
+ router = APIRouter()
21
+ logger = logging.getLogger(__name__)
22
+
23
+ # Store active connections per lead_id
24
+ # Structure: {lead_id: {websocket1, websocket2, ...}}
25
+ active_connections: Dict[str, Set[WebSocket]] = {}
26
+
27
+
28
+ class ConnectionManager:
29
+ """Manages WebSocket connections for chat."""
30
+
31
+ def __init__(self):
32
+ self.connections: Dict[str, Set[WebSocket]] = {}
33
+
34
+ async def connect(self, lead_id: str, websocket: WebSocket):
35
+ """Add a connection for a lead."""
36
+ if lead_id not in self.connections:
37
+ self.connections[lead_id] = set()
38
+ self.connections[lead_id].add(websocket)
39
+ logger.info(f"πŸ”Œ Chat WS connected: lead={lead_id}, total={len(self.connections[lead_id])}")
40
+
41
+ def disconnect(self, lead_id: str, websocket: WebSocket):
42
+ """Remove a connection."""
43
+ if lead_id in self.connections:
44
+ self.connections[lead_id].discard(websocket)
45
+ if not self.connections[lead_id]:
46
+ del self.connections[lead_id]
47
+ logger.info(f"πŸ”Œ Chat WS disconnected: lead={lead_id}")
48
+
49
+ async def broadcast_to_lead(self, lead_id: str, message: dict):
50
+ """Send message to all connections watching a lead."""
51
+ if lead_id in self.connections:
52
+ dead_connections = set()
53
+ for ws in self.connections[lead_id]:
54
+ try:
55
+ await ws.send_json(message)
56
+ except Exception as e:
57
+ logger.warning(f"Failed to send to WS: {e}")
58
+ dead_connections.add(ws)
59
+
60
+ # Clean up dead connections
61
+ for ws in dead_connections:
62
+ self.connections[lead_id].discard(ws)
63
+
64
+
65
+ manager = ConnectionManager()
66
+
67
+
68
+ @router.websocket("/{lead_id}")
69
+ async def chat_websocket(
70
+ websocket: WebSocket,
71
+ lead_id: str,
72
+ token: str = Query(...)
73
+ ):
74
+ """
75
+ WebSocket endpoint for real-time chat updates.
76
+
77
+ Events sent to client:
78
+ - new_message: New message in conversation
79
+ - lead_updated: Lead data changed
80
+ - typing: Someone is typing
81
+
82
+ Client can send:
83
+ - ping: Keep-alive
84
+ - typing: Notify others of typing
85
+ """
86
+ await websocket.accept()
87
+
88
+ # Authenticate
89
+ try:
90
+ payload = decode_access_token(token)
91
+ user_id = payload.get("sub")
92
+ tenant_id = payload.get("tenant_id")
93
+
94
+ if not user_id:
95
+ await websocket.close(code=4001, reason="Invalid token")
96
+ return
97
+
98
+ logger.info(f"πŸ”Œ Chat WS authenticated: user={user_id}, lead={lead_id}")
99
+
100
+ except Exception as e:
101
+ logger.error(f"Chat WS auth failed: {e}")
102
+ await websocket.close(code=4003, reason="Authentication failed")
103
+ return
104
+
105
+ # Connect
106
+ await manager.connect(lead_id, websocket)
107
+
108
+ try:
109
+ # Send initial connection confirmation
110
+ await websocket.send_json({
111
+ "type": "connected",
112
+ "lead_id": lead_id
113
+ })
114
+
115
+ while True:
116
+ # Receive messages from client
117
+ message = await websocket.receive()
118
+
119
+ if "text" in message:
120
+ try:
121
+ data = json.loads(message["text"])
122
+ msg_type = data.get("type")
123
+
124
+ if msg_type == "ping":
125
+ await websocket.send_json({"type": "pong"})
126
+
127
+ elif msg_type == "typing":
128
+ # Broadcast typing indicator to others
129
+ await manager.broadcast_to_lead(lead_id, {
130
+ "type": "typing",
131
+ "user_id": user_id
132
+ })
133
+
134
+ except json.JSONDecodeError:
135
+ pass
136
+
137
+ except WebSocketDisconnect:
138
+ manager.disconnect(lead_id, websocket)
139
+ except Exception as e:
140
+ logger.error(f"Chat WS error: {e}")
141
+ manager.disconnect(lead_id, websocket)
142
+ try:
143
+ await websocket.close()
144
+ except:
145
+ pass
146
+
147
+
148
+ async def notify_new_message(lead_id: str, message_data: dict):
149
+ """
150
+ Call this from message handlers to notify WebSocket clients.
151
+
152
+ Args:
153
+ lead_id: The lead ID
154
+ message_data: Message dict with id, content, sender_type, media_url, etc.
155
+ """
156
+ await manager.broadcast_to_lead(str(lead_id), {
157
+ "type": "new_message",
158
+ "message": message_data
159
+ })
160
+
161
+
162
+ async def notify_lead_updated(lead_id: str, lead_data: dict):
163
+ """
164
+ Call this when lead data changes (status, heat_level, etc.)
165
+ """
166
+ await manager.broadcast_to_lead(str(lead_id), {
167
+ "type": "lead_updated",
168
+ "lead": lead_data
169
+ })
backend/app/main.py CHANGED
@@ -7,7 +7,7 @@ from app.core.config import settings
7
  from app.core.database import init_pgvector
8
  from app.core.logging import configure_logging, get_logger
9
  from app.middleware.request_id import RequestIDMiddleware
10
- from app.api import webhook, leads, knowledge, channels, auth, tenants, analytics, chats, playbook, billing, ai_training, crm, admin, team, telegram_webhook, partners, notifications, products, bookings, jobs, system, meta_webhooks, voice, google_calendar, websocket_voice, oauth, landing, site_settings
11
 
12
  # ... (omitted lines)
13
 
@@ -192,6 +192,7 @@ app.include_router(system.router, prefix="/api/v1") # System Announcements
192
  app.include_router(oauth.router, prefix="/api/v1") # OAuth for Meta Embedded Signup - enable when META_APP_ID is set
193
  app.include_router(voice.router, prefix="/api/v1/voice", tags=["Voice"])
194
  app.include_router(websocket_voice.router, prefix="/ws/voice", tags=["Voice Stream"])
 
195
  app.include_router(google_calendar.router, prefix="/api/v1/google-calendar", tags=["Google Calendar"])
196
  app.include_router(landing.router, prefix="/api/v1/landing", tags=["Landing Page"])
197
  app.include_router(site_settings.router, prefix="/api/v1", tags=["Site Settings"])
 
7
  from app.core.database import init_pgvector
8
  from app.core.logging import configure_logging, get_logger
9
  from app.middleware.request_id import RequestIDMiddleware
10
+ from app.api import webhook, leads, knowledge, channels, auth, tenants, analytics, chats, playbook, billing, ai_training, crm, admin, team, telegram_webhook, partners, notifications, products, bookings, jobs, system, meta_webhooks, voice, google_calendar, websocket_voice, websocket_chat, oauth, landing, site_settings
11
 
12
  # ... (omitted lines)
13
 
 
192
  app.include_router(oauth.router, prefix="/api/v1") # OAuth for Meta Embedded Signup - enable when META_APP_ID is set
193
  app.include_router(voice.router, prefix="/api/v1/voice", tags=["Voice"])
194
  app.include_router(websocket_voice.router, prefix="/ws/voice", tags=["Voice Stream"])
195
+ app.include_router(websocket_chat.router, prefix="/ws/chat", tags=["Chat Stream"])
196
  app.include_router(google_calendar.router, prefix="/api/v1/google-calendar", tags=["Google Calendar"])
197
  app.include_router(landing.router, prefix="/api/v1/landing", tags=["Landing Page"])
198
  app.include_router(site_settings.router, prefix="/api/v1", tags=["Site Settings"])
frontend/components/ChatWindow.tsx CHANGED
@@ -8,6 +8,7 @@ import { AnimatePresence } from 'framer-motion'
8
  import { ClientCard } from './ClientCard'
9
  import { subscribeToMessages, isRealtimeEnabled } from '@/lib/supabaseClient'
10
  import { BookingModal } from '@/components/bookings/BookingModal'
 
11
 
12
  // Import refactored sub-components
13
  import { ChatHeader } from './ChatWindow/ChatHeader'
@@ -117,6 +118,18 @@ export function ChatWindow({
117
  return () => { unsubscribe() }
118
  }, [leadId, tenantId, conversationId])
119
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  // ============================================================================
121
  // Handlers
122
  // ============================================================================
 
8
  import { ClientCard } from './ClientCard'
9
  import { subscribeToMessages, isRealtimeEnabled } from '@/lib/supabaseClient'
10
  import { BookingModal } from '@/components/bookings/BookingModal'
11
+ import { useChatWebSocket } from '@/hooks/useChatWebSocket'
12
 
13
  // Import refactored sub-components
14
  import { ChatHeader } from './ChatWindow/ChatHeader'
 
118
  return () => { unsubscribe() }
119
  }, [leadId, tenantId, conversationId])
120
 
121
+ // WebSocket real-time updates (instant, doesn't require page refresh)
122
+ const { isConnected: wsConnected } = useChatWebSocket({
123
+ leadId,
124
+ onNewMessage: (newMessage) => {
125
+ setRealtimeMessages(prev => {
126
+ if (prev.some(m => m.id === newMessage.id)) return prev
127
+ console.log('πŸ”” WebSocket: New message received', newMessage.id)
128
+ return [...prev, newMessage]
129
+ })
130
+ }
131
+ })
132
+
133
  // ============================================================================
134
  // Handlers
135
  // ============================================================================
frontend/components/ChatWindow/MessageBubble.tsx CHANGED
@@ -1,9 +1,10 @@
1
  'use client'
2
 
3
  import { cn, formatDate } from '@/lib/utils'
4
- import { Bot, User } from 'lucide-react'
5
  import { motion } from 'framer-motion'
6
  import type { Message } from '@/types'
 
7
 
8
  interface MessageBubbleProps {
9
  message: Message
@@ -14,6 +15,140 @@ interface MessageBubbleProps {
14
  dateLabel: string
15
  }
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  export function MessageBubble({
18
  message,
19
  isMe,
@@ -22,6 +157,9 @@ export function MessageBubble({
22
  showDate,
23
  dateLabel,
24
  }: MessageBubbleProps) {
 
 
 
25
  return (
26
  <div>
27
  {showDate && (
@@ -63,9 +201,15 @@ export function MessageBubble({
63
  ? "bg-gradient-to-r from-indigo-600 to-violet-600 text-white rounded-2xl rounded-br-none shadow-[0_4px_15px_-3px_rgba(99,102,241,0.3)]"
64
  : "bg-[#1E2030] text-slate-200 border border-white/5 rounded-2xl rounded-bl-none",
65
  isSequence && isMe && "rounded-tr-md rounded-br-md",
66
- isSequence && !isMe && "rounded-tl-md rounded-bl-md"
 
 
67
  )}>
68
- {message.content}
 
 
 
 
69
  </div>
70
  {!isSequence && (
71
  <span className={cn(
 
1
  'use client'
2
 
3
  import { cn, formatDate } from '@/lib/utils'
4
+ import { Bot, User, FileText, Download, Play, Pause } from 'lucide-react'
5
  import { motion } from 'framer-motion'
6
  import type { Message } from '@/types'
7
+ import { useState, useRef } from 'react'
8
 
9
  interface MessageBubbleProps {
10
  message: Message
 
15
  dateLabel: string
16
  }
17
 
18
+ /**
19
+ * Renders media content (audio, image, video, file) in message bubble
20
+ */
21
+ function MediaContent({ message, isMe }: { message: Message; isMe: boolean }) {
22
+ const [isPlaying, setIsPlaying] = useState(false)
23
+ const audioRef = useRef<HTMLAudioElement>(null)
24
+
25
+ if (!message.media_url) return null
26
+
27
+ const mediaType = message.media_type?.toLowerCase() || ''
28
+
29
+ // Audio player
30
+ if (mediaType.includes('audio') || mediaType === 'voice') {
31
+ return (
32
+ <div className="mt-2">
33
+ <div className={cn(
34
+ "flex items-center gap-2 p-2 rounded-xl",
35
+ isMe ? "bg-white/10" : "bg-black/20"
36
+ )}>
37
+ <button
38
+ onClick={() => {
39
+ if (audioRef.current) {
40
+ if (isPlaying) {
41
+ audioRef.current.pause()
42
+ } else {
43
+ audioRef.current.play()
44
+ }
45
+ setIsPlaying(!isPlaying)
46
+ }
47
+ }}
48
+ className={cn(
49
+ "w-10 h-10 rounded-full flex items-center justify-center transition-colors",
50
+ isMe
51
+ ? "bg-white/20 hover:bg-white/30"
52
+ : "bg-indigo-500/20 hover:bg-indigo-500/30"
53
+ )}
54
+ >
55
+ {isPlaying ? (
56
+ <Pause className="w-5 h-5" />
57
+ ) : (
58
+ <Play className="w-5 h-5 ml-0.5" />
59
+ )}
60
+ </button>
61
+ <div className="flex-1">
62
+ <div className="text-xs opacity-70">ГолосовоС сообщСниС</div>
63
+ <audio
64
+ ref={audioRef}
65
+ src={message.media_url}
66
+ onEnded={() => setIsPlaying(false)}
67
+ className="hidden"
68
+ />
69
+ {/* Waveform visualization placeholder */}
70
+ <div className="h-6 flex items-center gap-0.5 mt-1">
71
+ {[...Array(20)].map((_, i) => (
72
+ <div
73
+ key={i}
74
+ className={cn(
75
+ "w-1 rounded-full transition-all",
76
+ isMe ? "bg-white/40" : "bg-indigo-400/40"
77
+ )}
78
+ style={{
79
+ height: `${8 + Math.random() * 16}px`,
80
+ opacity: isPlaying ? 0.8 : 0.4
81
+ }}
82
+ />
83
+ ))}
84
+ </div>
85
+ </div>
86
+ </div>
87
+ </div>
88
+ )
89
+ }
90
+
91
+ // Image
92
+ if (mediaType.includes('image')) {
93
+ return (
94
+ <div className="mt-2">
95
+ <img
96
+ src={message.media_url}
97
+ alt={message.media_name || 'Image'}
98
+ className="rounded-xl max-w-full max-h-64 object-cover cursor-pointer hover:opacity-90 transition-opacity"
99
+ onClick={() => window.open(message.media_url!, '_blank')}
100
+ />
101
+ </div>
102
+ )
103
+ }
104
+
105
+ // Video
106
+ if (mediaType.includes('video')) {
107
+ return (
108
+ <div className="mt-2">
109
+ <video
110
+ src={message.media_url}
111
+ controls
112
+ className="rounded-xl max-w-full max-h-64"
113
+ />
114
+ </div>
115
+ )
116
+ }
117
+
118
+ // Document/File
119
+ return (
120
+ <div className="mt-2">
121
+ <a
122
+ href={message.media_url}
123
+ target="_blank"
124
+ rel="noopener noreferrer"
125
+ className={cn(
126
+ "flex items-center gap-3 p-3 rounded-xl transition-colors",
127
+ isMe
128
+ ? "bg-white/10 hover:bg-white/20"
129
+ : "bg-black/20 hover:bg-black/30"
130
+ )}
131
+ >
132
+ <div className={cn(
133
+ "w-10 h-10 rounded-lg flex items-center justify-center",
134
+ isMe ? "bg-white/20" : "bg-indigo-500/20"
135
+ )}>
136
+ <FileText className="w-5 h-5" />
137
+ </div>
138
+ <div className="flex-1 min-w-0">
139
+ <div className="text-sm font-medium truncate">
140
+ {message.media_name || 'Π€Π°ΠΉΠ»'}
141
+ </div>
142
+ <div className="text-xs opacity-60">
143
+ НаТмитС для скачивания
144
+ </div>
145
+ </div>
146
+ <Download className="w-4 h-4 opacity-60" />
147
+ </a>
148
+ </div>
149
+ )
150
+ }
151
+
152
  export function MessageBubble({
153
  message,
154
  isMe,
 
157
  showDate,
158
  dateLabel,
159
  }: MessageBubbleProps) {
160
+ const hasMedia = !!message.media_url
161
+ const hasText = !!message.content?.trim()
162
+
163
  return (
164
  <div>
165
  {showDate && (
 
201
  ? "bg-gradient-to-r from-indigo-600 to-violet-600 text-white rounded-2xl rounded-br-none shadow-[0_4px_15px_-3px_rgba(99,102,241,0.3)]"
202
  : "bg-[#1E2030] text-slate-200 border border-white/5 rounded-2xl rounded-bl-none",
203
  isSequence && isMe && "rounded-tr-md rounded-br-md",
204
+ isSequence && !isMe && "rounded-tl-md rounded-bl-md",
205
+ // If only media and no text, remove padding
206
+ hasMedia && !hasText && "p-2"
207
  )}>
208
+ {/* Text content */}
209
+ {hasText && message.content}
210
+
211
+ {/* Media content (audio, image, video, file) */}
212
+ <MediaContent message={message} isMe={isMe} />
213
  </div>
214
  {!isSequence && (
215
  <span className={cn(
frontend/components/LeadsList.tsx CHANGED
@@ -274,7 +274,7 @@ export function LeadsList({
274
  "text-xs truncate transition-colors",
275
  isSelected ? "text-slate-400" : "text-slate-500 group-hover:text-slate-400"
276
  )}>
277
- ПослСднСС сообщСниС...
278
  </p>
279
  </div>
280
  </div>
 
274
  "text-xs truncate transition-colors",
275
  isSelected ? "text-slate-400" : "text-slate-500 group-hover:text-slate-400"
276
  )}>
277
+ {(lead as any).last_message || 'НСт сообщСний'}
278
  </p>
279
  </div>
280
  </div>
frontend/hooks/useChatWebSocket.ts ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use client'
2
+
3
+ import { useEffect, useRef, useCallback, useState } from 'react'
4
+ import type { Message } from '@/types'
5
+
6
+ interface UseChatWebSocketOptions {
7
+ leadId: string | undefined
8
+ onNewMessage: (message: Message) => void
9
+ onTyping?: (userId: string) => void
10
+ onLeadUpdated?: (lead: any) => void
11
+ }
12
+
13
+ interface UseChatWebSocketReturn {
14
+ isConnected: boolean
15
+ sendTyping: () => void
16
+ }
17
+
18
+ /**
19
+ * WebSocket hook for real-time chat updates.
20
+ * Auto-connects when leadId is provided, auto-reconnects on disconnect.
21
+ */
22
+ export function useChatWebSocket({
23
+ leadId,
24
+ onNewMessage,
25
+ onTyping,
26
+ onLeadUpdated
27
+ }: UseChatWebSocketOptions): UseChatWebSocketReturn {
28
+ const wsRef = useRef<WebSocket | null>(null)
29
+ const reconnectTimeoutRef = useRef<NodeJS.Timeout | null>(null)
30
+ const [isConnected, setIsConnected] = useState(false)
31
+
32
+ const connect = useCallback(() => {
33
+ if (!leadId) return
34
+
35
+ const token = localStorage.getItem('auth_token')
36
+ if (!token) {
37
+ console.warn('πŸ”Œ No auth token for WebSocket')
38
+ return
39
+ }
40
+
41
+ // Close existing connection
42
+ if (wsRef.current) {
43
+ wsRef.current.close()
44
+ }
45
+
46
+ // Determine WebSocket URL
47
+ const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'
48
+ const wsProtocol = apiUrl.startsWith('https') ? 'wss' : 'ws'
49
+ const wsHost = apiUrl.replace(/^https?:\/\//, '')
50
+ const wsUrl = `${wsProtocol}://${wsHost}/ws/chat/${leadId}?token=${token}`
51
+
52
+ console.log('πŸ”Œ Connecting WebSocket:', wsUrl.replace(token, '***'))
53
+
54
+ const ws = new WebSocket(wsUrl)
55
+ wsRef.current = ws
56
+
57
+ ws.onopen = () => {
58
+ console.log('πŸ”Œ WebSocket connected')
59
+ setIsConnected(true)
60
+ }
61
+
62
+ ws.onmessage = (event) => {
63
+ try {
64
+ const data = JSON.parse(event.data)
65
+
66
+ switch (data.type) {
67
+ case 'new_message':
68
+ console.log('πŸ“¨ New message via WebSocket:', data.message)
69
+ onNewMessage(data.message as Message)
70
+ break
71
+
72
+ case 'typing':
73
+ onTyping?.(data.user_id)
74
+ break
75
+
76
+ case 'lead_updated':
77
+ onLeadUpdated?.(data.lead)
78
+ break
79
+
80
+ case 'connected':
81
+ console.log('πŸ”Œ WebSocket confirmed connection for lead:', data.lead_id)
82
+ break
83
+
84
+ case 'pong':
85
+ // Heartbeat response
86
+ break
87
+ }
88
+ } catch (err) {
89
+ console.error('WebSocket message parse error:', err)
90
+ }
91
+ }
92
+
93
+ ws.onclose = (event) => {
94
+ console.log('πŸ”Œ WebSocket closed:', event.code, event.reason)
95
+ setIsConnected(false)
96
+
97
+ // Auto-reconnect after 3 seconds (unless intentional close)
98
+ if (event.code !== 1000) {
99
+ reconnectTimeoutRef.current = setTimeout(() => {
100
+ console.log('πŸ”„ Attempting WebSocket reconnect...')
101
+ connect()
102
+ }, 3000)
103
+ }
104
+ }
105
+
106
+ ws.onerror = (error) => {
107
+ console.error('πŸ”Œ WebSocket error:', error)
108
+ }
109
+ }, [leadId, onNewMessage, onTyping, onLeadUpdated])
110
+
111
+ // Connect when leadId changes
112
+ useEffect(() => {
113
+ if (leadId) {
114
+ connect()
115
+ }
116
+
117
+ return () => {
118
+ // Cleanup on unmount
119
+ if (reconnectTimeoutRef.current) {
120
+ clearTimeout(reconnectTimeoutRef.current)
121
+ }
122
+ if (wsRef.current) {
123
+ wsRef.current.close(1000, 'Component unmounted')
124
+ }
125
+ }
126
+ }, [leadId, connect])
127
+
128
+ // Heartbeat to keep connection alive
129
+ useEffect(() => {
130
+ const interval = setInterval(() => {
131
+ if (wsRef.current?.readyState === WebSocket.OPEN) {
132
+ wsRef.current.send(JSON.stringify({ type: 'ping' }))
133
+ }
134
+ }, 30000) // Every 30 seconds
135
+
136
+ return () => clearInterval(interval)
137
+ }, [])
138
+
139
+ const sendTyping = useCallback(() => {
140
+ if (wsRef.current?.readyState === WebSocket.OPEN) {
141
+ wsRef.current.send(JSON.stringify({ type: 'typing' }))
142
+ }
143
+ }, [])
144
+
145
+ return {
146
+ isConnected,
147
+ sendTyping
148
+ }
149
+ }