fix bug message
This commit is contained in:
@@ -31,7 +31,7 @@ const ShopInformation = ({ product }: ShopInformationProps) => {
|
||||
|
||||
const handleChatWithSeller = () => {
|
||||
// Navigate to chat page with product and shop context
|
||||
router.push(`/profile/chat?productId=${product._id}&shopId=${shop._id}`)
|
||||
router.push(`/profile/chat?productId=${product._id}&shopId=${shop.owner}`)
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
'use client'
|
||||
import { useState, useRef, useEffect, useMemo } from 'react'
|
||||
import Image from 'next/image'
|
||||
import { Trash, More, EmojiHappy, AttachCircle, Send, Shop, Call, VideoPlay } from 'iconsax-react'
|
||||
import { Send, Shop } from 'iconsax-react'
|
||||
import { useSocket } from '../hooks/useSocket'
|
||||
import { Message as SocketMessage } from '../service/SocketService'
|
||||
import { useChatDetail, useMarkChatAsRead } from '../../hooks/useChatData'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { isAuthenticated } from '@/config/func'
|
||||
import { ChatMessage as APIMessage } from '../../types/ProfileTypes'
|
||||
|
||||
@@ -17,17 +18,16 @@ interface Message {
|
||||
}
|
||||
|
||||
interface ChatMessagesProps {
|
||||
productId?: string | null
|
||||
shopId?: string | null
|
||||
chatId?: string
|
||||
}
|
||||
|
||||
export default function ChatMessages({ productId, shopId, chatId }: ChatMessagesProps) {
|
||||
export default function ChatMessages({ chatId }: ChatMessagesProps) {
|
||||
const [messageText, setMessageText] = useState('')
|
||||
const [isTyping, setIsTyping] = useState(false)
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null)
|
||||
const [isUserAuthenticated, setIsUserAuthenticated] = useState<boolean | null>(null)
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null)
|
||||
const messagesContainerRef = useRef<HTMLDivElement>(null)
|
||||
const typingTimeoutRef = useRef<NodeJS.Timeout | null>(null)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const markedAsReadRef = useRef<Set<string>>(new Set())
|
||||
@@ -51,37 +51,42 @@ export default function ChatMessages({ productId, shopId, chatId }: ChatMessages
|
||||
connect
|
||||
} = useSocket()
|
||||
|
||||
const queryClient = useQueryClient()
|
||||
const { data: chatData, isLoading, error } = useChatDetail(chatId)
|
||||
|
||||
const markAsRead = useMarkChatAsRead()
|
||||
|
||||
// Convert API messages to component format
|
||||
const messages: Message[] = useMemo(() =>
|
||||
chatData?.results?.messages?.map((msg: APIMessage) => ({
|
||||
const messages: Message[] = useMemo(() => {
|
||||
const apiMessages = chatData?.results?.messages
|
||||
if (Array.isArray(apiMessages)) {
|
||||
return apiMessages.map((msg: APIMessage) => ({
|
||||
id: msg._id,
|
||||
text: msg.content,
|
||||
time: new Date(msg.createdAt).toLocaleTimeString('fa-IR', {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
}),
|
||||
sender: msg.sender === 'customer' ? 'user' : 'admin',
|
||||
sender: msg.senderRef === 'User' ? 'user' : 'admin',
|
||||
status: msg.status
|
||||
})) || []
|
||||
, [chatData?.results?.messages])
|
||||
}))
|
||||
}
|
||||
return []
|
||||
}, [chatData?.results?.messages])
|
||||
|
||||
const scrollToBottom = () => {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" })
|
||||
if (messagesContainerRef.current) {
|
||||
messagesContainerRef.current.scrollTop = messagesContainerRef.current.scrollHeight
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
scrollToBottom()
|
||||
}, [messages])
|
||||
|
||||
// اتصال به چت وقتی chatId تنظیم شده و کاربر لاگین کرده
|
||||
// اتصال به سوکت وقتی chatId تنظیم شده و کاربر لاگین کرده
|
||||
useEffect(() => {
|
||||
if (chatId && chatId !== '' && isUserAuthenticated === true) {
|
||||
// اتصال به سوکت اگر متصل نیست
|
||||
if (!isConnected) {
|
||||
if (chatId && chatId !== '' && isUserAuthenticated === true && !isConnected) {
|
||||
console.log('🔌 اتصال به سوکت برای چت...')
|
||||
connect().catch((error) => {
|
||||
console.error('❌ خطا در اتصال سوکت:', error.message)
|
||||
@@ -92,17 +97,18 @@ export default function ChatMessages({ productId, shopId, chatId }: ChatMessages
|
||||
}
|
||||
})
|
||||
}
|
||||
}, [chatId, isUserAuthenticated, isConnected, connect])
|
||||
|
||||
// اتصال به چت
|
||||
if (isConnected) {
|
||||
// اتصال به چت وقتی سوکت متصل شد
|
||||
useEffect(() => {
|
||||
if (chatId && chatId !== '' && isConnected) {
|
||||
console.log('🔗 اتصال به چت:', chatId)
|
||||
joinChat(chatId)
|
||||
return () => {
|
||||
leaveChat(chatId)
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [chatId, isConnected, joinChat, leaveChat, connect, isUserAuthenticated])
|
||||
}, [chatId, isConnected, joinChat, leaveChat])
|
||||
|
||||
// Mark messages as read - فقط یک بار برای هر chatId
|
||||
useEffect(() => {
|
||||
@@ -123,9 +129,12 @@ export default function ChatMessages({ productId, shopId, chatId }: ChatMessages
|
||||
const handleNewMessage = (socketMessage: unknown) => {
|
||||
const message = socketMessage as SocketMessage
|
||||
if (message.chatId === chatId) {
|
||||
// The message will be added via React Query invalidation
|
||||
// or we can update local state if needed
|
||||
console.log('New message received:', message)
|
||||
// Invalidate chat detail query to refetch messages
|
||||
// This will handle both sent and received messages
|
||||
queryClient.invalidateQueries({ queryKey: ['chat', 'detail', chatId] })
|
||||
// Scroll to bottom after a short delay to ensure new message is rendered
|
||||
setTimeout(scrollToBottom, 100)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,7 +153,7 @@ export default function ChatMessages({ productId, shopId, chatId }: ChatMessages
|
||||
return () => {
|
||||
// Cleanup will be handled by the hook
|
||||
}
|
||||
}, [chatId, onNewMessage, onError])
|
||||
}, [chatId, onNewMessage, onError, queryClient])
|
||||
|
||||
const handleTyping = () => {
|
||||
if (!isTyping) {
|
||||
@@ -173,9 +182,9 @@ export default function ChatMessages({ productId, shopId, chatId }: ChatMessages
|
||||
}
|
||||
}
|
||||
|
||||
const handleAttachClick = () => {
|
||||
fileInputRef.current?.click()
|
||||
}
|
||||
// const handleAttachClick = () => {
|
||||
// fileInputRef.current?.click()
|
||||
// }
|
||||
|
||||
const handleSend = () => {
|
||||
if ((messageText.trim() || selectedFile) && chatId) {
|
||||
@@ -192,7 +201,17 @@ export default function ChatMessages({ productId, shopId, chatId }: ChatMessages
|
||||
// For now, just send text message
|
||||
// TODO: Implement file upload when server supports it
|
||||
if (content) {
|
||||
sendMessage(chatId, content)
|
||||
const receiver = chat?.seller
|
||||
if (receiver) {
|
||||
sendMessage(chatId, content, receiver)
|
||||
// Invalidate query to show sent message immediately after socket event
|
||||
// Note: This might cause duplicate if socket event also invalidates
|
||||
setTimeout(() => {
|
||||
queryClient.invalidateQueries({ queryKey: ['chat', 'detail', chatId] })
|
||||
}, 500)
|
||||
} else {
|
||||
console.error('❌ receiver یافت نشد - نمیتوان پیام ارسال کرد')
|
||||
}
|
||||
}
|
||||
|
||||
// Scroll to bottom after sending
|
||||
@@ -232,7 +251,7 @@ export default function ChatMessages({ productId, shopId, chatId }: ChatMessages
|
||||
className="object-cover"
|
||||
/>
|
||||
) : (
|
||||
<Shop size={18} className="text-primary" variant="Bold" />
|
||||
<Shop size={18} color="#1a73e8" variant="Bold" />
|
||||
)}
|
||||
</div>
|
||||
{/* وضعیت آنلاین در این API موجود نیست */}
|
||||
@@ -245,30 +264,6 @@ export default function ChatMessages({ productId, shopId, chatId }: ChatMessages
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<button className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
|
||||
<Call size={18} />
|
||||
</button>
|
||||
<button className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
|
||||
<VideoPlay size={18} />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => {
|
||||
// TODO: Implement delete chat functionality
|
||||
console.log('🗑️ درخواست حذف چت:', chatId)
|
||||
if (confirm('آیا از حذف این گفتگو مطمئن هستید؟')) {
|
||||
// deleteChatMutation.mutate(chatId)
|
||||
alert('این قابلیت هنوز پیادهسازی نشده است.')
|
||||
}
|
||||
}}
|
||||
className="p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors"
|
||||
>
|
||||
<Trash size={18} />
|
||||
</button>
|
||||
<button className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
|
||||
<More size={18} className="rotate-90" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center text-gray-500">
|
||||
@@ -278,7 +273,7 @@ export default function ChatMessages({ productId, shopId, chatId }: ChatMessages
|
||||
</div>
|
||||
|
||||
{/* Messages Area */}
|
||||
<div className="flex-1 overflow-y-auto bg-gray-50/30">
|
||||
<div ref={messagesContainerRef} className="flex-1 overflow-y-auto bg-gray-50/30">
|
||||
{/* Socket Status Alert */}
|
||||
{!isConnected && (
|
||||
<div className="px-6 py-3">
|
||||
@@ -286,7 +281,6 @@ export default function ChatMessages({ productId, shopId, chatId }: ChatMessages
|
||||
<div className="text-xs text-blue-800 leading-relaxed">
|
||||
<div className="font-semibold mb-2">ℹ️ اتصال به چت</div>
|
||||
<div className="space-y-1">
|
||||
<div>• در حال اتصال به سرور چت...</div>
|
||||
<div>• لطفاً چند لحظه صبر کنید</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -311,7 +305,7 @@ export default function ChatMessages({ productId, shopId, chatId }: ChatMessages
|
||||
<div key={i} className={`flex ${i % 2 === 0 ? 'justify-start' : 'justify-end'}`}>
|
||||
<div className="max-w-[70%]">
|
||||
<div className="w-16 h-4 bg-gray-200 rounded animate-pulse mb-2"></div>
|
||||
<div className={`rounded-2xl px-4 py-3 ${i % 2 === 0 ? 'bg-white' : 'bg-primary'} animate-pulse`}>
|
||||
<div className="rounded-2xl px-4 py-3 bg-gray-200 animate-pulse">
|
||||
<div className="w-32 h-4 bg-gray-100 rounded"></div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -325,17 +319,17 @@ export default function ChatMessages({ productId, shopId, chatId }: ChatMessages
|
||||
) : messages.length > 0 ? (
|
||||
messages.map((message, index) => {
|
||||
const isFirstInGroup = index === 0 || messages[index - 1].sender !== message.sender
|
||||
const senderName = message.sender === 'admin' ?
|
||||
(chat?.sellerRef || 'فروشگاه') : 'شما'
|
||||
const senderName = message.sender === 'user' ? 'شما' :
|
||||
(typeof chat?.sellerRef === 'string' ? chat.sellerRef : 'فروشگاه')
|
||||
|
||||
return (
|
||||
<div
|
||||
key={message.id}
|
||||
className={`flex ${message.sender === 'admin' ? 'justify-start' : 'justify-end'}`}
|
||||
className={`flex ${message.sender === 'user' ? 'justify-start' : 'justify-end'}`}
|
||||
>
|
||||
<div className={`max-w-[70%] ${message.sender === 'admin' ? 'mr-0' : 'ml-0'}`}>
|
||||
<div className={`max-w-[70%] ${message.sender === 'user' ? 'mr-0' : 'ml-0'}`}>
|
||||
{isFirstInGroup && (
|
||||
<div className={`flex items-center gap-2 mb-2 ${message.sender === 'admin' ? 'justify-start' : 'justify-end'}`}>
|
||||
<div className={`flex items-center gap-2 mb-2 ${message.sender === 'user' ? 'justify-start' : 'justify-end'}`}>
|
||||
<span className="text-xs text-gray-500 font-medium">
|
||||
{senderName}
|
||||
</span>
|
||||
@@ -344,16 +338,16 @@ export default function ChatMessages({ productId, shopId, chatId }: ChatMessages
|
||||
)}
|
||||
|
||||
<div
|
||||
className={`rounded-2xl px-4 py-3 shadow-sm ${message.sender === 'admin'
|
||||
className={`rounded-2xl px-4 py-3 shadow-sm ${message.sender === 'user'
|
||||
? 'bg-white text-gray-800 border border-gray-100'
|
||||
: 'bg-primary text-primary-foreground'
|
||||
}`}
|
||||
>
|
||||
<p className="text-sm leading-relaxed">{message.text}</p>
|
||||
<p className="text-sm leading-relaxed">{typeof message.text === 'string' ? message.text : 'پیام نامعتبر'}</p>
|
||||
</div>
|
||||
|
||||
{message.sender === 'user' && (
|
||||
<div className="flex justify-end mt-1">
|
||||
<div className="flex justify-start mt-1">
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="text-xs text-gray-400">{message.time}</span>
|
||||
{message.status === 'read' && (
|
||||
@@ -381,21 +375,21 @@ export default function ChatMessages({ productId, shopId, chatId }: ChatMessages
|
||||
|
||||
{/* Typing Indicator */}
|
||||
{isTyping && (
|
||||
<div className="flex justify-start mb-4">
|
||||
<div className="flex justify-end mb-4">
|
||||
<div className="max-w-[70%]">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<div className="flex items-center gap-2 mb-2 justify-end">
|
||||
<span className="text-xs text-gray-500 font-medium">
|
||||
{chat?.sellerRef || 'فروشگاه'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="bg-white border border-gray-100 rounded-2xl px-4 py-3 shadow-sm">
|
||||
<div className="bg-primary text-primary-foreground rounded-2xl px-4 py-3 shadow-sm">
|
||||
<div className="flex items-center gap-1">
|
||||
<div className="flex gap-1">
|
||||
<div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0ms' }}></div>
|
||||
<div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '150ms' }}></div>
|
||||
<div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '300ms' }}></div>
|
||||
<div className="w-2 h-2 bg-white rounded-full animate-bounce" style={{ animationDelay: '0ms' }}></div>
|
||||
<div className="w-2 h-2 bg-white rounded-full animate-bounce" style={{ animationDelay: '150ms' }}></div>
|
||||
<div className="w-2 h-2 bg-white rounded-full animate-bounce" style={{ animationDelay: '300ms' }}></div>
|
||||
</div>
|
||||
<span className="text-xs text-gray-500 ml-2">در حال تایپ...</span>
|
||||
<span className="text-xs text-white ml-2">در حال تایپ...</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -406,15 +400,16 @@ export default function ChatMessages({ productId, shopId, chatId }: ChatMessages
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Input Area */}
|
||||
{/* Input Area - Only show when chat is selected */}
|
||||
{chatId && chatId !== '' && (
|
||||
<div className="border-t border-gray-100 px-6 py-4 bg-white">
|
||||
<div className="flex items-end gap-3">
|
||||
<button
|
||||
<div className="flex items-center gap-3">
|
||||
{/* <button
|
||||
onClick={handleAttachClick}
|
||||
className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg transition-colors flex-shrink-0"
|
||||
>
|
||||
<AttachCircle size={20} />
|
||||
</button>
|
||||
<AttachCircle color='#8C90A3' size={20} />
|
||||
</button> */}
|
||||
|
||||
{/* Hidden file input */}
|
||||
<input
|
||||
@@ -461,23 +456,20 @@ export default function ChatMessages({ productId, shopId, chatId }: ChatMessages
|
||||
}}
|
||||
placeholder={selectedFile ? "توضیحات فایل را بنویسید..." : "پیام خود را بنویسید..."}
|
||||
rows={1}
|
||||
className="w-full resize-none bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 pr-12 text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent max-h-32"
|
||||
className="w-full resize-none bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent max-h-32"
|
||||
style={{ minHeight: '44px' }}
|
||||
/>
|
||||
<button className="absolute left-2 top-1/2 -translate-y-1/2 p-1.5 text-gray-400 hover:text-gray-600 hover:bg-gray-200 rounded-lg transition-colors">
|
||||
<EmojiHappy size={16} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleSend}
|
||||
disabled={(!messageText.trim() && !selectedFile) || !isConnected}
|
||||
className={`p-3 rounded-xl transition-all flex-shrink-0 ${(messageText.trim() || selectedFile) && isConnected
|
||||
? 'bg-primary hover:bg-primary/90 text-primary-foreground shadow-lg'
|
||||
className={`p-3 -mt-1 rounded-xl transition-all flex-shrink-0 ${(messageText.trim() || selectedFile) && isConnected
|
||||
? 'bg-primary hover:bg-primary/90 text-primary-foreground '
|
||||
: 'bg-gray-100 text-gray-400 cursor-not-allowed'
|
||||
}`}
|
||||
>
|
||||
<Send size={18} className="rotate-180" variant="Bold" />
|
||||
<Send color='#fff' size={18} className="rotate-180" variant="Bold" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -485,6 +477,7 @@ export default function ChatMessages({ productId, shopId, chatId }: ChatMessages
|
||||
پیام شما بعد از ارسال قابل حذف نیست
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
'use client'
|
||||
import { Shop, SearchNormal1 } from 'iconsax-react'
|
||||
import Image from 'next/image'
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useSocket } from '../hooks/useSocket'
|
||||
import { useChatList } from '../../hooks/useChatData'
|
||||
@@ -16,9 +17,9 @@ export default function ChatSidebar({ selectedChatId, onChatSelect }: ChatSideba
|
||||
const [isUserAuthenticated, setIsUserAuthenticated] = useState<boolean | null>(null)
|
||||
const [isConnecting, setIsConnecting] = useState(false)
|
||||
const router = useRouter()
|
||||
const { onUserOnline, onUserOffline, connect, isConnected, isServerSupported } = useSocket()
|
||||
const { onUserOnline, onUserOffline, connect, isConnected } = useSocket()
|
||||
const { data: chatData, isLoading, error } = useChatList({
|
||||
enabled: isUserAuthenticated === true // Only fetch if user is logged in
|
||||
enabled: isUserAuthenticated === true && isConnected // Only fetch if user is logged in AND socket is connected
|
||||
})
|
||||
|
||||
// Check authentication on mount
|
||||
@@ -33,17 +34,11 @@ export default function ChatSidebar({ selectedChatId, onChatSelect }: ChatSideba
|
||||
return
|
||||
}
|
||||
|
||||
// اگر سرور پشتیبانی نمیکند، اصلاً تلاش نکن
|
||||
if (!isServerSupported) {
|
||||
console.log('🚫 سرور Socket.IO پشتیبانی نمیکند، اتصال متوقف شد')
|
||||
return
|
||||
}
|
||||
|
||||
// فقط اگر قبلاً اتصال برقرار نشده، connect کنیم
|
||||
// اتصال به سوکت اگر متصل نیست
|
||||
if (!isConnected && !isConnecting) {
|
||||
console.log('🔌 شروع اتصال به سوکت...')
|
||||
setIsConnecting(true)
|
||||
connect('customer')
|
||||
connect()
|
||||
.then(() => {
|
||||
console.log('✅ اتصال سوکت موفق')
|
||||
setIsConnecting(false)
|
||||
@@ -51,6 +46,12 @@ export default function ChatSidebar({ selectedChatId, onChatSelect }: ChatSideba
|
||||
.catch((error) => {
|
||||
console.log('❌ اتصال سوکت شکست خورد:', error.message)
|
||||
setIsConnecting(false)
|
||||
|
||||
// اگر توکن expired است، redirect به login
|
||||
if (error.message === 'توکن منقضی شده' || error.message === 'توکن یافت نشد') {
|
||||
console.log('🔐 توکن نامعتبر، redirect به صفحه ورود')
|
||||
router.push('/auth')
|
||||
}
|
||||
})
|
||||
} else if (isConnected) {
|
||||
console.log('ℹ️ اتصال سوکت قبلاً برقرار شده')
|
||||
@@ -58,7 +59,7 @@ export default function ChatSidebar({ selectedChatId, onChatSelect }: ChatSideba
|
||||
}
|
||||
|
||||
checkAuth()
|
||||
}, [connect, router, isConnected, isConnecting, isServerSupported])
|
||||
}, [connect, router, isConnected, isConnecting])
|
||||
|
||||
// Listen for user online/offline events
|
||||
useEffect(() => {
|
||||
@@ -83,11 +84,15 @@ export default function ChatSidebar({ selectedChatId, onChatSelect }: ChatSideba
|
||||
}
|
||||
}, [onUserOnline, onUserOffline])
|
||||
|
||||
const chats = chatData?.results?.chats || []
|
||||
const chats = Array.isArray(chatData?.results?.chats) ? chatData.results.chats : []
|
||||
|
||||
const filteredChats = chats.filter(chat =>
|
||||
chat.participants.seller.shopName.toLowerCase().includes(searchQuery.toLowerCase())
|
||||
)
|
||||
const filteredChats = chats.filter(chat => {
|
||||
if (!chat || typeof chat !== 'object') return false
|
||||
if (!chat.seller || typeof chat.seller !== 'object') return false
|
||||
const fullName = chat.seller.fullName
|
||||
if (typeof fullName !== 'string') return false
|
||||
return fullName.toLowerCase().includes(searchQuery.toLowerCase())
|
||||
})
|
||||
|
||||
const handleChatClick = (chatId: string) => {
|
||||
if (onChatSelect) {
|
||||
@@ -117,8 +122,27 @@ export default function ChatSidebar({ selectedChatId, onChatSelect }: ChatSideba
|
||||
{/* Chat List */}
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
{isLoading ? (
|
||||
<div className="p-8 text-center text-gray-400">
|
||||
<p className="text-sm">در حال بارگذاری...</p>
|
||||
<div className="divide-y divide-gray-50">
|
||||
{[1, 2, 3, 4, 5].map((i) => (
|
||||
<div key={i} className="p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
{/* Avatar Skeleton */}
|
||||
<div className="relative flex-shrink-0">
|
||||
<div className="w-12 h-12 bg-gray-200 rounded-full animate-pulse"></div>
|
||||
</div>
|
||||
|
||||
{/* Content Skeleton */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<div className="h-4 bg-gray-200 rounded animate-pulse w-24"></div>
|
||||
<div className="h-3 bg-gray-200 rounded animate-pulse w-12"></div>
|
||||
</div>
|
||||
<div className="h-3 bg-gray-200 rounded animate-pulse w-32 mb-2"></div>
|
||||
<div className="h-3 bg-gray-200 rounded animate-pulse w-20"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="p-8 text-center text-red-400">
|
||||
@@ -129,55 +153,41 @@ export default function ChatSidebar({ selectedChatId, onChatSelect }: ChatSideba
|
||||
{filteredChats.map((chat) => (
|
||||
<div
|
||||
key={chat._id}
|
||||
onClick={() => handleChatClick(chat.chatId)}
|
||||
className={`p-4 cursor-pointer transition-all hover:bg-gray-50 ${selectedChatId === chat.chatId ? 'bg-primary/5 border-r-2 border-r-primary' : ''
|
||||
onClick={() => handleChatClick(chat._id)}
|
||||
className={`p-4 cursor-pointer transition-all hover:bg-gray-50 ${selectedChatId === chat._id ? 'bg-primary/5 border-r-2 border-r-primary' : ''
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
{/* Avatar */}
|
||||
<div className="relative flex-shrink-0">
|
||||
<div className="w-12 h-12 bg-gradient-to-br from-primary/10 to-primary/20 rounded-full flex items-center justify-center overflow-hidden">
|
||||
{chat.participants.seller.logo ? (
|
||||
<img
|
||||
src={chat.participants.seller.logo}
|
||||
alt={chat.participants.seller.shopName}
|
||||
className="w-full h-full object-cover"
|
||||
{chat.shopLogo?.logo ? (
|
||||
<Image
|
||||
src={chat.shopLogo.logo}
|
||||
alt={chat.seller?.fullName || 'فروشنده'}
|
||||
fill
|
||||
className="object-cover"
|
||||
/>
|
||||
) : (
|
||||
<Shop size={20} className="text-primary" variant="Bold" />
|
||||
)}
|
||||
</div>
|
||||
{chat.isOnline && (
|
||||
<div className="absolute -bottom-0.5 -right-0.5 w-4 h-4 bg-green-500 border-2 border-white rounded-full"></div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center justify-between mb-1">
|
||||
<h3 className="font-semibold text-gray-900 text-sm truncate">
|
||||
{chat.participants.seller.shopName}
|
||||
{typeof chat.seller?.fullName === 'string' ? chat.seller.fullName : 'فروشنده'}
|
||||
</h3>
|
||||
<span className="text-xs text-gray-400 flex-shrink-0">
|
||||
{chat.lastMessage ?
|
||||
new Date(chat.lastMessage.createdAt).toLocaleTimeString('fa-IR', {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
}) :
|
||||
new Date(chat.updatedAt).toLocaleDateString('fa-IR')
|
||||
}
|
||||
{new Date(chat.updatedAt).toLocaleDateString('fa-IR')}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-gray-500 truncate mb-2">
|
||||
{chat.lastMessage?.content || 'گفتگوی جدید'}
|
||||
{typeof chat.lastMessage === 'string' ? chat.lastMessage : 'گفتگوی جدید'}
|
||||
</p>
|
||||
|
||||
{chat.unreadCount > 0 && (
|
||||
<div className="inline-flex items-center px-2 py-0.5 bg-primary text-primary-foreground text-xs font-medium rounded-full">
|
||||
{chat.unreadCount}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -7,88 +7,84 @@ import {
|
||||
|
||||
export interface UseSocketReturn {
|
||||
isConnected: boolean;
|
||||
isConnecting: boolean;
|
||||
isServerSupported: boolean;
|
||||
connect: (type?: "customer" | "seller") => Promise<void>;
|
||||
connect: () => Promise<void>;
|
||||
disconnect: () => void;
|
||||
joinChat: (chatId: string) => void;
|
||||
leaveChat: (chatId: string) => void;
|
||||
sendMessage: (chatId: string, content: string) => void;
|
||||
onUserOnline: (callback: (userId: unknown) => void) => void;
|
||||
onUserOffline: (callback: (userId: unknown) => void) => void;
|
||||
onUnreadMessages: (callback: (messages: unknown) => void) => void;
|
||||
onNewMessage: (callback: (message: unknown) => void) => void;
|
||||
sendMessage: (chatId: string, content: string, receiver: string) => void;
|
||||
onNewMessage: (callback: (message: Message) => void) => void;
|
||||
onUnreadMessages: (callback: (messages: UnreadMessage[]) => void) => void;
|
||||
onUserOnline: (callback: (userId: string) => void) => void;
|
||||
onUserOffline: (callback: (userId: string) => void) => void;
|
||||
onError: (callback: (error: unknown) => void) => void;
|
||||
offUserOnline: (callback: (userId: unknown) => void) => void;
|
||||
offUserOffline: (callback: (userId: unknown) => void) => void;
|
||||
offUnreadMessages: (callback: (messages: unknown) => void) => void;
|
||||
offNewMessage: (callback: (message: unknown) => void) => void;
|
||||
offNewMessage: (callback: (message: Message) => void) => void;
|
||||
offUnreadMessages: (callback: (messages: UnreadMessage[]) => void) => void;
|
||||
offUserOnline: (callback: (userId: string) => void) => void;
|
||||
offUserOffline: (callback: (userId: string) => void) => void;
|
||||
offError: (callback: (error: unknown) => void) => void;
|
||||
}
|
||||
|
||||
export const useSocket = (): UseSocketReturn => {
|
||||
const [isConnected, setIsConnected] = useState(false);
|
||||
const [isConnecting, setIsConnecting] = useState(false);
|
||||
|
||||
// Connect to socket
|
||||
const connect = useCallback(
|
||||
async (type: "customer" | "seller" = "customer") => {
|
||||
if (isConnected || isConnecting) return;
|
||||
// اتصال به سوکت
|
||||
const connect = useCallback(async () => {
|
||||
if (isConnected) return;
|
||||
|
||||
setIsConnecting(true);
|
||||
try {
|
||||
await socketService.connect(type);
|
||||
console.log("🔌 شروع اتصال به سوکت...");
|
||||
await socketService.connect("User");
|
||||
setIsConnected(true);
|
||||
console.log("✅ سوکت متصل شد");
|
||||
} catch (error) {
|
||||
console.error("خطا در اتصال سوکت:", error);
|
||||
console.error("❌ خطا در اتصال سوکت:", error);
|
||||
throw error;
|
||||
} finally {
|
||||
setIsConnecting(false);
|
||||
}
|
||||
},
|
||||
[isConnected, isConnecting]
|
||||
);
|
||||
}, [isConnected]);
|
||||
|
||||
// Disconnect socket
|
||||
// قطع اتصال سوکت
|
||||
const disconnect = useCallback(() => {
|
||||
console.log("🔌 قطع اتصال سوکت");
|
||||
socketService.disconnect();
|
||||
setIsConnected(false);
|
||||
setIsConnecting(false);
|
||||
}, []);
|
||||
|
||||
// Join chat room
|
||||
// ورود به چت
|
||||
const joinChat = useCallback((chatId: string) => {
|
||||
socketService.joinChat(chatId);
|
||||
}, []);
|
||||
|
||||
// Leave chat room
|
||||
// خروج از چت
|
||||
const leaveChat = useCallback((chatId: string) => {
|
||||
socketService.leaveChat(chatId);
|
||||
}, []);
|
||||
|
||||
// Send message
|
||||
const sendMessage = useCallback((chatId: string, content: string) => {
|
||||
socketService.sendMessage(chatId, content);
|
||||
}, []);
|
||||
|
||||
// Event listeners
|
||||
const onUserOnline = useCallback((callback: (userId: unknown) => void) => {
|
||||
socketService.on("userOnline", callback);
|
||||
}, []);
|
||||
|
||||
const onUserOffline = useCallback((callback: (userId: unknown) => void) => {
|
||||
socketService.on("userOffline", callback);
|
||||
}, []);
|
||||
|
||||
const onUnreadMessages = useCallback(
|
||||
(callback: (messages: unknown) => void) => {
|
||||
socketService.on("unreadMessages", callback);
|
||||
// ارسال پیام
|
||||
const sendMessage = useCallback(
|
||||
(chatId: string, content: string, receiver: string) => {
|
||||
socketService.sendMessage(chatId, content, receiver);
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const onNewMessage = useCallback((callback: (message: unknown) => void) => {
|
||||
socketService.on("newMessage", callback);
|
||||
// Event listeners
|
||||
const onNewMessage = useCallback((callback: (message: Message) => void) => {
|
||||
socketService.on("newMessage", callback as (data: unknown) => void);
|
||||
}, []);
|
||||
|
||||
const onUnreadMessages = useCallback(
|
||||
(callback: (messages: UnreadMessage[]) => void) => {
|
||||
socketService.on("unreadMessages", callback as (data: unknown) => void);
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const onUserOnline = useCallback((callback: (userId: string) => void) => {
|
||||
socketService.on("userOnline", callback as (data: unknown) => void);
|
||||
}, []);
|
||||
|
||||
const onUserOffline = useCallback((callback: (userId: string) => void) => {
|
||||
socketService.on("userOffline", callback as (data: unknown) => void);
|
||||
}, []);
|
||||
|
||||
const onError = useCallback((callback: (error: unknown) => void) => {
|
||||
@@ -96,38 +92,45 @@ export const useSocket = (): UseSocketReturn => {
|
||||
}, []);
|
||||
|
||||
// Remove event listeners
|
||||
const offUserOnline = useCallback((callback: (userId: unknown) => void) => {
|
||||
socketService.off("userOnline", callback);
|
||||
}, []);
|
||||
|
||||
const offUserOffline = useCallback((callback: (userId: unknown) => void) => {
|
||||
socketService.off("userOffline", callback);
|
||||
const offNewMessage = useCallback((callback: (message: Message) => void) => {
|
||||
socketService.off("newMessage", callback as (data: unknown) => void);
|
||||
}, []);
|
||||
|
||||
const offUnreadMessages = useCallback(
|
||||
(callback: (messages: unknown) => void) => {
|
||||
socketService.off("unreadMessages", callback);
|
||||
(callback: (messages: UnreadMessage[]) => void) => {
|
||||
socketService.off("unreadMessages", callback as (data: unknown) => void);
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const offNewMessage = useCallback((callback: (message: unknown) => void) => {
|
||||
socketService.off("newMessage", callback);
|
||||
const offUserOnline = useCallback((callback: (userId: string) => void) => {
|
||||
socketService.off("userOnline", callback as (data: unknown) => void);
|
||||
}, []);
|
||||
|
||||
const offUserOffline = useCallback((callback: (userId: string) => void) => {
|
||||
socketService.off("userOffline", callback as (data: unknown) => void);
|
||||
}, []);
|
||||
|
||||
const offError = useCallback((callback: (error: unknown) => void) => {
|
||||
socketService.off("error", callback);
|
||||
}, []);
|
||||
|
||||
// Setup connection status listener
|
||||
// تنظیم وضعیت اتصال
|
||||
useEffect(() => {
|
||||
const handleConnect = () => setIsConnected(true);
|
||||
const handleDisconnect = () => setIsConnected(false);
|
||||
const handleConnect = () => {
|
||||
console.log("📡 سوکت متصل شد");
|
||||
setIsConnected(true);
|
||||
};
|
||||
|
||||
const handleDisconnect = () => {
|
||||
console.log("📡 سوکت قطع شد");
|
||||
setIsConnected(false);
|
||||
};
|
||||
|
||||
socketService.on("connect", handleConnect);
|
||||
socketService.on("disconnect", handleDisconnect);
|
||||
|
||||
// Check initial connection status
|
||||
// بررسی وضعیت اولیه
|
||||
setIsConnected(socketService.isConnected());
|
||||
|
||||
return () => {
|
||||
@@ -136,31 +139,22 @@ export const useSocket = (): UseSocketReturn => {
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Cleanup on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
// Don't disconnect on unmount, let the service manage its own lifecycle
|
||||
};
|
||||
}, []);
|
||||
|
||||
return {
|
||||
isConnected,
|
||||
isConnecting,
|
||||
isServerSupported: socketService.getServerSupported(),
|
||||
connect,
|
||||
disconnect,
|
||||
joinChat,
|
||||
leaveChat,
|
||||
sendMessage,
|
||||
onNewMessage,
|
||||
onUnreadMessages,
|
||||
onUserOnline,
|
||||
onUserOffline,
|
||||
onUnreadMessages,
|
||||
onNewMessage,
|
||||
onError,
|
||||
offNewMessage,
|
||||
offUnreadMessages,
|
||||
offUserOnline,
|
||||
offUserOffline,
|
||||
offUnreadMessages,
|
||||
offNewMessage,
|
||||
offError,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -6,18 +6,19 @@ import { useState, useEffect, Suspense } from "react"
|
||||
import Menu from "../components/Menu"
|
||||
import ChatSidebar from "./components/ChatSidebar"
|
||||
import ChatMessages from "./components/ChatMessages"
|
||||
import ChatProductCard from "./components/ChatProductCard"
|
||||
import { isAuthenticated } from "@/config/func"
|
||||
import { useCreateChat } from "../hooks/useChatData"
|
||||
|
||||
const ChatContent: React.FC = () => {
|
||||
const searchParams = useSearchParams()
|
||||
const productId = searchParams.get('productId')
|
||||
const shopId = searchParams.get('shopId')
|
||||
const createChat = useCreateChat()
|
||||
const router = useRouter()
|
||||
|
||||
const [selectedChatId, setSelectedChatId] = useState<string>('')
|
||||
const [isUserAuthenticated, setIsUserAuthenticated] = useState<boolean | null>(null)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [isInitialized, setIsInitialized] = useState(false)
|
||||
|
||||
// Check authentication on mount
|
||||
useEffect(() => {
|
||||
@@ -29,7 +30,13 @@ const ChatContent: React.FC = () => {
|
||||
if (!authenticated) {
|
||||
console.log('🔐 کاربر login نکرده یا توکن expire شده، redirect به صفحه ورود')
|
||||
router.push('/auth')
|
||||
return
|
||||
}
|
||||
|
||||
// کمی صبر کن تا کامپوننتها آماده شوند
|
||||
setTimeout(() => {
|
||||
setIsInitialized(true)
|
||||
}, 100)
|
||||
}
|
||||
|
||||
checkAuth()
|
||||
@@ -39,6 +46,14 @@ const ChatContent: React.FC = () => {
|
||||
setSelectedChatId(chatId)
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
if (shopId) {
|
||||
createChat.mutate({ sellerId: shopId })
|
||||
}
|
||||
|
||||
}, [shopId, createChat])
|
||||
|
||||
// Show loading while checking authentication
|
||||
if (isLoading) {
|
||||
return (
|
||||
@@ -73,36 +88,46 @@ const ChatContent: React.FC = () => {
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
return (
|
||||
<Layout>
|
||||
<div className="p-3 sm:p-4 md:p-6">
|
||||
<Menu pageActive='chat' />
|
||||
|
||||
<div className="mt-6 flex gap-8 h-[calc(100vh-200px)] min-h-[600px]">
|
||||
<div className="mt-6 h-[calc(100vh-200px)] min-h-[600px]">
|
||||
{/* Chat Section - Sidebar + Messages */}
|
||||
<div className="flex-1 flex border border-gray-200 shadow-sm rounded-xl bg-white">
|
||||
<div className="flex border border-gray-200 shadow-sm rounded-xl bg-white h-full">
|
||||
{/* Chat Sidebar - Left Side */}
|
||||
<div className="w-80 border-r border-gray-200">
|
||||
{isInitialized ? (
|
||||
<ChatSidebar
|
||||
selectedChatId={selectedChatId}
|
||||
onChatSelect={handleChatSelect}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-full">
|
||||
<div className="text-center">
|
||||
<div className="text-sm text-gray-500">در حال بارگذاری چت...</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Chat Messages - Right Side */}
|
||||
<div className="flex-1 min-w-0">
|
||||
{isInitialized ? (
|
||||
<ChatMessages
|
||||
productId={productId}
|
||||
shopId={shopId}
|
||||
chatId={selectedChatId}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-full">
|
||||
<div className="text-center">
|
||||
<div className="text-sm text-gray-500">در حال بارگذاری پیامها...</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Product Card - Right Side */}
|
||||
<div className="w-80 flex-shrink-0">
|
||||
<div className="bg-white rounded-xl border border-gray-200 shadow-sm">
|
||||
<ChatProductCard productId={productId} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -5,6 +5,7 @@ export interface Message {
|
||||
id: string;
|
||||
chatId: string;
|
||||
sender: string;
|
||||
receiver: string;
|
||||
content: string;
|
||||
createdAt: string;
|
||||
}
|
||||
@@ -12,18 +13,13 @@ export interface Message {
|
||||
export interface UnreadMessage {
|
||||
chatId: string;
|
||||
sender: string;
|
||||
receiver: string;
|
||||
content: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
class SocketService {
|
||||
private socket: Socket | null = null;
|
||||
private reconnectAttempts = 0;
|
||||
private maxReconnectAttempts = 1; // کاهش تعداد تلاشها
|
||||
private reconnectDelay = 2000; // افزایش delay
|
||||
private isServerSupported = false; // آیا سرور پشتیبانی میکند
|
||||
|
||||
// Event listeners
|
||||
private eventListeners: { [key: string]: ((data: unknown) => void)[] } = {};
|
||||
|
||||
constructor() {
|
||||
@@ -32,81 +28,87 @@ class SocketService {
|
||||
|
||||
private initializeEventListeners() {
|
||||
this.eventListeners = {
|
||||
userOnline: [],
|
||||
userOffline: [],
|
||||
unreadMessages: [],
|
||||
newMessage: [],
|
||||
error: [],
|
||||
unauthorized: [],
|
||||
connect: [],
|
||||
disconnect: [],
|
||||
newMessage: [],
|
||||
unreadMessages: [],
|
||||
userOnline: [],
|
||||
userOffline: [],
|
||||
error: [],
|
||||
};
|
||||
}
|
||||
|
||||
// Connect to socket server
|
||||
connect(type: "customer" | "seller" = "customer"): Promise<void> {
|
||||
// اتصال ساده به سوکت شبیه کد تست
|
||||
connect(type: "User" | "Seller" = "User"): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
// Get token from localStorage
|
||||
// دریافت توکن از localStorage با بررسی دقیق
|
||||
const token = localStorage.getItem(TOKEN_NAME);
|
||||
console.log("🔑 توکن سوکت:", token ? "موجود است" : "پیدا نشد");
|
||||
if (!token) {
|
||||
console.log("❌ اتصال رد شد: توکن موجود نیست");
|
||||
console.log(
|
||||
"🔑 توکن سوکت:",
|
||||
token ? `${token.substring(0, 20)}...` : "پیدا نشد"
|
||||
);
|
||||
|
||||
if (!token || token.trim() === "") {
|
||||
console.log("❌ اتصال رد شد: توکن موجود نیست یا خالی است");
|
||||
reject(new Error("توکن یافت نشد"));
|
||||
return;
|
||||
}
|
||||
|
||||
// اگر قبلاً تشخیص دادهایم سرور پشتیبانی نمیکند
|
||||
if (!this.isServerSupported && this.reconnectAttempts > 0) {
|
||||
console.log("🚫 اتصال رد شد: سرور Socket.IO پشتیبانی نمیکند");
|
||||
reject(new Error("سرور چت پشتیبانی نمیشود"));
|
||||
// بررسی اعتبار توکن (ساده)
|
||||
if (token.length < 10) {
|
||||
console.log("❌ اتصال رد شد: توکن نامعتبر است (خیلی کوتاه)");
|
||||
reject(new Error("توکن نامعتبر"));
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("🔌 شروع اتصال سوکت به:", `${BASE_URL}/ws-chat`);
|
||||
console.log("📝 پارامترهای اتصال:", {
|
||||
token: token.substring(0, 20) + "...",
|
||||
type,
|
||||
});
|
||||
// بررسی اینکه آیا توکن JWT است و expired نشده
|
||||
try {
|
||||
const payload = JSON.parse(atob(token.split(".")[1]));
|
||||
const currentTime = Math.floor(Date.now() / 1000);
|
||||
if (payload.exp && payload.exp < currentTime) {
|
||||
console.log("❌ اتصال رد شد: توکن expired است");
|
||||
reject(new Error("توکن منقضی شده"));
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
console.log("⚠️ نمیتوان اعتبار توکن را بررسی کرد، ادامه...");
|
||||
}
|
||||
|
||||
// Create socket connection
|
||||
console.log("🔌 شروع اتصال سوکت به:", `${BASE_URL}/ws-chat`);
|
||||
|
||||
// ایجاد اتصال سوکت دقیقاً مثل کد تست
|
||||
this.socket = io(BASE_URL, {
|
||||
path: "/ws-chat",
|
||||
query: {
|
||||
token,
|
||||
type,
|
||||
token: token.trim(), // حذف فضای خالی
|
||||
type: type,
|
||||
},
|
||||
transports: ["websocket"],
|
||||
timeout: 10000, // 10 seconds timeout
|
||||
timeout: 10000, // 10 ثانیه timeout
|
||||
});
|
||||
|
||||
// Setup event listeners
|
||||
// تنظیم event listeners
|
||||
this.setupSocketListeners();
|
||||
|
||||
// Handle connection
|
||||
// مدیریت اتصال موفق
|
||||
this.socket.on("connect", () => {
|
||||
console.log("✅ اتصال سوکت برقرار شد");
|
||||
this.reconnectAttempts = 0;
|
||||
this.isServerSupported = true; // سرور پشتیبانی میکند
|
||||
console.log("✅ اتصال سوکت برقرار شد، socket id:", this.socket?.id);
|
||||
this.emit("connect", null);
|
||||
resolve();
|
||||
});
|
||||
|
||||
this.socket.on("connect_error", (error) => {
|
||||
console.error("❌ خطا در اتصال سوکت:", error.message);
|
||||
console.log("⚠️ احتمالاً سرور Socket.IO پیادهسازی نشده است");
|
||||
// مدیریت خطای اتصال
|
||||
this.socket.on("connect_error", (err) => {
|
||||
console.error("❌ خطا در اتصال سوکت:", err.message);
|
||||
this.emit("error", err);
|
||||
reject(err);
|
||||
});
|
||||
|
||||
// اگر چندین بار شکست خورد، فرض میکنیم سرور پشتیبانی نمیکند
|
||||
if (this.reconnectAttempts >= 1) {
|
||||
console.log(
|
||||
"🚫 سرور Socket.IO پشتیبانی نمیشود، reconnect متوقف شد"
|
||||
);
|
||||
this.isServerSupported = false;
|
||||
reject(new Error("سرور چت پشتیبانی نمیشود"));
|
||||
return;
|
||||
}
|
||||
|
||||
reject(error);
|
||||
// مدیریت قطع اتصال
|
||||
this.socket.on("disconnect", () => {
|
||||
console.log("❌ اتصال سوکت قطع شد");
|
||||
this.emit("disconnect", null);
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("خطا در ایجاد اتصال سوکت:", error);
|
||||
@@ -115,122 +117,95 @@ class SocketService {
|
||||
});
|
||||
}
|
||||
|
||||
// Setup socket event listeners
|
||||
// تنظیم event listeners برای پیامها
|
||||
private setupSocketListeners() {
|
||||
if (!this.socket) return;
|
||||
|
||||
// User online/offline events
|
||||
this.socket.on("userOnline", (userId: string) => {
|
||||
console.log("کاربر آنلاین شد:", userId);
|
||||
this.emit("userOnline", userId);
|
||||
// پیام جدید
|
||||
this.socket.on("newMessage", (msg) => {
|
||||
console.log("💬 پیام جدید دریافت شد:", msg);
|
||||
this.emit("newMessage", msg);
|
||||
});
|
||||
|
||||
this.socket.on("userOffline", (userId: string) => {
|
||||
console.log("کاربر آفلاین شد:", userId);
|
||||
this.emit("userOffline", userId);
|
||||
});
|
||||
|
||||
// Unread messages
|
||||
this.socket.on("unreadMessages", (messages: UnreadMessage[]) => {
|
||||
console.log("پیامهای خوانده نشده:", messages);
|
||||
// پیامهای خوانده نشده
|
||||
this.socket.on("unreadMessages", (messages) => {
|
||||
console.log("📨 پیامهای خوانده نشده:", messages);
|
||||
this.emit("unreadMessages", messages);
|
||||
});
|
||||
|
||||
// New message
|
||||
this.socket.on("newMessage", (message: Message) => {
|
||||
console.log("پیام جدید:", message);
|
||||
this.emit("newMessage", message);
|
||||
// کاربر آنلاین
|
||||
this.socket.on("userOnline", (userId) => {
|
||||
console.log("🟢 کاربر آنلاین شد:", userId);
|
||||
this.emit("userOnline", userId);
|
||||
});
|
||||
|
||||
// Error handling
|
||||
this.socket.on("error", (error: { message: string }) => {
|
||||
console.error("خطای سوکت:", error.message);
|
||||
this.emit("error", error);
|
||||
// کاربر آفلاین
|
||||
this.socket.on("userOffline", (userId) => {
|
||||
console.log("🔴 کاربر آفلاین شد:", userId);
|
||||
this.emit("userOffline", userId);
|
||||
});
|
||||
|
||||
this.socket.on("unauthorized", (data: { message: string }) => {
|
||||
console.error("دسترسی غیرمجاز:", data.message);
|
||||
this.emit("unauthorized", data);
|
||||
});
|
||||
|
||||
// Connection events
|
||||
this.socket.on("disconnect", (reason: string) => {
|
||||
console.log("اتصال سوکت قطع شد:", reason);
|
||||
this.emit("disconnect", reason);
|
||||
|
||||
// Auto reconnect if not manual disconnect
|
||||
if (
|
||||
reason !== "io client disconnect" &&
|
||||
this.reconnectAttempts < this.maxReconnectAttempts
|
||||
) {
|
||||
this.scheduleReconnect();
|
||||
}
|
||||
// خطا
|
||||
this.socket.on("error", (data) => {
|
||||
console.error("⚠️ خطای سوکت:", data);
|
||||
this.emit("error", data);
|
||||
});
|
||||
}
|
||||
|
||||
// Schedule reconnection
|
||||
private scheduleReconnect() {
|
||||
// اگر سرور پشتیبانی نمیکند، reconnect نکن
|
||||
if (!this.isServerSupported) {
|
||||
console.log("🚫 reconnect متوقف شد چون سرور پشتیبانی نمیکند");
|
||||
return;
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
this.reconnectAttempts++;
|
||||
console.log(
|
||||
`🔄 تلاش برای اتصال مجدد (${this.reconnectAttempts}/${this.maxReconnectAttempts})`
|
||||
);
|
||||
|
||||
const token = localStorage.getItem(TOKEN_NAME);
|
||||
if (token && this.socket) {
|
||||
this.socket.connect();
|
||||
} else {
|
||||
console.log("❌ توکن یا سوکت موجود نیست، reconnect متوقف شد");
|
||||
}
|
||||
}, this.reconnectDelay * this.reconnectAttempts);
|
||||
}
|
||||
|
||||
// Join a chat room
|
||||
// ورود به چت
|
||||
joinChat(chatId: string): void {
|
||||
if (this.socket && this.socket.connected) {
|
||||
console.log("🔗 ورود به چت:", chatId);
|
||||
this.socket.emit("joinChat", chatId);
|
||||
console.log("ورود به چت:", chatId);
|
||||
} else {
|
||||
console.error("سوکت متصل نیست");
|
||||
this.emit("error", { message: "اتصال سوکت برقرار نیست" });
|
||||
console.error("سوکت متصل نیست - نمیتوان به چت وارد شد");
|
||||
}
|
||||
}
|
||||
|
||||
// Leave a chat room
|
||||
// خروج از چت
|
||||
leaveChat(chatId: string): void {
|
||||
if (this.socket && this.socket.connected) {
|
||||
console.log("🚪 خروج از چت:", chatId);
|
||||
this.socket.emit("leaveChat", chatId);
|
||||
console.log("خروج از چت:", chatId);
|
||||
}
|
||||
}
|
||||
|
||||
// Send a message
|
||||
sendMessage(chatId: string, content: string): void {
|
||||
// ارسال پیام
|
||||
sendMessage(chatId: string, content: string, receiver: string): void {
|
||||
if (this.socket && this.socket.connected) {
|
||||
console.log("📤 ارسال پیام:", { chatId, content, receiver });
|
||||
this.socket.emit("newMessage", {
|
||||
chatId,
|
||||
content,
|
||||
receiver,
|
||||
});
|
||||
console.log("ارسال پیام:", { chatId, content });
|
||||
} else {
|
||||
console.error("سوکت متصل نیست");
|
||||
this.emit("error", { message: "اتصال سوکت برقرار نیست" });
|
||||
console.error("سوکت متصل نیست - نمیتوان پیام ارسال کرد");
|
||||
}
|
||||
}
|
||||
|
||||
// Event system
|
||||
on(event: string, callback: (data: unknown) => void): void {
|
||||
if (this.eventListeners[event]) {
|
||||
this.eventListeners[event].push(callback);
|
||||
// قطع اتصال
|
||||
disconnect(): void {
|
||||
if (this.socket) {
|
||||
console.log("🔌 قطع اتصال سوکت");
|
||||
this.socket.disconnect();
|
||||
this.socket = null;
|
||||
}
|
||||
}
|
||||
|
||||
// بررسی اتصال
|
||||
isConnected(): boolean {
|
||||
return this.socket?.connected || false;
|
||||
}
|
||||
|
||||
// سیستم event
|
||||
on(event: string, callback: (data: unknown) => void): void {
|
||||
if (!this.eventListeners[event]) {
|
||||
this.eventListeners[event] = [];
|
||||
}
|
||||
this.eventListeners[event].push(callback);
|
||||
}
|
||||
|
||||
off(event: string, callback: (data: unknown) => void): void {
|
||||
if (this.eventListeners[event]) {
|
||||
this.eventListeners[event] = this.eventListeners[event].filter(
|
||||
@@ -244,31 +219,7 @@ class SocketService {
|
||||
this.eventListeners[event].forEach((callback) => callback(data));
|
||||
}
|
||||
}
|
||||
|
||||
// Disconnect socket
|
||||
disconnect(): void {
|
||||
if (this.socket) {
|
||||
this.socket.disconnect();
|
||||
this.socket = null;
|
||||
}
|
||||
this.reconnectAttempts = 0;
|
||||
}
|
||||
|
||||
// Check if socket is connected
|
||||
isConnected(): boolean {
|
||||
return this.socket?.connected || false;
|
||||
}
|
||||
|
||||
// Check if server supports socket
|
||||
getServerSupported(): boolean {
|
||||
return this.isServerSupported;
|
||||
}
|
||||
|
||||
// Get socket instance (for advanced usage)
|
||||
getSocket(): Socket | null {
|
||||
return this.socket;
|
||||
}
|
||||
}
|
||||
|
||||
// Create singleton instance
|
||||
// ایجاد instance singleton
|
||||
export const socketService = new SocketService();
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
getChatList,
|
||||
getChatMessages,
|
||||
createChat,
|
||||
markChatAsRead,
|
||||
getChatDetail,
|
||||
} from "../service/Service";
|
||||
import { CreateChatRequest } from "../types/ProfileTypes";
|
||||
|
||||
@@ -17,19 +17,6 @@ export const useChatList = (options?: { enabled?: boolean }) => {
|
||||
});
|
||||
};
|
||||
|
||||
// Get chat messages
|
||||
export const useChatMessages = (
|
||||
chatId: string,
|
||||
options?: { enabled?: boolean }
|
||||
) => {
|
||||
return useQuery({
|
||||
queryKey: ["chat", "messages", chatId],
|
||||
queryFn: () => getChatMessages(chatId),
|
||||
enabled: options?.enabled ?? !!chatId,
|
||||
staleTime: 1000 * 60 * 1, // 1 minute
|
||||
});
|
||||
};
|
||||
|
||||
// Create new chat
|
||||
export const useCreateChat = () => {
|
||||
const queryClient = useQueryClient();
|
||||
@@ -52,6 +39,17 @@ export const useMarkChatAsRead = () => {
|
||||
console.log("📤 ارسال درخواست markAsRead برای:", chatId);
|
||||
return markChatAsRead(chatId);
|
||||
},
|
||||
retry: (failureCount, error: unknown) => {
|
||||
// اگر ۴۰۴ است، retry نکن
|
||||
const axiosError = error as { response?: { status?: number } };
|
||||
if (axiosError?.response?.status === 404) {
|
||||
console.log("ℹ️ چت یافت نشد یا قبلاً mark شده - retry نمیکنیم");
|
||||
return false;
|
||||
}
|
||||
// برای سایر خطاها، حداکثر ۱ بار retry کن
|
||||
return failureCount < 1;
|
||||
},
|
||||
retryDelay: 1000,
|
||||
onSuccess: (_, chatId) => {
|
||||
console.log(
|
||||
"✅ پیامها با موفقیت به عنوان خوانده شده علامتگذاری شدند:",
|
||||
@@ -62,8 +60,21 @@ export const useMarkChatAsRead = () => {
|
||||
// Update messages to mark as read
|
||||
queryClient.invalidateQueries({ queryKey: ["chat", "messages", chatId] });
|
||||
},
|
||||
onError: (error, chatId) => {
|
||||
onError: (error: unknown, chatId) => {
|
||||
console.error("❌ خطا در markAsRead:", chatId, error);
|
||||
// اگر ۴۰۴ دریافت کردیم، شاید چت وجود ندارد یا قبلاً mark شده
|
||||
const axiosError = error as { response?: { status?: number } };
|
||||
if (axiosError?.response?.status === 404) {
|
||||
console.log("ℹ️ چت یافت نشد یا قبلاً mark شده:", chatId);
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export const useChatDetail = (chatId?: string) => {
|
||||
return useQuery({
|
||||
queryKey: ["chat", "detail", chatId],
|
||||
queryFn: () => getChatDetail(chatId!),
|
||||
enabled: !!chatId,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -318,6 +318,7 @@ export interface ChatMessage {
|
||||
chatId: string;
|
||||
content: string;
|
||||
sender: "customer" | "seller";
|
||||
senderRef: "User" | "Seller";
|
||||
senderInfo: ChatUser | ChatShop;
|
||||
createdAt: string;
|
||||
status: "sent" | "delivered" | "read";
|
||||
|
||||
Reference in New Issue
Block a user