fix: guest and admin logic

This commit is contained in:
2026-06-22 11:41:34 +07:00
parent b1a539235b
commit 860395cb14
61 changed files with 1291 additions and 244 deletions
+18 -4
View File
@@ -10,9 +10,10 @@ interface AddPhotoModalProps {
onClose: () => void;
tourId: string;
onSuccess?: () => void;
isPublicView?: boolean;
}
export const AddPhotoModal: React.FC<AddPhotoModalProps> = ({ isOpen, onClose, tourId, onSuccess }) => {
export const AddPhotoModal: React.FC<AddPhotoModalProps> = ({ isOpen, onClose, tourId, onSuccess, isPublicView }) => {
const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
const [previews, setPreviews] = useState<string[]>([]);
const [isUploading, setIsUploading] = useState(false);
@@ -136,13 +137,26 @@ export const AddPhotoModal: React.FC<AddPhotoModalProps> = ({ isOpen, onClose, t
type: 'success'
});
fetchTour(tourId);
if (onSuccess) onSuccess();
onClose();
// Giải phóng bộ nhớ sau khi hoàn tất
previews.forEach(url => URL.revokeObjectURL(url));
setSelectedFiles([]);
setPreviews([]);
// For public users: redirect to landing page after upload
// For authenticated users: refresh tour data and close modal
if (isPublicView) {
onClose();
// Give time for notification to show before redirecting
// Set flag so App.tsx knows to redirect to landing even if user is logged in
setTimeout(() => {
localStorage.setItem('fromPublicUpload', 'true');
window.location.href = '/';
}, 1000);
} else {
fetchTour(tourId);
if (onSuccess) onSuccess();
onClose();
}
} catch (error) {
notify({
title: 'Lỗi',
@@ -0,0 +1,296 @@
import React, { useState, useEffect } from 'react';
import { X, Mail, Lock, ArrowRight, Loader2, LogIn } from 'lucide-react';
import { useNotification } from '@/hooks/useNotification';
interface JoinTourLoginModalProps {
isOpen: boolean;
onClose: () => void;
inviteToken: string;
onJoinSuccess?: (user: any, tourData: any) => void;
onSwitchToSignup?: () => void;
}
export const JoinTourLoginModal: React.FC<JoinTourLoginModalProps> = ({
isOpen,
onClose,
inviteToken,
onJoinSuccess,
onSwitchToSignup
}) => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [isLoading, setIsLoading] = useState(false);
const notify = useNotification();
const handleGoogleLogin = async (googleResponse: any) => {
setError('');
setIsLoading(true);
try {
const response = await fetch(`/api/v1/auth/google`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ credential: googleResponse.credential }),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || 'Đăng nhập Google thất bại');
}
localStorage.setItem('token', data.access_token);
localStorage.setItem('user', JSON.stringify(data.user));
// Attempt to join tour with the token
try {
console.log('[JoinTourLogin] Attempting to join with token:', inviteToken.substring(0, 10) + '...');
const joinRes = await fetch(`/api/v1/tours/join-by-token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${data.access_token}`,
},
body: JSON.stringify({ token: inviteToken }),
});
console.log('[JoinTourLogin] Join response status:', joinRes.status);
const joinData = await joinRes.json().catch(() => ({}));
if (joinRes.ok) {
console.log('[JoinTourLogin] Join successful');
notify({
title: 'Thành công',
message: joinData.message || 'Bạn đã gia nhập tour!',
type: 'success'
});
localStorage.removeItem('pendingInviteToken');
if (onJoinSuccess) {
onJoinSuccess(data.user, joinData);
}
onClose();
} else {
// Email mismatch or other error
const errorMessage = joinData.message || `Không thể gia nhập tour (HTTP ${joinRes.status})`;
console.error('[JoinTourLogin] Join failed:', errorMessage);
setError(`Lỗi gia nhập tour: ${errorMessage}`);
setIsLoading(false);
}
} catch (e: any) {
console.error('[JoinTourLogin] Join exception:', e);
setError(`Lỗi khi gia nhập: ${e.message}`);
setIsLoading(false);
}
} catch (err: any) {
console.error('[JoinTourLogin] Google login error:', err);
setError(err.message);
setIsLoading(false);
}
};
const handleEmailPasswordJoin = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setIsLoading(true);
try {
const response = await fetch(`/api/v1/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || 'Đăng nhập thất bại');
}
localStorage.setItem('token', data.access_token);
localStorage.setItem('user', JSON.stringify(data.user));
// Attempt to join tour
try {
const joinRes = await fetch(`/api/v1/tours/join-by-token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${data.access_token}`,
},
body: JSON.stringify({ token: inviteToken }),
});
const joinData = await joinRes.json().catch(() => ({}));
if (joinRes.ok) {
notify({
title: 'Thành công',
message: joinData.message || 'Bạn đã gia nhập tour!',
type: 'success'
});
localStorage.removeItem('pendingInviteToken');
if (onJoinSuccess) {
onJoinSuccess(data.user, joinData);
}
onClose();
} else {
const errorMessage = joinData.message || 'Không thể gia nhập tour';
setError(`Lỗi gia nhập tour: ${errorMessage}`);
setIsLoading(false);
}
} catch (e: any) {
setError(`Lỗi khi gia nhập: ${e.message}`);
setIsLoading(false);
}
} catch (err: any) {
console.error('[JoinTourLogin] Login error:', err);
setError(err.message);
setIsLoading(false);
}
};
useEffect(() => {
if (!isOpen) return;
const timer = setTimeout(() => {
if (typeof window !== 'undefined' && (window as any).google) {
try {
(window as any).google.accounts.id.initialize({
client_id: (import.meta as any).env.VITE_GOOGLE_CLIENT_ID || '864264639911-dummyid.apps.googleusercontent.com',
callback: handleGoogleLogin,
});
(window as any).google.accounts.id.renderButton(
document.getElementById('google-signin-btn-join-tour'),
{ theme: 'outline', size: 'large', width: '380' }
);
} catch (e) {
console.error('Lỗi khởi tạo Google Sign-in:', e);
}
}
}, 100);
return () => clearTimeout(timer);
}, [isOpen]);
if (!isOpen) return null;
return (
<div className="fixed inset-0 z-[3000] flex items-center justify-center p-4 bg-black/50">
<div className="w-full max-w-md bg-white rounded-[32px] shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200">
{/* Header */}
<div className="relative h-32 bg-gradient-to-r from-blue-500 via-purple-500 to-pink-500 overflow-hidden">
<div className="absolute inset-0 opacity-10">
<div className="absolute inset-0 bg-[radial-gradient(circle_at_20%_50%,rgba(255,255,255,.3)_0%,transparent_50%)]" />
</div>
<button
onClick={onClose}
className="absolute top-4 right-4 z-10 p-2 hover:bg-white/20 rounded-full transition-colors"
>
<X className="w-5 h-5 text-white" />
</button>
<div className="absolute inset-0 flex items-center justify-center">
<LogIn className="w-12 h-12 text-white opacity-80" />
</div>
</div>
{/* Content */}
<div className="p-8">
<h2 className="text-3xl font-bold text-gray-900 mb-2 text-center">
Gia nhập tour
</h2>
<p className="text-center text-gray-600 mb-6">
Đăng nhập đ tham gia chuyến du lịch này
</p>
{error && (
<div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700">
{error}
</div>
)}
{/* Google OAuth Button */}
<div className="mb-6 flex justify-center">
<div id="google-signin-btn-join-tour" className="w-full" />
</div>
<div className="relative mb-6">
<div className="absolute inset-0 flex items-center">
<div className="w-full border-t border-gray-200" />
</div>
<div className="relative flex justify-center text-sm">
<span className="px-2 bg-white text-gray-500">Hoặc</span>
</div>
</div>
{/* Email/Password Form */}
<form onSubmit={handleEmailPasswordJoin} className="space-y-4">
<div>
<label className="block text-sm font-semibold text-gray-700 mb-2">
Email
</label>
<div className="relative">
<Mail className="absolute left-3 top-3.5 w-5 h-5 text-gray-400" />
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="your@email.com"
required
className="w-full pl-10 pr-4 py-2.5 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition"
/>
</div>
</div>
<div>
<label className="block text-sm font-semibold text-gray-700 mb-2">
Mật khẩu
</label>
<div className="relative">
<Lock className="absolute left-3 top-3.5 w-5 h-5 text-gray-400" />
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Nhập mật khẩu"
required
className="w-full pl-10 pr-4 py-2.5 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition"
/>
</div>
</div>
<button
type="submit"
disabled={isLoading}
className="w-full bg-gradient-to-r from-blue-500 to-purple-500 text-white font-semibold py-3 rounded-lg hover:shadow-lg transition-all disabled:opacity-50 flex items-center justify-center gap-2"
>
{isLoading ? (
<>
<Loader2 className="w-5 h-5 animate-spin" />
Đang gia nhập...
</>
) : (
<>
<ArrowRight className="w-5 h-5" />
Gia nhập tour
</>
)}
</button>
</form>
{/* Signup Link */}
<div className="mt-6 text-center text-sm text-gray-600">
Chưa tài khoản?{' '}
<button
onClick={() => {
onClose();
if (onSwitchToSignup) onSwitchToSignup();
}}
className="font-semibold text-blue-500 hover:text-blue-600 transition"
>
Đăng tại đây
</button>
</div>
</div>
</div>
</div>
);
};
+5 -41
View File
@@ -31,34 +31,16 @@ export const LoginModal: React.FC<LoginModalProps> = ({ isOpen, onClose, onSwitc
localStorage.setItem('token', data.access_token);
localStorage.setItem('user', JSON.stringify(data.user));
console.log('[OAuth] Google login successful');
// Tự động gia nhập tour nếu có pendingInviteToken
const pendingInviteToken = localStorage.getItem('pendingInviteToken');
if (pendingInviteToken) {
try {
const joinRes = await fetch(`/api/v1/tours/join-by-token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${data.access_token}`,
},
body: JSON.stringify({ token: pendingInviteToken }),
});
if (joinRes.ok) {
localStorage.removeItem('pendingInviteToken');
}
} catch (e) {
console.error('Lỗi tự động gia nhập:', e);
}
}
// Regular login - no auto-join for tour
if (onLoginSuccess) {
onLoginSuccess(data.user);
}
onClose();
} catch (err: any) {
console.error('[OAuth] Login error:', err);
setError(err.message);
} finally {
setIsLoading(false);
}
};
@@ -109,27 +91,9 @@ export const LoginModal: React.FC<LoginModalProps> = ({ isOpen, onClose, onSwitc
// Lưu phiên đăng nhập
localStorage.setItem('token', data.access_token);
localStorage.setItem('user', JSON.stringify(data.user));
// Tự động gia nhập tour nếu có pendingInviteToken
const pendingInviteToken = localStorage.getItem('pendingInviteToken');
if (pendingInviteToken) {
try {
const joinRes = await fetch(`/api/v1/tours/join-by-token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${data.access_token}`,
},
body: JSON.stringify({ token: pendingInviteToken }),
});
if (joinRes.ok) {
localStorage.removeItem('pendingInviteToken');
}
} catch (e) {
console.error('Lỗi tự động gia nhập:', e);
}
}
console.log('[LoginModal] Email/password login successful');
// Regular login - no auto-join for tour
if (onLoginSuccess) {
onLoginSuccess(data.user);
}
+47 -14
View File
@@ -390,15 +390,24 @@ export const PublicPhotoModal: React.FC<PublicPhotoModalProps> = ({
{/* Backdrop */}
<div
className="absolute inset-0 bg-slate-950/80 backdrop-blur-md animate-in fade-in duration-300"
onClick={onClose}
onClick={(e) => {
e.stopPropagation();
onClose();
}}
/>
{/* Container */}
<div className="fixed inset-0 overflow-y-auto flex flex-col bg-slate-900 text-slate-100 md:relative md:inset-auto md:overflow-hidden md:rounded-[32px] md:shadow-2xl md:border md:border-slate-800 md:w-full md:max-w-5xl md:h-[85vh] md:flex-row animate-in zoom-in-95 duration-300">
<div
className="fixed inset-0 overflow-y-auto flex flex-col bg-slate-900 text-slate-100 md:relative md:inset-auto md:overflow-hidden md:rounded-[32px] md:shadow-2xl md:border md:border-slate-800 md:w-full md:max-w-5xl md:h-[85vh] md:flex-row animate-in zoom-in-95 duration-300"
onClick={(e) => e.stopPropagation()}
>
{/* Close Button Mobile/Desktop */}
<button
onClick={onClose}
onClick={(e) => {
e.stopPropagation();
onClose();
}}
className="fixed md:absolute top-[calc(1rem+env(safe-area-inset-top,0px))] right-4 md:top-4 md:right-4 z-50 p-2 bg-slate-950/60 hover:bg-slate-800/80 border border-slate-700/50 rounded-full text-slate-300 hover:text-white transition-colors"
>
<X className="w-5 h-5" />
@@ -421,7 +430,10 @@ export const PublicPhotoModal: React.FC<PublicPhotoModalProps> = ({
{/* Like Button Overlay */}
<button
onClick={handleToggleLike}
onClick={(e) => {
e.stopPropagation();
handleToggleLike();
}}
className="absolute bottom-4 right-4 z-40 flex items-center gap-1.5 bg-slate-950/70 hover:bg-slate-900/80 border border-slate-700/50 text-slate-200 hover:text-white font-bold py-1.5 px-3 rounded-full transition-all active:scale-95 text-[11px] backdrop-blur-md md:absolute md:top-[calc(1rem+env(safe-area-inset-top,0px))] md:left-4 md:bottom-auto md:right-auto"
title={isLiked ? "Bỏ thích" : "Thích"}
>
@@ -457,22 +469,25 @@ export const PublicPhotoModal: React.FC<PublicPhotoModalProps> = ({
</div>
{/* Info & Timeline overlay inside photo panel */}
<div className="relative p-6 bg-slate-900 border-b border-slate-800/60 md:absolute md:bottom-0 md:left-0 md:right-0 md:bg-gradient-to-t md:from-black/60 md:via-black/20 md:to-transparent md:border-b-0 flex flex-col gap-4">
<div className="relative z-20 p-6 bg-slate-900 border-b border-slate-800/60 md:absolute md:bottom-0 md:left-0 md:right-0 md:bg-gradient-to-t md:from-black/60 md:via-black/20 md:to-transparent md:border-b-0 flex flex-col gap-4">
{/* Timeline scroll */}
{photoGroup && photoGroup.length > 1 && (
<div className="flex flex-col gap-2 border-b border-slate-800/80 pb-3">
<div className="flex flex-col gap-2 border-b border-slate-800/80 pb-3 relative z-20">
<span className="text-[10px] font-bold uppercase tracking-wider text-slate-400 flex items-center gap-1.5">
<span className="inline-block w-1.5 h-1.5 rounded-full bg-emerald-500 animate-ping"></span>
Lịch sử nh tại vị trí này ({photoGroup.length})
</span>
<div className="flex gap-3 overflow-x-auto no-scrollbar py-1">
<div className="flex gap-3 overflow-x-auto no-scrollbar py-1 relative z-20">
{photoGroup.map((p) => {
const isActive = p.id === photo.id;
return (
<button
key={p.id}
onClick={() => onSelectPhoto?.(p)}
onClick={(e) => {
e.stopPropagation();
onSelectPhoto?.(p);
}}
className={`relative w-12 h-12 rounded-xl overflow-hidden border-2 transition-all active:scale-95 shrink-0 ${
isActive ? 'border-emerald-500 scale-110 shadow-lg' : 'border-slate-700 hover:border-slate-500'
}`}
@@ -551,7 +566,10 @@ export const PublicPhotoModal: React.FC<PublicPhotoModalProps> = ({
<div className="flex justify-start">
<button
type="button"
onClick={() => setIsMapOpen(true)}
onClick={(e) => {
e.stopPropagation();
setIsMapOpen(true);
}}
className="flex items-center gap-1.5 px-3 py-1.5 bg-slate-800 hover:bg-slate-750 border border-slate-700/50 text-slate-300 hover:text-white rounded-xl text-[10px] font-bold transition-all"
>
<MapPin className="w-3.5 h-3.5 text-rose-500" />
@@ -562,14 +580,20 @@ export const PublicPhotoModal: React.FC<PublicPhotoModalProps> = ({
<div className="flex justify-end gap-2 mt-2">
<button
onClick={() => setIsEditing(false)}
onClick={(e) => {
e.stopPropagation();
setIsEditing(false);
}}
disabled={isSavingEdit}
className="px-3 py-1.5 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-lg text-xs font-bold transition-all"
>
Hủy
</button>
<button
onClick={handleSaveEdit}
onClick={(e) => {
e.stopPropagation();
handleSaveEdit();
}}
disabled={isSavingEdit}
className="flex items-center gap-1 px-4 py-1.5 bg-emerald-600 hover:bg-emerald-500 disabled:bg-slate-800 disabled:opacity-50 text-white rounded-lg text-xs font-bold transition-all"
>
@@ -606,7 +630,10 @@ export const PublicPhotoModal: React.FC<PublicPhotoModalProps> = ({
</div>
{isAuthorized && (
<button
onClick={() => setIsEditing(true)}
onClick={(e) => {
e.stopPropagation();
setIsEditing(true);
}}
className="p-1.5 bg-slate-800 hover:bg-slate-700 border border-slate-700/50 rounded-xl text-slate-300 hover:text-white transition-all shrink-0"
title="Chỉnh sửa thông tin"
>
@@ -713,7 +740,10 @@ export const PublicPhotoModal: React.FC<PublicPhotoModalProps> = ({
currentUser?.id === photo.uploaderId ||
currentUser?.id === photo.uploader?.id) && (
<button
onClick={() => handleDeleteComment(c.id)}
onClick={(e) => {
e.stopPropagation();
handleDeleteComment(c.id);
}}
className="text-slate-500 hover:text-rose-500 transition-colors p-0.5"
title={t('delete') || "Xóa"}
>
@@ -746,7 +776,10 @@ export const PublicPhotoModal: React.FC<PublicPhotoModalProps> = ({
disabled={isSending}
/>
<button
onClick={handleSend}
onClick={(e) => {
e.stopPropagation();
handleSend();
}}
disabled={!newComment.trim() || isSending}
className="p-3 bg-emerald-600 hover:bg-emerald-500 disabled:bg-slate-800 disabled:opacity-40 text-white rounded-2xl transition-all active:scale-95 shadow-lg shadow-emerald-950/30 flex items-center justify-center"
>
@@ -1,5 +1,6 @@
import React, { useState, useEffect } from 'react';
import { X, User, Trash2, Shield, ShieldAlert, Lock, Unlock, Loader2, Image as ImageIcon, Map, FileText, CheckCircle, Star, Settings } from 'lucide-react';
import { useConfirm } from '../hooks/useConfirm';
interface UserManagementModalProps {
isOpen: boolean;
@@ -7,6 +8,7 @@ interface UserManagementModalProps {
}
export const UserManagementModal: React.FC<UserManagementModalProps> = ({ isOpen, onClose }) => {
const confirm = useConfirm();
const [activeTab, setActiveTab] = useState<'users' | 'tours' | 'photos' | 'notes' | 'recommendations' | 'trash' | 'filters' | 'reports'>('users');
const [users, setUsers] = useState<any[]>([]);
const [photos, setPhotos] = useState<any[]>([]);
@@ -68,7 +70,10 @@ export const UserManagementModal: React.FC<UserManagementModalProps> = ({ isOpen
};
const handleDeleteReport = async (id: string) => {
if (!confirm('Bạn có chắc muốn xóa báo cáo này?')) return;
if (!await confirm({
title: 'Xóa báo cáo',
message: 'Bạn có chắc muốn xóa báo cáo này?'
})) return;
try {
const response = await fetch(`/api/v1/admin/reports/${id}`, {
method: 'DELETE',
@@ -492,8 +497,13 @@ export const UserManagementModal: React.FC<UserManagementModalProps> = ({ isOpen
const handleDeletePermanentTrash = async () => {
if (selectedTrashIds.length === 0) return;
if (!confirm(`CẢNH BÁO: Bạn có chắc muốn xóa VĨNH VIỄN ${selectedTrashIds.length} mục đã chọn? Thao tác này không thể hoàn tác.`)) return;
setTrashLoading(true);
const idsToDelete = [...selectedTrashIds];
setSelectedTrashIds([]);
try {
console.log('[Trash] Starting permanent delete for', idsToDelete.length, 'items');
const res = await fetch('/api/v1/admin/trash/delete-permanent', {
method: 'POST',
headers: {
@@ -502,16 +512,42 @@ export const UserManagementModal: React.FC<UserManagementModalProps> = ({ isOpen
},
body: JSON.stringify({
type: trashSubTab,
ids: selectedTrashIds
ids: idsToDelete
})
});
console.log('[Trash] Delete response status:', res.status);
if (res.ok) {
setSelectedTrashIds([]);
console.log('[Trash] Delete successful, clearing state immediately');
setError('');
alert('Đã xóa vĩnh viễn thành công!');
// Small delay to let alert close, then refresh data
setTimeout(() => {
console.log('[Trash] Refreshing trash data after delete');
fetchTrashData();
setTrashLoading(false);
}, 500);
return; // Important: exit early so finally doesn't run again
} else {
const errorData = await res.json().catch(() => ({}));
const errorMsg = errorData.message || `HTTP ${res.status}`;
console.error('[Trash] Delete failed:', errorMsg);
setError(errorMsg);
alert(`Xóa thất bại: ${errorMsg}`);
// Refresh on error
fetchTrashData();
setTrashLoading(false);
}
} catch (e) {
console.error(e);
} finally {
} catch (e: any) {
console.error('[Trash] Delete error:', e);
setError(e.message || 'Lỗi khi xóa các mục');
alert(`Lỗi: ${e.message}`);
// Refresh on error
fetchTrashData();
setTrashLoading(false);
}
};