fix: cập nhật giao diện và các trang dashboard từ máy B

This commit is contained in:
2026-06-27 11:44:28 +07:00
parent b5b6082d26
commit accda67b22
4 changed files with 166 additions and 87 deletions
+117 -1
View File
@@ -11,7 +11,116 @@ import { AdminDashboard } from './pages/AdminDashboard';
import { ShareJourneyPage } from './pages/ShareJourneyPage';
import { TourNavigationPage } from './pages/TourNavigationPage';
import { ConfirmProvider } from './hooks/useConfirm';
import { NotificationProvider } from './hooks/useNotification';
import { NotificationProvider, useNotification } from './hooks/useNotification';
import { io } from 'socket.io-client';
interface GlobalNotificationListenerProps {
user: any;
currentPage: string;
currentTourId: string | null;
}
const GlobalNotificationListener: React.FC<GlobalNotificationListenerProps> = ({ user, currentPage, currentTourId }) => {
const notify = useNotification();
// Request browser Notification permission once on mount
useEffect(() => {
if ('Notification' in window && Notification.permission === 'default') {
Notification.requestPermission();
}
}, []);
useEffect(() => {
if (!user?.id) return;
const socketInstance = io();
socketInstance.on('connect', () => {
console.log('[WS] Global notification socket connected:', socketInstance.id);
socketInstance.emit('joinUser', user.id);
});
socketInstance.on('tourMessageNotification', (data: any) => {
// Dispatch custom window event
window.dispatchEvent(new CustomEvent('app:tourMessageNotification', { detail: data }));
// Check if user is actively viewing this specific tour chat
const isViewingThisTourChat = currentPage === 'tourDetail' && currentTourId === data.tourId && (window as any).activeTourChatTab;
if (!isViewingThisTourChat) {
notify({
title: `Tin nhắn mới trong tour "${data.tourTitle}"`,
message: `${data.senderName}: "${data.content.substring(0, 30)}${data.content.length > 30 ? '...' : ''}"`,
type: 'success'
});
// Show push notification on desktop browser
if ('Notification' in window && Notification.permission === 'granted') {
try {
new Notification(`Tin nhắn mới trong tour "${data.tourTitle}"`, {
body: `${data.senderName}: ${data.content}`,
icon: '/favicon.ico'
});
} catch (e) {
console.error('System Notification error:', e);
}
}
}
});
socketInstance.on('messageReceived', (message: any) => {
// Dispatch custom window event
window.dispatchEvent(new CustomEvent('app:messageReceived', { detail: message }));
// Check if user is actively chatting with the sender
const isChattingWithSender = currentPage === 'dashboard' && (window as any).activeChatUserId === message.senderId;
if (!isChattingWithSender) {
notify({
title: 'Tin nhắn mới',
message: `${message.sender?.name || 'Ai đó'} gửi: "${message.content.substring(0, 30)}${message.content.length > 30 ? '...' : ''}"`,
type: 'success'
});
// Show push notification on desktop browser
if ('Notification' in window && Notification.permission === 'granted') {
try {
new Notification(`Tin nhắn mới từ ${message.sender?.name || 'Thành viên'}`, {
body: message.content,
icon: '/favicon.ico'
});
} catch (e) {
console.error('System Notification error:', e);
}
}
}
});
socketInstance.on('connectionAccepted', (data: any) => {
window.dispatchEvent(new CustomEvent('app:connectionAccepted', { detail: data }));
notify({
title: 'Kết nối mới',
message: `${data.acceptedByName} đã chấp nhận yêu cầu kết nối của bạn.`,
type: 'success'
});
});
socketInstance.on('joinRequestAccepted', (data: any) => {
window.dispatchEvent(new CustomEvent('app:joinRequestAccepted', { detail: data }));
notify({
title: 'Yêu cầu tham gia được duyệt',
message: `Yêu cầu tham gia hành trình "${data.tourTitle}" của bạn đã được chấp nhận!`,
type: 'success'
});
});
return () => {
socketInstance.disconnect();
};
}, [user?.id, currentPage, currentTourId]);
return null;
};
function App() {
const params = new URLSearchParams(window.location.search);
@@ -223,6 +332,13 @@ function App() {
return (
<ConfirmProvider>
<NotificationProvider>
{user && (
<GlobalNotificationListener
user={user}
currentPage={currentPage}
currentTourId={currentTourId}
/>
)}
{(() => {
if (currentPage === 'admin') {
return (
+12 -5
View File
@@ -32,13 +32,13 @@ export const TourChat: React.FC<TourChatProps> = ({ tourId, embedded = false })
const mentionRef = useRef<HTMLDivElement>(null);
const getHeaders = () => ({
'Authorization': `Bearer ${localStorage.getItem('token')}`,
'Authorization': `Bearer ${localStorage.getItem('token') || localStorage.getItem('guest_token')}`,
'Content-Type': 'application/json'
});
const currentUserId = (() => {
try {
const token = localStorage.getItem('token');
const token = localStorage.getItem('token') || localStorage.getItem('guest_token');
if (!token) return null;
const base64Url = token.split('.')[1];
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
@@ -311,7 +311,7 @@ export const TourChat: React.FC<TourChatProps> = ({ tourId, embedded = false })
const res = await fetch('/api/v1/upload', {
method: 'POST',
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`
'Authorization': `Bearer ${localStorage.getItem('token') || localStorage.getItem('guest_token')}`
},
body: formData
});
@@ -562,7 +562,7 @@ export const TourChat: React.FC<TourChatProps> = ({ tourId, embedded = false })
)}
{/* Locked Chat Input Footer */}
<div className="locked-chat-input-footer !flex-shrink-0 !w-full !border-t border-gray-200 bg-white !z-40" style={{ paddingBottom: 'env(safe-area-inset-bottom, 12px)' }}>
<div className="locked-chat-input-footer relative !flex-shrink-0 !w-full !border-t border-gray-200 bg-white !z-40" style={{ paddingBottom: 'env(safe-area-inset-bottom, 12px)' }}>
{/* Mention list dropdown */}
{showMentionList && filteredParticipants.length > 0 && (
<div
@@ -573,7 +573,14 @@ export const TourChat: React.FC<TourChatProps> = ({ tourId, embedded = false })
<button
key={member.id}
type="button"
onClick={() => insertMention(member)}
onMouseDown={(e) => {
e.preventDefault();
insertMention(member);
}}
onClick={(e) => {
e.preventDefault();
insertMention(member);
}}
className={`px-3 py-2 text-left text-xs font-semibold flex items-center gap-2 transition-colors ${
index === mentionIndex
? 'bg-blue-50 text-blue-700'
+29 -80
View File
@@ -1,5 +1,5 @@
import React, { useEffect, useState, useRef } from 'react';
import { io, Socket } from 'socket.io-client';
import {
Compass,
Users,
@@ -90,7 +90,14 @@ export const MemberDashboard: React.FC<MemberDashboardProps> = ({
const [chatMessages, setChatMessages] = useState<any[]>([]);
const [newMessage, setNewMessage] = useState('');
const messagesEndRef = useRef<HTMLDivElement>(null);
const socketRef = useRef<Socket | null>(null);
useEffect(() => {
(window as any).activeChatUserId = activeChatUser?.id;
return () => {
(window as any).activeChatUserId = undefined;
};
}, [activeChatUser]);
const [unreadChatSenders, setUnreadChatSenders] = useState<string[]>([]);
const [unreadTourSenders, setUnreadTourSenders] = useState<string[]>([]);
@@ -333,26 +340,7 @@ export const MemberDashboard: React.FC<MemberDashboardProps> = ({
return () => window.removeEventListener('resize', handleResize);
}, []);
// Request browser Notification permission
useEffect(() => {
if ('Notification' in window && Notification.permission === 'default') {
Notification.requestPermission();
}
}, []);
const showSystemNotification = (title: string, body: string) => {
if (muteNotificationsRef.current) return;
if ('Notification' in window && Notification.permission === 'granted') {
try {
new Notification(title, {
body,
icon: '/favicon.ico'
});
} catch (e) {
console.error('System Notification error:', e);
}
}
};
const isMemberOfMyTours = (senderId: string) => {
if (!publicTours) return false;
@@ -535,86 +523,47 @@ export const MemberDashboard: React.FC<MemberDashboardProps> = ({
muteNotificationsRef.current = muteNotifications;
});
// Socket connection for realtime messaging
// Socket connection for realtime messaging - changed to listen to global socket events
useEffect(() => {
if (!user?.id) return;
// Connect to WebSocket using same origin/proxy
const socket = io();
socketRef.current = socket;
socket.on('connect', () => {
console.log('[WS] MemberDashboard connected:', socket.id);
socket.emit('joinUser', user.id);
});
socket.on('messageReceived', (message: any) => {
const handleMessageReceived = (e: Event) => {
const message = (e as CustomEvent).detail;
// If we are actively chatting with the sender of this message
if (activeChatUser && (message.senderId === activeChatUser.id || message.receiverId === activeChatUser.id)) {
setChatMessages(prev => [...prev, message]);
} else {
if (!muteNotificationsRef.current) {
// Show notification toast for new message
notify({
title: 'Tin nhắn mới',
message: `${message.sender?.name || 'Ai đó'} gửi: "${message.content.substring(0, 30)}${message.content.length > 30 ? '...' : ''}"`,
type: 'success'
});
// Show push notification
showSystemNotification(
`Tin nhắn mới từ ${message.sender?.name || 'Thành viên'}`,
message.content
);
}
// Add to unread states
setUnreadChatSenders(prev => prev.includes(message.senderId) ? prev : [...prev, message.senderId]);
if (isMemberOfMyToursRef.current(message.senderId)) {
setUnreadTourSenders(prev => prev.includes(message.senderId) ? prev : [...prev, message.senderId]);
}
}
});
};
socket.on('connectionAccepted', (data: any) => {
if (!muteNotificationsRef.current) {
notify({
title: 'Kết nối mới',
message: `${data.acceptedByName} đã chấp nhận yêu cầu kết nối của bạn.`,
type: 'success'
});
}
const handleConnectionAccepted = () => {
fetchConnectionsRef.current();
});
socket.on('tourMessageNotification', (data: any) => {
if (!muteNotificationsRef.current) {
notify({
title: `Tin nhắn mới trong tour "${data.tourTitle}"`,
message: `${data.senderName}: "${data.content.substring(0, 30)}${data.content.length > 30 ? '...' : ''}"`,
type: 'success'
});
showSystemNotification(
`Tin nhắn mới trong tour "${data.tourTitle}"`,
`${data.senderName}: ${data.content}`
);
}
};
const handleTourMessageNotification = (e: Event) => {
const data = (e as CustomEvent).detail;
setUnreadTourChats(prev => prev.includes(data.tourId) ? prev : [...prev, data.tourId]);
});
};
socket.on('joinRequestAccepted', (data: any) => {
if (!muteNotificationsRef.current) {
notify({
title: 'Yêu cầu tham gia được duyệt',
message: `Yêu cầu tham gia hành trình "${data.tourTitle}" của bạn đã được chấp nhận!`,
type: 'success'
});
}
const handleJoinRequestAccepted = () => {
fetchPublicToursRef.current();
});
};
window.addEventListener('app:messageReceived', handleMessageReceived);
window.addEventListener('app:connectionAccepted', handleConnectionAccepted);
window.addEventListener('app:tourMessageNotification', handleTourMessageNotification);
window.addEventListener('app:joinRequestAccepted', handleJoinRequestAccepted);
return () => {
socket.disconnect();
window.removeEventListener('app:messageReceived', handleMessageReceived);
window.removeEventListener('app:connectionAccepted', handleConnectionAccepted);
window.removeEventListener('app:tourMessageNotification', handleTourMessageNotification);
window.removeEventListener('app:joinRequestAccepted', handleJoinRequestAccepted);
};
}, [user?.id, activeChatUser]);
+7
View File
@@ -398,6 +398,13 @@ export const TourDetailPage = ({
const [isAddMemberOpen, setIsAddMemberOpen] = useState(false);
const [isAddPhotoOpen, setIsAddPhotoOpen] = useState(false);
useEffect(() => {
(window as any).activeTourChatTab = activeTab === 'chat';
return () => {
(window as any).activeTourChatTab = false;
};
}, [activeTab]);
const [isRatingModalOpen, setIsRatingModalOpen] = useState(false);
const [ratingTargetUser, setRatingTargetUser] = useState<any>(null);
const [ratingScores, setRatingScores] = useState({