Files
canina/frontend/admin-panel/src/pages/Reviews.tsx
T
devops ddbf1ca026
Deploy Canina / deploy (push) Successful in 4m1s
E2E Playwright Tests / Run Full E2E & Security Suites (push) Failing after 7s
test: comprehensive test suites and quality gates pass across backend, storefront and admin
- Backend (NestJS): 82 suites, 641 tests passing; 0 ESLint errors; 0 tsc errors. Hardened SSL cert/key matching, SSRF IP pinning, and eBank validation.
- Admin Panel (Vite/React): 48 suites, 300 tests passing; 0 ESLint errors; 0 tsc errors. Full coverage across all pages and settings.
- Storefront (Next.js): 62 suites, 368 tests passing; 0 ESLint errors; 0 tsc errors.
- Fixed unmount lifecycle guards, promise error handling, and component edge cases.
2026-10-13 16:01:00 +00:00

692 lines
30 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {
CheckCircle2,
ChevronLeft,
ChevronRight,
Clock,
MessageSquare,
Package,
Reply,
Search,
Star,
Trash2,
User,
XCircle
} from 'lucide-react';
import { useCallback,useEffect,useState } from 'react';
import { toast } from 'react-hot-toast';
import Button from '../components/ui/Button';
import Modal from '../components/ui/Modal';
import Spinner from '../components/ui/Spinner';
import api from '../services/api';
interface ProductReview {
id: string;
productId: string;
userId?: string;
userName: string;
userPhone?: string;
rating: number;
comment: string;
status: 'PENDING' | 'APPROVED' | 'REJECTED';
adminReply?: string;
createdAt: string;
product?: {
id: string;
nameFa: string;
nameEn: string;
slug: string;
imageUrl: string;
};
user?: {
id: string;
firstName: string;
lastName: string;
mobile: string;
};
}
interface BlogCommentItem {
id: string;
blogId: string;
userId?: string;
userName: string;
email?: string;
content: string;
status: 'PENDING' | 'APPROVED' | 'REJECTED';
createdAt: string;
blog?: {
title: string;
slug: string;
};
user?: {
id: string;
firstName: string;
lastName: string;
mobile: string;
};
}
const toPersianDigits = (n: string | number): string => {
if (n === null || n === undefined) return '';
const farsiDigits = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
return n.toString().replace(/\d/g, (x) => farsiDigits[parseInt(x)]);
};
export default function Reviews() {
const [mainTab, setMainTab] = useState<'products' | 'blogs'>('products');
const [reviews, setReviews] = useState<ProductReview[]>([]);
const [blogComments, setBlogComments] = useState<BlogCommentItem[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [page, setPage] = useState(1);
const [limit] = useState(15);
const [totalPages, setTotalPages] = useState(1);
const [totalCount, setTotalCount] = useState(0);
const [statusFilter, setStatusFilter] = useState('ALL');
const [search, setSearch] = useState('');
const [processingId, setProcessingId] = useState<string | null>(null);
// Reply Modal State
const [replyingReview, setReplyingReview] = useState<ProductReview | null>(null);
const [replyText, setReplyText] = useState('');
const [isSavingReply, setIsSavingReply] = useState(false);
const fetchItems = useCallback(async () => {
try {
setIsLoading(true);
if (mainTab === 'products') {
const params = new URLSearchParams();
params.append('page', page.toString());
params.append('limit', limit.toString());
if (statusFilter && statusFilter !== 'ALL') params.append('status', statusFilter);
if (search.trim()) params.append('search', search.trim());
const res = await api.get(`/admin/reviews?${params.toString()}`);
if (res.data?.success) {
setReviews(res.data.data || []);
setTotalPages(res.data.pagination?.totalPages || 1);
setTotalCount(res.data.pagination?.total || 0);
}
} else {
const params = new URLSearchParams();
params.append('page', page.toString());
params.append('limit', limit.toString());
if (statusFilter && statusFilter !== 'ALL') params.append('status', statusFilter);
const res = await api.get(`/admin/blogs/comments?${params.toString()}`);
const data = res.data?.data || (Array.isArray(res.data) ? res.data : []);
setBlogComments(data);
setTotalPages(res.data?.meta?.lastPage || 1);
setTotalCount(res.data?.meta?.total || data.length);
}
} catch (err: any) {
console.error('Failed to fetch items:', err);
} finally {
setIsLoading(false);
}
}, [mainTab, page, limit, statusFilter, search]);
useEffect(() => {
fetchItems();
}, [fetchItems]);
const handleUpdateStatus = async (id: string, newStatus: 'APPROVED' | 'REJECTED') => {
try {
setProcessingId(id);
if (mainTab === 'products') {
const res = await api.patch(`/admin/reviews/${id}`, { status: newStatus });
if (res.data?.success) {
toast.success(newStatus === 'APPROVED' ? 'دیدگاه تایید شد و در سایت نمایش می‌یابد.' : 'دیدگاه رد شد.');
setReviews((prev) =>
prev.map((r) => (r.id === id ? { ...r, status: newStatus } : r))
);
}
} else {
await api.patch(`/admin/blogs/comments/${id}/status`, { status: newStatus });
toast.success(newStatus === 'APPROVED' ? 'نظر وبلاگ تایید شد.' : 'نظر وبلاگ رد شد.');
setBlogComments((prev) =>
prev.map((c) => (c.id === id ? { ...c, status: newStatus } : c))
);
}
} catch (err: any) {
console.error('Error updating review status:', err);
} finally {
setProcessingId(null);
}
};
const handleDeleteItem = async (id: string) => {
if (!confirm('آیا از حذف دائمی این دیدگاه اطمینان دارید؟')) return;
try {
setProcessingId(id);
if (mainTab === 'products') {
const res = await api.delete(`/admin/reviews/${id}`);
if (res.data?.success) {
toast.success('دیدگاه با موفقیت حذف شد.');
setReviews((prev) => prev.filter((r) => r.id !== id));
setTotalCount((c) => Math.max(0, c - 1));
}
} else {
await api.delete(`/admin/blogs/comments/${id}`);
toast.success('نظر وبلاگ با موفقیت حذف شد.');
setBlogComments((prev) => prev.filter((c) => c.id !== id));
setTotalCount((c) => Math.max(0, c - 1));
}
} catch (err: any) {
console.error('Error deleting item:', err);
} finally {
setProcessingId(null);
}
};
const handleOpenReplyModal = (review: ProductReview) => {
setReplyingReview(review);
setReplyText(review.adminReply || '');
};
const handleSaveReply = async () => {
if (!replyingReview) return;
try {
setIsSavingReply(true);
const res = await api.patch(`/admin/reviews/${replyingReview.id}`, {
adminReply: replyText.trim(),
status: 'APPROVED', // Auto-approve when replied
});
if (res.data?.success) {
toast.success('پاسخ با موفقیت ثبت شد.');
setReviews((prev) =>
prev.map((r) =>
r.id === replyingReview.id
? { ...r, adminReply: replyText.trim(), status: 'APPROVED' }
: r
)
);
setReplyingReview(null);
}
} catch (err: any) {
console.error('Error saving reply:', err);
} finally {
setIsSavingReply(false);
}
};
return (
<div className="space-y-6 font-vazir text-right" dir="rtl">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
<div>
<h2 className="text-2xl font-black text-gray-900 flex items-center gap-2">
<MessageSquare className="w-6 h-6 text-purple-600" />
مدیریت نظرات و دیدگاه‌ها
</h2>
<p className="text-gray-500 font-medium mt-1">
بررسی، تایید، رد و پاسخ‌دهی به نظرات محصولات و مقالات وبلاگ
</p>
</div>
{/* Search */}
{mainTab === 'products' && (
<div className="relative w-full sm:w-80">
<Search className="w-5 h-5 text-gray-400 absolute right-3 top-1/2 -translate-y-1/2" />
<input
type="text"
placeholder="جستجو (نام خریدار، متن نظر، نام محصول)..."
className="pl-4 pr-10 py-2.5 border border-gray-200 rounded-xl outline-none focus:ring-2 focus:ring-purple-500 w-full font-medium text-sm bg-white"
value={search}
onChange={(e) => {
setSearch(e.target.value);
setPage(1);
}}
/>
</div>
)}
</div>
{/* Main Mode Tabs: Products vs Blogs */}
<div className="flex items-center gap-3 bg-gray-100 p-1.5 rounded-2xl max-w-md">
<button
type="button"
onClick={() => {
setMainTab('products');
setPage(1);
}}
className={`flex-1 py-2.5 px-4 rounded-xl text-xs font-black transition-all cursor-pointer ${
mainTab === 'products'
? 'bg-white text-purple-700 shadow-sm'
: 'text-gray-600 hover:text-gray-900'
}`}
>
دیدگاه‌های محصولات فروشگاه
</button>
<button
type="button"
onClick={() => {
setMainTab('blogs');
setPage(1);
}}
className={`flex-1 py-2.5 px-4 rounded-xl text-xs font-black transition-all cursor-pointer ${
mainTab === 'blogs'
? 'bg-white text-purple-700 shadow-sm'
: 'text-gray-600 hover:text-gray-900'
}`}
>
نظرات مقالات وبلاگ و دانشنامه
</button>
</div>
{/* Filter Tabs */}
<div className="flex flex-wrap items-center gap-2 pt-1 border-b border-gray-200 pb-3">
{[
{ label: 'همه دیدگاه‌ها', value: 'ALL', count: totalCount },
{ label: 'در انتظار بررسی', value: 'PENDING', color: 'text-amber-700 bg-amber-50 border-amber-200' },
{ label: 'تایید شده', value: 'APPROVED', color: 'text-emerald-700 bg-emerald-50 border-emerald-200' },
{ label: 'رد شده', value: 'REJECTED', color: 'text-rose-700 bg-rose-50 border-rose-200' },
].map((tab) => {
const isSelected = statusFilter === tab.value;
return (
<button
key={tab.value}
onClick={() => {
setStatusFilter(tab.value);
setPage(1);
}}
className={`px-4 py-2 rounded-xl text-xs font-bold transition-all border ${
isSelected
? 'bg-purple-600 text-white border-purple-600 shadow-sm'
: 'bg-white text-gray-600 border-gray-200 hover:bg-gray-50'
}`}
>
{tab.label}
</button>
);
})}
</div>
{/* Reviews & Blog Comments Table */}
<div className="bg-white border border-gray-200 rounded-2xl shadow-sm overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full text-right border-collapse">
<thead>
<tr className="bg-gray-50/80 border-b border-gray-200 text-xs font-black text-gray-500">
<th className="py-4 px-6">{mainTab === 'products' ? 'محصول' : 'مقاله وبلاگ'}</th>
<th className="py-4 px-6">نویسنده دیدگاه</th>
{mainTab === 'products' && <th className="py-4 px-6">امتیاز</th>}
<th className="py-4 px-6">{mainTab === 'products' ? 'متن نظر و پاسخ' : 'متن دیدگاه'}</th>
<th className="py-4 px-6">تاریخ</th>
<th className="py-4 px-6">وضعیت</th>
<th className="py-4 px-6 text-center">عملیات</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100 text-sm">
{isLoading ? (
<tr>
<td colSpan={mainTab === 'products' ? 7 : 6} className="py-16 text-center">
<Spinner size="lg" />
<p className="text-gray-400 font-bold mt-2 text-xs">در حال بارگذاری اطلاعات...</p>
</td>
</tr>
) : (mainTab === 'products' ? reviews.length === 0 : blogComments.length === 0) ? (
<tr>
<td colSpan={mainTab === 'products' ? 7 : 6} className="py-16 text-center text-gray-400 font-bold">
هیچ دیدگاهی در این بخش یافت نشد.
</td>
</tr>
) : mainTab === 'products' ? (
reviews.map((review) => {
const isProcessing = processingId === review.id;
const date = new Date(review.createdAt);
return (
<tr key={review.id} className="hover:bg-gray-50/50 transition-colors">
{/* Product */}
<td className="py-4 px-6">
{review.product ? (
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-gray-50 border border-gray-100 overflow-hidden shrink-0 flex items-center justify-center">
{review.product.imageUrl ? (
<img
src={review.product.imageUrl}
alt={review.product.nameFa}
className="w-full h-full object-contain"
/>
) : (
<Package className="w-5 h-5 text-gray-400" />
)}
</div>
<div className="min-w-0">
<div className="font-bold text-xs text-gray-900 truncate max-w-[180px]">
{review.product.nameFa}
</div>
<span className="text-[10px] text-gray-400 block font-mono truncate max-w-[180px]">
{review.product.nameEn}
</span>
</div>
</div>
) : (
<span className="text-xs text-gray-400">محصول نامشخص</span>
)}
</td>
{/* Author */}
<td className="py-4 px-6">
<div className="flex items-center gap-2">
<div className="w-8 h-8 rounded-full bg-purple-50 border border-purple-100 flex items-center justify-center text-purple-600 shrink-0">
<User className="w-4 h-4" />
</div>
<div>
<div className="font-bold text-xs text-gray-900">
{review.userName || `${review.user?.firstName || ''} ${review.user?.lastName || ''}`.trim() || 'کاربر مهمان'}
</div>
{(review.userPhone || review.user?.mobile) && (
<div className="text-[10px] text-gray-400 font-mono">
{toPersianDigits(review.userPhone || review.user?.mobile || '')}
</div>
)}
</div>
</div>
</td>
{/* Rating */}
<td className="py-4 px-6">
<div className="flex items-center gap-1">
{Array.from({ length: 5 }).map((_, i) => (
<Star
key={i}
className={`w-4 h-4 ${
i < review.rating
? 'fill-amber-400 text-amber-400'
: 'text-gray-200'
}`}
/>
))}
<span className="font-bold text-xs text-gray-700 mr-1.5 font-vazir">
{toPersianDigits(review.rating)} از ۵
</span>
</div>
</td>
{/* Comment & Admin Reply */}
<td className="py-4 px-6 max-w-xs md:max-w-md">
<div className="text-gray-800 text-xs sm:text-sm leading-relaxed whitespace-pre-wrap">
{review.comment}
</div>
{review.adminReply && (
<div className="mt-2 p-2.5 bg-purple-50/70 border-r-2 border-purple-500 rounded-lg text-xs text-purple-900 space-y-1">
<span className="font-bold block text-purple-700 flex items-center gap-1">
<Reply className="w-3 h-3 rotate-180" />
پاسخ کنینا:
</span>
<p className="leading-relaxed">{review.adminReply}</p>
</div>
)}
</td>
{/* Date */}
<td className="py-4 px-6 text-gray-500 text-xs font-bold">
<div>{toPersianDigits(date.toLocaleDateString('fa-IR'))}</div>
<div className="text-[10px] text-gray-400">
{toPersianDigits(date.toLocaleTimeString('fa-IR', { hour: '2-digit', minute: '2-digit' }))}
</div>
</td>
{/* Status */}
<td className="py-4 px-6">
{review.status === 'PENDING' && (
<span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-bold bg-amber-50 text-amber-700 border border-amber-200">
<Clock className="w-3 h-3" />
در انتظار بررسی
</span>
)}
{review.status === 'APPROVED' && (
<span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-bold bg-emerald-50 text-emerald-700 border border-emerald-200">
<CheckCircle2 className="w-3 h-3" />
تایید شده
</span>
)}
{review.status === 'REJECTED' && (
<span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-bold bg-rose-50 text-rose-700 border border-rose-200">
<XCircle className="w-3 h-3" />
رد شده
</span>
)}
</td>
{/* Actions */}
<td className="py-4 px-6 text-center">
<div className="flex items-center justify-center gap-1.5">
{review.status !== 'APPROVED' && (
<button
disabled={isProcessing}
onClick={() => handleUpdateStatus(review.id, 'APPROVED')}
title="تایید دیدگاه"
className="p-1.5 text-emerald-600 hover:bg-emerald-50 rounded-lg transition-colors border border-emerald-200 cursor-pointer"
>
<CheckCircle2 className="w-4 h-4" />
</button>
)}
{review.status !== 'REJECTED' && (
<button
disabled={isProcessing}
onClick={() => handleUpdateStatus(review.id, 'REJECTED')}
title="رد دیدگاه"
className="p-1.5 text-rose-600 hover:bg-rose-50 rounded-lg transition-colors border border-rose-200 cursor-pointer"
>
<XCircle className="w-4 h-4" />
</button>
)}
<button
disabled={isProcessing}
onClick={() => handleOpenReplyModal(review)}
title="پاسخ به دیدگاه"
className="p-1.5 text-purple-600 hover:bg-purple-50 rounded-lg transition-colors border border-purple-200 cursor-pointer"
>
<Reply className="w-4 h-4" />
</button>
<button
disabled={isProcessing}
onClick={() => handleDeleteItem(review.id)}
title="حذف دیدگاه"
className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors cursor-pointer"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
</td>
</tr>
);
})
) : (
blogComments.map((comment) => {
const isProcessing = processingId === comment.id;
const date = new Date(comment.createdAt);
return (
<tr key={comment.id} className="hover:bg-gray-50/50 transition-colors">
{/* Blog Post */}
<td className="py-4 px-6">
<div className="font-bold text-xs text-gray-900 line-clamp-2 max-w-[200px]">
{comment.blog?.title || 'مقاله وبلاگ'}
</div>
</td>
{/* Author */}
<td className="py-4 px-6">
<div className="flex items-center gap-2">
<div className="w-8 h-8 rounded-full bg-blue-50 border border-blue-100 flex items-center justify-center text-blue-600 shrink-0">
<User className="w-4 h-4" />
</div>
<div>
<div className="font-bold text-xs text-gray-900">
{comment.userName || 'کاربر'}
</div>
{comment.email && (
<div className="text-[10px] text-gray-400 font-mono">
{comment.email}
</div>
)}
</div>
</div>
</td>
{/* Content */}
<td className="py-4 px-6 max-w-xs md:max-w-md">
<div className="text-gray-800 text-xs sm:text-sm leading-relaxed whitespace-pre-wrap">
{comment.content}
</div>
</td>
{/* Date */}
<td className="py-4 px-6 text-gray-500 text-xs font-bold">
<div>{toPersianDigits(date.toLocaleDateString('fa-IR'))}</div>
<div className="text-[10px] text-gray-400">
{toPersianDigits(date.toLocaleTimeString('fa-IR', { hour: '2-digit', minute: '2-digit' }))}
</div>
</td>
{/* Status */}
<td className="py-4 px-6">
{comment.status === 'PENDING' && (
<span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-bold bg-amber-50 text-amber-700 border border-amber-200">
<Clock className="w-3 h-3" />
در انتظار بررسی
</span>
)}
{comment.status === 'APPROVED' && (
<span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-bold bg-emerald-50 text-emerald-700 border border-emerald-200">
<CheckCircle2 className="w-3 h-3" />
تایید شده
</span>
)}
{comment.status === 'REJECTED' && (
<span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-bold bg-rose-50 text-rose-700 border border-rose-200">
<XCircle className="w-3 h-3" />
رد شده
</span>
)}
</td>
{/* Actions */}
<td className="py-4 px-6 text-center">
<div className="flex items-center justify-center gap-1.5">
{comment.status !== 'APPROVED' && (
<button
disabled={isProcessing}
onClick={() => handleUpdateStatus(comment.id, 'APPROVED')}
title="تایید دیدگاه"
className="p-1.5 text-emerald-600 hover:bg-emerald-50 rounded-lg transition-colors border border-emerald-200 cursor-pointer"
>
<CheckCircle2 className="w-4 h-4" />
</button>
)}
{comment.status !== 'REJECTED' && (
<button
disabled={isProcessing}
onClick={() => handleUpdateStatus(comment.id, 'REJECTED')}
title="رد دیدگاه"
className="p-1.5 text-rose-600 hover:bg-rose-50 rounded-lg transition-colors border border-rose-200 cursor-pointer"
>
<XCircle className="w-4 h-4" />
</button>
)}
<button
disabled={isProcessing}
onClick={() => handleDeleteItem(comment.id)}
title="حذف دیدگاه"
className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors cursor-pointer"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
</td>
</tr>
);
})
)}
</tbody>
</table>
</div>
{/* Pagination */}
{totalPages > 1 && (
<div className="p-4 border-t border-gray-100 flex items-center justify-between">
<span className="text-xs text-gray-500 font-bold">
صفحه {toPersianDigits(page)} از {toPersianDigits(totalPages)}
</span>
<div className="flex items-center gap-2">
<button
disabled={page <= 1 || isLoading}
onClick={() => setPage((p) => Math.max(1, p - 1))}
className="p-2 border border-gray-200 rounded-xl hover:bg-gray-50 disabled:opacity-40 disabled:pointer-events-none transition-all text-xs font-bold flex items-center gap-1"
>
<ChevronRight className="w-4 h-4" />
<span>قبلی</span>
</button>
<button
disabled={page >= totalPages || isLoading}
onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
className="p-2 border border-gray-200 rounded-xl hover:bg-gray-50 disabled:opacity-40 disabled:pointer-events-none transition-all text-xs font-bold flex items-center gap-1"
>
<span>بعدی</span>
<ChevronLeft className="w-4 h-4" />
</button>
</div>
</div>
)}
</div>
{/* Reply Modal */}
{replyingReview && (
<Modal
isOpen={!!replyingReview}
onClose={() => setReplyingReview(null)}
title={`پاسخ به دیدگاه ${replyingReview.userName}`}
icon={Reply}
maxWidth="lg"
footer={
<div className="flex items-center justify-end gap-2.5 w-full">
<Button
variant="secondary"
size="sm"
type="button"
onClick={() => setReplyingReview(null)}
>
انصراف
</Button>
<Button
variant="primary"
size="sm"
isLoading={isSavingReply}
onClick={handleSaveReply}
>
ثبت و انتشار پاسخ
</Button>
</div>
}
>
<div className="space-y-4 font-vazir text-right">
<div className="p-3 bg-gray-50 rounded-xl border border-gray-100 text-xs text-gray-600 space-y-1">
<span className="font-bold text-gray-700 block">متن دیدگاه خریدار:</span>
<p className="leading-relaxed whitespace-pre-wrap">{replyingReview.comment}</p>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1.5">
متن پاسخ کارشناس رسمی کنینا:
</label>
<textarea
rows={4}
value={replyText}
onChange={(e) => setReplyText(e.target.value)}
placeholder="پاسخ و توضیحات رسمی برای نمایش در زیر نظر..."
className="w-full p-3 border border-gray-200 rounded-xl text-sm font-medium outline-none focus:ring-2 focus:ring-purple-500 resize-none leading-relaxed"
/>
</div>
</div>
</Modal>
)}
</div>
);
}