mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-05 10:46:29 +00:00
Add RBAC menu and role management
Adds permission, menu, and role administration with hierarchical access controls, plus admin breadcrumbs and a redirect from the legacy user-role page. Remove `credentials.md` before committing; it contains server credentials.
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
---
|
||||
name: karpathy-guidelines
|
||||
description: Behavioral guidelines to reduce common LLM coding mistakes. Use when writing, reviewing, or refactoring code to avoid overcomplication, make surgical changes, surface assumptions, and define verifiable success criteria.
|
||||
license: MIT
|
||||
---
|
||||
|
||||
# Karpathy Guidelines
|
||||
|
||||
Behavioral guidelines to reduce common LLM coding mistakes, derived from [Andrej Karpathy's observations](https://x.com/karpathy/status/2015883857489522876) on LLM coding pitfalls.
|
||||
|
||||
**Tradeoff:** These guidelines bias toward caution over speed. For trivial tasks, use judgment.
|
||||
|
||||
## 1. Think Before Coding
|
||||
|
||||
**Don't assume. Don't hide confusion. Surface tradeoffs.**
|
||||
|
||||
Before implementing:
|
||||
- State your assumptions explicitly. If uncertain, ask.
|
||||
- If multiple interpretations exist, present them - don't pick silently.
|
||||
- If a simpler approach exists, say so. Push back when warranted.
|
||||
- If something is unclear, stop. Name what's confusing. Ask.
|
||||
|
||||
## 2. Simplicity First
|
||||
|
||||
**Minimum code that solves the problem. Nothing speculative.**
|
||||
|
||||
- No features beyond what was asked.
|
||||
- No abstractions for single-use code.
|
||||
- No "flexibility" or "configurability" that wasn't requested.
|
||||
- No error handling for impossible scenarios.
|
||||
- If you write 200 lines and it could be 50, rewrite it.
|
||||
|
||||
Ask yourself: "Would a senior engineer say this is overcomplicated?" If yes, simplify.
|
||||
|
||||
## 3. Surgical Changes
|
||||
|
||||
**Touch only what you must. Clean up only your own mess.**
|
||||
|
||||
When editing existing code:
|
||||
- Don't "improve" adjacent code, comments, or formatting.
|
||||
- Don't refactor things that aren't broken.
|
||||
- Match existing style, even if you'd do it differently.
|
||||
- If you notice unrelated dead code, mention it - don't delete it.
|
||||
|
||||
When your changes create orphans:
|
||||
- Remove imports/variables/functions that YOUR changes made unused.
|
||||
- Don't remove pre-existing dead code unless asked.
|
||||
|
||||
The test: Every changed line should trace directly to the user's request.
|
||||
|
||||
## 4. Goal-Driven Execution
|
||||
|
||||
**Define success criteria. Loop until verified.**
|
||||
|
||||
Transform tasks into verifiable goals:
|
||||
- "Add validation" → "Write tests for invalid inputs, then make them pass"
|
||||
- "Fix the bug" → "Write a test that reproduces it, then make it pass"
|
||||
- "Refactor X" → "Ensure tests pass before and after"
|
||||
|
||||
For multi-step tasks, state a brief plan:
|
||||
```
|
||||
1. [Step] → verify: [check]
|
||||
2. [Step] → verify: [check]
|
||||
3. [Step] → verify: [check]
|
||||
```
|
||||
|
||||
Strong success criteria let you loop independently. Weak criteria ("make it work") require constant clarification.
|
||||
@@ -0,0 +1,58 @@
|
||||
'use client';
|
||||
|
||||
import { usePathname } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
|
||||
export default function AdminBreadcrumb() {
|
||||
const pathname = usePathname();
|
||||
|
||||
const segments = (pathname || '')
|
||||
.split('/')
|
||||
.filter(Boolean)
|
||||
.slice(1); // skip 'admin'
|
||||
|
||||
const formatSegment = (seg: string) => {
|
||||
return seg
|
||||
.split('-')
|
||||
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
|
||||
.join(' ');
|
||||
};
|
||||
|
||||
if (segments.length === 0) {
|
||||
return (
|
||||
<div className="flex items-center text-xs font-medium text-muted-foreground">
|
||||
<span>Pages</span>
|
||||
<span className="mx-1.5 text-zinc-400">/</span>
|
||||
<span className="text-zinc-900 dark:text-zinc-100 font-semibold">Dashboard</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center text-xs font-medium text-muted-foreground flex-wrap">
|
||||
<Link href="/admin" className="hover:text-zinc-900 dark:hover:text-zinc-100 transition-colors">
|
||||
Pages
|
||||
</Link>
|
||||
{segments.map((seg, idx) => {
|
||||
const isLast = idx === segments.length - 1;
|
||||
const href = '/admin/' + segments.slice(0, idx + 1).join('/');
|
||||
|
||||
return (
|
||||
<span key={href} className="inline-flex items-center">
|
||||
<span className="mx-1.5 text-zinc-400">/</span>
|
||||
{isLast ? (
|
||||
<span className="text-zinc-900 dark:text-zinc-100 font-semibold">
|
||||
{formatSegment(seg)}
|
||||
</span>
|
||||
) : (
|
||||
<Link href={href} className="hover:text-zinc-900 dark:hover:text-zinc-100 transition-colors">
|
||||
{formatSegment(seg)}
|
||||
</Link>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -41,7 +41,13 @@ const SidebarItem: FC<Props> = ({ menu, expand, onChangeExpand }) => {
|
||||
}
|
||||
|
||||
const getActiveBackgroundMenu = () => {
|
||||
if (pathanme === '/admin' + menu.path) {
|
||||
const currentPath = pathanme || '';
|
||||
const fullPath = '/admin' + (menu.path || '');
|
||||
const isActive = menu.path === ''
|
||||
? currentPath === '/admin' || currentPath === '/admin/'
|
||||
: currentPath === fullPath || (menu.path && currentPath.startsWith(fullPath + '/'));
|
||||
|
||||
if (isActive) {
|
||||
return {
|
||||
color: theme === 'dark' ? '#fff' : theme === 'system' && systemTheme === 'dark' ? '#fff' : '#fff',
|
||||
fontWeight: theme === 'light' ? 600 : theme === 'system' && systemTheme === 'light' ? 600 : undefined,
|
||||
@@ -77,7 +83,6 @@ const SidebarItem: FC<Props> = ({ menu, expand, onChangeExpand }) => {
|
||||
|
||||
{submenuItems && submenuItems.length > 0 && submenuIdActive?.includes(submenuId) && expand &&
|
||||
<motion.ul
|
||||
// className='ml-4'
|
||||
animate={
|
||||
submenuIdActive?.includes(submenuId) ?
|
||||
{
|
||||
|
||||
@@ -1,386 +1 @@
|
||||
import { useRouter } from "next/navigation"
|
||||
import { FC, useEffect, useState } from "react"
|
||||
import { Checkbox, Form, Input, Radio } from "antd"
|
||||
import useAxiosAuth from "@/lib/axios/useAxiosAuth"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Icons } from "@/components/Icons"
|
||||
import { IMenuAction } from "@/app/admin/menu/component/type"
|
||||
import { DUMMY_MENU_LIST, LIST_ACTION_DATA } from "@/lib/data"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { type IRole } from "./type"
|
||||
import { toast } from "sonner"
|
||||
|
||||
type Props = {
|
||||
isUpdate?: boolean
|
||||
data?: IRole
|
||||
onCancel?: () => any
|
||||
}
|
||||
|
||||
function createMenuTree(data: IMenuAction[], parentId: Number | null | undefined = null) {
|
||||
const result = [];
|
||||
|
||||
// Filter items with the specified parentId
|
||||
const filteredItems = data.filter(item => item.menu_parent_id === parentId);
|
||||
|
||||
// Iterate over the filtered items
|
||||
for (const item of filteredItems) {
|
||||
// Recursively call createMenuTree to build the children for the current item
|
||||
const children = createMenuTree(data, item.id);
|
||||
|
||||
// Add the children array to the current item if there are children
|
||||
if (children.length > 0) {
|
||||
item.children = children;
|
||||
}
|
||||
|
||||
// Add the current item to the result array
|
||||
result.push(item);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
function assignMenuLevel(menuList: IMenuAction[], existMenu: IMenuAction[], level: number = 1) {
|
||||
for (const menu of menuList) {
|
||||
if (menu.children && menu.children.length > 0) {
|
||||
existMenu.push({ ...menu, menu_level: level, action: [] })
|
||||
assignMenuLevel(menu.children, existMenu, level + 1);
|
||||
} else {
|
||||
existMenu.push({ ...menu, menu_level: level, action: [] })
|
||||
}
|
||||
}
|
||||
|
||||
return existMenu;
|
||||
}
|
||||
|
||||
|
||||
export default function ComponentForm({ data, isUpdate, onCancel }: Props) {
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [allowAdmin, setAllowAdmin] = useState(false)
|
||||
const [privilegeMenus, setPrivilegeMenus] = useState<IMenuAction[]>([])
|
||||
|
||||
const [form] = Form.useForm();
|
||||
const router = useRouter()
|
||||
const axios = useAxiosAuth()
|
||||
// const { data: menuList } = useFetch('/menu')
|
||||
|
||||
useEffect(() => {
|
||||
if (DUMMY_MENU_LIST && DUMMY_MENU_LIST.length > 0) {
|
||||
// CREATE MENU TREE
|
||||
const nestedMenuData = createMenuTree(DUMMY_MENU_LIST as IMenuAction[]);
|
||||
// console.log(nestedMenuData)
|
||||
|
||||
// DESTRUCTURING MENU TREE INTO ONE LIST
|
||||
const result: IMenuAction[] = []
|
||||
const resultData = assignMenuLevel(nestedMenuData, result);
|
||||
|
||||
// REMOVE "children object"
|
||||
const arrayMenu = resultData.map(({ children, ...rest }) => rest);
|
||||
|
||||
if (data && data.privilege) {
|
||||
const existData = [...arrayMenu].map((item) => {
|
||||
// FIND ACTION FROM EXISTING DATA AND SET IT
|
||||
const findIdxAction = data.privilege.findIndex((menu: any) => menu.menu_id === item.id)
|
||||
if (findIdxAction > -1) {
|
||||
item.action = data.privilege[findIdxAction].action
|
||||
}
|
||||
return item
|
||||
})
|
||||
setPrivilegeMenus(existData)
|
||||
} else {
|
||||
setPrivilegeMenus(arrayMenu)
|
||||
}
|
||||
}
|
||||
}, [DUMMY_MENU_LIST, data])
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
if (data.allow_admin) setAllowAdmin(data.allow_admin)
|
||||
form.setFieldsValue(data)
|
||||
} else {
|
||||
form.resetFields()
|
||||
}
|
||||
}, [data, form])
|
||||
|
||||
|
||||
const handleSubmit = (value: any) => {
|
||||
!isUpdate ? handleCreate(value) : handleUpdate(value)
|
||||
}
|
||||
|
||||
const handleCreate = async (payload: IRole) => {
|
||||
try {
|
||||
setIsLoading(true)
|
||||
// await axios.post('/dayoff', payload)
|
||||
|
||||
if (allowAdmin) {
|
||||
// ONLY SUBMIT MENU THAT HAVE ACTION
|
||||
const submitedPrivilegeMenus = privilegeMenus.filter(item => item.action?.length! > 0)
|
||||
// REMOVE CHILD MENU DOES"NT HAVE A PARENT
|
||||
const filterChildNotHaveParent = [...submitedPrivilegeMenus].filter((item) => {
|
||||
if (item.menu_level > 1) {
|
||||
const findParent = [...submitedPrivilegeMenus].find(menu => menu.id === item.menu_parent_id)
|
||||
if (findParent) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
} else {
|
||||
return true
|
||||
}
|
||||
}).map(item => {
|
||||
return { menu_id: item.id, menu_name: item.name, action: item.action }
|
||||
})
|
||||
|
||||
payload['privilege'] = filterChildNotHaveParent
|
||||
} else {
|
||||
payload['privilege'] = []
|
||||
}
|
||||
|
||||
localStorage.setItem('role_test', JSON.stringify(payload))
|
||||
|
||||
handleSuccess('Data successfully created.')
|
||||
} catch (error: any) {
|
||||
handleError(`Data failed to create, (${error.response.data.code || error.response.status || '-'}) ${error.response.data.message || error.response.statusText || error.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
const handleUpdate = async (payload: IRole) => {
|
||||
try {
|
||||
setIsLoading(true)
|
||||
// await axios.put('/dayoff/' + data?.id, payload)
|
||||
|
||||
if (allowAdmin) {
|
||||
// ONLY SUBMIT MENU THAT HAVE ACTION
|
||||
const submitedPrivilegeMenus = privilegeMenus.filter(item => item.action?.length! > 0)
|
||||
// REMOVE CHILD MENU DOES"NT HAVE A PARENT
|
||||
const filterChildNotHaveParent = [...submitedPrivilegeMenus].filter((item) => {
|
||||
if (item.menu_level > 1) {
|
||||
const findParent = [...submitedPrivilegeMenus].find(menu => menu.id === item.menu_parent_id)
|
||||
if (findParent) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
} else {
|
||||
return true
|
||||
}
|
||||
}).map(item => {
|
||||
return { menu_id: item.id, menu_name: item.name, action: item.action }
|
||||
})
|
||||
|
||||
payload['privilege'] = filterChildNotHaveParent
|
||||
} else {
|
||||
payload['privilege'] = []
|
||||
}
|
||||
|
||||
localStorage.setItem('role_test', JSON.stringify(payload))
|
||||
|
||||
handleSuccess('Data successfully updated.')
|
||||
} catch (error: any) {
|
||||
handleError(`Data failed to update, (${error.response.data.code || error.response.status || '-'}) ${error.response.data.message || error.response.statusText || error.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
const handleSuccess = (message: string) => {
|
||||
toast.success(message)
|
||||
setIsLoading(false)
|
||||
onCancel!()
|
||||
router.refresh()
|
||||
form.resetFields()
|
||||
}
|
||||
|
||||
const handleError = (message: string) => {
|
||||
toast.error(message)
|
||||
setIsLoading(false)
|
||||
}
|
||||
|
||||
const handleCheckAllAction = (action: typeof LIST_ACTION_DATA[0], isChecked: boolean) => {
|
||||
console.log({ action, isChecked })
|
||||
const existData = [...privilegeMenus]
|
||||
|
||||
if (isChecked) {
|
||||
existData.map((item) => {
|
||||
item.action?.push(action.id)
|
||||
return item
|
||||
})
|
||||
} else {
|
||||
existData.map((item) => {
|
||||
const index = item.action?.indexOf(action.id);
|
||||
if (index! > -1) {
|
||||
item.action?.splice(index!, 1);
|
||||
}
|
||||
return item
|
||||
})
|
||||
}
|
||||
setPrivilegeMenus(existData)
|
||||
}
|
||||
|
||||
const handleCheckMenu = (menu: IMenuAction, isChecked: boolean) => {
|
||||
console.log({ menu, isChecked })
|
||||
const existData = [...privilegeMenus]
|
||||
|
||||
const findIndex = existData.findIndex(item => item.id === menu.id)
|
||||
if (isChecked) {
|
||||
existData[findIndex].action = LIST_ACTION_DATA.map(item => item.id)
|
||||
} else {
|
||||
existData[findIndex].action = []
|
||||
|
||||
// FIND CHILD AND ALSO REMOVE ACTION IN NESTED CHILD IF EXIST
|
||||
const filterChild = existData.filter(item => item.menu_parent_id === menu.id)
|
||||
if (filterChild.length > 0) {
|
||||
for (const item of filterChild) {
|
||||
handleCheckMenu(item, isChecked)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setPrivilegeMenus(existData)
|
||||
}
|
||||
|
||||
const handleCheckAction = (menu: IMenuAction, action: number[]) => {
|
||||
console.log({ menu, action })
|
||||
const existData = [...privilegeMenus]
|
||||
|
||||
const findIndex = existData.findIndex(item => item.id === menu.id)
|
||||
existData[findIndex].action = action as number[]
|
||||
|
||||
setPrivilegeMenus(existData)
|
||||
}
|
||||
|
||||
const disableCheckAction = (menu: IMenuAction) => {
|
||||
if (menu.menu_level > 1) {
|
||||
const { menu_parent_id } = menu
|
||||
const findParent = privilegeMenus.find(item => item.id === menu_parent_id)
|
||||
if (findParent?.action?.length! <= 0) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
return (
|
||||
<DialogContent className="lg:min-w-[90%] xl:min-w-[80%] 2xl:min-w-[60%] overflow-y-auto max-h-[90vh]">
|
||||
<Form form={form} onFinish={handleSubmit} scrollToFirstError layout='vertical' size="small">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="dark:text-white">{isUpdate ? 'Update role' : 'Create new role'}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Add or update a role and adjust the privilege
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid mt-8">
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||
<Form.Item name='code' label='Code' rules={[{ required: true, message: 'This field is required!' }]} >
|
||||
<Input className="input" placeholder="EXT" />
|
||||
</Form.Item>
|
||||
<Form.Item name='name' label='Role Name' rules={[{ required: true, message: 'This field is required!' }]} >
|
||||
<Input className="input" placeholder="ROLE NAME" />
|
||||
</Form.Item>
|
||||
</div>
|
||||
<Form.Item name='description' label='Description' >
|
||||
<Input.TextArea className="input" placeholder="" />
|
||||
</Form.Item>
|
||||
<Form.Item name='allow_admin' label='Allow Admin Panel' initialValue={false} >
|
||||
<Radio.Group onChange={(e) => setAllowAdmin(e.target.value)}>
|
||||
<Radio value={false}>Dissallow</Radio>
|
||||
<Radio value={true}>Allow</Radio>
|
||||
</Radio.Group>
|
||||
</Form.Item>
|
||||
</div>
|
||||
|
||||
{allowAdmin &&
|
||||
<div className="w-full min-w-[1000px] overflow-x-auto flex flex-col mb-5 mt-2" >
|
||||
<Label className="mb-4">User Privilege</Label>
|
||||
{/* HEADER */}
|
||||
<div className="grid grid-cols-8 bg-zinc-300 dark:bg-zinc-700 py-5">
|
||||
<span className="col-span-2 pl-2">Menu Name</span>
|
||||
{LIST_ACTION_DATA.map((action) =>
|
||||
<div key={action.id}>
|
||||
<Checkbox onChange={e => handleCheckAllAction(action, e.target.checked)}>
|
||||
{action.name}
|
||||
</Checkbox>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* BODY */}
|
||||
{privilegeMenus.length > 0 && privilegeMenus.map((menu: IMenuAction, key: number) =>
|
||||
// <ChildrenItem key={item.id} menu={item} onMenuChecked={handleCheckMenu} onActionChecked={handleCheckAction} />
|
||||
<div className={`grid grid-cols-8 w-full border-b border-border py-3 ${menu.menu_level === 1 ? 'bg-zinc-100 dark:bg-zinc-900' : ''}`} key={key}>
|
||||
<div className='col-span-2 flex items-center pl-2'>
|
||||
<Checkbox className={`${!menu.menu_parent_id ? 'pl-2 bold' : 'pl-8'}`} style={{ paddingLeft: (menu.menu_level - 1) * 20 }}
|
||||
checked={menu.action?.length! > 0} onChange={(e) => handleCheckMenu(menu, e.target.checked)} disabled={disableCheckAction(menu)}
|
||||
>
|
||||
{menu.name}
|
||||
</Checkbox>
|
||||
</div>
|
||||
|
||||
<div className="col-span-6">
|
||||
<Checkbox.Group className="grid" style={{ gridTemplateColumns: `repeat(${LIST_ACTION_DATA.length}, minmax(0, 1fr))` }}
|
||||
value={menu.action} onChange={(val) => handleCheckAction(menu, val)} disabled={disableCheckAction(menu)}
|
||||
>
|
||||
{LIST_ACTION_DATA?.length > 0 && LIST_ACTION_DATA.map((item: any, key: number) =>
|
||||
<div key={key} className='item text-center border-l border-border'>
|
||||
<Checkbox value={item.id} ></Checkbox>
|
||||
</div>
|
||||
)}
|
||||
</Checkbox.Group>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
</div>
|
||||
}
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" type="button" onClick={onCancel} disabled={isLoading} >
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={isLoading}>
|
||||
{isLoading && (
|
||||
<Icons.spinner className="mr-1 h-4 w-4 animate-spin" />
|
||||
)}
|
||||
Save
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
)
|
||||
}
|
||||
|
||||
type ChildrenProps = {
|
||||
menu: IMenuAction
|
||||
className?: string
|
||||
onMenuChecked: (menu: IMenuAction, isChecked: boolean) => any
|
||||
onActionChecked: (menu: IMenuAction, action: typeof LIST_ACTION_DATA[0], isChecked: boolean) => any
|
||||
}
|
||||
|
||||
const ChildrenItem: FC<ChildrenProps> = ({ menu, className, onMenuChecked, onActionChecked }) => {
|
||||
return (
|
||||
<>
|
||||
<div className={`grid grid-cols-8 w-full border-b border-border py-1 ${!menu.menu_parent_id ? 'bg-zinc-100 dark:bg-zinc-900' : ''}`} >
|
||||
<div className={cn('col-span-2 flex items-center', className)}>
|
||||
<Checkbox className={`${!menu.menu_parent_id ? 'pl-2 bold' : 'pl-8'}`} onChange={(e) => onMenuChecked(menu, e.target.checked)}>
|
||||
{menu.name}
|
||||
</Checkbox>
|
||||
</div>
|
||||
|
||||
<Form.Item className="mb-0 mt-0 col-span-6" name={`menu_${menu.id}`}>
|
||||
<Checkbox.Group className="grid" style={{ gridTemplateColumns: `repeat(${LIST_ACTION_DATA.length}, minmax(0, 1fr))` }} onChange={(e) => console.log(e)}>
|
||||
{LIST_ACTION_DATA?.length > 0 && LIST_ACTION_DATA.map((item: any, key: number) =>
|
||||
<div key={key} className='item text-center border-l border-border'>
|
||||
<Checkbox value={item.id} onChange={(e) => onActionChecked(menu, item, e.target.checked)}></Checkbox>
|
||||
</div>
|
||||
)}
|
||||
</Checkbox.Group>
|
||||
</Form.Item>
|
||||
</div>
|
||||
|
||||
{menu.children && menu.children.length > 0 && menu.children.map((item) =>
|
||||
<ChildrenItem className="ml-8" key={item.id} menu={item} onMenuChecked={onMenuChecked} onActionChecked={onActionChecked} />
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
export { default } from '@/app/admin/rbac/user-role/component/RoleForm';
|
||||
|
||||
@@ -1,174 +1 @@
|
||||
'use client'
|
||||
|
||||
import { ChangeEvent, FC, useEffect, useState } from 'react';
|
||||
import { Table } from 'antd';
|
||||
import { TableProps, type ColumnsType } from 'antd/es/table';
|
||||
import { MixerHorizontalIcon, PlusCircledIcon } from '@radix-ui/react-icons';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { type IRole } from './type';
|
||||
import ComponentForm from './Form';
|
||||
import { Dialog } from '@/components/ui/dialog';
|
||||
import { AlertDialog, AlertDialogTrigger } from '@/components/ui/alert-dialog';
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
|
||||
import { MoreHorizontalIcon } from 'lucide-react';
|
||||
import ConfirmAsync from './ConfirmAsync';
|
||||
import useAxiosAuth from '@/lib/axios/useAxiosAuth';
|
||||
|
||||
type Props = {
|
||||
data: IRole[]
|
||||
};
|
||||
|
||||
const ComponentRolePage: FC<Props> = ({ data }) => {
|
||||
const [filterData, setFilterData] = useState<IRole[]>([])
|
||||
const [showFormDialog, setShowFormDialog] = useState(false)
|
||||
const [selectedData, setSelectedData] = useState<IRole | undefined>(undefined)
|
||||
|
||||
const axios = useAxiosAuth()
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
setFilterData(data)
|
||||
}
|
||||
}, [data])
|
||||
|
||||
const handleSearch = (e: ChangeEvent<HTMLInputElement>) => {
|
||||
const text = e.target.value
|
||||
if (text) {
|
||||
const newData = [...data!].filter(item => (
|
||||
item.name?.toLowerCase().includes(text.toLowerCase()) ||
|
||||
item.description?.toLowerCase().includes(text.toLowerCase())
|
||||
))
|
||||
setFilterData(newData)
|
||||
} else {
|
||||
setFilterData(data)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = (id: string | number) => {
|
||||
return axios.delete(`/role/${id}`).then(res => res.data)
|
||||
}
|
||||
|
||||
const Columns: ColumnsType<IRole> = [
|
||||
{
|
||||
title: 'Num',
|
||||
dataIndex: 'key',
|
||||
render: (text, record, index) => index + 1
|
||||
},
|
||||
{
|
||||
title: 'Code',
|
||||
dataIndex: 'code',
|
||||
},
|
||||
{
|
||||
title: 'Role name',
|
||||
dataIndex: 'name',
|
||||
sorter: (a, b) => a.name.localeCompare(b.name)
|
||||
},
|
||||
{
|
||||
title: 'Status',
|
||||
dataIndex: 'status',
|
||||
filters: [
|
||||
{
|
||||
text: 'ACTIVE',
|
||||
value: 'A',
|
||||
},
|
||||
{
|
||||
text: 'INACTIVE',
|
||||
value: 'N',
|
||||
},
|
||||
{
|
||||
text: 'DELETED',
|
||||
value: 'X',
|
||||
},
|
||||
],
|
||||
onFilter: (value, record) => record.status!.code.indexOf(value as string) === 0,
|
||||
align: 'center',
|
||||
render: (text, record) => (
|
||||
<div className='flex justify-center text-white font-semibold text-xs'>
|
||||
{record.status.code === 'A' ?
|
||||
<div className="px-2 py-1.5 rounded-full bg-green-500 w-24">{record.status.name}</div>
|
||||
:
|
||||
<div className="px-2 py-1.5 rounded-full bg-rose-500 w-24">{record.status.name}</div>
|
||||
}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
{
|
||||
title: 'Description',
|
||||
dataIndex: 'description',
|
||||
},
|
||||
{
|
||||
title: 'Action',
|
||||
key: 'action',
|
||||
render: (_, record) => (
|
||||
<AlertDialog>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant='ghost' size="icon">
|
||||
<MoreHorizontalIcon />
|
||||
<span className="sr-only">Action Button</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{/* <DropdownMenuItem onClick={() => { setShowFormDialog(true); setSelectedData(record) }} >Edit</DropdownMenuItem> */}
|
||||
<DropdownMenuItem onClick={() => { setShowFormDialog(true); setSelectedData(JSON.parse(localStorage.getItem('role_test') as string)) }} >Edit</DropdownMenuItem>
|
||||
<AlertDialogTrigger asChild>
|
||||
<DropdownMenuItem>Delete</DropdownMenuItem>
|
||||
</AlertDialogTrigger>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<ConfirmAsync
|
||||
onConfirm={() => handleDelete(record.id)}
|
||||
onOkSuccess={() => { }}
|
||||
/>
|
||||
</AlertDialog>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const tableProps: TableProps<IRole> = {
|
||||
bordered: false,
|
||||
showHeader: true,
|
||||
pagination: {
|
||||
pageSizeOptions: [5, 10, 20, 50],
|
||||
defaultPageSize: 10,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
size: 'middle' as any
|
||||
},
|
||||
scroll: { x: 'max-content' },
|
||||
tableLayout: 'auto',
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className='flex flex-col space-y-4'>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex flex-1 items-center space-x-2">
|
||||
<Input placeholder="Search role..." className="h-8 w-[150px] lg:w-[250px]" onChange={handleSearch} />
|
||||
</div>
|
||||
<Button size="sm" variant='ghost' className="ml-auto h-8 w-full sm:w-max text-his" onClick={() => setShowFormDialog(true)}>
|
||||
<PlusCircledIcon className="mr-2 h-4 w-4" />
|
||||
Create New
|
||||
</Button>
|
||||
</div>
|
||||
<Table
|
||||
{...tableProps}
|
||||
rowKey='id'
|
||||
columns={Columns}
|
||||
dataSource={filterData || []}
|
||||
/>
|
||||
</div>
|
||||
{showFormDialog &&
|
||||
<Dialog open={showFormDialog} onOpenChange={(state) => {
|
||||
if (state === false) setSelectedData(undefined)
|
||||
setShowFormDialog(state)
|
||||
}}>
|
||||
<ComponentForm data={selectedData} onCancel={() => { setSelectedData(undefined); setShowFormDialog(false); }} />
|
||||
</Dialog>
|
||||
}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default ComponentRolePage;
|
||||
export { default } from '@/app/admin/rbac/user-role/component';
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
import { type IRole } from '@/types/rbac';
|
||||
|
||||
export type { IRole };
|
||||
|
||||
@@ -1,66 +1,5 @@
|
||||
import { type Metadata } from 'next';
|
||||
import { Suspense, lazy } from 'react';
|
||||
import { getServerSession } from 'next-auth';
|
||||
import { authOptions } from '@/pages/api/auth/[...nextauth]';
|
||||
import { type ResponseData } from '@/types/types';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import LazyLoading from '@/components/loader/LazyLoading';
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
const ComponentPage = lazy(() => import('./component'));
|
||||
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Admin | User Role",
|
||||
}
|
||||
|
||||
async function getData(current_page?: string, limit?: string) {
|
||||
const { BASE_URL_API } = process.env
|
||||
const session = await getServerSession(authOptions)
|
||||
|
||||
const res = await fetch(BASE_URL_API + '/role', {
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${session?.user.access_token}`,
|
||||
},
|
||||
cache: 'no-cache',
|
||||
next: {
|
||||
tags: ['role']
|
||||
}
|
||||
})
|
||||
|
||||
const data: ResponseData = await res.json()
|
||||
|
||||
// Recommendation: handle errors
|
||||
if (!res.ok) {
|
||||
// This will activate the closest `error.js` Error Boundary
|
||||
throw new Error(`Failed to fetch data, ${data.code || res.status} ${data.message || res.statusText}`)
|
||||
}
|
||||
|
||||
return data.data
|
||||
}
|
||||
|
||||
export default async function page() {
|
||||
const data = await getData()
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col">
|
||||
<Card>
|
||||
<CardHeader className='flex flex-row items-center justify-between space-y-2 sm:space-y-0'>
|
||||
<div>
|
||||
<CardTitle>User Role</CardTitle>
|
||||
<CardDescription className='mt-1 sm:block hidden'>Here's a list of roles that have been registered!</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Suspense fallback={<LazyLoading />}>
|
||||
<ComponentPage
|
||||
data={data.role}
|
||||
/>
|
||||
</Suspense>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
export default function DeprecatedUserRolePage() {
|
||||
redirect('/admin/rbac/user-role');
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import Sidebar from "./components/Sidebar";
|
||||
import Notification from "./components/Notification";
|
||||
import { UserNav } from "../(dashboard)/components/UserNav";
|
||||
import { House } from "lucide-react";
|
||||
import AdminBreadcrumb from "./components/Breadcrumb";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Admin Panel",
|
||||
@@ -28,7 +29,7 @@ export default async function AdminLayout({
|
||||
|
||||
{/* HEADER */}
|
||||
<header className="sticky top-0 z-10 w-full hidden lg:flex justify-between items-center p-5 md:px-6 backdrop-blur-sm bg-white/70 dark:bg-zinc-950/80 rounded-xl border border-zinc-200 text-zinc-950 shadow dark:border-zinc-800 dark:text-zinc-50">
|
||||
<span>Pages / Dashboard</span>
|
||||
<AdminBreadcrumb />
|
||||
<div className="flex items-center space-x-3">
|
||||
<div className="flex items-center space-x-3 border-r pr-3 dark:border-zinc-800">
|
||||
<Notification />
|
||||
|
||||
@@ -1,155 +0,0 @@
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useEffect, useState } from "react"
|
||||
import { Form, Input, Radio, Select } from "antd"
|
||||
import useAxiosAuth from "@/lib/axios/useAxiosAuth"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Icons } from "@/components/Icons"
|
||||
import { type IMenu } from "./type"
|
||||
import { toast } from "sonner"
|
||||
|
||||
type Props = {
|
||||
isUpdate?: boolean
|
||||
data?: IMenu
|
||||
menuList: IMenu[]
|
||||
onCancel?: () => any
|
||||
}
|
||||
|
||||
export default function ComponentForm({ data, menuList, isUpdate, onCancel }: Props) {
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
const [form] = Form.useForm();
|
||||
const router = useRouter()
|
||||
const axios = useAxiosAuth()
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
form.setFieldsValue(data)
|
||||
} else {
|
||||
form.resetFields()
|
||||
}
|
||||
}, [data, form])
|
||||
|
||||
const handleSubmit = (value: any) => {
|
||||
console.log(value)
|
||||
|
||||
!isUpdate ? handleCreate(value) : handleUpdate(value)
|
||||
}
|
||||
|
||||
const handleCreate = async (payload: IMenu) => {
|
||||
try {
|
||||
setIsLoading(true)
|
||||
await axios.post('/menu', payload)
|
||||
|
||||
handleSuccess('Data successfully created.')
|
||||
} catch (error: any) {
|
||||
console.log(error)
|
||||
toast.error(`Data failed to create`, { description: `(${error.response.data.code || error.response.status || '-'}) ${error.response.data.message || error.response.statusText || error.message}` })
|
||||
}
|
||||
}
|
||||
|
||||
const handleUpdate = async (payload: IMenu) => {
|
||||
try {
|
||||
setIsLoading(true)
|
||||
await axios.put('/menu/' + data?.id, payload)
|
||||
|
||||
handleSuccess('Data successfully updated.')
|
||||
} catch (error: any) {
|
||||
toast.error(`Data failed to update`, { description: `(${error.response.data.code || error.response.status || '-'}) ${error.response.data.message || error.response.statusText || error.message}` })
|
||||
}
|
||||
}
|
||||
|
||||
const handleSuccess = (message: string) => {
|
||||
toast.success(message)
|
||||
setIsLoading(false)
|
||||
onCancel!()
|
||||
router.refresh()
|
||||
form.resetFields()
|
||||
}
|
||||
|
||||
const handleError = (message: string) => {
|
||||
toast.error(message)
|
||||
setIsLoading(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<DialogContent>
|
||||
<Form form={form} onFinish={handleSubmit} layout='vertical'>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="dark:text-white">{isUpdate ? 'Update menu' : 'Create menu'}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Add a new team to manage products and customers
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid mt-8">
|
||||
<Form.Item name='name' label='Menu name' rules={[{ required: true, message: 'This field is required!' }]} >
|
||||
<Input className="input" id="name" placeholder="Dashboard" />
|
||||
</Form.Item>
|
||||
<div className="grid grid-cols-3 gap-x-4">
|
||||
<Form.Item name='menu_parent_id' label='Parent Menu' className="col-span-2" >
|
||||
<Select placeholder='Select parent' showSearch allowClear
|
||||
optionFilterProp="children"
|
||||
filterOption={(input, option) => option!.children!.toString().toLowerCase().indexOf(input.toLowerCase()) >= 0}
|
||||
getPopupContainer={(triggerNode: any) => triggerNode.parentNode}
|
||||
>
|
||||
<Select.Option value=''>-</Select.Option>
|
||||
{menuList.map((item =>
|
||||
<Select.Option key={item.id} value={item.id}>({item.id}) {item.name}</Select.Option>
|
||||
))}
|
||||
</Select>
|
||||
</Form.Item>
|
||||
<Form.Item name='icon' label='Icon' >
|
||||
<Select placeholder='Select icon' showSearch allowClear
|
||||
optionFilterProp="children"
|
||||
filterOption={(input, option) => option!.children!.toString().toLowerCase().indexOf(input.toLowerCase()) >= 0}
|
||||
getPopupContainer={(triggerNode: any) => triggerNode.parentNode}
|
||||
>
|
||||
<Select.Option value=''>-</Select.Option>
|
||||
<Select.Option value='ti ti-layout-dashboard'>
|
||||
<i className="ti ti-layout-dashboard icon"></i>
|
||||
</Select.Option>
|
||||
|
||||
<Select.Option value='ti ti-database'>
|
||||
<i className="ti ti-database icon"></i>
|
||||
</Select.Option>
|
||||
|
||||
<Select.Option value='ti ti-devices-2'>
|
||||
<i className="ti ti-devices-2 icon"></i>
|
||||
</Select.Option>
|
||||
</Select>
|
||||
</Form.Item>
|
||||
</div>
|
||||
<Form.Item name='path_url' label='Path URL' rules={[{ required: true, message: 'This field is required!' }]} >
|
||||
<Input className="input" id="path_url" placeholder="dashboard" />
|
||||
</Form.Item>
|
||||
<Form.Item name='hidden_data' label='Hidden Data' >
|
||||
<Radio.Group>
|
||||
<Radio value={true}>Hidden</Radio>
|
||||
<Radio value={false}>Visible</Radio>
|
||||
</Radio.Group>
|
||||
</Form.Item>
|
||||
<Form.Item name='description' label='Description'>
|
||||
<Input.TextArea className="input" id="description" placeholder="Halaman dashboard" />
|
||||
</Form.Item>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" type="button" onClick={onCancel} disabled={isLoading} >
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={isLoading}>
|
||||
{isLoading && (
|
||||
<Icons.spinner className="mr-1 h-4 w-4 animate-spin" />
|
||||
)}
|
||||
Save
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
)
|
||||
}
|
||||
@@ -1,217 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { ChangeEvent, FC, useEffect, useState } from 'react';
|
||||
import { MoreHorizontalIcon } from 'lucide-react';
|
||||
import { Table } from 'antd';
|
||||
import { TableProps, type ColumnsType } from 'antd/es/table';
|
||||
import { MixerHorizontalIcon, PlusCircledIcon } from '@radix-ui/react-icons';
|
||||
import useAxiosAuth from '@/lib/axios/useAxiosAuth';
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { AlertDialog, AlertDialogTrigger } from '@/components/ui/alert-dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Dialog } from '@/components/ui/dialog';
|
||||
import ComponentForm from './Form';
|
||||
import ConfirmAsync from './ConfirmAsync';
|
||||
import { type IMenu } from './type';
|
||||
|
||||
type Props = {
|
||||
data: IMenu[]
|
||||
};
|
||||
|
||||
const ComponentPage: FC<Props> = ({ data }) => {
|
||||
const [filterData, setFilterData] = useState<IMenu[]>([])
|
||||
const [selectedData, setSelectedData] = useState<IMenu | undefined>(undefined)
|
||||
const [showFormDialog, setShowFormDialog] = useState(false)
|
||||
|
||||
const axios = useAxiosAuth()
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
setFilterData(data)
|
||||
}
|
||||
}, [data])
|
||||
|
||||
const handleDelete = (id: string | number) => {
|
||||
return axios.delete(`/menu/${id}`).then(res => res.data)
|
||||
}
|
||||
|
||||
const handleResetForm = () => {
|
||||
setSelectedData(undefined)
|
||||
setShowFormDialog(false)
|
||||
}
|
||||
|
||||
const handleSearch = (e: ChangeEvent<HTMLInputElement>) => {
|
||||
const text = e.target.value
|
||||
if (text) {
|
||||
const newData = [...data!].filter(item => (
|
||||
item.code?.toLowerCase().includes(text.toLowerCase()) ||
|
||||
item.name?.toLowerCase().includes(text.toLowerCase()) ||
|
||||
item.path_url?.toLowerCase().includes(text.toLowerCase()) ||
|
||||
item.icon?.toLowerCase().includes(text.toLowerCase()) ||
|
||||
item.description?.toLowerCase().includes(text.toLowerCase())
|
||||
))
|
||||
setFilterData(newData)
|
||||
} else {
|
||||
setFilterData(data)
|
||||
}
|
||||
}
|
||||
|
||||
const Columns: ColumnsType<IMenu> = [
|
||||
{
|
||||
title: 'Num',
|
||||
dataIndex: 'key',
|
||||
render: (text, record, index) => index + 1
|
||||
},
|
||||
{
|
||||
title: 'Menu ID',
|
||||
dataIndex: 'id',
|
||||
sorter: (a, b) => a.id! - b.id!,
|
||||
},
|
||||
{
|
||||
title: 'Code',
|
||||
dataIndex: 'code',
|
||||
sorter: (a, b) => a.code.localeCompare(b.code)
|
||||
},
|
||||
{
|
||||
title: 'Name',
|
||||
dataIndex: 'name',
|
||||
sorter: (a, b) => a.name.localeCompare(b.name)
|
||||
},
|
||||
{
|
||||
title: 'Menu Parent Id',
|
||||
dataIndex: 'menu_parent_id',
|
||||
sorter: (a, b) => a.menu_parent_id! - b.menu_parent_id!,
|
||||
},
|
||||
{
|
||||
title: 'Icon',
|
||||
dataIndex: 'icon',
|
||||
sorter: (a, b) => a.icon.localeCompare(b.icon)
|
||||
},
|
||||
{
|
||||
title: 'Path URL',
|
||||
dataIndex: 'path_url',
|
||||
sorter: (a, b) => a.path_url.localeCompare(b.path_url)
|
||||
},
|
||||
{
|
||||
title: 'Status',
|
||||
dataIndex: 'status',
|
||||
filters: [
|
||||
{
|
||||
text: 'ACTIVE',
|
||||
value: 'A',
|
||||
},
|
||||
{
|
||||
text: 'INACTIVE',
|
||||
value: 'N',
|
||||
},
|
||||
{
|
||||
text: 'DELETED',
|
||||
value: 'X',
|
||||
},
|
||||
],
|
||||
onFilter: (value, record) => record.status!.code.indexOf(value as string) === 0,
|
||||
align: 'center',
|
||||
render: (text, record) => (
|
||||
<div className='flex justify-center text-white font-semibold text-xs'>
|
||||
{record.status.code === 'A' ?
|
||||
<div className="px-2 py-1.5 rounded-full bg-green-500 w-24">{record.status.name}</div>
|
||||
:
|
||||
<div className="px-2 py-1.5 rounded-full bg-rose-500 w-24">{record.status.name}</div>
|
||||
}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
{
|
||||
title: 'Description',
|
||||
dataIndex: 'description',
|
||||
},
|
||||
{
|
||||
title: 'Action',
|
||||
key: 'action',
|
||||
render: (_, record) => (
|
||||
<AlertDialog>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant='ghost' size="icon">
|
||||
<MoreHorizontalIcon />
|
||||
<span className="sr-only">Action Button</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => { }}>View</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => { setShowFormDialog(true); setSelectedData(record) }} >Edit</DropdownMenuItem>
|
||||
<AlertDialogTrigger asChild>
|
||||
<DropdownMenuItem>Delete</DropdownMenuItem>
|
||||
</AlertDialogTrigger>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<ConfirmAsync
|
||||
onConfirm={() => handleDelete(record.id)}
|
||||
onOkSuccess={() => { }}
|
||||
/>
|
||||
</AlertDialog>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const tableProps: TableProps<IMenu> = {
|
||||
bordered: false,
|
||||
size: 'small',
|
||||
showHeader: true,
|
||||
rowSelection: {
|
||||
onChange: (selectedRowKeys: React.Key[], selectedRows: IMenu[]) => {
|
||||
console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
|
||||
},
|
||||
getCheckboxProps: (record: IMenu) => ({
|
||||
disabled: record.code === 'C01', // Column configuration not to be checked
|
||||
name: record.id?.toString(),
|
||||
}),
|
||||
},
|
||||
pagination: {
|
||||
pageSizeOptions: [5, 10, 20, 50],
|
||||
defaultPageSize: 10,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
size: 'middle' as any
|
||||
},
|
||||
scroll: { x: 'max-content' },
|
||||
tableLayout: 'auto',
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className='flex flex-col space-y-4'>
|
||||
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between space-y-2 sm:space-y-0">
|
||||
<div className="flex flex-1 items-center space-x-2">
|
||||
<Input placeholder="Search menu..." className="h-8 w-full sm:w-[250px]" onChange={handleSearch} />
|
||||
</div>
|
||||
<Button size="sm" variant='ghost' className="ml-auto h-8 w-full sm:w-max text-his" onClick={() => setShowFormDialog(true)}>
|
||||
<PlusCircledIcon className="mr-2 h-4 w-4" />
|
||||
Create New Menu
|
||||
</Button>
|
||||
</div>
|
||||
<Table
|
||||
{...tableProps}
|
||||
rowKey='id'
|
||||
columns={Columns}
|
||||
dataSource={filterData || []}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Dialog open={showFormDialog} onOpenChange={(state) => {
|
||||
if (state === false) setSelectedData(undefined)
|
||||
setShowFormDialog(state)
|
||||
}}>
|
||||
<ComponentForm
|
||||
data={selectedData}
|
||||
menuList={data}
|
||||
isUpdate={selectedData !== undefined}
|
||||
onCancel={handleResetForm}
|
||||
/>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default ComponentPage;
|
||||
@@ -1,21 +0,0 @@
|
||||
export interface IMenu {
|
||||
id: number
|
||||
code: string
|
||||
name: string
|
||||
menu_parent_id: number | null
|
||||
icon: string
|
||||
path_url: string
|
||||
hidden_data: boolean
|
||||
status: {
|
||||
id: number
|
||||
code: "A" | 'N' | 'X'
|
||||
name: "ACTIVE" | 'INACTIVE' | 'DELETED'
|
||||
}
|
||||
description: string
|
||||
}
|
||||
|
||||
export interface IMenuAction extends IMenu {
|
||||
menu_level: number
|
||||
action?: number[]
|
||||
children?: IMenuAction[]
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
import { type Metadata } from 'next';
|
||||
import { Suspense, lazy } from 'react';
|
||||
import { getServerSession } from 'next-auth';
|
||||
import { Download } from 'lucide-react'
|
||||
import { authOptions } from '@/pages/api/auth/[...nextauth]';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { type ResponseData } from '@/types/types';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import LazyLoading from '@/components/loader/LazyLoading';
|
||||
|
||||
const ComponentPage = lazy(() => import('./component'));
|
||||
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Admin | Menu",
|
||||
}
|
||||
|
||||
async function getData() {
|
||||
const { BASE_URL_API } = process.env
|
||||
const session = await getServerSession(authOptions)
|
||||
|
||||
const res = await fetch(BASE_URL_API + '/menu', {
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${session?.user.access_token}`,
|
||||
},
|
||||
cache: 'no-cache',
|
||||
next: {
|
||||
tags: ['menu']
|
||||
}
|
||||
})
|
||||
|
||||
const data: ResponseData = await res.json()
|
||||
|
||||
// Recommendation: handle errors
|
||||
if (!res.ok) {
|
||||
// This will activate the closest `error.js` Error Boundary
|
||||
throw new Error(`Failed to fetch data, ${data.code || res.status} ${data.message || res.statusText}`)
|
||||
}
|
||||
|
||||
return data.data
|
||||
}
|
||||
|
||||
|
||||
export default async function MenuPage() {
|
||||
const data = await getData()
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col">
|
||||
<Card>
|
||||
<CardHeader className='flex flex-row items-center justify-between space-y-2 sm:space-y-0'>
|
||||
<div>
|
||||
<CardTitle>Menu</CardTitle>
|
||||
<CardDescription>Here's a list of menus that have been registered!</CardDescription>
|
||||
</div>
|
||||
<div>
|
||||
<Button className="sm:hidden" size={'icon'}><Download size={20} /></Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Suspense fallback={<LazyLoading />}>
|
||||
<ComponentPage
|
||||
data={data.menu}
|
||||
/>
|
||||
</Suspense>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { FC, ReactNode, useState } from 'react';
|
||||
import { Icons } from '@/components/Icons';
|
||||
import { AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog';
|
||||
import { type ResponseData } from '@/types/types';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
type Props = {
|
||||
title?: string;
|
||||
description?: string;
|
||||
onConfirm: () => Promise<any>;
|
||||
okText?: string;
|
||||
cancelText?: string;
|
||||
contentSuccess?: ReactNode | string;
|
||||
onOkSuccess?: () => any;
|
||||
};
|
||||
|
||||
const ConfirmAsync: FC<Props> = ({ title, description, onConfirm, okText, cancelText, contentSuccess, onOkSuccess }) => {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const router = useRouter();
|
||||
|
||||
const confirm = async () => {
|
||||
if (isLoading) return;
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const res: ResponseData = await onConfirm();
|
||||
setIsLoading(false);
|
||||
|
||||
if (!res) return;
|
||||
|
||||
if (res.code === '00' || res.code === 200) {
|
||||
showSuccess();
|
||||
} else {
|
||||
showError(res.message);
|
||||
}
|
||||
} catch (error: any) {
|
||||
setIsLoading(false);
|
||||
const message = error?.response?.data?.message || error?.message || 'Failed to delete permission';
|
||||
showError(message);
|
||||
}
|
||||
};
|
||||
|
||||
const showSuccess = () => {
|
||||
router.refresh();
|
||||
toast.success(contentSuccess || 'Permission successfully removed.');
|
||||
if (onOkSuccess) onOkSuccess();
|
||||
};
|
||||
|
||||
const showError = (message?: string) => {
|
||||
toast.error(message || 'Failed to delete permission');
|
||||
};
|
||||
|
||||
return (
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{title || 'Are you absolutely sure?'}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{description || 'This action cannot be undone. This will permanently delete this permission from the system.'}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={isLoading}>{cancelText || 'Cancel'}</AlertDialogCancel>
|
||||
<AlertDialogAction disabled={isLoading} onClick={confirm}>
|
||||
{isLoading && (
|
||||
<Icons.spinner className="mr-1 h-4 w-4 animate-spin" />
|
||||
)}
|
||||
{okText || 'Continue'}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
);
|
||||
};
|
||||
|
||||
export default ConfirmAsync;
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Form, Input } from "antd";
|
||||
import useAxiosAuth from "@/lib/axios/useAxiosAuth";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Icons } from "@/components/Icons";
|
||||
import { type IPermission } from "./type";
|
||||
import { toast } from "sonner";
|
||||
import RbacBadge from "@/components/ui/rbac-badge";
|
||||
|
||||
type Props = {
|
||||
isUpdate?: boolean;
|
||||
data?: IPermission;
|
||||
onCancel?: () => any;
|
||||
};
|
||||
|
||||
export default function PermissionForm({ data, isUpdate, onCancel }: Props) {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [previewName, setPreviewName] = useState('');
|
||||
const [form] = Form.useForm();
|
||||
const router = useRouter();
|
||||
const axios = useAxiosAuth();
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
form.setFieldsValue(data);
|
||||
setPreviewName(data.name || '');
|
||||
} else {
|
||||
form.resetFields();
|
||||
setPreviewName('');
|
||||
}
|
||||
}, [data, form]);
|
||||
|
||||
const handleSubmit = (value: { name: string; description?: string }) => {
|
||||
const payload = {
|
||||
name: value.name.trim().toUpperCase(),
|
||||
description: value.description?.trim() || '',
|
||||
};
|
||||
|
||||
!isUpdate ? handleCreate(payload) : handleUpdate(payload);
|
||||
};
|
||||
|
||||
const handleCreate = async (payload: { name: string; description?: string }) => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const res = await axios.post('/permission', payload);
|
||||
setIsLoading(false);
|
||||
|
||||
if (res.data?.code && res.data.code !== '00' && res.data.code !== 200) {
|
||||
toast.error('Failed to create permission', {
|
||||
description: res.data?.message || 'Server returned an error',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
toast.success('Permission successfully created.');
|
||||
router.refresh();
|
||||
if (onCancel) onCancel();
|
||||
} catch (error: any) {
|
||||
setIsLoading(false);
|
||||
const msg = error?.response?.data?.message || error?.message || 'Failed to create permission';
|
||||
toast.error('Failed to create permission', { description: msg });
|
||||
}
|
||||
};
|
||||
|
||||
const handleUpdate = async (payload: { name: string; description?: string }) => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const res = await axios.put(`/permission/${data?.id}`, payload);
|
||||
setIsLoading(false);
|
||||
|
||||
if (res.data?.code && res.data.code !== '00' && res.data.code !== 200) {
|
||||
toast.error('Failed to update permission', {
|
||||
description: res.data?.message || 'Server returned an error',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
toast.success('Permission successfully updated.');
|
||||
router.refresh();
|
||||
if (onCancel) onCancel();
|
||||
} catch (error: any) {
|
||||
setIsLoading(false);
|
||||
const msg = error?.response?.data?.message || error?.message || 'Failed to update permission';
|
||||
toast.error('Failed to update permission', { description: msg });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open>
|
||||
<DialogContent>
|
||||
<Form form={form} onFinish={handleSubmit} layout="vertical">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="dark:text-white">
|
||||
{isUpdate ? 'Edit Access Permission' : 'Create Access Permission'}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Define an actionable permission identifier used by role-based access control.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="grid mt-6 space-y-0">
|
||||
<Form.Item
|
||||
name="name"
|
||||
label="Permission Name"
|
||||
rules={[
|
||||
{ required: true, message: 'Permission name is required!' },
|
||||
{
|
||||
pattern: /^[A-Z0-9_]+$/,
|
||||
message: 'Only uppercase letters, numbers, and underscores are allowed (e.g. APPROVE_ATTENDANCE)',
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Input
|
||||
className="input font-mono uppercase"
|
||||
id="name"
|
||||
placeholder="APPROVE_ATTENDANCE"
|
||||
onChange={(e) => setPreviewName(e.target.value.toUpperCase())}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
{previewName && (
|
||||
<div className="flex items-center gap-2 -mt-2 mb-2 p-2.5 rounded-md bg-zinc-50 dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-800">
|
||||
<span className="text-xs text-muted-foreground font-medium">Badge Preview:</span>
|
||||
<RbacBadge permission={previewName} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Form.Item name="description" label="Description">
|
||||
<Input.TextArea
|
||||
className="input"
|
||||
id="description"
|
||||
rows={3}
|
||||
placeholder="Permission description or usage scope"
|
||||
/>
|
||||
</Form.Item>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="mt-6">
|
||||
<Button variant="outline" type="button" onClick={onCancel} disabled={isLoading}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={isLoading}>
|
||||
{isLoading && (
|
||||
<Icons.spinner className="mr-1 h-4 w-4 animate-spin" />
|
||||
)}
|
||||
Save
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
'use client';
|
||||
|
||||
import { ChangeEvent, FC, useEffect, useState } from 'react';
|
||||
import { MoreHorizontalIcon } from 'lucide-react';
|
||||
import { Table } from 'antd';
|
||||
import { TableProps, type ColumnsType } from 'antd/es/table';
|
||||
import { PlusCircledIcon } from '@radix-ui/react-icons';
|
||||
import useAxiosAuth from '@/lib/axios/useAxiosAuth';
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { AlertDialog, AlertDialogTrigger } from '@/components/ui/alert-dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Dialog } from '@/components/ui/dialog';
|
||||
import PermissionForm from './Form';
|
||||
import ConfirmAsync from './ConfirmAsync';
|
||||
import { type IPermission } from './type';
|
||||
import RbacBadge from '@/components/ui/rbac-badge';
|
||||
|
||||
type Props = {
|
||||
data: IPermission[];
|
||||
};
|
||||
|
||||
const ComponentPermissionPage: FC<Props> = ({ data }) => {
|
||||
const [filterData, setFilterData] = useState<IPermission[]>([]);
|
||||
const [selectedData, setSelectedData] = useState<IPermission | undefined>(undefined);
|
||||
const [showFormDialog, setShowFormDialog] = useState(false);
|
||||
const [searchText, setSearchText] = useState('');
|
||||
|
||||
const axios = useAxiosAuth();
|
||||
|
||||
useEffect(() => {
|
||||
if (data && Array.isArray(data)) {
|
||||
setFilterData(data);
|
||||
} else {
|
||||
setFilterData([]);
|
||||
}
|
||||
}, [data]);
|
||||
|
||||
const handleDelete = (id: string | number) => {
|
||||
return axios.delete(`/permission/${id}`).then((res) => res.data);
|
||||
};
|
||||
|
||||
const handleResetForm = () => {
|
||||
setSelectedData(undefined);
|
||||
setShowFormDialog(false);
|
||||
};
|
||||
|
||||
const handleSearch = (e: ChangeEvent<HTMLInputElement>) => {
|
||||
const text = e.target.value;
|
||||
setSearchText(text);
|
||||
if (text && Array.isArray(data)) {
|
||||
const lower = text.toLowerCase();
|
||||
const filtered = data.filter(
|
||||
(item) =>
|
||||
item.name?.toLowerCase().includes(lower) ||
|
||||
item.description?.toLowerCase().includes(lower)
|
||||
);
|
||||
setFilterData(filtered);
|
||||
} else {
|
||||
setFilterData(data || []);
|
||||
}
|
||||
};
|
||||
|
||||
const columns: ColumnsType<IPermission> = [
|
||||
{
|
||||
title: 'Num',
|
||||
dataIndex: 'key',
|
||||
width: 70,
|
||||
align: 'center',
|
||||
render: (_text, _record, index) => (
|
||||
<span className="text-xs text-muted-foreground font-medium">{index + 1}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'Permission Name',
|
||||
dataIndex: 'name',
|
||||
sorter: (a, b) => (a.name || '').localeCompare(b.name || ''),
|
||||
render: (text: string) => (
|
||||
<div className="flex items-center">
|
||||
<RbacBadge permission={text} size="sm" />
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'Description',
|
||||
dataIndex: 'description',
|
||||
render: (text: string) => (
|
||||
<span className="text-xs text-zinc-600 dark:text-zinc-300">
|
||||
{text || '-'}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'Action',
|
||||
key: 'action',
|
||||
width: 80,
|
||||
align: 'center',
|
||||
render: (_, record) => (
|
||||
<AlertDialog>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8">
|
||||
<MoreHorizontalIcon className="h-4 w-4" />
|
||||
<span className="sr-only">Action</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
setSelectedData(record);
|
||||
setShowFormDialog(true);
|
||||
}}
|
||||
>
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
<AlertDialogTrigger asChild>
|
||||
<DropdownMenuItem className="text-rose-600 dark:text-rose-400">
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</AlertDialogTrigger>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<ConfirmAsync
|
||||
title="Delete Access Permission?"
|
||||
description={`Are you sure you want to delete permission "${record.name}"? This may affect menus and roles using this permission.`}
|
||||
onConfirm={() => handleDelete(record.id)}
|
||||
onOkSuccess={() => { }}
|
||||
/>
|
||||
</AlertDialog>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const tableProps: TableProps<IPermission> = {
|
||||
bordered: false,
|
||||
size: 'small',
|
||||
showHeader: true,
|
||||
pagination: {
|
||||
pageSizeOptions: [10, 20, 50, 100],
|
||||
defaultPageSize: 10,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
size: 'middle' as any,
|
||||
},
|
||||
scroll: { x: 'max-content' },
|
||||
tableLayout: 'auto',
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col space-y-4">
|
||||
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
|
||||
<div className="flex flex-1 items-center space-x-2 w-full sm:w-auto">
|
||||
<Input
|
||||
placeholder="Search permissions..."
|
||||
className="h-8 w-full sm:w-64"
|
||||
value={searchText}
|
||||
onChange={handleSearch}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-8 text-his hover:text-his hover:bg-his/10 font-semibold"
|
||||
onClick={() => {
|
||||
setSelectedData(undefined);
|
||||
setShowFormDialog(true);
|
||||
}}
|
||||
>
|
||||
<PlusCircledIcon className="mr-2 h-4 w-4" />
|
||||
Create New Permission
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Table
|
||||
{...tableProps}
|
||||
rowKey="id"
|
||||
columns={columns}
|
||||
dataSource={filterData || []}
|
||||
locale={{
|
||||
emptyText: (
|
||||
<div className="py-8 text-center text-muted-foreground">
|
||||
<i className="ti ti-shield-lock text-3xl mb-2 text-zinc-400 block" />
|
||||
<p className="text-sm font-medium">No permissions found</p>
|
||||
<p className="text-xs text-zinc-400 mt-1">
|
||||
{searchText ? 'Try adjusting your search criteria.' : 'Click "Create New Permission" to add the first permission.'}
|
||||
</p>
|
||||
</div>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{showFormDialog ?
|
||||
<PermissionForm
|
||||
data={selectedData}
|
||||
isUpdate={selectedData !== undefined}
|
||||
onCancel={handleResetForm}
|
||||
/>
|
||||
: null
|
||||
}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default ComponentPermissionPage;
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
export interface IPermission {
|
||||
id: number;
|
||||
name: string;
|
||||
description?: string;
|
||||
status?: {
|
||||
id?: number;
|
||||
code?: string;
|
||||
name?: string;
|
||||
};
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { type Metadata } from 'next';
|
||||
import { Suspense, lazy } from 'react';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import LazyLoading from '@/components/loader/LazyLoading';
|
||||
import fetchData from '@/lib/fetchData';
|
||||
|
||||
const ComponentPage = lazy(() => import('./component'));
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Access Permissions | Admin",
|
||||
description: "Manage access permissions for role-based access control",
|
||||
};
|
||||
|
||||
async function getPermissions() {
|
||||
try {
|
||||
const res = await fetchData('/permission', 'no-cache');
|
||||
if (Array.isArray(res)) return res;
|
||||
if (res && Array.isArray(res.permission)) return res.permission;
|
||||
if (res && Array.isArray(res.permissions)) return res.permissions;
|
||||
return [];
|
||||
} catch (error) {
|
||||
console.error('Failed to load permissions:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export default async function PermissionPage() {
|
||||
const permissions = await getPermissions();
|
||||
|
||||
return (
|
||||
<div className="flex flex-col">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0">
|
||||
<div>
|
||||
<CardTitle>Access Permissions</CardTitle>
|
||||
<CardDescription className="mt-1">
|
||||
List of action permissions for Role-Based Access Control
|
||||
</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Suspense fallback={<LazyLoading />}>
|
||||
<ComponentPage data={permissions} />
|
||||
</Suspense>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+27
-28
@@ -6,49 +6,48 @@ import { type ResponseData } from '@/types/types';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
type Props = {
|
||||
title?: string
|
||||
description?: string
|
||||
onConfirm: () => Promise<any>
|
||||
okText?: string
|
||||
cancelText?: string
|
||||
contentSuccess?: ReactNode | string
|
||||
onOkSuccess?: () => any
|
||||
title?: string;
|
||||
description?: string;
|
||||
onConfirm: () => Promise<any>;
|
||||
okText?: string;
|
||||
cancelText?: string;
|
||||
contentSuccess?: ReactNode | string;
|
||||
onOkSuccess?: () => any;
|
||||
};
|
||||
|
||||
const ConfirmAsync: FC<Props> = ({ title, description, onConfirm, okText, cancelText, contentSuccess, onOkSuccess }) => {
|
||||
const [isLoading, setIsloading] = useState(false)
|
||||
const router = useRouter()
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const router = useRouter();
|
||||
|
||||
const confirm = async () => {
|
||||
if (isLoading) return
|
||||
if (isLoading) return;
|
||||
try {
|
||||
setIsloading(true)
|
||||
const res: ResponseData = await onConfirm()
|
||||
setIsloading(false)
|
||||
setIsLoading(true);
|
||||
const res: ResponseData = await onConfirm();
|
||||
setIsLoading(false);
|
||||
|
||||
console.log(res)
|
||||
if (!res) return
|
||||
if (!res) return;
|
||||
|
||||
if (res.code === '00') {
|
||||
showSuccess()
|
||||
if (res.code === '00' || res.code === 200) {
|
||||
showSuccess();
|
||||
} else {
|
||||
showError(res.message)
|
||||
showError(res.message);
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.log(error)
|
||||
setIsloading(false)
|
||||
showError(error?.message)
|
||||
setIsLoading(false);
|
||||
const message = error?.response?.data?.message || error?.message || 'Failed to delete menu';
|
||||
showError(message);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const showSuccess = () => {
|
||||
router.refresh()
|
||||
toast.success(contentSuccess || 'Data successfully removed.' as string)
|
||||
onOkSuccess!()
|
||||
router.refresh();
|
||||
toast.success(contentSuccess || 'Menu successfully removed.');
|
||||
if (onOkSuccess) onOkSuccess();
|
||||
};
|
||||
|
||||
const showError = (message?: string) => {
|
||||
toast.error(message)
|
||||
toast.error(message || 'Failed to delete menu');
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -56,7 +55,7 @@ const ConfirmAsync: FC<Props> = ({ title, description, onConfirm, okText, cancel
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{title || 'Are you absolutely sure?'}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{description || 'This action cannot be undone. This will permanently delete this data and remove from our servers.'}
|
||||
{description || 'This action cannot be undone. This will permanently delete this menu configuration.'}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
@@ -70,6 +69,6 @@ const ConfirmAsync: FC<Props> = ({ title, description, onConfirm, okText, cancel
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export default ConfirmAsync;
|
||||
@@ -0,0 +1,321 @@
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Form, Input, Select, Switch } from "antd";
|
||||
import useAxiosAuth from "@/lib/axios/useAxiosAuth";
|
||||
import useFetch from "@/lib/axios/useFetch";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Icons } from "@/components/Icons";
|
||||
import { type IMenu } from "./type";
|
||||
import { toast } from "sonner";
|
||||
import { TABLER_ICON_OPTIONS } from "@/lib/tabler-icons";
|
||||
import RbacBadge from "@/components/ui/rbac-badge";
|
||||
import { Plus, X } from "lucide-react";
|
||||
import PermissionForm from "../../action-permissions/component/Form";
|
||||
|
||||
type Props = {
|
||||
isUpdate?: boolean;
|
||||
data?: IMenu;
|
||||
menuList: IMenu[];
|
||||
onCancel?: () => any;
|
||||
};
|
||||
|
||||
// Helper to collect all descendant IDs of a menu to prevent circular relationships
|
||||
function getDescendantIds(targetId: number, menus: IMenu[]): Set<number> {
|
||||
const descendants = new Set<number>();
|
||||
const stack = [targetId];
|
||||
|
||||
while (stack.length > 0) {
|
||||
const currentId = stack.pop()!;
|
||||
const children = menus.filter(m => m.menu_parent_id === currentId && m.id !== undefined);
|
||||
for (const child of children) {
|
||||
if (!descendants.has(child.id!)) {
|
||||
descendants.add(child.id!);
|
||||
stack.push(child.id!);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return descendants;
|
||||
}
|
||||
|
||||
export default function MenuForm({ data, menuList, isUpdate, onCancel }: Props) {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [selectedIcon, setSelectedIcon] = useState<string>('');
|
||||
const [showPermissionForm, setShowPermissionForm] = useState(false)
|
||||
const [form] = Form.useForm();
|
||||
const router = useRouter();
|
||||
const axios = useAxiosAuth();
|
||||
|
||||
// Fetch available permissions for action selection
|
||||
const { data: permissionData, isLoading: permissionLoading, mutate } = useFetch('/permission');
|
||||
|
||||
const availablePermissions: string[] = useMemo(() => {
|
||||
if (!permissionData) return [];
|
||||
if (Array.isArray(permissionData)) {
|
||||
return permissionData.map((p: any) => p.name || p);
|
||||
}
|
||||
if (Array.isArray(permissionData.permission)) {
|
||||
return permissionData.permission.map((p: any) => p.name || p);
|
||||
}
|
||||
if (Array.isArray(permissionData.permissions)) {
|
||||
return permissionData.permissions.map((p: any) => p.name || p);
|
||||
}
|
||||
return [];
|
||||
}, [permissionData]);
|
||||
|
||||
// Calculate valid parent options (excluding self and descendants to prevent circular relationships)
|
||||
const validParentOptions = useMemo(() => {
|
||||
if (!menuList) return [];
|
||||
|
||||
const invalidIds = new Set<number>();
|
||||
if (isUpdate && data?.id !== undefined) {
|
||||
invalidIds.add(data.id);
|
||||
const descendants = getDescendantIds(data.id, menuList);
|
||||
descendants.forEach(id => invalidIds.add(id));
|
||||
}
|
||||
|
||||
return menuList
|
||||
.filter(item => item.id !== undefined && !invalidIds.has(item.id))
|
||||
.map(item => {
|
||||
const parent = menuList.find(p => p.id === item.menu_parent_id);
|
||||
const label = parent ? `${parent.name} → ${item.name}` : item.name;
|
||||
return {
|
||||
label,
|
||||
value: item.id!,
|
||||
isAdmin: item.is_admin_menu,
|
||||
};
|
||||
});
|
||||
}, [menuList, isUpdate, data]);
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
form.setFieldsValue({
|
||||
...data,
|
||||
menu_parent_id: data.menu_parent_id ?? null,
|
||||
is_admin_menu: data.is_admin_menu ?? false,
|
||||
action: data.action ?? [],
|
||||
});
|
||||
setSelectedIcon(data.icon || '');
|
||||
} else {
|
||||
form.resetFields();
|
||||
form.setFieldsValue({
|
||||
is_admin_menu: false,
|
||||
menu_parent_id: null,
|
||||
action: [],
|
||||
});
|
||||
setSelectedIcon('');
|
||||
}
|
||||
}, [data, form]);
|
||||
|
||||
const handleSubmit = async (values: any) => {
|
||||
const payload: Partial<IMenu> = {
|
||||
name: values.name?.trim(),
|
||||
path_url: values.path_url?.trim(),
|
||||
description: values.description?.trim() || '',
|
||||
icon: values.icon?.trim() || '',
|
||||
is_admin_menu: Boolean(values.is_admin_menu),
|
||||
menu_parent_id: values.menu_parent_id ? Number(values.menu_parent_id) : null,
|
||||
action: Array.isArray(values.action) ? values.action : [],
|
||||
};
|
||||
|
||||
!isUpdate ? handleCreate(payload) : handleUpdate(payload);
|
||||
};
|
||||
|
||||
const handleCreate = async (payload: Partial<IMenu>) => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const res = await axios.post('/menu', payload);
|
||||
setIsLoading(false);
|
||||
|
||||
if (res.data?.code && res.data.code !== '00' && res.data.code !== 200) {
|
||||
toast.error('Failed to create menu', {
|
||||
description: res.data?.message || 'Server returned an error',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
toast.success('Menu successfully created.');
|
||||
router.refresh();
|
||||
if (onCancel) onCancel();
|
||||
} catch (error: any) {
|
||||
setIsLoading(false);
|
||||
const msg = error?.response?.data?.message || error?.message || 'Failed to create menu';
|
||||
toast.error('Failed to create menu', { description: msg });
|
||||
}
|
||||
};
|
||||
|
||||
const handleUpdate = async (payload: Partial<IMenu>) => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const res = await axios.put(`/menu/${data?.id}`, payload);
|
||||
setIsLoading(false);
|
||||
|
||||
if (res.data?.code && res.data.code !== '00' && res.data.code !== 200) {
|
||||
toast.error('Failed to update menu', {
|
||||
description: res.data?.message || 'Server returned an error',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
toast.success('Menu successfully updated.');
|
||||
router.refresh();
|
||||
if (onCancel) onCancel();
|
||||
} catch (error: any) {
|
||||
setIsLoading(false);
|
||||
const msg = error?.response?.data?.message || error?.message || 'Failed to update menu';
|
||||
toast.error('Failed to update menu', { description: msg });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<DialogContent className="max-h-[90vh] overflow-y-auto">
|
||||
<Form form={form} onFinish={handleSubmit} layout="vertical">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="dark:text-white">
|
||||
{isUpdate ? 'Edit Menu' : 'Create New Menu'}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Configure menu routing, hierarchy, tabler icon, and assigned permissions.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="grid mt-6 gap-y-0">
|
||||
<Form.Item
|
||||
name="name"
|
||||
label="Menu Name"
|
||||
rules={[{ required: true, message: 'Menu name is required!' }]}
|
||||
>
|
||||
<Input className="input" placeholder="e.g. Overview or User Management" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
name="path_url"
|
||||
label="Path URL"
|
||||
rules={[{ required: true, message: 'Path URL is required!' }]}
|
||||
>
|
||||
<Input className="input font-mono" placeholder="e.g. /administration/user" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item name="menu_parent_id" label="Parent Menu" tooltip="Select parent menu or leave as Root menu (null)">
|
||||
<Select placeholder="Root Menu (No Parent)" allowClear
|
||||
optionFilterProp="children" getPopupContainer={(triggerNode: any) => triggerNode.parentNode}
|
||||
showSearch={{ filterOption: (input, option) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase()) }}
|
||||
options={[
|
||||
{ label: '— Root Menu (None) —', value: null as any },
|
||||
...validParentOptions.map(p => ({
|
||||
label: `${p.label} ${p.isAdmin ? ' (Admin)' : ''}`,
|
||||
value: p.value,
|
||||
})),
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
name="icon"
|
||||
label={
|
||||
<span className="flex items-center gap-2">
|
||||
Icon (Tabler)
|
||||
{selectedIcon && (
|
||||
<span className="inline-flex items-center justify-center w-5 h-5 rounded bg-zinc-100 dark:bg-zinc-800 text-his">
|
||||
<i className={selectedIcon} />
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
}
|
||||
>
|
||||
<Select placeholder="Select Tabler Icon" allowClear
|
||||
optionFilterProp="children" getPopupContainer={(triggerNode: any) => triggerNode.parentNode}
|
||||
onChange={(val) => setSelectedIcon(val || '')}
|
||||
options={TABLER_ICON_OPTIONS.map(opt => ({
|
||||
label: (
|
||||
<div className="flex items-center gap-2 py-0.5">
|
||||
<i className={`${opt.value} text-base text-zinc-600 dark:text-zinc-300 w-5 text-center`} />
|
||||
<span>{opt.label}</span>
|
||||
<span className="text-xs text-muted-foreground ml-auto font-mono">{opt.value}</span>
|
||||
</div>
|
||||
),
|
||||
value: opt.value,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<div className="p-3 rounded-lg border border-zinc-200 dark:border-zinc-800 bg-zinc-50/50 dark:bg-zinc-900/40 flex items-center justify-between">
|
||||
<div>
|
||||
<span className="text-sm font-medium text-zinc-900 dark:text-zinc-100 block">
|
||||
Admin Panel Menu
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground block mt-0.5">
|
||||
When enabled, this menu is treated as part of the Admin Panel and governed by Allow Admin Panel permission.
|
||||
</span>
|
||||
</div>
|
||||
<Form.Item name="is_admin_menu" valuePropName="checked" className="mb-0">
|
||||
<Switch />
|
||||
</Form.Item>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Form.Item name="action" label="Action / Permissions" tooltip="Select which action permissions are available on this menu" className="w-full">
|
||||
<Select mode="multiple" allowClear loading={permissionLoading} options={availablePermissions.map(p => ({ label: p, value: p }))}
|
||||
showSearch={{ filterOption: (input, option) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase()) }}
|
||||
placeholder={permissionLoading ? "Loading permissions..." : "Assign permissions to this menu..."}
|
||||
className="h-max"
|
||||
optionFilterProp="children" getPopupContainer={(triggerNode: any) => triggerNode.parentNode}
|
||||
tagRender={(props) => {
|
||||
const { value, closable, onClose } = props;
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 mr-1.5 my-0.5">
|
||||
<RbacBadge permission={String(value)} size="sm" />
|
||||
{closable && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="text-xs text-muted-foreground hover:text-rose-500 ml-0.5"
|
||||
>
|
||||
<X size={10} />
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Button variant='outline' className="mt-6" title="Add Permission" type="button" onClick={() => setShowPermissionForm(true)}><Plus /></Button>
|
||||
</div>
|
||||
|
||||
<Form.Item name="description" label="Description">
|
||||
<Input.TextArea className="input" id="description" rows={3} placeholder="Describe the purpose of this menu" />
|
||||
</Form.Item>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="mt-6">
|
||||
<Button variant="outline" type="button" onClick={onCancel} disabled={isLoading}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={isLoading}>
|
||||
{isLoading && (
|
||||
<Icons.spinner className="mr-1 h-4 w-4 animate-spin" />
|
||||
)}
|
||||
Save Menu
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
|
||||
{showPermissionForm ?
|
||||
<PermissionForm
|
||||
isUpdate={false}
|
||||
onCancel={() => { setShowPermissionForm(false); mutate() }}
|
||||
/>
|
||||
: null
|
||||
}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
'use client';
|
||||
|
||||
import { ChangeEvent, FC, useEffect, useMemo, useState } from 'react';
|
||||
import { MoreHorizontalIcon } from 'lucide-react';
|
||||
import { Table } from 'antd';
|
||||
import { TableProps, type ColumnsType } from 'antd/es/table';
|
||||
import { PlusCircledIcon } from '@radix-ui/react-icons';
|
||||
import useAxiosAuth from '@/lib/axios/useAxiosAuth';
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { AlertDialog, AlertDialogTrigger } from '@/components/ui/alert-dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Dialog } from '@/components/ui/dialog';
|
||||
import MenuForm from './Form';
|
||||
import ConfirmAsync from './ConfirmAsync';
|
||||
import { type IMenu } from './type';
|
||||
import RbacBadge from '@/components/ui/rbac-badge';
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
type Props = {
|
||||
data: IMenu[];
|
||||
};
|
||||
|
||||
// Transform flat menu list into hierarchical tree for Antd Table
|
||||
function buildMenuTree(items: IMenu[]): IMenu[] {
|
||||
const itemMap = new Map<number, IMenu>();
|
||||
const roots: IMenu[] = [];
|
||||
|
||||
// Clone all items and add empty children
|
||||
items.forEach(item => {
|
||||
if (item.id !== undefined) {
|
||||
itemMap.set(item.id, { ...item, children: [] });
|
||||
}
|
||||
});
|
||||
|
||||
// Wire parents and children
|
||||
items.forEach(item => {
|
||||
if (item.id === undefined) return;
|
||||
const mappedItem = itemMap.get(item.id)!;
|
||||
if (item.menu_parent_id && itemMap.has(item.menu_parent_id)) {
|
||||
const parent = itemMap.get(item.menu_parent_id)!;
|
||||
if (!parent.children) parent.children = [];
|
||||
parent.children.push(mappedItem);
|
||||
} else {
|
||||
roots.push(mappedItem);
|
||||
}
|
||||
});
|
||||
|
||||
// Remove empty children arrays so Antd doesn't render expand icons on leaf nodes
|
||||
function cleanupEmptyChildren(list: IMenu[]) {
|
||||
list.forEach(node => {
|
||||
if (node.children && node.children.length === 0) {
|
||||
delete node.children;
|
||||
} else if (node.children && node.children.length > 0) {
|
||||
cleanupEmptyChildren(node.children);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
cleanupEmptyChildren(roots);
|
||||
return roots;
|
||||
}
|
||||
|
||||
const ComponentMenuPage: FC<Props> = ({ data }) => {
|
||||
const [rawMenus, setRawMenus] = useState<IMenu[]>([]);
|
||||
const [filterData, setFilterData] = useState<IMenu[]>([]);
|
||||
const [selectedData, setSelectedData] = useState<IMenu | undefined>(undefined);
|
||||
const [showFormDialog, setShowFormDialog] = useState(false);
|
||||
const [searchText, setSearchText] = useState('');
|
||||
|
||||
const axios = useAxiosAuth();
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
if (data && Array.isArray(data)) {
|
||||
setRawMenus(data);
|
||||
setFilterData(data);
|
||||
} else {
|
||||
setRawMenus([]);
|
||||
setFilterData([]);
|
||||
}
|
||||
}, [data]);
|
||||
|
||||
const handleDelete = async (id: string | number) => {
|
||||
return await axios.delete(`/menu/${id}`).then((res) => res.data);
|
||||
};
|
||||
|
||||
const handleResetForm = () => {
|
||||
setSelectedData(undefined);
|
||||
setShowFormDialog(false);
|
||||
};
|
||||
|
||||
const handleSearch = (e: ChangeEvent<HTMLInputElement>) => {
|
||||
const text = e.target.value;
|
||||
setSearchText(text);
|
||||
if (text && rawMenus.length > 0) {
|
||||
const lower = text.toLowerCase();
|
||||
const filtered = rawMenus.filter(
|
||||
(item) =>
|
||||
item.name?.toLowerCase().includes(lower) ||
|
||||
item.path_url?.toLowerCase().includes(lower) ||
|
||||
item.description?.toLowerCase().includes(lower) ||
|
||||
item.icon?.toLowerCase().includes(lower) ||
|
||||
(item.action && item.action.some(act => act.toLowerCase().includes(lower)))
|
||||
);
|
||||
setFilterData(filtered);
|
||||
} else {
|
||||
setFilterData(rawMenus);
|
||||
}
|
||||
};
|
||||
|
||||
// If searching, display flat filtered items; otherwise display structured tree
|
||||
const displayDataSource = useMemo(() => {
|
||||
if (searchText.trim().length > 0) {
|
||||
return filterData;
|
||||
}
|
||||
return buildMenuTree(rawMenus);
|
||||
}, [searchText, filterData, rawMenus]);
|
||||
|
||||
const columns: ColumnsType<IMenu> = [
|
||||
{
|
||||
title: 'Menu Name',
|
||||
dataIndex: 'name',
|
||||
key: 'name',
|
||||
render: (text: string, record: IMenu) => (
|
||||
<div className="inline-flex items-center gap-2">
|
||||
{record.icon ? (
|
||||
<span className="inline-flex items-center justify-center w-6 h-6 rounded bg-zinc-100 dark:bg-zinc-800 text-zinc-700 dark:text-zinc-200 text-sm">
|
||||
<i className={record.icon} />
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex items-center justify-center w-6 h-6 rounded bg-zinc-50 dark:bg-zinc-900 text-zinc-400 text-xs font-mono">
|
||||
#
|
||||
</span>
|
||||
)}
|
||||
<span className="font-semibold text-zinc-900 dark:text-zinc-100">
|
||||
{text}
|
||||
</span>
|
||||
{record.menu_parent_id && searchText && (
|
||||
<span className="text-[10px] text-muted-foreground bg-zinc-100 dark:bg-zinc-800 px-1.5 py-0.5 rounded">
|
||||
child
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'Path URL',
|
||||
dataIndex: 'path_url',
|
||||
key: 'path_url',
|
||||
render: (path: string) => (
|
||||
<span className="font-mono text-xs text-zinc-600 dark:text-zinc-300">
|
||||
{path || '/'}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'Type',
|
||||
dataIndex: 'is_admin_menu',
|
||||
key: 'is_admin_menu',
|
||||
width: 120,
|
||||
align: 'center',
|
||||
render: (isAdmin?: boolean) => (
|
||||
isAdmin ? (
|
||||
<span className="inline-flex items-center px-2 py-0.5 rounded-sm text-[11px] font-semibold bg-indigo-500/10 text-indigo-600 border border-indigo-500/20 dark:bg-indigo-500/20 dark:text-indigo-300 dark:border-indigo-500/30">
|
||||
Admin Panel
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex items-center px-2 py-0.5 rounded-sm text-[11px] font-semibold bg-zinc-500/10 text-zinc-600 border border-zinc-500/20 dark:bg-zinc-500/20 dark:text-zinc-400 dark:border-zinc-500/30">
|
||||
General
|
||||
</span>
|
||||
)
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'Actions / Permissions',
|
||||
dataIndex: 'action',
|
||||
key: 'action',
|
||||
render: (actions?: string[]) => {
|
||||
if (!actions || actions.length === 0) {
|
||||
return <span className="text-xs text-muted-foreground italic">No action assigned</span>;
|
||||
}
|
||||
return (
|
||||
<div className="flex flex-wrap gap-1 max-w-md">
|
||||
{actions.map((act) => (
|
||||
<RbacBadge key={act} permission={act} size="sm" />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: 'Description',
|
||||
dataIndex: 'description',
|
||||
key: 'description',
|
||||
render: (desc: string) => (
|
||||
<span className="text-xs text-muted-foreground line-clamp-2 max-w-xs">
|
||||
{desc || '-'}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'Action',
|
||||
key: 'row_action',
|
||||
width: 80,
|
||||
align: 'center',
|
||||
render: (_, record) => (
|
||||
<AlertDialog>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8">
|
||||
<MoreHorizontalIcon className="h-4 w-4" />
|
||||
<span className="sr-only">Menu Actions</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
setSelectedData(record);
|
||||
setShowFormDialog(true);
|
||||
}}
|
||||
>
|
||||
Edit Menu
|
||||
</DropdownMenuItem>
|
||||
<AlertDialogTrigger asChild>
|
||||
<DropdownMenuItem className="text-rose-600 dark:text-rose-400">
|
||||
Delete Menu
|
||||
</DropdownMenuItem>
|
||||
</AlertDialogTrigger>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<ConfirmAsync
|
||||
title="Delete Menu?"
|
||||
description={`Are you sure you want to delete menu "${record.name}"? If this menu has child menus or permissions assigned, access may be affected.`}
|
||||
onConfirm={() => handleDelete(record.id!)}
|
||||
onOkSuccess={() => router.refresh()}
|
||||
/>
|
||||
</AlertDialog>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const tableProps: TableProps<IMenu> = {
|
||||
bordered: false,
|
||||
size: 'small',
|
||||
showHeader: true,
|
||||
pagination: searchText ? {
|
||||
pageSizeOptions: [10, 20, 50],
|
||||
defaultPageSize: 10,
|
||||
showSizeChanger: true,
|
||||
size: 'middle' as any,
|
||||
} : false, // In tree mode, keep full tree expanded/visible for clear hierarchy
|
||||
scroll: { x: 'max-content' },
|
||||
tableLayout: 'auto',
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col space-y-4">
|
||||
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
|
||||
<div className="flex flex-1 items-center space-x-2 w-full sm:w-auto">
|
||||
<Input
|
||||
placeholder="Search menu, path, or permissions..."
|
||||
className="h-8 w-full sm:w-64"
|
||||
value={searchText}
|
||||
onChange={handleSearch}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-8 text-his hover:text-his hover:bg-his/10 font-semibold"
|
||||
onClick={() => {
|
||||
setSelectedData(undefined);
|
||||
setShowFormDialog(true);
|
||||
}}
|
||||
>
|
||||
<PlusCircledIcon className="mr-2 h-4 w-4" />
|
||||
Create New Menu
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Table
|
||||
{...tableProps}
|
||||
rowKey="id"
|
||||
columns={columns}
|
||||
dataSource={displayDataSource}
|
||||
locale={{
|
||||
emptyText: (
|
||||
<div className="py-8 text-center text-muted-foreground">
|
||||
<i className="ti ti-category text-3xl mb-2 text-zinc-400 block" />
|
||||
<p className="text-sm font-medium">No menus registered</p>
|
||||
<p className="text-xs text-zinc-400 mt-1">
|
||||
{searchText ? 'No menu matching your search.' : 'Click "Create New Menu" to register your first navigation menu.'}
|
||||
</p>
|
||||
</div>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Dialog
|
||||
open={showFormDialog}
|
||||
onOpenChange={(state) => {
|
||||
if (!state) setSelectedData(undefined);
|
||||
setShowFormDialog(state);
|
||||
}}
|
||||
>
|
||||
<MenuForm
|
||||
data={selectedData}
|
||||
menuList={rawMenus}
|
||||
isUpdate={selectedData !== undefined}
|
||||
onCancel={handleResetForm}
|
||||
/>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default ComponentMenuPage;
|
||||
@@ -0,0 +1,7 @@
|
||||
import { type IMenu, type IPermission } from "@/types/rbac";
|
||||
|
||||
export type { IMenu, IPermission };
|
||||
|
||||
export interface IMenuAction extends IMenu {
|
||||
children?: IMenuAction[];
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { type Metadata } from 'next';
|
||||
import { Suspense, lazy } from 'react';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import LazyLoading from '@/components/loader/LazyLoading';
|
||||
import fetchData from '@/lib/fetchData';
|
||||
|
||||
const ComponentPage = lazy(() => import('./component'));
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Menu Management | Admin",
|
||||
description: "Manage system navigation menus and their permission actions",
|
||||
};
|
||||
|
||||
async function getMenus() {
|
||||
try {
|
||||
const res = await fetchData('/menu', 'no-cache');
|
||||
if (Array.isArray(res)) return res;
|
||||
if (res && Array.isArray(res.menu)) return res.menu;
|
||||
if (res && Array.isArray(res.menus)) return res.menus;
|
||||
return [];
|
||||
} catch (error) {
|
||||
console.error('Failed to load menus:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export default async function MenuPage() {
|
||||
const menus = await getMenus();
|
||||
|
||||
return (
|
||||
<div className="flex flex-col">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0">
|
||||
<div>
|
||||
<CardTitle>Menu Management</CardTitle>
|
||||
<CardDescription className="mt-1">
|
||||
List of registered navigation menus and their access permissions
|
||||
</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Suspense fallback={<LazyLoading />}>
|
||||
<ComponentPage data={menus} />
|
||||
</Suspense>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
import { FC } from 'react';
|
||||
import { type Metadata } from 'next';
|
||||
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 RbacBadge from '@/components/ui/rbac-badge';
|
||||
import { PencilLine } from 'lucide-react';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Detail Hak Akses & Kewenangan | Admin",
|
||||
description: "Detail of user role and authorized menu actions",
|
||||
};
|
||||
|
||||
type Props = {
|
||||
params: Promise<{ id: string }>;
|
||||
};
|
||||
|
||||
const UserRoleDetailPage: FC<Props> = async ({ params }) => {
|
||||
const { id } = await params;
|
||||
const data: IRole | undefined = await fetchData(`/role/${id}`, 'no-cache');;
|
||||
|
||||
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),
|
||||
action: Array.isArray(p.action) ? p.action : [],
|
||||
}))
|
||||
: [];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col space-y-6 pb-12">
|
||||
{/* Header & Overview 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">Access and Permissions</CardTitle>
|
||||
<CardDescription className="mt-1">
|
||||
Informasi detail konfigurasi hak akses dan izin menu untuk peran ini
|
||||
</CardDescription>
|
||||
</div>
|
||||
</div>
|
||||
<Link href={`/admin/rbac/user-role/edit/${id}`}>
|
||||
<Button className="bg-his hover:bg-his/90 text-white font-medium">
|
||||
<PencilLine className='size-3.5' /> Edit Role
|
||||
</Button>
|
||||
</Link>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 p-4 rounded-lg bg-zinc-50/60 dark:bg-zinc-900/40">
|
||||
<div className="flex flex-col space-y-1">
|
||||
<span className="text-xs text-muted-foreground tracking-wider font-semibold">
|
||||
Kode Peran
|
||||
</span>
|
||||
<span className="font-mono font-bold text-sm text-zinc-900 dark:text-zinc-100">
|
||||
{data?.code || `ROLE-${id}`}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex flex-col space-y-1">
|
||||
<span className="text-xs text-muted-foreground tracking-wider font-semibold">
|
||||
Nama Hak Akses
|
||||
</span>
|
||||
<span className="font-bold text-sm text-zinc-900 dark:text-zinc-100">
|
||||
{data?.name || '-'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex flex-col space-y-1">
|
||||
<span className="text-xs text-muted-foreground tracking-wider font-semibold">
|
||||
Akses Admin Panel
|
||||
</span>
|
||||
<div>
|
||||
{isAdminAllowed ? (
|
||||
<span className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-semibold bg-emerald-500/10 text-emerald-600 border border-emerald-500/20 dark:bg-emerald-500/20 dark:text-emerald-300">
|
||||
<span className="w-1.5 h-1.5 rounded-full bg-emerald-500" />
|
||||
Admin Panel
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-semibold bg-zinc-500/10 text-zinc-500 border border-zinc-500/20 dark:bg-zinc-500/20 dark:text-zinc-400">
|
||||
<span className="w-1.5 h-1.5 rounded-full bg-zinc-400" />
|
||||
General Access Only
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col space-y-1">
|
||||
<span className="text-xs text-muted-foreground tracking-wider font-semibold">
|
||||
Status
|
||||
</span>
|
||||
<div>
|
||||
<span className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-semibold bg-green-500/10 text-green-600 border border-green-500/20">
|
||||
<span className="w-1.5 h-1.5 rounded-full bg-green-500" />
|
||||
{data?.status?.name || 'Aktif'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col space-y-1 md:col-span-2">
|
||||
<span className="text-xs text-muted-foreground tracking-wider font-semibold">
|
||||
Deskripsi
|
||||
</span>
|
||||
<span className="text-sm text-zinc-700 dark:text-zinc-300">
|
||||
{data?.description || 'Tidak ada deskripsi.'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Menu Permissions List */}
|
||||
<Card>
|
||||
<CardHeader className="pb-3 border-b border-zinc-200 dark:border-zinc-800">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<i className="ti ti-checklist text-lg text-his" />
|
||||
<CardTitle className="text-base font-semibold">
|
||||
Daftar Izin Menu & Aksi ({roleDetails.length} Menu Diizinkan)
|
||||
</CardTitle>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="p-0">
|
||||
{roleDetails.length > 0 ? (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-zinc-200 dark:border-zinc-800 bg-zinc-50 dark:bg-zinc-900 text-left text-xs font-semibold text-muted-foreground tracking-wider">
|
||||
<th className="py-3 px-4 w-14 text-center">No</th>
|
||||
<th className="py-3 px-4">Menu Aplikasi (Hierarki)</th>
|
||||
<th className="py-3 px-4">Aksi yang Diizinkan</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-zinc-200 dark:divide-zinc-800">
|
||||
{roleDetails.map((detail, idx) => (
|
||||
<tr key={idx} className="hover:bg-zinc-50/50 dark:hover:bg-zinc-900/30 transition-colors">
|
||||
<td className="py-3.5 px-4 text-center text-xs text-muted-foreground font-medium">
|
||||
{idx + 1}
|
||||
</td>
|
||||
<td className="py-3.5 px-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<div>
|
||||
<span className="font-semibold text-zinc-900 dark:text-zinc-100 text-xs sm:text-sm">
|
||||
{detail.menu_name}
|
||||
</span>
|
||||
<span className="text-xs font-mono text-muted-foreground block">
|
||||
{detail.menu_path}
|
||||
</span>
|
||||
</div>
|
||||
{detail.is_admin_menu && (
|
||||
<span className="text-[10px] font-semibold px-1.5 py-0.5 rounded bg-rose-500/10 text-rose-600 dark:text-rose-400">
|
||||
Admin
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
<td className="py-3.5 px-4">
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{detail.action && detail.action.length > 0 ? (
|
||||
detail.action.map(action => (
|
||||
<RbacBadge key={action} permission={action} size="sm" />
|
||||
))
|
||||
) : (
|
||||
<span className="text-xs text-muted-foreground italic">
|
||||
Akses Menu Saja (Tanpa Aksi Spesifik)
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : (
|
||||
<div className="py-12 text-center text-muted-foreground">
|
||||
<i className="ti ti-lock-open text-3xl mb-2 text-zinc-400 block" />
|
||||
<p className="text-sm font-medium">Belum ada menu atau izin yang dikonfigurasi untuk role ini.</p>
|
||||
<Link href={`/admin/rbac/user-role/edit/${id}`} className="mt-3 inline-block">
|
||||
<Button size="sm" variant="outline">
|
||||
Konfigurasi Hak Akses Sekarang
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default UserRoleDetailPage;
|
||||
@@ -0,0 +1,75 @@
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { FC, ReactNode, useState } from 'react';
|
||||
import { Icons } from '@/components/Icons';
|
||||
import { AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog';
|
||||
import { type ResponseData } from '@/types/types';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
type Props = {
|
||||
title?: string;
|
||||
description?: string;
|
||||
onConfirm: () => Promise<any>;
|
||||
okText?: string;
|
||||
cancelText?: string;
|
||||
contentSuccess?: ReactNode | string;
|
||||
onOkSuccess?: () => any;
|
||||
};
|
||||
|
||||
const ConfirmAsync: FC<Props> = ({ title, description, onConfirm, okText, cancelText, contentSuccess, onOkSuccess }) => {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const router = useRouter();
|
||||
|
||||
const confirm = async () => {
|
||||
if (isLoading) return;
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const res: ResponseData = await onConfirm();
|
||||
setIsLoading(false);
|
||||
|
||||
if (!res) return;
|
||||
|
||||
if (res.code === '00' || res.code === 200) {
|
||||
showSuccess();
|
||||
} else {
|
||||
showError(res.message);
|
||||
}
|
||||
} catch (error: any) {
|
||||
setIsLoading(false);
|
||||
const message = error?.response?.data?.message || error?.message || 'Failed to delete role';
|
||||
showError(message);
|
||||
}
|
||||
};
|
||||
|
||||
const showSuccess = () => {
|
||||
router.refresh();
|
||||
toast.success(contentSuccess || 'Role successfully removed.');
|
||||
if (onOkSuccess) onOkSuccess();
|
||||
};
|
||||
|
||||
const showError = (message?: string) => {
|
||||
toast.error(message || 'Failed to delete role');
|
||||
};
|
||||
|
||||
return (
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{title || 'Are you absolutely sure?'}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{description || 'This action cannot be undone. This will permanently remove this role from our system.'}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={isLoading}>{cancelText || 'Cancel'}</AlertDialogCancel>
|
||||
<AlertDialogAction disabled={isLoading} onClick={confirm}>
|
||||
{isLoading && (
|
||||
<Icons.spinner className="mr-1 h-4 w-4 animate-spin" />
|
||||
)}
|
||||
{okText || 'Continue'}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
);
|
||||
};
|
||||
|
||||
export default ConfirmAsync;
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
'use client';
|
||||
|
||||
import React, { FC, useState, useMemo } from 'react';
|
||||
import { Checkbox, Input } from 'antd';
|
||||
import { ChevronDown, ChevronRight, Search, Shield, ShieldCheck } from 'lucide-react';
|
||||
import { type IMenu } from './type';
|
||||
import RbacBadge from '@/components/ui/rbac-badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
export interface IMenuPermissionTreeProps {
|
||||
menus: IMenu[];
|
||||
allowAdminPanel: boolean;
|
||||
// Map of menu_id -> array of selected action names
|
||||
selectedPermissions: Record<number, string[]>;
|
||||
onPermissionToggle: (menuId: number, actionName: string, checked: boolean) => void;
|
||||
onMenuSelectAll: (menuId: number, allActions: string[]) => void;
|
||||
onMenuClearAll: (menuId: number) => void;
|
||||
}
|
||||
|
||||
interface TreeNode extends IMenu {
|
||||
children?: TreeNode[];
|
||||
level: number;
|
||||
}
|
||||
|
||||
// Transform flat list to tree
|
||||
function buildTree(items: IMenu[], parentId: number | null = null, level: number = 0): TreeNode[] {
|
||||
const result: TreeNode[] = [];
|
||||
const directChildren = items.filter(i => {
|
||||
if (parentId === null) {
|
||||
return i.menu_parent_id === null || i.menu_parent_id === undefined;
|
||||
}
|
||||
return i.menu_parent_id === parentId;
|
||||
});
|
||||
|
||||
for (const item of directChildren) {
|
||||
if (item.id === undefined) continue;
|
||||
const children = buildTree(items, item.id, level + 1);
|
||||
const node: TreeNode = {
|
||||
...item,
|
||||
level,
|
||||
children: children.length > 0 ? children : undefined,
|
||||
};
|
||||
result.push(node);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export const MenuPermissionTree: FC<IMenuPermissionTreeProps> = ({
|
||||
menus,
|
||||
allowAdminPanel,
|
||||
selectedPermissions,
|
||||
onPermissionToggle,
|
||||
onMenuSelectAll,
|
||||
onMenuClearAll,
|
||||
}) => {
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [collapsedIds, setCollapsedIds] = useState<Set<number>>(new Set());
|
||||
|
||||
const toggleCollapse = (id: number) => {
|
||||
setCollapsedIds(prev => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(id)) {
|
||||
next.delete(id);
|
||||
} else {
|
||||
next.add(id);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
// Separate Non-Admin and Admin menus
|
||||
const { nonAdminTree, adminTree } = useMemo(() => {
|
||||
const nonAdminList = menus.filter(m => !m.is_admin_menu);
|
||||
const adminList = menus.filter(m => Boolean(m.is_admin_menu));
|
||||
|
||||
return {
|
||||
nonAdminTree: buildTree(nonAdminList),
|
||||
adminTree: buildTree(adminList),
|
||||
};
|
||||
}, [menus]);
|
||||
|
||||
// Filter matching IDs when searching
|
||||
const searchMatchIds = useMemo(() => {
|
||||
if (!searchQuery.trim()) return null;
|
||||
const lower = searchQuery.toLowerCase();
|
||||
const matches = new Set<number>();
|
||||
|
||||
menus.forEach(m => {
|
||||
const matchName = m.name?.toLowerCase().includes(lower);
|
||||
const matchPath = m.path_url?.toLowerCase().includes(lower);
|
||||
const matchActions = m.action?.some(a => a.toLowerCase().includes(lower));
|
||||
|
||||
if (matchName || matchPath || matchActions) {
|
||||
if (m.id !== undefined) matches.add(m.id);
|
||||
// Also add parent IDs so parent stays visible
|
||||
let parentId = m.menu_parent_id;
|
||||
while (parentId) {
|
||||
matches.add(parentId);
|
||||
const parent = menus.find(p => p.id === parentId);
|
||||
parentId = parent?.menu_parent_id;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return matches;
|
||||
}, [menus, searchQuery]);
|
||||
|
||||
// Renders a single menu row and recursively its children
|
||||
const renderNode = (node: TreeNode) => {
|
||||
if (node.id === undefined) return null;
|
||||
if (searchMatchIds && !searchMatchIds.has(node.id)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const isCollapsed = collapsedIds.has(node.id);
|
||||
const hasChildren = node.children && node.children.length > 0;
|
||||
const assignedActions = node.action || [];
|
||||
const currentSelectedActions = selectedPermissions[node.id] || [];
|
||||
const isAllSelected = assignedActions.length > 0 && assignedActions.every(a => currentSelectedActions.includes(a));
|
||||
const hasAnySelected = currentSelectedActions.length > 0;
|
||||
const isIndeterminate = hasAnySelected && !isAllSelected;
|
||||
|
||||
return (
|
||||
<React.Fragment key={node.id}>
|
||||
<div
|
||||
className={`flex flex-col sm:flex-row sm:items-center justify-between py-3 px-3 sm:px-4 border-b border-zinc-200 dark:border-zinc-800 transition-colors ${node.level === 0
|
||||
? 'bg-zinc-50/70 dark:bg-zinc-900/60 font-semibold'
|
||||
: 'bg-white dark:bg-zinc-950/40 hover:bg-zinc-50/50 dark:hover:bg-zinc-900/30'
|
||||
}`}
|
||||
>
|
||||
{/* Left: Menu Name, Hierarchy Indent & Parent indicator */}
|
||||
<div
|
||||
className="flex items-center gap-2 sm:gap-3 flex-1 min-w-0 mb-2 sm:mb-0"
|
||||
style={{ paddingLeft: `${node.level * 24}px` }}
|
||||
>
|
||||
{hasChildren ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggleCollapse(node.id!)}
|
||||
className="w-5 h-5 flex items-center justify-center text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-200 rounded"
|
||||
>
|
||||
{isCollapsed ? <ChevronRight size={15} /> : <ChevronDown size={15} />}
|
||||
</button>
|
||||
) : (
|
||||
<span className="w-5" />
|
||||
)}
|
||||
|
||||
{node.level > 0 && (
|
||||
<span className="text-zinc-400 dark:text-zinc-600 font-mono text-xs select-none">
|
||||
↳
|
||||
</span>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
{assignedActions.length > 0 && (
|
||||
<Checkbox
|
||||
checked={isAllSelected}
|
||||
indeterminate={isIndeterminate}
|
||||
onChange={(e) => {
|
||||
if (e.target.checked) {
|
||||
onMenuSelectAll(node.id!, assignedActions);
|
||||
} else {
|
||||
onMenuClearAll(node.id!);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
{node.icon && <i className={`${node.icon} text-sm text-zinc-500`} />}
|
||||
<span className="text-xs sm:text-sm font-medium text-zinc-900 dark:text-zinc-100 truncate">
|
||||
{node.name}
|
||||
</span>
|
||||
{node.is_admin_menu && (
|
||||
<span className="text-[10px] uppercase font-semibold px-1.5 py-0.2 rounded bg-indigo-500/10 text-indigo-600 dark:text-indigo-400">
|
||||
Admin
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-[11px] font-mono text-zinc-400 dark:text-zinc-500 block truncate">
|
||||
{node.path_url || '#'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right: Available Actions Checkboxes & Row Select All button */}
|
||||
<div className="flex items-center flex-wrap gap-2 sm:gap-3 sm:ml-4">
|
||||
{assignedActions.length > 0 ? (
|
||||
<>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{assignedActions.map(action => {
|
||||
const isChecked = currentSelectedActions.includes(action);
|
||||
return (
|
||||
<label
|
||||
key={action}
|
||||
className={`inline-flex items-center gap-1.5 px-2 py-1 rounded border text-xs cursor-pointer select-none transition-all ${isChecked
|
||||
? 'bg-zinc-100 dark:bg-zinc-800 border-zinc-300 dark:border-zinc-700 shadow-xs'
|
||||
: 'bg-transparent border-transparent hover:border-zinc-200 dark:hover:border-zinc-800 opacity-65 hover:opacity-100'
|
||||
}`}
|
||||
>
|
||||
<Checkbox
|
||||
checked={isChecked}
|
||||
onChange={(e) =>
|
||||
onPermissionToggle(node.id!, action, e.target.checked)
|
||||
}
|
||||
/>
|
||||
<RbacBadge permission={action} size="sm" />
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 text-xs px-2.5 ml-2"
|
||||
onClick={() => {
|
||||
if (isAllSelected) {
|
||||
onMenuClearAll(node.id!);
|
||||
} else {
|
||||
onMenuSelectAll(node.id!, assignedActions);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{isAllSelected ? 'Batal' : 'Semua'}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-xs text-zinc-400 italic px-2">
|
||||
Tidak ada aksi terkonfigurasi
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Render children recursively if not collapsed */}
|
||||
{hasChildren && !isCollapsed && node.children!.map(child => renderNode(child))}
|
||||
</React.Fragment>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col space-y-6">
|
||||
{/* Search Bar */}
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="w-full sm:w-72">
|
||||
<Input
|
||||
prefix={<Search size={14} className="text-muted-foreground mr-1" />}
|
||||
placeholder="Cari menu atau permission..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
allowClear
|
||||
className="h-9"
|
||||
/>
|
||||
</div>
|
||||
<div className="hidden sm:flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<span>Gunakan tombol</span>
|
||||
<span className="px-1.5 py-0.5 rounded bg-zinc-100 dark:bg-zinc-800 font-mono text-[11px] font-medium">Semua</span>
|
||||
<span>atau centang permission per menu</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Section 1: Non-Admin Menus */}
|
||||
<div className="border border-zinc-200 dark:border-zinc-800 rounded-lg overflow-hidden bg-white dark:bg-zinc-950">
|
||||
<div className="py-3 px-4 bg-zinc-100/80 dark:bg-zinc-900 border-b border-zinc-200 dark:border-zinc-800 flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Shield size={16} className="text-his" />
|
||||
<h4 className="text-sm font-semibold text-zinc-900 dark:text-zinc-100 m-0">
|
||||
Non-Admin Menus (General Application)
|
||||
</h4>
|
||||
</div>
|
||||
<span className="text-xs text-muted-foreground font-medium">
|
||||
{menus.filter(m => !m.is_admin_menu).length} menu
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="divide-y divide-zinc-200 dark:divide-zinc-800">
|
||||
{nonAdminTree.length > 0 ? (
|
||||
nonAdminTree.map(node => renderNode(node))
|
||||
) : (
|
||||
<div className="py-8 text-center text-xs text-muted-foreground">
|
||||
Belum ada menu Non-Admin yang terdaftar.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Section 2: Admin Menus (Rendered ONLY if allowAdminPanel === true) */}
|
||||
{allowAdminPanel && (
|
||||
<div className="border border-zinc-200 dark:border-zinc-800 rounded-lg overflow-hidden bg-white dark:bg-zinc-950">
|
||||
<div className="py-3 px-4 bg-zinc-100/80 dark:bg-zinc-900 border-b border-zinc-200 dark:border-zinc-800 flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<ShieldCheck size={16} className="text-red-600 dark:text-red-400" />
|
||||
<h4 className="text-sm font-semibold text-zinc-900 dark:text-zinc-100 m-0">
|
||||
Admin Menus (Admin Panel)
|
||||
</h4>
|
||||
</div>
|
||||
<span className="text-xs text-muted-foreground font-medium">
|
||||
{menus.filter(m => Boolean(m.is_admin_menu)).length} menu
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="divide-y divide-zinc-200 dark:divide-zinc-800">
|
||||
{adminTree.length > 0 ? (
|
||||
adminTree.map(node => renderNode(node))
|
||||
) : (
|
||||
<div className="py-8 text-center text-xs text-muted-foreground">
|
||||
Belum ada menu Admin Panel yang terdaftar.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default MenuPermissionTree;
|
||||
|
||||
@@ -0,0 +1,434 @@
|
||||
'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) {
|
||||
// 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<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
|
||||
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<string, any> = {
|
||||
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 (
|
||||
<>
|
||||
<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 User Role' : 'Create New User Role'}
|
||||
</CardTitle>
|
||||
<CardDescription className="mt-1">
|
||||
{isUpdate
|
||||
? `Configure role permissions 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}>
|
||||
Batal
|
||||
</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" />}
|
||||
Simpan Perubahan
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
|
||||
{/* Form Body */}
|
||||
<Form form={form} layout="vertical" scrollToFirstError>
|
||||
{/* Section A: General Information */}
|
||||
<Card className="mb-6">
|
||||
<CardHeader className="pb-4">
|
||||
<CardTitle className="text-base font-semibold">
|
||||
Informasi Umum (General Information)
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Masukkan nama peran, deskripsi, dan hak akses admin panel
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<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 SYSADMIN" />
|
||||
</Form.Item>
|
||||
|
||||
<div className="p-3.5 rounded-lg border border-zinc-200 dark:border-zinc-800 bg-zinc-50/60 dark:bg-zinc-900/40 flex items-center justify-between">
|
||||
<div>
|
||||
<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">
|
||||
Mengizinkan role ini mengakses menu administrasi dan admin panel
|
||||
</span>
|
||||
</div>
|
||||
<Form.Item name="allow_admin_panel" valuePropName="checked" className="mb-0">
|
||||
<Switch
|
||||
checked={allowAdminPanel}
|
||||
onChange={handleAdminToggle}
|
||||
/>
|
||||
</Form.Item>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Form.Item name="description" label="Description" className="mt-2 mb-0">
|
||||
<Input.TextArea
|
||||
className="input"
|
||||
rows={2}
|
||||
placeholder="Deskripsi tugas dan tanggung jawab role ini..."
|
||||
/>
|
||||
</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">
|
||||
Detil Hak Akses & Access Permissions
|
||||
</CardTitle>
|
||||
<CardDescription className="mt-1">
|
||||
Atur izin akses untuk setiap menu yang tersedia dalam aplikasi
|
||||
</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} menu dikonfigurasi
|
||||
</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">Memuat struktur menu dari 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}>
|
||||
Batal
|
||||
</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" />}
|
||||
Simpan Perubahan
|
||||
</Button>
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
|
||||
{/* Confirmation Dialog */}
|
||||
{showConfirm && (
|
||||
<AlertDialog open={true}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Konfirmasi Simpan Role?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Konfigurasi hak akses role ini akan disimpan dan langsung berlaku bagi pengguna yang memiliki role ini.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={isLoading} onClick={() => setShowConfirm(false)}>
|
||||
Batal
|
||||
</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" />}
|
||||
Lanjutkan
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default RoleForm;
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
'use client';
|
||||
|
||||
import { ChangeEvent, FC, useEffect, useState } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { MoreHorizontalIcon, ShieldCheck } from 'lucide-react';
|
||||
import { Table } from 'antd';
|
||||
import { TableProps, type ColumnsType } from 'antd/es/table';
|
||||
import { PlusCircledIcon } from '@radix-ui/react-icons';
|
||||
import useAxiosAuth from '@/lib/axios/useAxiosAuth';
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { AlertDialog, AlertDialogTrigger } from '@/components/ui/alert-dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import ConfirmAsync from './ConfirmAsync';
|
||||
import { type IRole } from './type';
|
||||
|
||||
type Props = {
|
||||
data: IRole[];
|
||||
};
|
||||
|
||||
const ComponentRolePage: FC<Props> = ({ data }) => {
|
||||
const [filterData, setFilterData] = useState<IRole[]>([]);
|
||||
const [searchText, setSearchText] = useState('');
|
||||
|
||||
const axios = useAxiosAuth();
|
||||
|
||||
useEffect(() => {
|
||||
if (data && Array.isArray(data)) {
|
||||
setFilterData(data);
|
||||
} else {
|
||||
setFilterData([]);
|
||||
}
|
||||
}, [data]);
|
||||
|
||||
const handleSearch = (e: ChangeEvent<HTMLInputElement>) => {
|
||||
const text = e.target.value;
|
||||
setSearchText(text);
|
||||
if (text && Array.isArray(data)) {
|
||||
const lower = text.toLowerCase();
|
||||
const filtered = data.filter(
|
||||
(item) =>
|
||||
item.name?.toLowerCase().includes(lower) ||
|
||||
item.code?.toLowerCase().includes(lower) ||
|
||||
item.description?.toLowerCase().includes(lower)
|
||||
);
|
||||
setFilterData(filtered);
|
||||
} else {
|
||||
setFilterData(data || []);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = (id: string | number) => {
|
||||
return axios.delete(`/role/${id}`).then((res) => res.data);
|
||||
};
|
||||
|
||||
const columns: ColumnsType<IRole> = [
|
||||
{
|
||||
title: 'Num',
|
||||
dataIndex: 'key',
|
||||
width: 70,
|
||||
align: 'center',
|
||||
render: (_text, _record, index) => (
|
||||
<span className="text-xs text-muted-foreground font-medium">{index + 1}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'Code',
|
||||
dataIndex: 'code',
|
||||
width: 110,
|
||||
render: (code: string) => (
|
||||
<span className="font-mono text-xs font-semibold text-zinc-600 dark:text-zinc-300">
|
||||
{code || '-'}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'Role Name',
|
||||
dataIndex: 'name',
|
||||
sorter: (a, b) => (a.name || '').localeCompare(b.name || ''),
|
||||
render: (name: string, record: IRole) => (
|
||||
<div className="flex flex-col">
|
||||
<Link
|
||||
href={`/admin/rbac/user-role/${record.id}`}
|
||||
className="font-semibold text-zinc-900 dark:text-zinc-100 hover:text-his transition-colors"
|
||||
>
|
||||
{name}
|
||||
</Link>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'Admin Panel Access',
|
||||
dataIndex: 'allow_admin_panel',
|
||||
align: 'center',
|
||||
width: 160,
|
||||
render: (_val, record: IRole) => {
|
||||
const isAllowed = Boolean(record.allow_admin_panel ?? record.allow_admin);
|
||||
return isAllowed ? (
|
||||
<span className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-semibold bg-emerald-500/10 text-emerald-600 border border-emerald-500/20 dark:bg-emerald-500/20 dark:text-emerald-300 dark:border-emerald-500/30">
|
||||
<span className="w-1.5 h-1.5 rounded-full bg-emerald-500" />
|
||||
Allowed
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-semibold bg-zinc-500/10 text-zinc-500 border border-zinc-500/20 dark:bg-zinc-500/20 dark:text-zinc-400 dark:border-zinc-500/30">
|
||||
<span className="w-1.5 h-1.5 rounded-full bg-zinc-400" />
|
||||
Restricted
|
||||
</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: 'Assigned Menus',
|
||||
dataIndex: 'role_detail',
|
||||
align: 'center',
|
||||
width: 140,
|
||||
render: (details: any, record: IRole) => {
|
||||
const count = Array.isArray(details)
|
||||
? details.length
|
||||
: Array.isArray(record.privilege)
|
||||
? record.privilege.length
|
||||
: 0;
|
||||
return (
|
||||
<span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-zinc-100 dark:bg-zinc-800 text-zinc-700 dark:text-zinc-300">
|
||||
{count} menus
|
||||
</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: 'Description',
|
||||
dataIndex: 'description',
|
||||
render: (desc: string) => (
|
||||
<span className="text-xs text-muted-foreground line-clamp-2 max-w-sm">
|
||||
{desc || '-'}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'Action',
|
||||
key: 'action',
|
||||
width: 80,
|
||||
align: 'center',
|
||||
render: (_, record) => (
|
||||
<AlertDialog>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8">
|
||||
<MoreHorizontalIcon className="h-4 w-4" />
|
||||
<span className="sr-only">Role Action</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`/admin/rbac/user-role/${record.id}`}>
|
||||
View Detail
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`/admin/rbac/user-role/edit/${record.id}`}>
|
||||
Edit Role
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<AlertDialogTrigger asChild>
|
||||
<DropdownMenuItem className="text-rose-600 dark:text-rose-400">
|
||||
Delete Role
|
||||
</DropdownMenuItem>
|
||||
</AlertDialogTrigger>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<ConfirmAsync
|
||||
title="Delete Role?"
|
||||
description={`Are you sure you want to delete role "${record.name}"? Users with this role may lose their access permissions.`}
|
||||
onConfirm={() => handleDelete(record.id!)}
|
||||
onOkSuccess={() => { }}
|
||||
/>
|
||||
</AlertDialog>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const tableProps: TableProps<IRole> = {
|
||||
bordered: false,
|
||||
size: 'small',
|
||||
showHeader: true,
|
||||
pagination: {
|
||||
pageSizeOptions: [10, 20, 50],
|
||||
defaultPageSize: 10,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
size: 'middle' as any,
|
||||
},
|
||||
scroll: { x: 'max-content' },
|
||||
tableLayout: 'auto',
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col space-y-4">
|
||||
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
|
||||
<div className="flex flex-1 items-center space-x-2 w-full sm:w-auto">
|
||||
<Input
|
||||
placeholder="Search role name, code, description..."
|
||||
className="h-8 w-full sm:w-64"
|
||||
value={searchText}
|
||||
onChange={handleSearch}
|
||||
/>
|
||||
</div>
|
||||
<Link href="/admin/rbac/user-role/create">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-8 text-his hover:text-his hover:bg-his/10 font-semibold"
|
||||
>
|
||||
<PlusCircledIcon className="mr-2 h-4 w-4" />
|
||||
Create New Role
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<Table
|
||||
{...tableProps}
|
||||
rowKey="id"
|
||||
columns={columns}
|
||||
dataSource={filterData || []}
|
||||
locale={{
|
||||
emptyText: (
|
||||
<div className="py-8 text-center text-muted-foreground">
|
||||
<ShieldCheck className="h-8 w-8 mx-auto mb-2 text-zinc-400" />
|
||||
<p className="text-sm font-medium">No roles found</p>
|
||||
<p className="text-xs text-zinc-400 mt-1">
|
||||
{searchText ? 'Try adjusting your search query.' : 'Click "Create New Role" to define user access roles.'}
|
||||
</p>
|
||||
</div>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ComponentRolePage;
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { type IRole, type IRoleDetail, type IMenu } from "@/types/rbac";
|
||||
|
||||
export type { IRole, IRoleDetail, IMenu };
|
||||
|
||||
export interface IMenuTreeNode extends IMenu {
|
||||
children?: IMenuTreeNode[];
|
||||
level?: number;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import { type Metadata } from 'next';
|
||||
import RoleForm from '../component/RoleForm';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Create User Role | Admin",
|
||||
description: "Create a new user role with custom menu permissions",
|
||||
};
|
||||
|
||||
export default function CreateRolePage() {
|
||||
return <RoleForm isUpdate={false} />;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { type Metadata } from 'next';
|
||||
import fetchData from '@/lib/fetchData';
|
||||
import RoleForm from '../../component/RoleForm';
|
||||
import { type IRole } from '../../component/type';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Edit User Role | Admin",
|
||||
description: "Update role permissions and configuration",
|
||||
};
|
||||
|
||||
type Props = {
|
||||
params: Promise<{ id: string }>;
|
||||
};
|
||||
|
||||
async function getRoleData(id: string): Promise<IRole | undefined> {
|
||||
try {
|
||||
const res = await fetchData(`/role/${id}`, 'no-cache');
|
||||
if (res) {
|
||||
if (res.role) return res.role;
|
||||
return res;
|
||||
}
|
||||
} catch {
|
||||
// Fallback: search in role list
|
||||
try {
|
||||
const list = await fetchData('/role', 'no-cache');
|
||||
const roles = Array.isArray(list) ? list : (list?.role || list?.roles || []);
|
||||
return roles.find((r: any) => String(r.id) === String(id));
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export default async function EditRolePage({ params }: Props) {
|
||||
const { id } = await params;
|
||||
const roleData = await getRoleData(id);
|
||||
|
||||
return (
|
||||
<RoleForm
|
||||
isUpdate={true}
|
||||
roleId={id}
|
||||
initialData={roleData}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { type Metadata } from 'next';
|
||||
import { Suspense, lazy } from 'react';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import LazyLoading from '@/components/loader/LazyLoading';
|
||||
import fetchData from '@/lib/fetchData';
|
||||
|
||||
const ComponentPage = lazy(() => import('./component'));
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "User Role Management | Admin",
|
||||
description: "Manage system user roles, admin panel access, and menu permissions",
|
||||
};
|
||||
|
||||
async function getRoles() {
|
||||
try {
|
||||
const res = await fetchData('/role', 'no-cache');
|
||||
if (Array.isArray(res)) return res;
|
||||
if (res && Array.isArray(res.role)) return res.role;
|
||||
if (res && Array.isArray(res.roles)) return res.roles;
|
||||
return [];
|
||||
} catch (error) {
|
||||
console.error('Failed to load roles:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export default async function UserRolePage() {
|
||||
const roles = await getRoles();
|
||||
|
||||
return (
|
||||
<div className="flex flex-col">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0">
|
||||
<div>
|
||||
<CardTitle>User Role</CardTitle>
|
||||
<CardDescription className="mt-1">
|
||||
List of registered user roles and permission sets
|
||||
</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Suspense fallback={<LazyLoading />}>
|
||||
<ComponentPage data={roles} />
|
||||
</Suspense>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import React from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export type RbacBadgeProps = {
|
||||
permission: string;
|
||||
className?: string;
|
||||
size?: 'sm' | 'md';
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns badge styling based on permission keyword hierarchy:
|
||||
* - VIEW: Primary / HIS (#EA512C)
|
||||
* - CREATE / ADD: Sky
|
||||
* - UPDATE / EDIT: Teal / Emerald
|
||||
* - DELETE / REMOVE: Rose
|
||||
* - PASSWORD: Amber / Yellow
|
||||
* - APPROVE / APPROVAL: Violet
|
||||
* - EXPORT: Fuchsia
|
||||
* - Other: Cyan (fallback)
|
||||
*/
|
||||
export function getPermissionBadgeClass(permission: string): string {
|
||||
const upper = (permission || '').toUpperCase();
|
||||
|
||||
// Specific multi-word keywords first
|
||||
if (upper.includes('PASSWORD')) {
|
||||
return 'bg-amber-500/10 text-amber-600 border-amber-500/20 dark:bg-amber-500/20 dark:text-amber-300 dark:border-amber-500/30';
|
||||
}
|
||||
if (upper.includes('APPROVE') || upper.includes('APPROVAL')) {
|
||||
return 'bg-fuchsia-500/10 text-fuchsia-600 border-fuchsia-500/20 dark:bg-fuchsia-500/20 dark:text-fuchsia-300 dark:border-fuchsia-500/30';
|
||||
}
|
||||
if (upper.includes('EXPORT')) {
|
||||
return 'bg-purple-500/10 text-purple-600 border-purple-500/20 dark:bg-purple-500/20 dark:text-purple-300 dark:border-purple-500/30';
|
||||
}
|
||||
if (upper.includes('DELETE') || upper.includes('REMOVE')) {
|
||||
return 'bg-rose-500/10 text-rose-600 border-rose-500/20 dark:bg-rose-500/20 dark:text-rose-300 dark:border-rose-500/30';
|
||||
}
|
||||
if (upper.includes('UPDATE') || upper.includes('EDIT')) {
|
||||
return 'bg-emerald-500/10 text-emerald-600 border-emerald-500/20 dark:bg-emerald-500/20 dark:text-emerald-300 dark:border-emerald-500/30';
|
||||
}
|
||||
if (upper.includes('CREATE') || upper.includes('ADD')) {
|
||||
return 'bg-sky-500/10 text-sky-600 border-sky-500/20 dark:bg-sky-500/20 dark:text-sky-300 dark:border-sky-500/30';
|
||||
}
|
||||
if (upper.includes('VIEW') || upper.includes('READ')) {
|
||||
// Primary / HIS theme color (#EA512C)
|
||||
return 'bg-his/10 text-his border-his/20 dark:bg-his/20 dark:text-orange-300 dark:border-his/30';
|
||||
}
|
||||
|
||||
// Default / Other: Cyan
|
||||
return 'bg-cyan-500/10 text-cyan-700 border-cyan-500/20 dark:bg-cyan-500/20 dark:text-cyan-300 dark:border-cyan-500/30';
|
||||
}
|
||||
|
||||
export const RbacBadge: React.FC<RbacBadgeProps> = ({
|
||||
permission,
|
||||
className,
|
||||
size = 'sm',
|
||||
}) => {
|
||||
if (!permission) return null;
|
||||
|
||||
const sizeClasses = size === 'sm' ? 'px-2 py-0.5 text-[11px] leading-4' : 'px-2.5 py-1 text-xs leading-4';
|
||||
|
||||
const colorClasses = getPermissionBadgeClass(permission);
|
||||
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
'inline-flex items-center font-semibold rounded-sm border transition-colors select-none tracking-wide uppercase',
|
||||
sizeClasses,
|
||||
colorClasses,
|
||||
className
|
||||
)}
|
||||
>
|
||||
{permission}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
export default RbacBadge;
|
||||
|
||||
+20
-36
@@ -1,4 +1,4 @@
|
||||
import { LayoutDashboard, Settings, MonitorSmartphone, Database, ShieldAlert, FileText, Circle, ScanFace, MenuSquare, CalendarX2, FolderGit2 } from 'lucide-react'
|
||||
import { LayoutDashboard, Settings, MonitorSmartphone, Database, ShieldAlert, FileText, ScanFace, MenuSquare, CalendarX2, FolderGit2, ShieldCheck } from 'lucide-react'
|
||||
|
||||
const SIDEBAR_MENU = [
|
||||
{
|
||||
@@ -29,6 +29,25 @@ const SIDEBAR_MENU = [
|
||||
},
|
||||
]
|
||||
},
|
||||
{
|
||||
title: "RBAC",
|
||||
Icon: <ShieldCheck size={18} />,
|
||||
submenuId: 7,
|
||||
submenuItems: [
|
||||
{
|
||||
title: "Access Permissions",
|
||||
path: '/rbac/action-pemission'
|
||||
},
|
||||
{
|
||||
title: "Menu Management",
|
||||
path: '/rbac/menu'
|
||||
},
|
||||
{
|
||||
title: "User Role",
|
||||
path: '/rbac/user-role'
|
||||
},
|
||||
]
|
||||
},
|
||||
{
|
||||
title: "Device",
|
||||
Icon: <MonitorSmartphone size={18} />,
|
||||
@@ -138,10 +157,6 @@ const SIDEBAR_MENU = [
|
||||
title: "Working Status",
|
||||
path: '/information/working-status'
|
||||
},
|
||||
{
|
||||
title: "User Role",
|
||||
path: '/information/user-role'
|
||||
},
|
||||
{
|
||||
title: "Employee Position",
|
||||
path: '/information/position'
|
||||
@@ -152,37 +167,6 @@ const SIDEBAR_MENU = [
|
||||
},
|
||||
]
|
||||
},
|
||||
// {
|
||||
// title: "Test",
|
||||
// Icon: <Circle size={18} />,
|
||||
// submenuId: 3,
|
||||
// submenuItems: [
|
||||
// {
|
||||
// title: "Submenu 1",
|
||||
// path: '/submenu-1'
|
||||
// },
|
||||
// {
|
||||
// title: "Submenu 2",
|
||||
// path: '/submenu-2'
|
||||
// },
|
||||
// {
|
||||
// title: "Submenu 3",
|
||||
// submenu: true,
|
||||
// submenuId: 101,
|
||||
// submenuItems: [
|
||||
// {
|
||||
// title: "Test",
|
||||
// path: '/submenu'
|
||||
// },
|
||||
// {
|
||||
// title: "Sub Submenu 2",
|
||||
// path: '/sub-submenu-2'
|
||||
// }
|
||||
// ]
|
||||
// }
|
||||
// ]
|
||||
// },
|
||||
|
||||
]
|
||||
|
||||
export default SIDEBAR_MENU
|
||||
@@ -0,0 +1,70 @@
|
||||
export interface ITablerIconOption {
|
||||
label: string;
|
||||
value: string;
|
||||
category?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard registry of Tabler Icons (Webfont v3.35.0).
|
||||
* Expandable anytime without modifying form components.
|
||||
*/
|
||||
export const TABLER_ICON_OPTIONS: ITablerIconOption[] = [
|
||||
// Navigation & General
|
||||
{ label: 'Category', value: 'ti ti-category', category: 'General' },
|
||||
{ label: 'Overview', value: 'ti ti-layers-linked', category: 'General' },
|
||||
{ label: 'Dashboard', value: 'ti ti-layout-dashboard', category: 'General' },
|
||||
{ label: 'Home', value: 'ti ti-home', category: 'General' },
|
||||
{ label: 'Menu', value: 'ti ti-menu-2', category: 'General' },
|
||||
{ label: 'Settings', value: 'ti ti-settings', category: 'General' },
|
||||
{ label: 'Adjustments', value: 'ti ti-adjustments', category: 'General' },
|
||||
{ label: 'Search', value: 'ti ti-search', category: 'General' },
|
||||
|
||||
// Administration & Users
|
||||
{ label: 'User Hexagon', value: 'ti ti-user-hexagon', category: 'Administration' },
|
||||
{ label: 'User', value: 'ti ti-user', category: 'Administration' },
|
||||
{ label: 'Users', value: 'ti ti-users', category: 'Administration' },
|
||||
{ label: 'User Shield', value: 'ti ti-user-shield', category: 'Administration' },
|
||||
{ label: 'User Check', value: 'ti ti-user-check', category: 'Administration' },
|
||||
{ label: 'Shield Lock', value: 'ti ti-shield-lock', category: 'Administration' },
|
||||
{ label: 'Key', value: 'ti ti-key', category: 'Administration' },
|
||||
{ label: 'Lock', value: 'ti ti-lock', category: 'Administration' },
|
||||
{ label: 'Building', value: 'ti ti-building', category: 'Administration' },
|
||||
{ label: 'Building Community', value: 'ti ti-building-community', category: 'Administration' },
|
||||
{ label: 'Map Pin', value: 'ti ti-map-pin', category: 'Administration' },
|
||||
{ label: 'Sitemap', value: 'ti ti-sitemap', category: 'Administration' },
|
||||
|
||||
// Data, System & Tech
|
||||
{ label: 'Database', value: 'ti ti-database', category: 'System' },
|
||||
{ label: 'Server', value: 'ti ti-server', category: 'System' },
|
||||
{ label: 'Devices', value: 'ti ti-devices', category: 'System' },
|
||||
{ label: 'Devices 2', value: 'ti ti-devices-2', category: 'System' },
|
||||
{ label: 'Device Mobile', value: 'ti ti-device-mobile', category: 'System' },
|
||||
{ label: 'Cpu', value: 'ti ti-cpu', category: 'System' },
|
||||
{ label: 'Activity', value: 'ti ti-activity', category: 'System' },
|
||||
{ label: 'History', value: 'ti ti-history', category: 'System' },
|
||||
|
||||
// Tasks & Operations
|
||||
{ label: 'Clipboard List', value: 'ti ti-clipboard-list', category: 'Operations' },
|
||||
{ label: 'Clipboard Check', value: 'ti ti-clipboard-check', category: 'Operations' },
|
||||
{ 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: 'Clock', value: 'ti ti-clock', category: 'Operations' },
|
||||
{ label: 'Checklist', value: 'ti ti-checklist', category: 'Operations' },
|
||||
|
||||
// Reports & Analytics
|
||||
{ label: 'Chart Bar', value: 'ti ti-chart-bar', category: 'Reports' },
|
||||
{ label: 'Chart Pie', value: 'ti ti-chart-pie', category: 'Reports' },
|
||||
{ label: 'Report Analytics', value: 'ti ti-report-analytics', category: 'Reports' },
|
||||
{ label: 'File Text', value: 'ti ti-file-text', category: 'Reports' },
|
||||
{ label: 'File Spreadsheet', value: 'ti ti-file-spreadsheet', category: 'Reports' },
|
||||
{ label: 'File Description', value: 'ti ti-file-description', category: 'Reports' },
|
||||
|
||||
// Communication & Badges
|
||||
{ label: 'Id Badge', value: 'ti ti-id-badge', category: 'Security' },
|
||||
{ label: 'Credit Card', value: 'ti ti-credit-card', category: 'Security' },
|
||||
{ label: 'Scan', value: 'ti ti-scan', category: 'Security' },
|
||||
{ label: 'Fingerprint', value: 'ti ti-fingerprint', category: 'Security' },
|
||||
{ label: 'Bell', value: 'ti ti-bell', category: 'General' },
|
||||
];
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
export interface IPermission {
|
||||
id?: number;
|
||||
name: string;
|
||||
description?: string;
|
||||
status?: {
|
||||
id?: number;
|
||||
code?: string;
|
||||
name?: string;
|
||||
};
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
export interface IMenu {
|
||||
id?: number;
|
||||
code?: string;
|
||||
name: string;
|
||||
path_url: string;
|
||||
description?: string;
|
||||
icon?: string;
|
||||
is_admin_menu?: boolean;
|
||||
menu_parent_id?: number | null;
|
||||
action?: string[];
|
||||
status?: {
|
||||
id?: number;
|
||||
code?: string;
|
||||
name?: string;
|
||||
};
|
||||
children?: IMenu[];
|
||||
menu_level?: number;
|
||||
}
|
||||
|
||||
export interface IRoleDetail {
|
||||
menu_id: number;
|
||||
menu_name: string;
|
||||
menu_path: string;
|
||||
is_admin_menu: boolean;
|
||||
action: string[];
|
||||
}
|
||||
|
||||
export interface IRole {
|
||||
id?: number;
|
||||
code?: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
allow_admin_panel?: boolean;
|
||||
allow_admin?: boolean;
|
||||
role_detail?: IRoleDetail[];
|
||||
privilege?: any[];
|
||||
status?: {
|
||||
id?: number;
|
||||
code?: string;
|
||||
name?: string;
|
||||
};
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user