From b149903b2e0f30ff64e3007f6f43778e7729b296 Mon Sep 17 00:00:00 2001 From: Ichsan Kurniawan <43689091+ichsankurnia@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:59:25 +0700 Subject: [PATCH] Add hierarchical role permission controls Make parent menus gate child permissions and cascade select or clear actions through descendants. Update role detail rendering for nested menus and the revised API shape, with related RBAC UI and sidebar adjustments. --- .../action-permissions/component/index.tsx | 2 +- app/admin/rbac/menu/component/index.tsx | 6 +- app/admin/rbac/user-role/[id]/page.tsx | 101 +++++++++++----- .../component/MenuPermissionTree.tsx | 108 +++++++++++++++++- .../rbac/user-role/component/RoleForm.tsx | 82 +++++++++---- app/admin/rbac/user-role/component/index.tsx | 8 +- .../component/role-permission-row.tsx | 76 ++++++++---- lib/data-sidebar.tsx | 5 - lib/tabler-icons.ts | 2 + types/rbac.ts | 12 +- 10 files changed, 304 insertions(+), 98 deletions(-) diff --git a/app/admin/rbac/action-permissions/component/index.tsx b/app/admin/rbac/action-permissions/component/index.tsx index 85d1a50..c187937 100644 --- a/app/admin/rbac/action-permissions/component/index.tsx +++ b/app/admin/rbac/action-permissions/component/index.tsx @@ -155,7 +155,7 @@ const ComponentPermissionPage: FC = ({ data }) => {
diff --git a/app/admin/rbac/menu/component/index.tsx b/app/admin/rbac/menu/component/index.tsx index 70436f0..0d4b4b7 100644 --- a/app/admin/rbac/menu/component/index.tsx +++ b/app/admin/rbac/menu/component/index.tsx @@ -174,7 +174,7 @@ const ComponentMenuPage: FC = ({ data }) => { }, }, { - title: 'Permissions', + title: 'Permissions List', dataIndex: 'action', key: 'action', render: (actions?: string[]) => { @@ -182,7 +182,7 @@ const ComponentMenuPage: FC = ({ data }) => { return No permissions assigned; } return ( -
+
{actions.map((act) => ( ))} @@ -262,7 +262,7 @@ const ComponentMenuPage: FC = ({ data }) => {
diff --git a/app/admin/rbac/user-role/[id]/page.tsx b/app/admin/rbac/user-role/[id]/page.tsx index 0e53128..f55d994 100644 --- a/app/admin/rbac/user-role/[id]/page.tsx +++ b/app/admin/rbac/user-role/[id]/page.tsx @@ -4,8 +4,9 @@ import Link from 'next/link'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import fetchData from '@/lib/fetchData'; import { Button } from '@/components/ui/button'; -import { type IRole, type IRoleDetail } from '../component/type'; +import { type IRole } from '../component/type'; import RolePermissionRow from "../component/role-permission-row"; +import { PencilLine } from 'lucide-react'; export const dynamic = 'force-dynamic'; @@ -41,18 +42,54 @@ const UserRoleDetailPage: FC = async ({ params }) => { const { id } = await params; const data: IRole | undefined = await getRoleData(id); - const isAdminAllowed = Boolean(data?.allow_admin_panel ?? data?.allow_admin); - const roleDetails: IRoleDetail[] = Array.isArray(data?.role_detail) - ? data.role_detail - : Array.isArray(data?.privilege) - ? data.privilege.map((p: any) => ({ - menu_id: p.menu_id || p.id, - menu_name: p.menu_name || p.name, - menu_path: p.menu_path || p.path || '#', - is_admin_menu: Boolean(p.is_admin_menu ?? p.is_menu_admin), - action: Array.isArray(p.action) ? p.action : [], - })) - : []; + const isAdminAllowed = Boolean(data?.allow_admin_panel); + const rawList = Array.isArray(data?.role_detail) ? data.role_detail : []; + + const normalizedDetails = rawList.map((item: any) => { + const menuObj = item.menu || {}; + return { + pemrission_id: item.id, + id: menuObj.id, + name: menuObj.name ?? '', + path_url: menuObj.path_url ?? '#', + icon: menuObj.icon ?? '', + is_admin_menu: Boolean(menuObj.is_admin_menu), + menu_parent_id: menuObj.menu_parent_id ?? null, + action: Array.isArray(item.action) ? item.action : [], + }; + }); + + // Build hierarchy map so parent-child relationships are preserved with indentation + const detailMap = new Map(); + normalizedDetails.forEach(d => { if (d.id !== undefined) detailMap.set(d.id, d); }); + + const getLevel = (item: any): number => { + if (!item.menu_parent_id || !detailMap.has(item.menu_parent_id)) return 0; + return getLevel(detailMap.get(item.menu_parent_id)) + 1; + }; + + // Arrange items hierarchically: root menus first, followed immediately by their children + function sortHierarchical(items: any[]): any[] { + const roots = items.filter(i => !i.menu_parent_id || !detailMap.has(i.menu_parent_id)); + const result: any[] = []; + + function appendNode(node: any) { + result.push({ ...node, level: getLevel(node) }); + const children = items.filter(c => c.menu_parent_id === node.id); + children.forEach(appendNode); + } + + roots.forEach(appendNode); + items.forEach(item => { + if (!result.some(r => r.id === item.id)) { + result.push({ ...item, level: getLevel(item) }); + } + }); + + return result; + } + + const orderedDetails = sortHierarchical(normalizedDetails); return (
@@ -74,14 +111,14 @@ const UserRoleDetailPage: FC = async ({ params }) => {
-
+
- + Role Code @@ -89,22 +126,22 @@ const UserRoleDetailPage: FC = async ({ params }) => {
- + Role Name - + {data?.name || '-'}
- + Admin Panel Access
{isAdminAllowed ? ( - Web CMS & Admin Panel + Admin Panel ) : ( @@ -115,18 +152,18 @@ const UserRoleDetailPage: FC = async ({ params }) => {
- + Status
- {data?.status?.name || 'Active'} + {data?.status?.name}
- + Description @@ -144,23 +181,25 @@ const UserRoleDetailPage: FC = async ({ params }) => {
- Authorized Menu Permissions ({roleDetails.length} Menus Allowed) + Authorized Menu Permissions ({orderedDetails.length} Menus Allowed)
- {roleDetails.length > 0 ? ( + {orderedDetails.length > 0 ? (
- {roleDetails.map((detail, idx) => ( + {orderedDetails.map((detail, idx) => ( c.menu_parent_id === detail.id), action: detail.action, }} mode="readonly" diff --git a/app/admin/rbac/user-role/component/MenuPermissionTree.tsx b/app/admin/rbac/user-role/component/MenuPermissionTree.tsx index 82cf9f8..855a7bb 100644 --- a/app/admin/rbac/user-role/component/MenuPermissionTree.tsx +++ b/app/admin/rbac/user-role/component/MenuPermissionTree.tsx @@ -14,6 +14,8 @@ export interface IMenuPermissionTreeProps { onPermissionToggle: (menuId: number, actionName: string, checked: boolean) => void; onMenuSelectAll: (menuId: number, allActions: string[]) => void; onMenuClearAll: (menuId: number) => void; + onBatchSelectAll?: (updates: Record) => void; + onBatchClearAll?: (menuIds: number[]) => void; } interface TreeNode extends IMenu { @@ -52,6 +54,8 @@ export const MenuPermissionTree: FC = ({ onPermissionToggle, onMenuSelectAll, onMenuClearAll, + onBatchSelectAll, + onBatchClearAll, }) => { const [searchQuery, setSearchQuery] = useState(''); const [collapsedIds, setCollapsedIds] = useState>(new Set()); @@ -68,6 +72,41 @@ export const MenuPermissionTree: FC = ({ }); }; + // Group all menus by ID for quick ancestor & descendant traversal + const menuMap = useMemo(() => { + const map = new Map(); + menus.forEach(m => { + if (m.id !== undefined) map.set(m.id, m); + }); + return map; + }, [menus]); + + // Helper: get all descendants recursively for a menu ID + const getDescendants = (menuId: number): IMenu[] => { + const list: IMenu[] = []; + const directChildren = menus.filter(m => m.menu_parent_id === menuId && m.id !== undefined); + directChildren.forEach(child => { + list.push(child); + list.push(...getDescendants(child.id!)); + }); + return list; + }; + + // Helper: is a menu considered "checked" (has at least 1 action or is explicitly marked) + const isMenuChecked = (menuId: number): boolean => { + const acts = selectedPermissions[menuId]; + return Boolean(acts && acts.length > 0); + }; + + // Helper: check if a menu is enabled (all ancestors must be checked) + const isMenuEnabled = (node: TreeNode | IMenu): boolean => { + if (!node.menu_parent_id) return true; // Root menu is always enabled + const parent = menuMap.get(node.menu_parent_id); + if (!parent || parent.id === undefined) return true; + // Parent must be checked AND parent must be enabled + return isMenuChecked(parent.id) && isMenuEnabled(parent); + }; + // Separate Non-Admin and Admin menus const { nonAdminTree, adminTree } = useMemo(() => { const nonAdminList = menus.filter(m => !(m.is_admin_menu)); @@ -105,6 +144,66 @@ export const MenuPermissionTree: FC = ({ return matches; }, [menus, searchQuery]); + // Helper: compute aggregate isAllChecked and isIndeterminate for a node (including its descendants) + const computeNodeSelectionState = (node: TreeNode) => { + const descendants = getDescendants(node.id!); + const allNodes = [node, ...descendants]; + + let totalActionsCount = 0; + let selectedActionsCount = 0; + let hasAnyActionSelected = false; + + allNodes.forEach(m => { + const valid = m.action && m.action.length > 0 ? m.action : ['__CHECKED__']; + totalActionsCount += valid.length; + const cur = selectedPermissions[m.id!] || []; + const matching = cur.filter(a => valid.includes(a)); + selectedActionsCount += matching.length; + if (matching.length > 0) hasAnyActionSelected = true; + }); + + const isAllChecked = totalActionsCount > 0 && selectedActionsCount === totalActionsCount; + const isIndeterminate = hasAnyActionSelected && !isAllChecked; + + return { isAllChecked, isIndeterminate }; + }; + + // When selecting a node: select all actions of the node AND all of its descendants + const handleNodeSelectAll = (node: TreeNode) => { + const descendants = getDescendants(node.id!); + const allNodes = [node, ...descendants]; + const updates: Record = {}; + + allNodes.forEach(m => { + if (m.id !== undefined) { + const actions = m.action && m.action.length > 0 ? [...m.action] : ['__CHECKED__']; + updates[m.id] = actions; + } + }); + + if (onBatchSelectAll) { + onBatchSelectAll(updates); + } else { + Object.entries(updates).forEach(([idStr, acts]) => { + onMenuSelectAll(Number(idStr), acts); + }); + } + }; + + // When clearing a node: clear the node AND all of its descendants + const handleNodeClearAll = (node: TreeNode) => { + const descendants = getDescendants(node.id!); + const allIds = [node.id!, ...descendants.map(d => d.id!).filter(Boolean) as number[]]; + + if (onBatchClearAll) { + onBatchClearAll(allIds); + } else { + allIds.forEach(id => { + onMenuClearAll(id); + }); + } + }; + // Renders a single menu row and recursively its children using unified RolePermissionRow const renderNode = (node: TreeNode) => { if (node.id === undefined) return null; @@ -116,6 +215,8 @@ export const MenuPermissionTree: FC = ({ const hasChildren = Boolean(node.children && node.children.length > 0); const assignedActions = node.action || []; const currentSelectedActions = selectedPermissions[node.id] || []; + const isEnabled = isMenuEnabled(node); + const { isAllChecked, isIndeterminate } = computeNodeSelectionState(node); return ( @@ -132,13 +233,16 @@ export const MenuPermissionTree: FC = ({ action: assignedActions, }} mode="interactive" + disabled={!isEnabled} + isAllChecked={isAllChecked} + isIndeterminate={isIndeterminate} selectedActions={currentSelectedActions} onToggleCollapse={() => toggleCollapse(node.id!)} onPermissionToggle={(actionName, checked) => onPermissionToggle(node.id!, actionName, checked) } - onSelectAll={() => onMenuSelectAll(node.id!, assignedActions)} - onClearAll={() => onMenuClearAll(node.id!)} + onSelectAll={() => handleNodeSelectAll(node)} + onClearAll={() => handleNodeClearAll(node)} /> {/* Render children recursively if not collapsed */} diff --git a/app/admin/rbac/user-role/component/RoleForm.tsx b/app/admin/rbac/user-role/component/RoleForm.tsx index 8720375..c6a20a5 100644 --- a/app/admin/rbac/user-role/component/RoleForm.tsx +++ b/app/admin/rbac/user-role/component/RoleForm.tsx @@ -29,6 +29,17 @@ type Props = { 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); @@ -55,7 +66,7 @@ export const RoleForm: FC = ({ isUpdate, roleId, initialData }) => { useEffect(() => { if (initialData) { const isAdminAllowed = Boolean( - initialData.allow_admin_panel ?? initialData.allow_admin ?? false + initialData.allow_admin_panel ?? false ); setAllowAdminPanel(isAdminAllowed); @@ -68,22 +79,20 @@ export const RoleForm: FC = ({ isUpdate, roleId, initialData }) => { // 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) { - 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) - ); - } - }); - } + const rawDetails = Array.isArray(initialData.role_detail) + ? initialData.role_detail + : Array.isArray(initialData.privilege) + ? initialData.privilege + : []; + + 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 { @@ -132,16 +141,20 @@ export const RoleForm: FC = ({ isUpdate, roleId, initialData }) => { nextActions = currentActions.filter((a) => a !== actionName); } + const next = { ...prev }; + if (nextActions.length === 0) { - const copy = { ...prev }; - delete copy[menuId]; - return copy; + 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 { - ...prev, - [menuId]: nextActions, - }; + return next; }); }; @@ -162,6 +175,25 @@ export const RoleForm: FC = ({ isUpdate, roleId, initialData }) => { }); }; + // 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 { @@ -379,6 +411,8 @@ export const RoleForm: FC = ({ isUpdate, roleId, initialData }) => { onPermissionToggle={handlePermissionToggle} onMenuSelectAll={handleMenuSelectAll} onMenuClearAll={handleMenuClearAll} + onBatchSelectAll={handleBatchSelectAll} + onBatchClearAll={handleBatchClearAll} /> )} diff --git a/app/admin/rbac/user-role/component/index.tsx b/app/admin/rbac/user-role/component/index.tsx index fdb9629..8a61f2f 100644 --- a/app/admin/rbac/user-role/component/index.tsx +++ b/app/admin/rbac/user-role/component/index.tsx @@ -96,7 +96,7 @@ const ComponentRolePage: FC = ({ data }) => { align: 'center', width: 160, render: (_val, record: IRole) => { - const isAllowed = Boolean(record.allow_admin_panel ?? record.allow_admin); + const isAllowed = Boolean(record.allow_admin_panel); return isAllowed ? ( @@ -119,8 +119,8 @@ const ComponentRolePage: FC = ({ data }) => { const count = Array.isArray(details) ? details.length : Array.isArray(record.privilege) - ? record.privilege.length - : 0; + ? record.privilege.length + : 0; return ( {count} menus @@ -201,7 +201,7 @@ const ComponentRolePage: FC = ({ data }) => {
diff --git a/app/admin/rbac/user-role/component/role-permission-row.tsx b/app/admin/rbac/user-role/component/role-permission-row.tsx index 84a5fb1..37bf880 100644 --- a/app/admin/rbac/user-role/component/role-permission-row.tsx +++ b/app/admin/rbac/user-role/component/role-permission-row.tsx @@ -24,6 +24,9 @@ export interface IRolePermissionRowProps { mode?: 'interactive' | 'readonly'; selectedActions?: string[]; index?: number; + disabled?: boolean; + isAllChecked?: boolean; + isIndeterminate?: boolean; onToggleCollapse?: () => void; onPermissionToggle?: (actionName: string, checked: boolean) => void; onSelectAll?: () => void; @@ -35,6 +38,9 @@ export const RolePermissionRow: FC = ({ mode = 'interactive', selectedActions = [], index, + disabled = false, + isAllChecked: isAllCheckedProp, + isIndeterminate: isIndeterminateProp, onToggleCollapse, onPermissionToggle, onSelectAll, @@ -44,9 +50,12 @@ export const RolePermissionRow: FC = ({ const assignedActions = node.action || []; const currentSelected = selectedActions; - const isAllSelected = assignedActions.length > 0 && assignedActions.every(a => currentSelected.includes(a)); + const isNodeAllSelected = assignedActions.length > 0 && assignedActions.every(a => currentSelected.includes(a)); const hasAnySelected = currentSelected.length > 0; - const isIndeterminate = hasAnySelected && !isAllSelected; + const isNodeIndeterminate = hasAnySelected && !isNodeAllSelected; + + const effectiveAllSelected = isAllCheckedProp !== undefined ? isAllCheckedProp : isNodeAllSelected; + const effectiveIndeterminate = isIndeterminateProp !== undefined ? isIndeterminateProp : isNodeIndeterminate; const indentPx = node.level * 22; const actionsIndentPx = indentPx + (isInteractive ? 40 : 28); @@ -57,7 +66,8 @@ export const RolePermissionRow: FC = ({ 'flex flex-col py-3 px-3 sm:px-4 border-b border-zinc-200/80 dark:border-zinc-800/80 transition-colors', node.level === 0 ? 'bg-zinc-50/70 dark:bg-zinc-900/50' - : 'bg-white dark:bg-zinc-950/40 hover:bg-zinc-50/40 dark:hover:bg-zinc-900/20' + : 'bg-white dark:bg-zinc-950/40 hover:bg-zinc-50/40 dark:hover:bg-zinc-900/20', + disabled && 'opacity-60 bg-zinc-50/40 dark:bg-zinc-950/20' )} > {/* Top row: Hierarchy, Menu Identifier & Row Actions */} @@ -89,11 +99,13 @@ export const RolePermissionRow: FC = ({ {/* Checkbox (interactive) or Row Index (readonly) */} {isInteractive ? ( - assignedActions.length > 0 && ( + (assignedActions.length > 0 || node.hasChildren) && ( { + if (disabled) return; if (e.target.checked) { onSelectAll?.(); } else { @@ -103,13 +115,14 @@ export const RolePermissionRow: FC = ({ className="shrink-0" /> ) - ) : ( - index !== undefined && ( - - {index + 1} - - ) - )} + ) : + // index !== undefined && ( + // + // {index + 1} + // + // ) + null + } {/* Icon, Title, Path & Admin Badge */}
@@ -123,13 +136,16 @@ export const RolePermissionRow: FC = ({ )} - + {node.name} {node.path_url && ( - {node.path_url} + `{node.path_url}` )} @@ -138,13 +154,19 @@ export const RolePermissionRow: FC = ({ Admin )} + + {disabled && ( + + (Enable parent first) + + )}
{/* Right: Summary Count & Row Select/Clear Action */}
{isInteractive ? ( - assignedActions.length > 0 && ( + (assignedActions.length > 0 || node.hasChildren) && ( <> {currentSelected.length} / {assignedActions.length} selected @@ -153,16 +175,18 @@ export const RolePermissionRow: FC = ({ type="button" variant="outline" size="sm" + disabled={disabled} className="h-7 text-xs px-2.5 font-medium" onClick={() => { - if (isAllSelected) { + if (disabled) return; + if (effectiveAllSelected) { onClearAll?.(); } else { onSelectAll?.(); } }} > - {isAllSelected ? 'Clear All' : 'Select All'} + {effectiveAllSelected ? 'Clear All' : 'Select All'} ) @@ -189,15 +213,21 @@ export const RolePermissionRow: FC = ({ diff --git a/lib/data-sidebar.tsx b/lib/data-sidebar.tsx index 6358d3b..afc9d61 100644 --- a/lib/data-sidebar.tsx +++ b/lib/data-sidebar.tsx @@ -68,11 +68,6 @@ const SIDEBAR_MENU = [ Icon: , path: '/global-parameter' }, - { - title: "Menu", - Icon: , - path: '/menu' - }, { title: "Day Off", Icon: , diff --git a/lib/tabler-icons.ts b/lib/tabler-icons.ts index 4037a74..4e9856e 100644 --- a/lib/tabler-icons.ts +++ b/lib/tabler-icons.ts @@ -49,6 +49,7 @@ export const TABLER_ICON_OPTIONS: ITablerIconOption[] = [ { label: 'Briefcase', value: 'ti ti-briefcase', category: 'Operations' }, { label: 'Calendar Event', value: 'ti ti-calendar-event', category: 'Operations' }, { label: 'Calendar Time', value: 'ti ti-calendar-time', category: 'Operations' }, + { label: 'Calendar Off', value: 'ti ti-calendar-x', category: 'Operations' }, { label: 'Clock', value: 'ti ti-clock', category: 'Operations' }, { label: 'Checklist', value: 'ti ti-checklist', category: 'Operations' }, @@ -68,5 +69,6 @@ export const TABLER_ICON_OPTIONS: ITablerIconOption[] = [ { label: 'Face id', value: 'ti ti-face-id', category: 'Security' }, { label: 'Fingerprint', value: 'ti ti-fingerprint', category: 'Security' }, { label: 'Bell', value: 'ti ti-bell', category: 'General' }, + { label: 'Information Circle', value: 'ti ti-info-circle', category: 'General' }, ]; diff --git a/types/rbac.ts b/types/rbac.ts index 72df0bb..08d332e 100644 --- a/types/rbac.ts +++ b/types/rbac.ts @@ -31,10 +31,13 @@ export interface IMenu { } export interface IRoleDetail { - menu_id: number; - menu_name: string; - menu_path: string; - is_admin_menu: boolean; + id?: number; + role_id?: number; + menu_id?: number; + menu_name?: string; + menu_path?: string; + is_admin_menu?: boolean; + menu?: IMenu; action: string[]; } @@ -44,7 +47,6 @@ export interface IRole { name: string; description?: string; allow_admin_panel?: boolean; - allow_admin?: boolean; role_detail?: IRoleDetail[]; privilege?: any[]; status?: {