'use client'; import { FC, useEffect, useState, useMemo } from 'react'; import Link from 'next/link'; import { useRouter } from 'next/navigation'; import { Form, Input, Switch } from 'antd'; import { Icons } from '@/components/Icons'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from '@/components/ui/alert-dialog'; import useAxiosAuth from '@/lib/axios/useAxiosAuth'; import useFetch from '@/lib/axios/useFetch'; import { toast } from 'sonner'; import { type IRole, type IMenu, type IRoleDetail } from './type'; import MenuPermissionTree from './MenuPermissionTree'; type Props = { isUpdate?: boolean; roleId?: string | number; initialData?: IRole; }; // Helper to collect all descendant IDs of a menu function getDescendantIds(targetId: number, allMenus: IMenu[]): number[] { const ids: number[] = []; const direct = allMenus.filter(m => m.menu_parent_id === targetId && m.id !== undefined); direct.forEach(c => { ids.push(c.id!); ids.push(...getDescendantIds(c.id!, allMenus)); }); return ids; } export const RoleForm: FC = ({ isUpdate, roleId, initialData }) => { const [isLoading, setIsLoading] = useState(false); const [showConfirm, setShowConfirm] = useState(false); const [allowAdminPanel, setAllowAdminPanel] = useState(false); // Key: menu_id -> array of action strings const [selectedPermissions, setSelectedPermissions] = useState>({}); const [form] = Form.useForm(); const router = useRouter(); const axios = useAxiosAuth(); // Fetch menus from backend const { data: menuData, isLoading: menuLoading } = useFetch('/menu'); const menus: IMenu[] = useMemo(() => { if (!menuData) return []; if (Array.isArray(menuData)) return menuData; if (Array.isArray(menuData.menu)) return menuData.menu; if (Array.isArray(menuData.menus)) return menuData.menus; return []; }, [menuData]); // Prepopulate form on mount or when initialData changes useEffect(() => { if (initialData) { const isAdminAllowed = Boolean( initialData.allow_admin_panel ?? false ); setAllowAdminPanel(isAdminAllowed); form.setFieldsValue({ name: initialData.name, description: initialData.description || '', allow_admin_panel: isAdminAllowed, }); // Map existing permissions into selectedPermissions dictionary const initialSelection: Record = {}; const rawDetails = Array.isArray(initialData.role_detail) ? initialData.role_detail : []; rawDetails.forEach((item: any) => { // Support both new API format (item.menu.id) and legacy format (item.menu_id) const mId = item.menu?.id ?? item.menu_id ?? (typeof item.menu === 'number' ? item.menu : undefined); const actions = Array.isArray(item.action) ? item.action : []; if (mId !== undefined && actions.length > 0) { initialSelection[mId] = actions; } }); setSelectedPermissions(initialSelection); } else { form.resetFields(); form.setFieldsValue({ allow_admin_panel: false, }); setAllowAdminPanel(false); setSelectedPermissions({}); } }, [initialData, form]); // Handle allow_admin_panel toggle const handleAdminToggle = (checked: boolean) => { setAllowAdminPanel(checked); form.setFieldValue('allow_admin_panel', checked); // When toggled to false, clean all Admin Menu assignments from form state if (!checked) { setSelectedPermissions((prev) => { const next = { ...prev }; menus.forEach((m) => { const isAdmin = Boolean(m.is_admin_menu); if (isAdmin && m.id !== undefined && next[m.id]) { delete next[m.id]; } }); return next; }); } }; // Permission toggle handler for a single action const handlePermissionToggle = (menuId: number, actionName: string, checked: boolean) => { setSelectedPermissions((prev) => { const currentActions = prev[menuId] || []; let nextActions: string[]; if (checked) { if (!currentActions.includes(actionName)) { nextActions = [...currentActions, actionName]; } else { nextActions = currentActions; } } else { nextActions = currentActions.filter((a) => a !== actionName); } const next = { ...prev }; if (nextActions.length === 0) { delete next[menuId]; // When parent loses all actions, all descendants are also cleared const descendantIds = getDescendantIds(menuId, menus); descendantIds.forEach((dId) => { delete next[dId]; }); } else { next[menuId] = nextActions; } return next; }); }; // Select all actions on a menu row const handleMenuSelectAll = (menuId: number, allActions: string[]) => { setSelectedPermissions((prev) => ({ ...prev, [menuId]: [...allActions], })); }; // Clear all actions on a menu row const handleMenuClearAll = (menuId: number) => { setSelectedPermissions((prev) => { const copy = { ...prev }; delete copy[menuId]; return copy; }); }; // Batch select all actions on multiple menu rows (parent + descendants) const handleBatchSelectAll = (updates: Record) => { setSelectedPermissions((prev) => ({ ...prev, ...updates, })); }; // Batch clear actions on multiple menu rows (parent + descendants) const handleBatchClearAll = (menuIds: number[]) => { setSelectedPermissions((prev) => { const next = { ...prev }; menuIds.forEach((id) => { delete next[id]; }); return next; }); }; // Final payload construction according to backend contract const handleSubmit = async () => { try { const values = await form.validateFields(); setIsLoading(true); // Build role_detail array const roleDetail: IRoleDetail[] = []; // Group menus by ID for fast lookup const menuMap = new Map(); menus.forEach((m) => { if (m.id !== undefined) menuMap.set(m.id, m); }); // Iterate over selected permissions Object.entries(selectedPermissions).forEach(([menuIdStr, actions]) => { const menuId = Number(menuIdStr); const menu = menuMap.get(menuId); if (!menu || !actions || actions.length === 0) return; // Rule: If allow_admin_panel is false, exclude Admin menus const isAdmin = Boolean(menu.is_admin_menu); if (isAdmin && !allowAdminPanel) { return; } // Filter action to only valid actions configured on this menu const validMenuActions = menu.action || []; const safeActions = actions.filter( (a) => validMenuActions.length === 0 || validMenuActions.includes(a) ); if (safeActions.length > 0) { roleDetail.push({ menu_id: menu.id!, menu_name: menu.name, menu_path: menu.path_url || '#', is_admin_menu: isAdmin, action: safeActions, }); } }); const payload: Record = { code: values.name?.trim().replace(/\s/g, '_').toUpperCase(), name: values.name?.trim(), description: values.description?.trim() || '', allow_admin_panel: Boolean(allowAdminPanel), role_detail: roleDetail, }; if (!isUpdate) { const res = await axios.post('/role', payload); setIsLoading(false); if (res.data?.code && res.data.code !== '00' && res.data.code !== 200) { toast.error('Failed to create role', { description: res.data?.message || 'Server error', }); return; } toast.success('Role created successfully.'); router.push('/admin/rbac/user-role'); router.refresh(); } else { const res = await axios.put(`/role/${roleId}`, payload); setIsLoading(false); if (res.data?.code && res.data.code !== '00' && res.data.code !== 200) { toast.error('Failed to update role', { description: res.data?.message || 'Server error', }); return; } toast.success('Role updated successfully.'); router.push('/admin/rbac/user-role'); router.refresh(); } } catch (error: any) { setIsLoading(false); const msg = error?.response?.data?.message || error?.message || 'Failed to save role'; toast.error('Failed to save role', { description: msg }); } }; return ( <>
{/* Header Card */}
{isUpdate ? 'Edit Role' : 'Create Role'} {isUpdate ? `Update role permissions and configuration for role ID ${roleId}` : 'Define role details and assign hierarchical menu access'}
{/* Form Body */}
{/* Section A: General Information */} General Information Enter role name, description, and admin panel privileges
Allow Admin Panel Grants this role access to administration and admin panel menus
{/* Section B: Menu Permissions */}
Menu Permissions & Access Rights Configure access permissions for each menu available in the application
{Object.keys(selectedPermissions).length} menus configured
{menuLoading ? (
Loading menu structure from server...
) : ( )}
{/* Bottom Action Bar */}
{/* Confirmation Dialog */} {showConfirm && ( Save Role Configuration? These permission settings will be saved and immediately applied to users assigned to this role. setShowConfirm(false)}> Cancel { setShowConfirm(false); handleSubmit(); }} > {isLoading && } Save Changes )} ); }; export default RoleForm;