Files
canina/frontend/admin-panel/src/pages/MenuManager.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

507 lines
19 KiB
TypeScript

import {
ChevronDown,ChevronRight,
Edit2,
ExternalLink,
Eye,EyeOff,
Menu,Plus,
Trash2
} from 'lucide-react';
import { useCallback,useEffect,useState } from 'react';
import { toast } from 'react-hot-toast';
import Button from '../components/ui/Button';
import ConfirmModal from '../components/ui/ConfirmModal';
import Modal from '../components/ui/Modal';
import Spinner from '../components/ui/Spinner';
import api from '../services/api';
interface MenuItem {
id: string;
menuType: string;
label: string;
href: string;
parentId: string | null;
order: number;
isActive: boolean;
isExternal: boolean;
icon: string | null;
badge: string | null;
children?: MenuItem[];
}
type MenuType = 'HEADER' | 'FOOTER_COL1' | 'FOOTER_COL2' | 'FOOTER_COL3';
const MENU_TABS: { key: MenuType; label: string; color: string }[] = [
{ key: 'HEADER', label: '📌 منوی هدر', color: 'blue' },
{ key: 'FOOTER_COL1', label: '🔗 فوتر — ستون ۱', color: 'purple' },
{ key: 'FOOTER_COL2', label: '🔗 فوتر — ستون ۲', color: 'indigo' },
{ key: 'FOOTER_COL3', label: '🔗 فوتر — ستون ۳', color: 'violet' },
];
import { useSearchParams } from 'react-router-dom';
export default function MenuManager() {
const [searchParams, setSearchParams] = useSearchParams();
const tabFromUrl = (searchParams.get('tab') as MenuType) || 'HEADER';
const [activeTab, setActiveTabState] = useState<MenuType>(tabFromUrl);
const [allItems, setAllItems] = useState<MenuItem[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [isModalOpen, setIsModalOpen] = useState(false);
const [editingItem, setEditingItem] = useState<MenuItem | null>(null);
const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
const [isSaving, setIsSaving] = useState(false);
const updateUrlState = (updates: Record<string, string | null>) => {
const current = Object.fromEntries(searchParams.entries());
const merged = { ...current, ...updates };
const cleaned: Record<string, string> = {};
Object.entries(merged).forEach(([k, v]) => {
if (v !== null && v !== undefined && v !== '') cleaned[k] = v;
});
setSearchParams(cleaned, { replace: true });
};
const setActiveTab = (t: MenuType) => {
setActiveTabState(t);
updateUrlState({ tab: t === 'HEADER' ? null : t });
};
const [formData, setFormData] = useState({
menuType: 'HEADER' as MenuType,
label: '',
href: '',
parentId: null as string | null,
order: 0,
isActive: true,
isExternal: false,
icon: '',
badge: '',
});
const currentItems = allItems.filter(
(item) => item.menuType === activeTab && item.parentId === null
);
const openModal = (item: MenuItem | null = null, parentId?: string) => {
if (item) {
setEditingItem(item);
updateUrlState({ modal: 'edit', itemId: item.id });
setFormData({
menuType: item.menuType as MenuType,
label: item.label,
href: item.href,
parentId: item.parentId,
order: item.order,
isActive: item.isActive,
isExternal: item.isExternal,
icon: item.icon || '',
badge: item.badge || '',
});
} else {
setEditingItem(null);
updateUrlState({ modal: 'create', itemId: null });
setFormData({
menuType: activeTab,
label: '',
href: '',
parentId: parentId || null,
order: currentItems.length,
isActive: true,
isExternal: false,
icon: '',
badge: '',
});
}
setIsModalOpen(true);
};
const closeModal = () => {
setIsModalOpen(false);
updateUrlState({ modal: null, itemId: null });
};
const fetchAll = useCallback(async () => {
try {
setIsLoading(true);
const res = await api.get('/menu/admin');
const data: MenuItem[] = Array.isArray(res.data) ? res.data : (res.data?.data || []);
setAllItems(data);
const modalParam = searchParams.get('modal');
const itemIdParam = searchParams.get('itemId');
if (modalParam === 'create') {
openModal(null);
} else if (modalParam === 'edit' && itemIdParam) {
const found = data.find((it) => it.id === itemIdParam);
if (found) openModal(found);
}
} catch (err) {
console.error('Failed to fetch menu items:', err);
toast.error('خطا در دریافت آیتم‌های منو');
} finally {
setIsLoading(false);
}
}, [searchParams]);
useEffect(() => {
fetchAll();
}, [fetchAll]);
const handleSave = async (e: React.FormEvent) => {
e.preventDefault();
if (!formData.label.trim() || !formData.href.trim()) {
toast.error('عنوان و لینک اجباری هستند');
return;
}
try {
setIsSaving(true);
const payload = {
...formData,
icon: formData.icon || null,
badge: formData.badge || null,
};
if (editingItem) {
await api.put(`/menu/${editingItem.id}`, payload);
toast.success('آیتم منو بروزرسانی شد');
} else {
await api.post('/menu', payload);
toast.success('آیتم جدید اضافه شد');
}
setIsModalOpen(false);
fetchAll();
} catch (err) {
console.error('Failed to save menu item:', err);
toast.error('خطا در ذخیره');
} finally {
setIsSaving(false);
}
};
const toggleActive = async (item: MenuItem) => {
try {
await api.put(`/menu/${item.id}`, { isActive: !item.isActive });
toast.success(item.isActive ? 'مخفی شد' : 'فعال شد');
fetchAll();
} catch {
toast.error('خطا در تغییر وضعیت');
}
};
const confirmDelete = async () => {
if (!deleteTargetId) return;
try {
await api.delete(`/menu/${deleteTargetId}`);
toast.success('آیتم حذف شد');
fetchAll();
} catch {
toast.error('خطا در حذف');
} finally {
setDeleteTargetId(null);
}
};
const parentItems = allItems.filter(
(item) => item.menuType === formData.menuType && item.parentId === null && item.id !== editingItem?.id
);
return (
<div className="space-y-6">
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
<div>
<h2 className="text-2xl font-black text-gray-900 flex items-center gap-2">
<Menu className="w-6 h-6 text-blue-600" />
مدیریت منو
</h2>
<p className="text-gray-500 font-medium mt-1">
مدیریت آیتم‌های هدر و فوتر سایت — تغییرات بلادرنگ اعمال می‌شوند
</p>
</div>
<Button
variant="primary"
size="sm"
startIcon={Plus}
onClick={() => openModal()}
>
آیتم جدید
</Button>
</div>
{/* Tabs */}
<div className="flex gap-2 flex-wrap">
{MENU_TABS.map((tab) => (
<button
key={tab.key}
onClick={() => setActiveTab(tab.key)}
className={`px-4 py-2 rounded-xl text-sm font-bold transition-all ${
activeTab === tab.key
? 'bg-blue-600 text-white shadow-md shadow-blue-200'
: 'bg-white border border-gray-200 text-gray-600 hover:border-blue-300'
}`}
>
{tab.label}
</button>
))}
</div>
{/* Menu Items List */}
{isLoading ? (
<div className="flex justify-center py-12">
<Spinner size="lg" className="text-blue-600" />
</div>
) : currentItems.length === 0 ? (
<div className="bg-white rounded-2xl border border-dashed border-gray-300 py-16 text-center">
<Menu className="w-12 h-12 text-gray-300 mx-auto mb-3" />
<p className="text-gray-500 font-medium">هیچ آیتمی در این منو وجود ندارد</p>
<button
onClick={() => openModal()}
className="mt-4 text-blue-600 font-bold hover:underline text-sm"
>
اولین آیتم را اضافه کنید
</button>
</div>
) : (
<div className="space-y-2">
{currentItems.map((item) => (
<div key={item.id} className="bg-white rounded-2xl border border-gray-200 overflow-hidden">
{/* Parent Item */}
<div className={`flex items-center gap-3 p-4 ${!item.isActive ? 'opacity-50' : ''}`}>
<div className="flex items-center gap-2 text-gray-400 shrink-0">
<ChevronRight className="w-4 h-4" />
<span className="text-xs font-mono text-gray-300">#{item.order}</span>
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
{item.icon && <span className="text-base">{item.icon}</span>}
<span className="font-bold text-gray-900">{item.label}</span>
{item.badge && (
<span className="px-1.5 py-0.5 bg-blue-100 text-blue-700 text-[10px] font-bold rounded">
{item.badge}
</span>
)}
{item.isExternal && <ExternalLink className="w-3 h-3 text-gray-400" />}
</div>
<span className="text-xs text-gray-400 font-mono mt-0.5 block">{item.href}</span>
</div>
<div className="flex items-center gap-1 shrink-0">
<button
onClick={() => toggleActive(item)}
className={`p-2 rounded-lg transition-colors ${item.isActive ? 'text-green-600 hover:bg-green-50' : 'text-gray-400 hover:bg-gray-50'}`}
title={item.isActive ? 'مخفی کردن' : 'نمایش'}
>
{item.isActive ? <Eye className="w-4 h-4" /> : <EyeOff className="w-4 h-4" />}
</button>
<button
onClick={() => openModal(item)}
className="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
>
<Edit2 className="w-4 h-4" />
</button>
<button
onClick={() => setDeleteTargetId(item.id)}
className="p-2 text-red-500 hover:bg-red-50 rounded-lg transition-colors"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
</div>
{/* Children */}
{item.children && item.children.length > 0 && (
<div className="border-t border-gray-100 bg-gray-50/50">
{item.children.map((child) => (
<div key={child.id} className={`flex items-center gap-3 px-6 py-3 border-b border-gray-100 last:border-0 ${!child.isActive ? 'opacity-50' : ''}`}>
<ChevronDown className="w-3.5 h-3.5 text-gray-300 shrink-0" />
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="text-sm font-bold text-gray-700">{child.label}</span>
{child.isExternal && <ExternalLink className="w-3 h-3 text-gray-400" />}
</div>
<span className="text-xs text-gray-400 font-mono">{child.href}</span>
</div>
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="xs"
startIcon={Edit2}
onClick={() => openModal(child)}
className="text-blue-600 hover:bg-blue-50"
/>
<Button
variant="ghost"
size="xs"
startIcon={Trash2}
onClick={() => setDeleteTargetId(child.id)}
className="text-red-500 hover:bg-red-50"
/>
</div>
</div>
))}
</div>
)}
</div>
))}
</div>
)}
{/* Modal */}
{isModalOpen && (
<Modal
isOpen={isModalOpen}
onClose={closeModal}
title={editingItem ? 'ویرایش آیتم منو' : 'افزودن آیتم جدید'}
icon={Menu}
maxWidth="xl"
footer={
<div className="flex justify-end gap-2.5 w-full">
<Button
variant="secondary"
size="sm"
type="button"
onClick={closeModal}
>
انصراف
</Button>
<Button
variant="primary"
size="sm"
type="submit"
form="menuForm"
isLoading={isSaving}
>
ذخیره
</Button>
</div>
}
>
<div className="space-y-6 text-right font-vazir">
<form id="menuForm" onSubmit={handleSave} className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-bold text-gray-700 mb-1">موقعیت در منو</label>
<select
value={formData.menuType}
onChange={(e) => setFormData({ ...formData, menuType: e.target.value as MenuType, parentId: null })}
className="w-full px-3 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-sm bg-white"
>
{MENU_TABS.map((tab) => (
<option key={tab.key} value={tab.key}>{tab.label}</option>
))}
</select>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-1">زیر آیتم از</label>
<select
value={formData.parentId || ''}
onChange={(e) => setFormData({ ...formData, parentId: e.target.value || null })}
className="w-full px-3 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-sm bg-white"
>
<option value="">— آیتم اصلی —</option>
{parentItems.map((p) => (
<option key={p.id} value={p.id}>{p.label}</option>
))}
</select>
</div>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-1">عنوان <span className="text-red-500">*</span></label>
<input
required
type="text"
value={formData.label}
onChange={(e) => setFormData({ ...formData, label: e.target.value })}
placeholder="مثال: فروشگاه تخصصی"
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-sm"
/>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-1">لینک (href) <span className="text-red-500">*</span></label>
<input
required
type="text"
value={formData.href}
onChange={(e) => setFormData({ ...formData, href: e.target.value })}
placeholder="مثال: /shop یا https://..."
dir="ltr"
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-sm font-mono"
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-bold text-gray-700 mb-1">آیکون (اختیاری)</label>
<input
type="text"
value={formData.icon}
onChange={(e) => setFormData({ ...formData, icon: e.target.value })}
placeholder="🐕 یا نام آیکون"
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-sm"
/>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-1">Badge (اختیاری)</label>
<input
type="text"
value={formData.badge}
onChange={(e) => setFormData({ ...formData, badge: e.target.value })}
placeholder="مثال: جدید"
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-sm"
/>
</div>
</div>
<div className="grid grid-cols-3 gap-3">
<div>
<label className="block text-sm font-bold text-gray-700 mb-1">ترتیب</label>
<input
type="number"
value={formData.order}
onChange={(e) => setFormData({ ...formData, order: Number(e.target.value) })}
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-sm"
/>
</div>
<label className="flex items-center justify-between p-3 bg-green-50 rounded-xl border border-green-200 cursor-pointer col-span-1 mt-auto">
<span className="text-xs font-bold text-green-700">✅ فعال</span>
<input
type="checkbox"
checked={formData.isActive}
onChange={(e) => setFormData({ ...formData, isActive: e.target.checked })}
className="rounded text-green-600"
/>
</label>
<label className="flex items-center justify-between p-3 bg-gray-50 rounded-xl border border-gray-200 cursor-pointer col-span-1 mt-auto">
<span className="text-xs font-bold text-gray-700">🔗 لینک خارجی</span>
<input
type="checkbox"
checked={formData.isExternal}
onChange={(e) => setFormData({ ...formData, isExternal: e.target.checked })}
className="rounded"
/>
</label>
</div>
</form>
</div>
</Modal>
)}
{deleteTargetId && (
<ConfirmModal
isOpen={true}
title="حذف آیتم منو"
message="آیا از حذف این آیتم اطمینان دارید؟ آیتم‌های زیرمجموعه نیز حذف خواهند شد."
onConfirm={confirmDelete}
onCancel={() => setDeleteTargetId(null)}
/>
)}
</div>
);
}