'use client'; import { useState, useEffect, useCallback } from 'react'; import { Shield, Edit, Trash2, Users, Check, X, Loader2 } from 'lucide-react'; import { positionsAPI } from '@/lib/api/admin'; import type { PositionRole, PositionPermission } from '@/lib/api/admin'; import Modal from '@/components/Modal'; import LoadingSpinner from '@/components/LoadingSpinner'; const MODULES = [ { id: 'contacts', name: 'إدارة جهات الاتصال', nameEn: 'Contact Management' }, { id: 'crm', name: 'إدارة علاقات العملاء', nameEn: 'CRM' }, { id: 'inventory', name: 'المخزون والأصول', nameEn: 'Inventory & Assets' }, { id: 'projects', name: 'المهام والمشاريع', nameEn: 'Tasks & Projects' }, { id: 'hr', name: 'الموارد البشرية', nameEn: 'HR Management' }, { id: 'marketing', name: 'التسويق', nameEn: 'Marketing' }, { id: 'admin', name: 'لوحة الإدارة', nameEn: 'Admin' }, ]; const ACTIONS = [ { id: 'read', name: 'عرض' }, { id: 'create', name: 'إنشاء' }, { id: 'update', name: 'تعديل' }, { id: 'delete', name: 'حذف' }, { id: 'export', name: 'تصدير' }, { id: 'approve', name: 'اعتماد' }, { id: 'merge', name: 'دمج' }, ]; function hasAction(permission: PositionPermission | undefined, action: string): boolean { if (!permission?.actions) return false; const actions = Array.isArray(permission.actions) ? permission.actions : []; return actions.includes('*') || actions.includes('all') || actions.includes(action); } function buildPermissionsFromMatrix(matrix: Record>) { return MODULES.filter((m) => Object.values(matrix[m.id] || {}).some(Boolean)).map((m) => { const actions = ACTIONS.filter((a) => matrix[m.id]?.[a.id]).map((a) => a.id); return { module: m.id, resource: '*', actions: actions.length === ACTIONS.length ? ['*'] : actions, }; }); } function buildMatrixFromPermissions(permissions: PositionPermission[]): Record> { const matrix: Record> = {}; for (const m of MODULES) { matrix[m.id] = {}; const perm = permissions.find((p) => p.module === m.id && (p.resource === '*' || p.resource === m.id)); const hasAll = perm && (Array.isArray(perm.actions) ? (perm.actions as string[]).includes('*') || (perm.actions as string[]).includes('all') : false); for (const a of ACTIONS) { matrix[m.id][a.id] = hasAll || hasAction(perm, a.id); } } return matrix; } export default function RolesManagement() { const [roles, setRoles] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [selectedRoleId, setSelectedRoleId] = useState(null); const [showEditModal, setShowEditModal] = useState(false); const [permissionMatrix, setPermissionMatrix] = useState>>({}); const [saving, setSaving] = useState(false); const [showDeleteDialog, setShowDeleteDialog] = useState(false); const [deleting, setDeleting] = useState(false); const [roleToDelete, setRoleToDelete] = useState(null); const fetchRoles = useCallback(async () => { setLoading(true); setError(null); try { const pos = await positionsAPI.getAll(); setRoles(pos); if (selectedRoleId && !pos.find((p) => p.id === selectedRoleId)) { setSelectedRoleId(null); } } catch (err: unknown) { setError(err instanceof Error ? err.message : 'فشل تحميل الأدوار'); } finally { setLoading(false); } }, [selectedRoleId]); useEffect(() => { fetchRoles(); }, [fetchRoles]); const currentRole = roles.find((r) => r.id === selectedRoleId); useEffect(() => { if (currentRole) { setPermissionMatrix(buildMatrixFromPermissions(currentRole.permissions || [])); } }, [currentRole?.id, currentRole?.permissions]); const handleTogglePermission = (moduleId: string, actionId: string) => { setPermissionMatrix((prev) => ({ ...prev, [moduleId]: { ...(prev[moduleId] || {}), [actionId]: !prev[moduleId]?.[actionId], }, })); }; const handleSavePermissions = async () => { if (!selectedRoleId) return; setSaving(true); try { const permissions = buildPermissionsFromMatrix(permissionMatrix); await positionsAPI.updatePermissions(selectedRoleId, permissions); setShowEditModal(false); fetchRoles(); } catch (err: unknown) { alert(err instanceof Error ? err.message : 'فشل حفظ الصلاحيات'); } finally { setSaving(false); } }; const openDeleteDialog = (role: PositionRole) => { setRoleToDelete(role); setShowDeleteDialog(true); }; const handleDeleteRole = async () => { if (!roleToDelete) return; setDeleting(true); try { await positionsAPI.delete(roleToDelete.id); if (selectedRoleId === roleToDelete.id) { setSelectedRoleId(null); } setShowDeleteDialog(false); setRoleToDelete(null); await fetchRoles(); } catch (err: unknown) { const msg = (err as any)?.response?.data?.message || (err as any)?.response?.data?.error || (err as any)?.message || 'فشل حذف الدور'; alert(msg); } finally { setDeleting(false); } }; const handleSelectRole = (id: string) => { setSelectedRoleId(id); setShowEditModal(false); }; return (

الأدوار والصلاحيات

إدارة أدوار المستخدمين ومصفوفة الصلاحيات

{loading ? (
) : error ? (
{error}
) : (
{/* Roles List */}

الأدوار ({roles.length})

{roles.map((role) => (
handleSelectRole(role.id)} className={`p-4 rounded-xl border-2 cursor-pointer transition-all ${ selectedRoleId === role.id ? 'border-purple-600 bg-purple-50 shadow-md' : 'border-gray-200 bg-white hover:border-purple-300 hover:shadow-sm' }`} >

{role.titleAr || role.title}

{role.title}

{role.usersCount ?? role._count?.employees ?? 0} مستخدم
{/* Actions: Edit + Delete */}
))}
{/* Permission Matrix */}
{currentRole ? (

{currentRole.titleAr || currentRole.title}

{currentRole.title}

مصفوفة الصلاحيات

{ACTIONS.map((perm) => ( ))} {MODULES.map((module) => ( {ACTIONS.map((action) => { const hasPermission = permissionMatrix[module.id]?.[action.id]; return ( ); })} ))}
الوحدة {perm.name}

{module.name}

{module.nameEn}

{hasPermission ? : }
) : (

اختر دوراً لعرض الصلاحيات

اختر دور من القائمة لعرض وتعديل صلاحياته

)}
)} {/* Delete Confirmation Dialog */} {showDeleteDialog && roleToDelete && (
{ if (!deleting) { setShowDeleteDialog(false); setRoleToDelete(null); } }} />

حذف الدور

هذا الإجراء لا يمكن التراجع عنه

هل أنت متأكد أنك تريد حذف دور{' '} {roleToDelete.titleAr || roleToDelete.title}؟

)} {/* Edit Permissions Modal */} setShowEditModal(false)} title={`تعديل صلاحيات: ${currentRole?.titleAr || currentRole?.title || ''}`} size="2xl" > {currentRole && (
{ACTIONS.map((perm) => ( ))} {MODULES.map((module) => ( {ACTIONS.map((action) => { const hasPermission = permissionMatrix[module.id]?.[action.id]; return ( ); })} ))}
الوحدة {perm.name}

{module.name}

)}
); }