From 4af0082c03c9969d24ab11f5294e4fbf0c2cdeb7 Mon Sep 17 00:00:00 2001 From: hamid zarghami Date: Tue, 14 Oct 2025 16:45:33 +0330 Subject: [PATCH] Remove debug mode from chat and optimize image usage --- .../profile/chat/components/ChatMessages.tsx | 144 +++++++++--------- src/app/profile/service/Service.ts | 13 +- src/app/profile/types/ProfileTypes.ts | 68 ++++++++- 3 files changed, 141 insertions(+), 84 deletions(-) diff --git a/src/app/profile/chat/components/ChatMessages.tsx b/src/app/profile/chat/components/ChatMessages.tsx index 9cb6657..8575083 100644 --- a/src/app/profile/chat/components/ChatMessages.tsx +++ b/src/app/profile/chat/components/ChatMessages.tsx @@ -1,9 +1,10 @@ '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 { useSocket } from '../hooks/useSocket' import { Message as SocketMessage } from '../service/SocketService' -import { useChatMessages, useMarkChatAsRead } from '../../hooks/useChatData' +import { useChatDetail, useMarkChatAsRead } from '../../hooks/useChatData' import { isAuthenticated } from '@/config/func' import { ChatMessage as APIMessage } from '../../types/ProfileTypes' @@ -23,26 +24,13 @@ interface ChatMessagesProps { export default function ChatMessages({ productId, shopId, chatId }: ChatMessagesProps) { const [messageText, setMessageText] = useState('') - const [debugInfo, setDebugInfo] = useState('') const [isTyping, setIsTyping] = useState(false) const [selectedFile, setSelectedFile] = useState(null) const [isUserAuthenticated, setIsUserAuthenticated] = useState(null) const messagesEndRef = useRef(null) const typingTimeoutRef = useRef(null) const fileInputRef = useRef(null) - - // Server capabilities - temporarily disable features not implemented yet - const SERVER_CAPABILITIES = { - socketChat: false, // Socket.IO chat not implemented yet - markAsRead: false, // markAsRead endpoint not implemented yet - } - - // Calculate currentChatId from props - const currentChatId = chatId || (productId && shopId ? `chat_${shopId}_${productId}` : '') - - const { data: chatData, isLoading, error } = useChatMessages(currentChatId, { - enabled: isUserAuthenticated === true // Only fetch if user is logged in - }) + const markedAsReadRef = useRef>(new Set()) // Check authentication on mount useEffect(() => { @@ -52,7 +40,6 @@ export default function ChatMessages({ productId, shopId, chatId }: ChatMessages } checkAuth() }, []) - const markAsRead = useMarkChatAsRead() const { isConnected, @@ -60,9 +47,14 @@ export default function ChatMessages({ productId, shopId, chatId }: ChatMessages leaveChat, sendMessage, onNewMessage, - onError + onError, + connect } = useSocket() + 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) => ({ @@ -85,31 +77,52 @@ export default function ChatMessages({ productId, shopId, chatId }: ChatMessages scrollToBottom() }, [messages]) - // Join chat room when chatId is set and socket is connected (only if server supports it and user is logged in) + // اتصال به چت وقتی chatId تنظیم شده و کاربر لاگین کرده useEffect(() => { - if (currentChatId && currentChatId !== '' && isUserAuthenticated === true) { - if (SERVER_CAPABILITIES.socketChat && isConnected) { - console.log('🔗 اتصال به چت:', currentChatId) - joinChat(currentChatId) - return () => { - leaveChat(currentChatId) - } + if (chatId && chatId !== '' && isUserAuthenticated === true) { + // اتصال به سوکت اگر متصل نیست + if (!isConnected) { + console.log('🔌 اتصال به سوکت برای چت...') + connect().catch((error) => { + console.error('❌ خطا در اتصال سوکت:', error.message) + + // اگر توکن expired است، پیام نمایش بده + if (error.message === 'توکن منقضی شده' || error.message === 'توکن یافت نشد') { + console.log('🔐 توکن نامعتبر برای چت') + } + }) } - // Mark messages as read only if server supports it - if (SERVER_CAPABILITIES.markAsRead) { - markAsRead.mutate(currentChatId) - } else { - console.log('ℹ️ markAsRead غیرفعال است (سرور هنوز پشتیبانی نمی‌کند)') + // اتصال به چت + if (isConnected) { + console.log('🔗 اتصال به چت:', chatId) + joinChat(chatId) + return () => { + leaveChat(chatId) + } } } - }, [currentChatId, isConnected, joinChat, leaveChat, markAsRead, SERVER_CAPABILITIES.socketChat, SERVER_CAPABILITIES.markAsRead, isUserAuthenticated]) + }, [chatId, isConnected, joinChat, leaveChat, connect, isUserAuthenticated]) + + // Mark messages as read - فقط یک بار برای هر chatId + useEffect(() => { + if (chatId && chatId !== '' && isUserAuthenticated === true && isConnected) { + // بررسی اینکه آیا قبلاً برای این chatId mark as read کرده‌ایم + if (!markedAsReadRef.current.has(chatId)) { + console.log('📖 mark as read برای چت:', chatId) + markedAsReadRef.current.add(chatId) + markAsRead.mutate(chatId) + } else { + console.log('ℹ️ چت قبلاً mark as read شده:', chatId) + } + } + }, [chatId, isUserAuthenticated, isConnected, markAsRead]) // Listen for new messages useEffect(() => { const handleNewMessage = (socketMessage: unknown) => { const message = socketMessage as SocketMessage - if (message.chatId === currentChatId) { + 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) @@ -119,7 +132,6 @@ export default function ChatMessages({ productId, shopId, chatId }: ChatMessages const handleError = (error: unknown) => { const err = error as { message: string } console.error('🚨 خطای چت:', err.message) - setDebugInfo(`خطا: ${err.message}`) // You can show a toast notification here if (err.message === 'اتصال سوکت برقرار نیست') { console.warn('⚠️ راهنمایی: اگر این خطا تکرار می‌شود، احتمالاً سرور سوکت اجرا نمی‌شود یا قابل دسترسی نیست.') @@ -132,13 +144,13 @@ export default function ChatMessages({ productId, shopId, chatId }: ChatMessages return () => { // Cleanup will be handled by the hook } - }, [currentChatId, onNewMessage, onError]) + }, [chatId, onNewMessage, onError]) const handleTyping = () => { if (!isTyping) { setIsTyping(true) // Here you could emit a typing event to the server - // socketService.emit('typing', { chatId: currentChatId }) + // socketService.emit('typing', { chatId: chatId }) } // Clear previous timeout @@ -149,7 +161,7 @@ export default function ChatMessages({ productId, shopId, chatId }: ChatMessages // Set new timeout to stop typing indicator typingTimeoutRef.current = setTimeout(() => { setIsTyping(false) - // socketService.emit('stopTyping', { chatId: currentChatId }) + // socketService.emit('stopTyping', { chatId: chatId }) }, 2000) } @@ -166,7 +178,7 @@ export default function ChatMessages({ productId, shopId, chatId }: ChatMessages } const handleSend = () => { - if ((messageText.trim() || selectedFile) && currentChatId) { + if ((messageText.trim() || selectedFile) && chatId) { const content = messageText.trim() setMessageText('') setIsTyping(false) @@ -180,7 +192,7 @@ 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(currentChatId, content) + sendMessage(chatId, content) } // Scroll to bottom after sending @@ -189,23 +201,10 @@ export default function ChatMessages({ productId, shopId, chatId }: ChatMessages } const chat = chatData?.results?.chat - const seller = chat?.participants?.seller + const seller = chat?.shopLogo return (
- {/* Debug Info - فقط در محیط توسعه */} - {process.env.NODE_ENV === 'development' && ( -
-
🔍 دیباگ چت:
-
ChatId: {currentChatId || 'خالی'}
-
ProductId: {productId || 'خالی'}
-
ShopId: {shopId || 'خالی'}
-
Socket: {isConnected ? '🟢 متصل' : '🔴 قطع'}
-
Server Capabilities: Socket={SERVER_CAPABILITIES.socketChat ? '✅' : '❌'}, MarkAsRead={SERVER_CAPABILITIES.markAsRead ? '✅' : '❌'}
- {debugInfo &&
{debugInfo}
} -
- )} - {/* Header */}
{isLoading ? ( @@ -226,23 +225,22 @@ export default function ChatMessages({ productId, shopId, chatId }: ChatMessages
{seller.logo ? ( - {seller.shopName} ) : ( )}
- {chat?.isOnline && ( -
- )} + {/* وضعیت آنلاین در این API موجود نیست */}
-

{seller.shopName}

+

{chat?.sellerRef || 'فروشگاه'}

- {chat?.isOnline ? 'آنلاین' : 'آفلاین'} + آفلاین

@@ -257,9 +255,9 @@ export default function ChatMessages({ productId, shopId, chatId }: ChatMessages