@@ -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 (
-
-
-
- )
-}
\ 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) => (
-
-
-
-
-
- Action Button
-
-
-
- { }}>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 (
- <>
-
-
-
-
-
-
setShowFormDialog(true)}>
-
- Create New Menu
-
-
-
-
-
- {
- 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 (
+
+
+
+
+
+ );
+}
+
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) => (
+
+
+
+
+
+ Action
+
+
+
+ {
+ 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 (
+ <>
+
+
+
+
+
+
{
+ setSelectedData(undefined);
+ setShowFormDialog(true);
+ }}
+ >
+
+ Create New Permission
+
+
+
+
+
+ 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 (
+ <>
+
+
+
+
+ {showPermissionForm ?
+ { setShowPermissionForm(false); mutate() }}
+ />
+ : null
+ }
+ >
+ );
+}
diff --git a/app/admin/rbac/menu/component/index.tsx b/app/admin/rbac/menu/component/index.tsx
new file mode 100644
index 0000000..4259b91
--- /dev/null
+++ b/app/admin/rbac/menu/component/index.tsx
@@ -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();
+ 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 = ({ data }) => {
+ const [rawMenus, setRawMenus] = useState([]);
+ const [filterData, setFilterData] = useState([]);
+ const [selectedData, setSelectedData] = useState(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) => {
+ 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 = [
+ {
+ title: 'Menu Name',
+ dataIndex: 'name',
+ key: 'name',
+ render: (text: string, record: IMenu) => (
+
+ {record.icon ? (
+
+
+
+ ) : (
+
+ #
+
+ )}
+
+ {text}
+
+ {record.menu_parent_id && searchText && (
+
+ child
+
+ )}
+
+ ),
+ },
+ {
+ title: 'Path URL',
+ dataIndex: 'path_url',
+ key: 'path_url',
+ render: (path: string) => (
+
+ {path || '/'}
+
+ ),
+ },
+ {
+ title: 'Type',
+ dataIndex: 'is_admin_menu',
+ key: 'is_admin_menu',
+ width: 120,
+ align: 'center',
+ render: (isAdmin?: boolean) => (
+ isAdmin ? (
+
+ Admin Panel
+
+ ) : (
+
+ General
+
+ )
+ ),
+ },
+ {
+ title: 'Actions / Permissions',
+ dataIndex: 'action',
+ key: 'action',
+ render: (actions?: string[]) => {
+ if (!actions || actions.length === 0) {
+ return No action assigned ;
+ }
+ return (
+
+ {actions.map((act) => (
+
+ ))}
+
+ );
+ },
+ },
+ {
+ title: 'Description',
+ dataIndex: 'description',
+ key: 'description',
+ render: (desc: string) => (
+
+ {desc || '-'}
+
+ ),
+ },
+ {
+ title: 'Action',
+ key: 'row_action',
+ width: 80,
+ align: 'center',
+ render: (_, record) => (
+
+
+
+
+
+ Menu Actions
+
+
+
+ {
+ setSelectedData(record);
+ setShowFormDialog(true);
+ }}
+ >
+ Edit Menu
+
+
+
+ Delete Menu
+
+
+
+
+ handleDelete(record.id!)}
+ onOkSuccess={() => router.refresh()}
+ />
+
+ ),
+ },
+ ];
+
+ const tableProps: TableProps = {
+ 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 (
+ <>
+
+
+
+
+
+
{
+ setSelectedData(undefined);
+ setShowFormDialog(true);
+ }}
+ >
+
+ Create New Menu
+
+
+
+
+
+ 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
+
+
+
+
+
+ Edit Role
+
+
+
+
+
+
+
+ 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 ? (
+
+
+
+
+ No
+ Menu Aplikasi (Hierarki)
+ Aksi yang Diizinkan
+
+
+
+ {roleDetails.map((detail, idx) => (
+
+
+ {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.
+
+
+ Konfigurasi Hak Akses Sekarang
+
+
+
+ )}
+
+
+
+ );
+};
+
+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 ? (
+
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 ? : }
+
+ ) : (
+
+ )}
+
+ {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 (
+
+
+ onPermissionToggle(node.id!, action, e.target.checked)
+ }
+ />
+
+
+ );
+ })}
+
+
+
{
+ if (isAllSelected) {
+ onMenuClearAll(node.id!);
+ } else {
+ onMenuSelectAll(node.id!, assignedActions);
+ }
+ }}
+ >
+ {isAllSelected ? 'Batal' : 'Semua'}
+
+ >
+ ) : (
+
+ 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'}
+
+
+
+
+
+
+
+ Batal
+
+
+ setShowConfirm(true)}
+ disabled={isLoading || menuLoading}
+ >
+ {isLoading && }
+ Simpan Perubahan
+
+
+
+
+
+ {/* Form Body */}
+
+
+
+ {/* 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) => (
+
+
+
+
+
+ Role Action
+
+
+
+
+
+ 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 (
+
+
+
+
+
+
+
+
+ Create New Role
+
+
+
+
+
+
+ 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;
+}
+