Files
hats-app/app/admin/rbac/user-role/component/RoleForm.tsx
T
Ichsan Kurniawan 6ffe7746c8 Improve RBAC management and permissions UI
Unify interactive and read-only role permission rows, refine role and menu forms and labels, and correct the access-permissions sidebar route. Update role payloads and admin-menu handling.
2026-11-05 20:37:39 +07:00

441 lines
19 KiB
TypeScript

'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<Props> = ({ isUpdate, roleId, initialData }) => {
const [isLoading, setIsLoading] = useState(false);
const [showConfirm, setShowConfirm] = useState(false);
const [allowAdminPanel, setAllowAdminPanel] = useState<boolean>(false);
// Key: menu_id -> array of action strings
const [selectedPermissions, setSelectedPermissions] = useState<Record<number, string[]>>({});
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<number, string[]> = {};
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) {
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) => {
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);
}
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<number, IMenu>();
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<string, any> = {
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 (
<>
<div className="flex flex-col space-y-6 pb-12">
{/* Header Card */}
<Card>
<CardHeader className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
<div className="flex items-center space-x-4">
<Link href="/admin/rbac/user-role">
<Button variant="outline" size="icon" className="h-9 w-9">
<i className="ti ti-arrow-left text-lg" />
</Button>
</Link>
<div>
<CardTitle className="text-xl">
{isUpdate ? 'Edit Role' : 'Create Role'}
</CardTitle>
<CardDescription className="mt-1">
{isUpdate
? `Update role permissions and configuration for role ID ${roleId}`
: 'Define role details and assign hierarchical menu access'}
</CardDescription>
</div>
</div>
<div className="flex items-center gap-2 self-end sm:self-auto">
<Link href="/admin/rbac/user-role">
<Button variant="outline" size="sm" disabled={isLoading}>
Cancel
</Button>
</Link>
<Button
size="sm"
className="bg-his hover:bg-his/90 text-white font-medium"
onClick={() => setShowConfirm(true)}
disabled={isLoading || menuLoading}
>
{isLoading && <Icons.spinner className="mr-1.5 h-4 w-4 animate-spin" />}
Save Changes
</Button>
</div>
</CardHeader>
</Card>
{/* Form Body */}
<Form form={form} layout="vertical" scrollToFirstError size='small'>
{/* Section A: General Information */}
<Card className="mb-6">
<CardHeader className="pb-4">
<CardTitle className="text-base font-semibold">
General Information
</CardTitle>
<CardDescription>
Enter role name, description, and admin panel privileges
</CardDescription>
</CardHeader>
<CardContent>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 gap-y-0">
<Form.Item
name="name"
label="Role Name"
rules={[{ required: true, message: 'Role name is required!' }]}
>
<Input className="input font-medium" placeholder="e.g. Team Leader or Administrator" />
</Form.Item>
<div className="p-3.5 rounded-lg -mt-5!">
<div className='mb-2'>
<span className="text-sm font-semibold text-zinc-900 dark:text-zinc-100 block">
Allow Admin Panel
</span>
<span className="text-xs text-muted-foreground block mt-0.5">
Grants this role access to administration and admin panel menus
</span>
</div>
<Form.Item name="allow_admin_panel" valuePropName="checked">
<Switch
size='medium'
checked={allowAdminPanel}
onChange={handleAdminToggle}
style={{
backgroundColor: allowAdminPanel ? '#EA512C' : undefined,
}}
className="[&.ant-switch-checked]:bg-his! [&.ant-switch-checked:hover]:bg-his/90!"
/>
</Form.Item>
</div>
</div>
<Form.Item name="description" label="Description" className="mt-2 mb-0">
<Input.TextArea size='large'
className="input"
rows={2}
placeholder="Describe role responsibilities and permission scope..."
/>
</Form.Item>
</CardContent>
</Card>
{/* Section B: Menu Permissions */}
<Card>
<CardHeader className="pb-4">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
<div>
<CardTitle className="text-base font-semibold">
Menu Permissions & Access Rights
</CardTitle>
<CardDescription className="mt-1">
Configure access permissions for each menu available in the application
</CardDescription>
</div>
<div className="text-xs text-muted-foreground bg-zinc-100 dark:bg-zinc-800 px-2.5 py-1 rounded self-start sm:self-auto font-mono">
{Object.keys(selectedPermissions).length} menus configured
</div>
</div>
</CardHeader>
<CardContent>
{menuLoading ? (
<div className="py-12 flex flex-col items-center justify-center text-muted-foreground">
<Icons.spinner className="h-6 w-6 animate-spin mb-3 text-his" />
<span className="text-sm">Loading menu structure from server...</span>
</div>
) : (
<MenuPermissionTree
menus={menus}
allowAdminPanel={allowAdminPanel}
selectedPermissions={selectedPermissions}
onPermissionToggle={handlePermissionToggle}
onMenuSelectAll={handleMenuSelectAll}
onMenuClearAll={handleMenuClearAll}
/>
)}
</CardContent>
</Card>
{/* Bottom Action Bar */}
<div className="mt-6 flex justify-end items-center gap-3">
<Link href="/admin/rbac/user-role">
<Button variant="outline" type="button" disabled={isLoading} className='text-zinc-800! dark:text-white'>
Cancel
</Button>
</Link>
<Button
type="button"
className="bg-his hover:bg-his/90 text-white font-medium px-6"
onClick={() => setShowConfirm(true)}
disabled={isLoading || menuLoading}
>
{isLoading && <Icons.spinner className="mr-1.5 h-4 w-4 animate-spin" />}
Save Changes
</Button>
</div>
</Form>
</div>
{/* Confirmation Dialog */}
{showConfirm && (
<AlertDialog open={true}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Save Role Configuration?</AlertDialogTitle>
<AlertDialogDescription>
These permission settings will be saved and immediately applied to users assigned to this role.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isLoading} onClick={() => setShowConfirm(false)}>
Cancel
</AlertDialogCancel>
<AlertDialogAction
disabled={isLoading}
className="bg-his hover:bg-his/90 text-white"
onClick={() => {
setShowConfirm(false);
handleSubmit();
}}
>
{isLoading && <Icons.spinner className="mr-1.5 h-4 w-4 animate-spin" />}
Save Changes
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)}
</>
);
};
export default RoleForm;