'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; }; 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 ?? initialData.allow_admin ?? false ); setAllowAdminPanel(isAdminAllowed); form.setFieldsValue({ name: initialData.name, description: initialData.description || '', allow_admin_panel: isAdminAllowed, }); // Map existing permissions into selectedPermissions dictionary const initialSelection: Record = {}; if (Array.isArray(initialData.role_detail) && initialData.role_detail.length > 0) { initialData.role_detail.forEach((item: IRoleDetail) => { if (item.menu_id && Array.isArray(item.action)) { initialSelection[item.menu_id] = item.action; } }); } else if (Array.isArray(initialData.privilege) && initialData.privilege.length > 0) { // Support legacy privilege format initialData.privilege.forEach((item: any) => { const mId = item.menu_id || item.id; if (mId && Array.isArray(item.action)) { initialSelection[mId] = item.action.map((a: any) => (typeof a === 'string' ? a : a.name || a.code || String(a))); } }); } 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) => { if (m.is_admin_menu && 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); } if (nextActions.length === 0) { const copy = { ...prev }; delete copy[menuId]; return copy; } return { ...prev, [menuId]: nextActions, }; }); }; // 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; }); }; // 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 if (menu.is_admin_menu && !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: Boolean(menu.is_admin_menu), action: safeActions, }); } }); const payload: Record = { name: values.name?.trim(), description: values.description?.trim() || '', allow_admin_panel: Boolean(allowAdminPanel), allow_admin: Boolean(allowAdminPanel), // For backward compatibility with legacy endpoints role_detail: roleDetail, privilege: roleDetail, // For backward compatibility with legacy endpoints }; 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 successfully created.'); 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 successfully updated.'); 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 User Role' : 'Create New User Role'} {isUpdate ? `Configure role permissions for role ID ${roleId}` : 'Define role details and assign hierarchical menu access'}
{/* Form Body */}
{/* Section A: General Information */} Informasi Umum (General Information) Masukkan nama peran, deskripsi, dan hak akses admin panel
Allow Admin Panel Mengizinkan role ini mengakses menu administrasi dan admin panel
{/* Section B: Menu Permissions */}
Detil Hak Akses & Access Permissions Atur izin akses untuk setiap menu yang tersedia dalam aplikasi
{Object.keys(selectedPermissions).length} menu dikonfigurasi
{menuLoading ? (
Memuat struktur menu dari server...
) : ( )}
{/* Bottom Action Bar */}
{/* Confirmation Dialog */} {showConfirm && ( Konfirmasi Simpan Role? Konfigurasi hak akses role ini akan disimpan dan langsung berlaku bagi pengguna yang memiliki role ini. setShowConfirm(false)}> Batal { setShowConfirm(false); handleSubmit(); }} > {isLoading && } Lanjutkan )} ); }; export default RoleForm;