diff --git a/.agents/skills/karpathy-guidelines/SKILL.md b/.agents/skills/karpathy-guidelines/SKILL.md new file mode 100644 index 0000000..9f945db --- /dev/null +++ b/.agents/skills/karpathy-guidelines/SKILL.md @@ -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. \ No newline at end of file diff --git a/app/admin/components/Breadcrumb.tsx b/app/admin/components/Breadcrumb.tsx new file mode 100644 index 0000000..e78247f --- /dev/null +++ b/app/admin/components/Breadcrumb.tsx @@ -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 ( +
+ Pages + / + Dashboard +
+ ); + } + + return ( +
+ + Pages + + {segments.map((seg, idx) => { + const isLast = idx === segments.length - 1; + const href = '/admin/' + segments.slice(0, idx + 1).join('/'); + + return ( + + / + {isLast ? ( + + {formatSegment(seg)} + + ) : ( + + {formatSegment(seg)} + + )} + + ); + })} +
+ ); +} + diff --git a/app/admin/components/SidebarItem.tsx b/app/admin/components/SidebarItem.tsx index e390685..866af7d 100644 --- a/app/admin/components/SidebarItem.tsx +++ b/app/admin/components/SidebarItem.tsx @@ -41,7 +41,13 @@ const SidebarItem: FC = ({ 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 = ({ menu, expand, onChangeExpand }) => { {submenuItems && submenuItems.length > 0 && submenuIdActive?.includes(submenuId) && expand && = ({ menu, expand, onChangeExpand }) => { ); } -export default SidebarItem; \ No newline at end of file +export default SidebarItem; diff --git a/app/admin/information/user-role/component/Form.tsx b/app/admin/information/user-role/component/Form.tsx index 7c9c0dd..c3e8370 100644 --- a/app/admin/information/user-role/component/Form.tsx +++ b/app/admin/information/user-role/component/Form.tsx @@ -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([]) - - 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 ( - -
- - {isUpdate ? 'Update role' : 'Create new role'} - - Add or update a role and adjust the privilege - - -
-
- - - - - - -
- - - - - setAllowAdmin(e.target.value)}> - Dissallow - Allow - - -
- - {allowAdmin && -
- - {/* HEADER */} -
- Menu Name - {LIST_ACTION_DATA.map((action) => -
- handleCheckAllAction(action, e.target.checked)}> - {action.name} - -
- )} -
- - {/* BODY */} - {privilegeMenus.length > 0 && privilegeMenus.map((menu: IMenuAction, key: number) => - // -
-
- 0} onChange={(e) => handleCheckMenu(menu, e.target.checked)} disabled={disableCheckAction(menu)} - > - {menu.name} - -
- -
- handleCheckAction(menu, val)} disabled={disableCheckAction(menu)} - > - {LIST_ACTION_DATA?.length > 0 && LIST_ACTION_DATA.map((item: any, key: number) => -
- -
- )} -
-
-
- )} - -
- } - - - - - -
-
- ) -} - -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 = ({ menu, className, onMenuChecked, onActionChecked }) => { - return ( - <> -
-
- onMenuChecked(menu, e.target.checked)}> - {menu.name} - -
- - - console.log(e)}> - {LIST_ACTION_DATA?.length > 0 && LIST_ACTION_DATA.map((item: any, key: number) => -
- onActionChecked(menu, item, e.target.checked)}> -
- )} -
-
-
- - {menu.children && menu.children.length > 0 && menu.children.map((item) => - - )} - - ) -} \ No newline at end of file +export { default } from '@/app/admin/rbac/user-role/component/RoleForm'; diff --git a/app/admin/information/user-role/component/index.tsx b/app/admin/information/user-role/component/index.tsx index 0cce9cb..4805002 100644 --- a/app/admin/information/user-role/component/index.tsx +++ b/app/admin/information/user-role/component/index.tsx @@ -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 = ({ data }) => { - const [filterData, setFilterData] = useState([]) - const [showFormDialog, setShowFormDialog] = useState(false) - const [selectedData, setSelectedData] = useState(undefined) - - const axios = useAxiosAuth() - - useEffect(() => { - if (data) { - setFilterData(data) - } - }, [data]) - - const handleSearch = (e: ChangeEvent) => { - 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 = [ - { - 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) => ( -
- {record.status.code === 'A' ? -
{record.status.name}
- : -
{record.status.name}
- } -
- ) - }, - { - title: 'Description', - dataIndex: 'description', - }, - { - title: 'Action', - key: 'action', - render: (_, record) => ( - - - - - - - {/* { setShowFormDialog(true); setSelectedData(record) }} >Edit */} - { setShowFormDialog(true); setSelectedData(JSON.parse(localStorage.getItem('role_test') as string)) }} >Edit - - Delete - - - - handleDelete(record.id)} - onOkSuccess={() => { }} - /> - - ), - }, - ]; - - const tableProps: TableProps = { - 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 ( - <> -
-
-
- -
- -
- - - {showFormDialog && - { - if (state === false) setSelectedData(undefined) - setShowFormDialog(state) - }}> - { setSelectedData(undefined); setShowFormDialog(false); }} /> - - } - - ); -} - -export default ComponentRolePage; \ No newline at end of file +export { default } from '@/app/admin/rbac/user-role/component'; diff --git a/app/admin/information/user-role/component/type.ts b/app/admin/information/user-role/component/type.ts new file mode 100644 index 0000000..d3a4c18 --- /dev/null +++ b/app/admin/information/user-role/component/type.ts @@ -0,0 +1,4 @@ +import { type IRole } from '@/types/rbac'; + +export type { IRole }; + diff --git a/app/admin/information/user-role/page.tsx b/app/admin/information/user-role/page.tsx index d7b5a11..c31ef08 100644 --- a/app/admin/information/user-role/page.tsx +++ b/app/admin/information/user-role/page.tsx @@ -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", +export default function DeprecatedUserRolePage() { + redirect('/admin/rbac/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 ( - <> -
- - -
- User Role - Here's a list of roles that have been registered! -
-
- - }> - - - -
-
- - ); -} \ No newline at end of file diff --git a/app/admin/layout.tsx b/app/admin/layout.tsx index 9961f7a..8f87dce 100644 --- a/app/admin/layout.tsx +++ b/app/admin/layout.tsx @@ -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 */}
- Pages / Dashboard +
@@ -56,4 +57,4 @@ export default async function AdminLayout({ ); -} \ No newline at end of file +} diff --git a/app/admin/menu/component/Form.tsx b/app/admin/menu/component/Form.tsx deleted file mode 100644 index 9365423..0000000 --- a/app/admin/menu/component/Form.tsx +++ /dev/null @@ -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 ( - -
- - {isUpdate ? 'Update menu' : 'Create menu'} - - Add a new team to manage products and customers - - -
- - - -
- - - - - - -
- - - - - - Hidden - Visible - - - - - -
- - - - - -
- ) -} \ No newline at end of file diff --git a/app/admin/menu/component/index.tsx b/app/admin/menu/component/index.tsx deleted file mode 100644 index 8f5fb1a..0000000 --- a/app/admin/menu/component/index.tsx +++ /dev/null @@ -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 = ({ data }) => { - const [filterData, setFilterData] = useState([]) - const [selectedData, setSelectedData] = useState(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) => { - 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 = [ - { - 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) => ( -
- {record.status.code === 'A' ? -
{record.status.name}
- : -
{record.status.name}
- } -
- ) - }, - { - title: 'Description', - dataIndex: 'description', - }, - { - title: 'Action', - key: 'action', - render: (_, record) => ( - - - - - - - { }}>View - { setShowFormDialog(true); setSelectedData(record) }} >Edit - - Delete - - - - handleDelete(record.id)} - onOkSuccess={() => { }} - /> - - ), - }, - ]; - - const tableProps: TableProps = { - 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 ( - <> -
-
-
- -
- -
-
- - - { - if (state === false) setSelectedData(undefined) - setShowFormDialog(state) - }}> - - - - ); -} - -export default ComponentPage; \ No newline at end of file diff --git a/app/admin/menu/component/type.tsx b/app/admin/menu/component/type.tsx deleted file mode 100644 index 7622fab..0000000 --- a/app/admin/menu/component/type.tsx +++ /dev/null @@ -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[] -} \ No newline at end of file diff --git a/app/admin/menu/page.tsx b/app/admin/menu/page.tsx deleted file mode 100644 index d309427..0000000 --- a/app/admin/menu/page.tsx +++ /dev/null @@ -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 ( - <> -
- - -
- Menu - Here's a list of menus that have been registered! -
-
- -
-
- - }> - - - -
-
- - ); -} \ No newline at end of file diff --git a/app/admin/rbac/action-permissions/component/ConfirmAsync.tsx b/app/admin/rbac/action-permissions/component/ConfirmAsync.tsx new file mode 100644 index 0000000..a52010b --- /dev/null +++ b/app/admin/rbac/action-permissions/component/ConfirmAsync.tsx @@ -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; + okText?: string; + cancelText?: string; + contentSuccess?: ReactNode | string; + onOkSuccess?: () => any; +}; + +const ConfirmAsync: FC = ({ 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 ( + + + {title || 'Are you absolutely sure?'} + + {description || 'This action cannot be undone. This will permanently delete this permission from the system.'} + + + + {cancelText || 'Cancel'} + + {isLoading && ( + + )} + {okText || 'Continue'} + + + + ); +}; + +export default ConfirmAsync; + diff --git a/app/admin/rbac/action-permissions/component/Form.tsx b/app/admin/rbac/action-permissions/component/Form.tsx new file mode 100644 index 0000000..fa489e2 --- /dev/null +++ b/app/admin/rbac/action-permissions/component/Form.tsx @@ -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 ( + + +
+ + + {isUpdate ? 'Edit Access Permission' : 'Create Access Permission'} + + + Define an actionable permission identifier used by role-based access control. + + + +
+ + setPreviewName(e.target.value.toUpperCase())} + /> + + + {previewName && ( +
+ Badge Preview: + +
+ )} + + + + +
+ + + + + + +
+
+ ); +} + diff --git a/app/admin/rbac/action-permissions/component/index.tsx b/app/admin/rbac/action-permissions/component/index.tsx new file mode 100644 index 0000000..d89d75c --- /dev/null +++ b/app/admin/rbac/action-permissions/component/index.tsx @@ -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 = ({ data }) => { + const [filterData, setFilterData] = useState([]); + const [selectedData, setSelectedData] = useState(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) => { + 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 = [ + { + title: 'Num', + dataIndex: 'key', + width: 70, + align: 'center', + render: (_text, _record, index) => ( + {index + 1} + ), + }, + { + title: 'Permission Name', + dataIndex: 'name', + sorter: (a, b) => (a.name || '').localeCompare(b.name || ''), + render: (text: string) => ( +
+ +
+ ), + }, + { + title: 'Description', + dataIndex: 'description', + render: (text: string) => ( + + {text || '-'} + + ), + }, + { + title: 'Action', + key: 'action', + width: 80, + align: 'center', + render: (_, record) => ( + + + + + + + { + setSelectedData(record); + setShowFormDialog(true); + }} + > + Edit + + + + Delete + + + + + handleDelete(record.id)} + onOkSuccess={() => { }} + /> + + ), + }, + ]; + + const tableProps: TableProps = { + 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 ( + <> +
+
+
+ +
+ +
+ +
+ +

No permissions found

+

+ {searchText ? 'Try adjusting your search criteria.' : 'Click "Create New Permission" to add the first permission.'} +

+ + ), + }} + /> + + + {showFormDialog ? + + : null + } + + ); +}; + +export default ComponentPermissionPage; + diff --git a/app/admin/rbac/action-permissions/component/type.ts b/app/admin/rbac/action-permissions/component/type.ts new file mode 100644 index 0000000..22fe48d --- /dev/null +++ b/app/admin/rbac/action-permissions/component/type.ts @@ -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; +} + diff --git a/app/admin/rbac/action-permissions/page.tsx b/app/admin/rbac/action-permissions/page.tsx new file mode 100644 index 0000000..a427e5d --- /dev/null +++ b/app/admin/rbac/action-permissions/page.tsx @@ -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 ( +
+ + +
+ Access Permissions + + List of action permissions for Role-Based Access Control + +
+
+ + }> + + + +
+
+ ); +} diff --git a/app/admin/menu/component/ConfirmAsync.tsx b/app/admin/rbac/menu/component/ConfirmAsync.tsx similarity index 60% rename from app/admin/menu/component/ConfirmAsync.tsx rename to app/admin/rbac/menu/component/ConfirmAsync.tsx index f281bd9..29051b2 100644 --- a/app/admin/menu/component/ConfirmAsync.tsx +++ b/app/admin/rbac/menu/component/ConfirmAsync.tsx @@ -6,49 +6,48 @@ import { type ResponseData } from '@/types/types'; import { toast } from 'sonner'; type Props = { - title?: string - description?: string - onConfirm: () => Promise - okText?: string - cancelText?: string - contentSuccess?: ReactNode | string - onOkSuccess?: () => any + title?: string; + description?: string; + onConfirm: () => Promise; + okText?: string; + cancelText?: string; + contentSuccess?: ReactNode | string; + onOkSuccess?: () => any; }; const ConfirmAsync: FC = ({ 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 = ({ title, description, onConfirm, okText, cancel {title || 'Are you absolutely sure?'} - {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.'} @@ -70,6 +69,6 @@ const ConfirmAsync: FC = ({ title, description, onConfirm, okText, cancel ); -} +}; -export default ConfirmAsync; \ No newline at end of file +export default ConfirmAsync; diff --git a/app/admin/rbac/menu/component/Form.tsx b/app/admin/rbac/menu/component/Form.tsx new file mode 100644 index 0000000..d96fb56 --- /dev/null +++ b/app/admin/rbac/menu/component/Form.tsx @@ -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 { + const descendants = new Set(); + 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(''); + 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(); + 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 = { + 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) => { + 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) => { + 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 ( + <> + +
+ + + {isUpdate ? 'Edit Menu' : 'Create New Menu'} + + + Configure menu routing, hierarchy, tabler icon, and assigned permissions. + + + +
+ + + + + + + + + + triggerNode.parentNode} + onChange={(val) => setSelectedIcon(val || '')} + options={TABLER_ICON_OPTIONS.map(opt => ({ + label: ( +
+ + {opt.label} + {opt.value} +
+ ), + value: opt.value, + }))} + /> +
+ +
+
+ + Admin Panel Menu + + + When enabled, this menu is treated as part of the Admin Panel and governed by Allow Admin Panel permission. + +
+ + + +
+ +
+ + +
+ +
+ +
+ +

No menus registered

+

+ {searchText ? 'No menu matching your search.' : 'Click "Create New Menu" to register your first navigation menu.'} +

+ + ), + }} + /> + + + { + if (!state) setSelectedData(undefined); + setShowFormDialog(state); + }} + > + + + + ); +}; + +export default ComponentMenuPage; diff --git a/app/admin/rbac/menu/component/type.tsx b/app/admin/rbac/menu/component/type.tsx new file mode 100644 index 0000000..9b13ccf --- /dev/null +++ b/app/admin/rbac/menu/component/type.tsx @@ -0,0 +1,7 @@ +import { type IMenu, type IPermission } from "@/types/rbac"; + +export type { IMenu, IPermission }; + +export interface IMenuAction extends IMenu { + children?: IMenuAction[]; +} diff --git a/app/admin/rbac/menu/page.tsx b/app/admin/rbac/menu/page.tsx new file mode 100644 index 0000000..3756472 --- /dev/null +++ b/app/admin/rbac/menu/page.tsx @@ -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 ( +
+ + +
+ Menu Management + + List of registered navigation menus and their access permissions + +
+
+ + }> + + + +
+
+ ); +} diff --git a/app/admin/rbac/user-role/[id]/page.tsx b/app/admin/rbac/user-role/[id]/page.tsx new file mode 100644 index 0000000..5771c20 --- /dev/null +++ b/app/admin/rbac/user-role/[id]/page.tsx @@ -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 = 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 ( +
+ {/* Header & Overview Card */} + + +
+ + + +
+ Access and Permissions + + Informasi detail konfigurasi hak akses dan izin menu untuk peran ini + +
+
+ + + +
+ +
+
+ + Kode Peran + + + {data?.code || `ROLE-${id}`} + +
+
+ + Nama Hak Akses + + + {data?.name || '-'} + +
+
+ + Akses Admin Panel + +
+ {isAdminAllowed ? ( + + + Admin Panel + + ) : ( + + + General Access Only + + )} +
+
+
+ + Status + +
+ + + {data?.status?.name || 'Aktif'} + +
+
+
+ + Deskripsi + + + {data?.description || 'Tidak ada deskripsi.'} + +
+
+
+
+ + {/* Menu Permissions List */} + + +
+
+ + + Daftar Izin Menu & Aksi ({roleDetails.length} Menu Diizinkan) + +
+
+
+ + {roleDetails.length > 0 ? ( +
+
+ + + + + + + + + {roleDetails.map((detail, idx) => ( + + + + + + ))} + +
NoMenu Aplikasi (Hierarki)Aksi yang Diizinkan
+ {idx + 1} + +
+
+ + {detail.menu_name} + + + {detail.menu_path} + +
+ {detail.is_admin_menu && ( + + Admin + + )} +
+
+
+ {detail.action && detail.action.length > 0 ? ( + detail.action.map(action => ( + + )) + ) : ( + + Akses Menu Saja (Tanpa Aksi Spesifik) + + )} +
+
+
+ ) : ( +
+ +

Belum ada menu atau izin yang dikonfigurasi untuk role ini.

+ + + +
+ )} + + + + ); +}; + +export default UserRoleDetailPage; diff --git a/app/admin/rbac/user-role/component/ConfirmAsync.tsx b/app/admin/rbac/user-role/component/ConfirmAsync.tsx new file mode 100644 index 0000000..347cb4b --- /dev/null +++ b/app/admin/rbac/user-role/component/ConfirmAsync.tsx @@ -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; + okText?: string; + cancelText?: string; + contentSuccess?: ReactNode | string; + onOkSuccess?: () => any; +}; + +const ConfirmAsync: FC = ({ 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 ( + + + {title || 'Are you absolutely sure?'} + + {description || 'This action cannot be undone. This will permanently remove this role from our system.'} + + + + {cancelText || 'Cancel'} + + {isLoading && ( + + )} + {okText || 'Continue'} + + + + ); +}; + +export default ConfirmAsync; + diff --git a/app/admin/rbac/user-role/component/MenuPermissionTree.tsx b/app/admin/rbac/user-role/component/MenuPermissionTree.tsx new file mode 100644 index 0000000..e9f076c --- /dev/null +++ b/app/admin/rbac/user-role/component/MenuPermissionTree.tsx @@ -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; + 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 = ({ + menus, + allowAdminPanel, + selectedPermissions, + onPermissionToggle, + onMenuSelectAll, + onMenuClearAll, +}) => { + const [searchQuery, setSearchQuery] = useState(''); + const [collapsedIds, setCollapsedIds] = useState>(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(); + + 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 ( + +
+ {/* Left: Menu Name, Hierarchy Indent & Parent indicator */} +
+ {hasChildren ? ( + + ) : ( + + )} + + {node.level > 0 && ( + + ↳ + + )} + +
+ {assignedActions.length > 0 && ( + { + if (e.target.checked) { + onMenuSelectAll(node.id!, assignedActions); + } else { + onMenuClearAll(node.id!); + } + }} + /> + )} +
+
+ {node.icon && } + + {node.name} + + {node.is_admin_menu && ( + + Admin + + )} +
+ + {node.path_url || '#'} + +
+
+
+ + {/* Right: Available Actions Checkboxes & Row Select All button */} +
+ {assignedActions.length > 0 ? ( + <> +
+ {assignedActions.map(action => { + const isChecked = currentSelectedActions.includes(action); + return ( + + ); + })} +
+ + + + ) : ( + + Tidak ada aksi terkonfigurasi + + )} +
+
+ + {/* Render children recursively if not collapsed */} + {hasChildren && !isCollapsed && node.children!.map(child => renderNode(child))} +
+ ); + }; + + return ( +
+ {/* Search Bar */} +
+
+ } + placeholder="Cari menu atau permission..." + value={searchQuery} + onChange={(e) => setSearchQuery(e.target.value)} + allowClear + className="h-9" + /> +
+
+ Gunakan tombol + Semua + atau centang permission per menu +
+
+ + {/* Section 1: Non-Admin Menus */} +
+
+
+ +

+ Non-Admin Menus (General Application) +

+
+ + {menus.filter(m => !m.is_admin_menu).length} menu + +
+ +
+ {nonAdminTree.length > 0 ? ( + nonAdminTree.map(node => renderNode(node)) + ) : ( +
+ Belum ada menu Non-Admin yang terdaftar. +
+ )} +
+
+ + {/* Section 2: Admin Menus (Rendered ONLY if allowAdminPanel === true) */} + {allowAdminPanel && ( +
+
+
+ +

+ Admin Menus (Admin Panel) +

+
+ + {menus.filter(m => Boolean(m.is_admin_menu)).length} menu + +
+ +
+ {adminTree.length > 0 ? ( + adminTree.map(node => renderNode(node)) + ) : ( +
+ Belum ada menu Admin Panel yang terdaftar. +
+ )} +
+
+ )} +
+ ); +}; + +export default MenuPermissionTree; + diff --git a/app/admin/rbac/user-role/component/RoleForm.tsx b/app/admin/rbac/user-role/component/RoleForm.tsx new file mode 100644 index 0000000..eb2a631 --- /dev/null +++ b/app/admin/rbac/user-role/component/RoleForm.tsx @@ -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 = ({ isUpdate, roleId, initialData }) => { + const [isLoading, setIsLoading] = useState(false); + const [showConfirm, setShowConfirm] = useState(false); + const [allowAdminPanel, setAllowAdminPanel] = useState(false); + // Key: menu_id -> array of action strings + const [selectedPermissions, setSelectedPermissions] = useState>({}); + + const [form] = Form.useForm(); + const router = useRouter(); + const axios = useAxiosAuth(); + + // Fetch menus from backend + const { data: menuData, isLoading: menuLoading } = useFetch('/menu'); + + const menus: IMenu[] = useMemo(() => { + if (!menuData) return []; + if (Array.isArray(menuData)) return menuData; + if (Array.isArray(menuData.menu)) return menuData.menu; + if (Array.isArray(menuData.menus)) return menuData.menus; + return []; + }, [menuData]); + + // Prepopulate form on mount or when initialData changes + useEffect(() => { + if (initialData) { + const isAdminAllowed = Boolean( + initialData.allow_admin_panel ?? initialData.allow_admin ?? false + ); + setAllowAdminPanel(isAdminAllowed); + + form.setFieldsValue({ + name: initialData.name, + description: initialData.description || '', + allow_admin_panel: isAdminAllowed, + }); + + // Map existing permissions into selectedPermissions dictionary + const initialSelection: Record = {}; + + if (Array.isArray(initialData.role_detail) && initialData.role_detail.length > 0) { + initialData.role_detail.forEach((item: IRoleDetail) => { + if (item.menu_id && Array.isArray(item.action)) { + initialSelection[item.menu_id] = item.action; + } + }); + } else if (Array.isArray(initialData.privilege) && initialData.privilege.length > 0) { + // Support legacy privilege format + initialData.privilege.forEach((item: any) => { + const mId = item.menu_id || item.id; + if (mId && Array.isArray(item.action)) { + initialSelection[mId] = item.action.map((a: any) => (typeof a === 'string' ? a : a.name || a.code || String(a))); + } + }); + } + + setSelectedPermissions(initialSelection); + } else { + form.resetFields(); + form.setFieldsValue({ + allow_admin_panel: false, + }); + setAllowAdminPanel(false); + setSelectedPermissions({}); + } + }, [initialData, form]); + + // Handle allow_admin_panel toggle + const handleAdminToggle = (checked: boolean) => { + setAllowAdminPanel(checked); + form.setFieldValue('allow_admin_panel', checked); + + // When toggled to false, clean all Admin Menu assignments from form state + if (!checked) { + setSelectedPermissions((prev) => { + const next = { ...prev }; + menus.forEach((m) => { + if (m.is_admin_menu && m.id !== undefined && next[m.id]) { + delete next[m.id]; + } + }); + return next; + }); + } + }; + + // Permission toggle handler for a single action + const handlePermissionToggle = (menuId: number, actionName: string, checked: boolean) => { + setSelectedPermissions((prev) => { + const currentActions = prev[menuId] || []; + let nextActions: string[]; + + if (checked) { + if (!currentActions.includes(actionName)) { + nextActions = [...currentActions, actionName]; + } else { + nextActions = currentActions; + } + } else { + nextActions = currentActions.filter((a) => a !== actionName); + } + + if (nextActions.length === 0) { + const copy = { ...prev }; + delete copy[menuId]; + return copy; + } + + return { + ...prev, + [menuId]: nextActions, + }; + }); + }; + + // Select all actions on a menu row + const handleMenuSelectAll = (menuId: number, allActions: string[]) => { + setSelectedPermissions((prev) => ({ + ...prev, + [menuId]: [...allActions], + })); + }; + + // Clear all actions on a menu row + const handleMenuClearAll = (menuId: number) => { + setSelectedPermissions((prev) => { + const copy = { ...prev }; + delete copy[menuId]; + return copy; + }); + }; + + // Final payload construction according to backend contract + const handleSubmit = async () => { + try { + const values = await form.validateFields(); + setIsLoading(true); + + // Build role_detail array + const roleDetail: IRoleDetail[] = []; + + // Group menus by ID for fast lookup + const menuMap = new Map(); + menus.forEach((m) => { + if (m.id !== undefined) menuMap.set(m.id, m); + }); + + // Iterate over selected permissions + Object.entries(selectedPermissions).forEach(([menuIdStr, actions]) => { + const menuId = Number(menuIdStr); + const menu = menuMap.get(menuId); + if (!menu || !actions || actions.length === 0) return; + + // Rule: If allow_admin_panel is false, exclude Admin menus + if (menu.is_admin_menu && !allowAdminPanel) { + return; + } + + // Filter action to only valid actions configured on this menu + const validMenuActions = menu.action || []; + const safeActions = actions.filter( + (a) => validMenuActions.length === 0 || validMenuActions.includes(a) + ); + + if (safeActions.length > 0) { + roleDetail.push({ + menu_id: menu.id!, + menu_name: menu.name, + menu_path: menu.path_url || '#', + is_admin_menu: Boolean(menu.is_admin_menu), + action: safeActions, + }); + } + }); + + const payload: Record = { + name: values.name?.trim(), + description: values.description?.trim() || '', + allow_admin_panel: Boolean(allowAdminPanel), + allow_admin: Boolean(allowAdminPanel), // For backward compatibility with legacy endpoints + role_detail: roleDetail, + privilege: roleDetail, // For backward compatibility with legacy endpoints + }; + + if (!isUpdate) { + const res = await axios.post('/role', payload); + setIsLoading(false); + + if (res.data?.code && res.data.code !== '00' && res.data.code !== 200) { + toast.error('Failed to create role', { + description: res.data?.message || 'Server error', + }); + return; + } + + toast.success('Role successfully created.'); + router.push('/admin/rbac/user-role'); + router.refresh(); + } else { + const res = await axios.put(`/role/${roleId}`, payload); + setIsLoading(false); + + if (res.data?.code && res.data.code !== '00' && res.data.code !== 200) { + toast.error('Failed to update role', { + description: res.data?.message || 'Server error', + }); + return; + } + + toast.success('Role successfully updated.'); + router.push('/admin/rbac/user-role'); + router.refresh(); + } + } catch (error: any) { + setIsLoading(false); + const msg = error?.response?.data?.message || error?.message || 'Failed to save role'; + toast.error('Failed to save role', { description: msg }); + } + }; + + return ( + <> +
+ {/* Header Card */} + + +
+ + + +
+ + {isUpdate ? 'Edit User Role' : 'Create New User Role'} + + + {isUpdate + ? `Configure role permissions for role ID ${roleId}` + : 'Define role details and assign hierarchical menu access'} + +
+
+ +
+ + + + +
+
+
+ + {/* Form Body */} + + {/* Section A: General Information */} + + + + Informasi Umum (General Information) + + + Masukkan nama peran, deskripsi, dan hak akses admin panel + + + +
+ + + + +
+
+ + Allow Admin Panel + + + Mengizinkan role ini mengakses menu administrasi dan admin panel + +
+ + + +
+
+ + + + +
+
+ + {/* Section B: Menu Permissions */} + + +
+
+ + Detil Hak Akses & Access Permissions + + + Atur izin akses untuk setiap menu yang tersedia dalam aplikasi + +
+
+ {Object.keys(selectedPermissions).length} menu dikonfigurasi +
+
+
+ + {menuLoading ? ( +
+ + Memuat struktur menu dari server... +
+ ) : ( + + )} +
+
+ + {/* Bottom Action Bar */} +
+ + + + +
+ +
+ + {/* Confirmation Dialog */} + {showConfirm && ( + + + + Konfirmasi Simpan Role? + + Konfigurasi hak akses role ini akan disimpan dan langsung berlaku bagi pengguna yang memiliki role ini. + + + + setShowConfirm(false)}> + Batal + + { + setShowConfirm(false); + handleSubmit(); + }} + > + {isLoading && } + Lanjutkan + + + + + )} + + ); +}; + +export default RoleForm; + diff --git a/app/admin/rbac/user-role/component/index.tsx b/app/admin/rbac/user-role/component/index.tsx new file mode 100644 index 0000000..aa0c971 --- /dev/null +++ b/app/admin/rbac/user-role/component/index.tsx @@ -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 = ({ data }) => { + const [filterData, setFilterData] = useState([]); + const [searchText, setSearchText] = useState(''); + + const axios = useAxiosAuth(); + + useEffect(() => { + if (data && Array.isArray(data)) { + setFilterData(data); + } else { + setFilterData([]); + } + }, [data]); + + const handleSearch = (e: ChangeEvent) => { + 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 = [ + { + title: 'Num', + dataIndex: 'key', + width: 70, + align: 'center', + render: (_text, _record, index) => ( + {index + 1} + ), + }, + { + title: 'Code', + dataIndex: 'code', + width: 110, + render: (code: string) => ( + + {code || '-'} + + ), + }, + { + title: 'Role Name', + dataIndex: 'name', + sorter: (a, b) => (a.name || '').localeCompare(b.name || ''), + render: (name: string, record: IRole) => ( +
+ + {name} + +
+ ), + }, + { + 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 ? ( + + + Allowed + + ) : ( + + + Restricted + + ); + }, + }, + { + 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 ( + + {count} menus + + ); + }, + }, + { + title: 'Description', + dataIndex: 'description', + render: (desc: string) => ( + + {desc || '-'} + + ), + }, + { + title: 'Action', + key: 'action', + width: 80, + align: 'center', + render: (_, record) => ( + + + + + + + + + View Detail + + + + + Edit Role + + + + + Delete Role + + + + + handleDelete(record.id!)} + onOkSuccess={() => { }} + /> + + ), + }, + ]; + + const tableProps: TableProps = { + 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 ( +
+
+
+ +
+ + + +
+ + + +

No roles found

+

+ {searchText ? 'Try adjusting your search query.' : 'Click "Create New Role" to define user access roles.'} +

+ + ), + }} + /> + + ); +}; + +export default ComponentRolePage; + diff --git a/app/admin/rbac/user-role/component/type.ts b/app/admin/rbac/user-role/component/type.ts new file mode 100644 index 0000000..b2816b2 --- /dev/null +++ b/app/admin/rbac/user-role/component/type.ts @@ -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; +} + diff --git a/app/admin/rbac/user-role/create/page.tsx b/app/admin/rbac/user-role/create/page.tsx new file mode 100644 index 0000000..d9e6a21 --- /dev/null +++ b/app/admin/rbac/user-role/create/page.tsx @@ -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 ; +} + diff --git a/app/admin/rbac/user-role/edit/[id]/page.tsx b/app/admin/rbac/user-role/edit/[id]/page.tsx new file mode 100644 index 0000000..805dd0d --- /dev/null +++ b/app/admin/rbac/user-role/edit/[id]/page.tsx @@ -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 { + 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 ( + + ); +} diff --git a/app/admin/rbac/user-role/page.tsx b/app/admin/rbac/user-role/page.tsx new file mode 100644 index 0000000..3ab2094 --- /dev/null +++ b/app/admin/rbac/user-role/page.tsx @@ -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 ( +
+ + +
+ User Role + + List of registered user roles and permission sets + +
+
+ + }> + + + +
+
+ ); +} diff --git a/components/ui/rbac-badge.tsx b/components/ui/rbac-badge.tsx new file mode 100644 index 0000000..58c22c2 --- /dev/null +++ b/components/ui/rbac-badge.tsx @@ -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 = ({ + 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 ( + + {permission} + + ); +}; + +export default RbacBadge; + diff --git a/lib/data-sidebar.tsx b/lib/data-sidebar.tsx index 0643c6e..aa5b42e 100644 --- a/lib/data-sidebar.tsx +++ b/lib/data-sidebar.tsx @@ -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: , + 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: , @@ -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: , - // 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 \ No newline at end of file +export default SIDEBAR_MENU diff --git a/lib/tabler-icons.ts b/lib/tabler-icons.ts new file mode 100644 index 0000000..435ff0a --- /dev/null +++ b/lib/tabler-icons.ts @@ -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' }, +]; + diff --git a/types/rbac.ts b/types/rbac.ts new file mode 100644 index 0000000..cfb09fa --- /dev/null +++ b/types/rbac.ts @@ -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; +} +