mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-06 19:56:28 +00:00
Add RBAC menu and role management
Adds permission, menu, and role administration with hierarchical access controls, plus admin breadcrumbs and a redirect from the legacy user-role page. Remove `credentials.md` before committing; it contains server credentials.
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { FC, ReactNode, useState } from 'react';
|
||||
import { Icons } from '@/components/Icons';
|
||||
import { AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog';
|
||||
import { type ResponseData } from '@/types/types';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
type Props = {
|
||||
title?: string;
|
||||
description?: string;
|
||||
onConfirm: () => Promise<any>;
|
||||
okText?: string;
|
||||
cancelText?: string;
|
||||
contentSuccess?: ReactNode | string;
|
||||
onOkSuccess?: () => any;
|
||||
};
|
||||
|
||||
const ConfirmAsync: FC<Props> = ({ title, description, onConfirm, okText, cancelText, contentSuccess, onOkSuccess }) => {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const router = useRouter();
|
||||
|
||||
const confirm = async () => {
|
||||
if (isLoading) return;
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const res: ResponseData = await onConfirm();
|
||||
setIsLoading(false);
|
||||
|
||||
if (!res) return;
|
||||
|
||||
if (res.code === '00' || res.code === 200) {
|
||||
showSuccess();
|
||||
} else {
|
||||
showError(res.message);
|
||||
}
|
||||
} catch (error: any) {
|
||||
setIsLoading(false);
|
||||
const message = error?.response?.data?.message || error?.message || 'Failed to delete menu';
|
||||
showError(message);
|
||||
}
|
||||
};
|
||||
|
||||
const showSuccess = () => {
|
||||
router.refresh();
|
||||
toast.success(contentSuccess || 'Menu successfully removed.');
|
||||
if (onOkSuccess) onOkSuccess();
|
||||
};
|
||||
|
||||
const showError = (message?: string) => {
|
||||
toast.error(message || 'Failed to delete menu');
|
||||
};
|
||||
|
||||
return (
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{title || 'Are you absolutely sure?'}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{description || 'This action cannot be undone. This will permanently delete this menu configuration.'}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={isLoading}>{cancelText || 'Cancel'}</AlertDialogCancel>
|
||||
<AlertDialogAction disabled={isLoading} onClick={confirm}>
|
||||
{isLoading && (
|
||||
<Icons.spinner className="mr-1 h-4 w-4 animate-spin" />
|
||||
)}
|
||||
{okText || 'Continue'}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
);
|
||||
};
|
||||
|
||||
export default ConfirmAsync;
|
||||
@@ -0,0 +1,321 @@
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Form, Input, Select, Switch } from "antd";
|
||||
import useAxiosAuth from "@/lib/axios/useAxiosAuth";
|
||||
import useFetch from "@/lib/axios/useFetch";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Icons } from "@/components/Icons";
|
||||
import { type IMenu } from "./type";
|
||||
import { toast } from "sonner";
|
||||
import { TABLER_ICON_OPTIONS } from "@/lib/tabler-icons";
|
||||
import RbacBadge from "@/components/ui/rbac-badge";
|
||||
import { Plus, X } from "lucide-react";
|
||||
import PermissionForm from "../../action-permissions/component/Form";
|
||||
|
||||
type Props = {
|
||||
isUpdate?: boolean;
|
||||
data?: IMenu;
|
||||
menuList: IMenu[];
|
||||
onCancel?: () => any;
|
||||
};
|
||||
|
||||
// Helper to collect all descendant IDs of a menu to prevent circular relationships
|
||||
function getDescendantIds(targetId: number, menus: IMenu[]): Set<number> {
|
||||
const descendants = new Set<number>();
|
||||
const stack = [targetId];
|
||||
|
||||
while (stack.length > 0) {
|
||||
const currentId = stack.pop()!;
|
||||
const children = menus.filter(m => m.menu_parent_id === currentId && m.id !== undefined);
|
||||
for (const child of children) {
|
||||
if (!descendants.has(child.id!)) {
|
||||
descendants.add(child.id!);
|
||||
stack.push(child.id!);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return descendants;
|
||||
}
|
||||
|
||||
export default function MenuForm({ data, menuList, isUpdate, onCancel }: Props) {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [selectedIcon, setSelectedIcon] = useState<string>('');
|
||||
const [showPermissionForm, setShowPermissionForm] = useState(false)
|
||||
const [form] = Form.useForm();
|
||||
const router = useRouter();
|
||||
const axios = useAxiosAuth();
|
||||
|
||||
// Fetch available permissions for action selection
|
||||
const { data: permissionData, isLoading: permissionLoading, mutate } = useFetch('/permission');
|
||||
|
||||
const availablePermissions: string[] = useMemo(() => {
|
||||
if (!permissionData) return [];
|
||||
if (Array.isArray(permissionData)) {
|
||||
return permissionData.map((p: any) => p.name || p);
|
||||
}
|
||||
if (Array.isArray(permissionData.permission)) {
|
||||
return permissionData.permission.map((p: any) => p.name || p);
|
||||
}
|
||||
if (Array.isArray(permissionData.permissions)) {
|
||||
return permissionData.permissions.map((p: any) => p.name || p);
|
||||
}
|
||||
return [];
|
||||
}, [permissionData]);
|
||||
|
||||
// Calculate valid parent options (excluding self and descendants to prevent circular relationships)
|
||||
const validParentOptions = useMemo(() => {
|
||||
if (!menuList) return [];
|
||||
|
||||
const invalidIds = new Set<number>();
|
||||
if (isUpdate && data?.id !== undefined) {
|
||||
invalidIds.add(data.id);
|
||||
const descendants = getDescendantIds(data.id, menuList);
|
||||
descendants.forEach(id => invalidIds.add(id));
|
||||
}
|
||||
|
||||
return menuList
|
||||
.filter(item => item.id !== undefined && !invalidIds.has(item.id))
|
||||
.map(item => {
|
||||
const parent = menuList.find(p => p.id === item.menu_parent_id);
|
||||
const label = parent ? `${parent.name} → ${item.name}` : item.name;
|
||||
return {
|
||||
label,
|
||||
value: item.id!,
|
||||
isAdmin: item.is_admin_menu,
|
||||
};
|
||||
});
|
||||
}, [menuList, isUpdate, data]);
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
form.setFieldsValue({
|
||||
...data,
|
||||
menu_parent_id: data.menu_parent_id ?? null,
|
||||
is_admin_menu: data.is_admin_menu ?? false,
|
||||
action: data.action ?? [],
|
||||
});
|
||||
setSelectedIcon(data.icon || '');
|
||||
} else {
|
||||
form.resetFields();
|
||||
form.setFieldsValue({
|
||||
is_admin_menu: false,
|
||||
menu_parent_id: null,
|
||||
action: [],
|
||||
});
|
||||
setSelectedIcon('');
|
||||
}
|
||||
}, [data, form]);
|
||||
|
||||
const handleSubmit = async (values: any) => {
|
||||
const payload: Partial<IMenu> = {
|
||||
name: values.name?.trim(),
|
||||
path_url: values.path_url?.trim(),
|
||||
description: values.description?.trim() || '',
|
||||
icon: values.icon?.trim() || '',
|
||||
is_admin_menu: Boolean(values.is_admin_menu),
|
||||
menu_parent_id: values.menu_parent_id ? Number(values.menu_parent_id) : null,
|
||||
action: Array.isArray(values.action) ? values.action : [],
|
||||
};
|
||||
|
||||
!isUpdate ? handleCreate(payload) : handleUpdate(payload);
|
||||
};
|
||||
|
||||
const handleCreate = async (payload: Partial<IMenu>) => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const res = await axios.post('/menu', payload);
|
||||
setIsLoading(false);
|
||||
|
||||
if (res.data?.code && res.data.code !== '00' && res.data.code !== 200) {
|
||||
toast.error('Failed to create menu', {
|
||||
description: res.data?.message || 'Server returned an error',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
toast.success('Menu successfully created.');
|
||||
router.refresh();
|
||||
if (onCancel) onCancel();
|
||||
} catch (error: any) {
|
||||
setIsLoading(false);
|
||||
const msg = error?.response?.data?.message || error?.message || 'Failed to create menu';
|
||||
toast.error('Failed to create menu', { description: msg });
|
||||
}
|
||||
};
|
||||
|
||||
const handleUpdate = async (payload: Partial<IMenu>) => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const res = await axios.put(`/menu/${data?.id}`, payload);
|
||||
setIsLoading(false);
|
||||
|
||||
if (res.data?.code && res.data.code !== '00' && res.data.code !== 200) {
|
||||
toast.error('Failed to update menu', {
|
||||
description: res.data?.message || 'Server returned an error',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
toast.success('Menu successfully updated.');
|
||||
router.refresh();
|
||||
if (onCancel) onCancel();
|
||||
} catch (error: any) {
|
||||
setIsLoading(false);
|
||||
const msg = error?.response?.data?.message || error?.message || 'Failed to update menu';
|
||||
toast.error('Failed to update menu', { description: msg });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<DialogContent className="max-h-[90vh] overflow-y-auto">
|
||||
<Form form={form} onFinish={handleSubmit} layout="vertical">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="dark:text-white">
|
||||
{isUpdate ? 'Edit Menu' : 'Create New Menu'}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Configure menu routing, hierarchy, tabler icon, and assigned permissions.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="grid mt-6 gap-y-0">
|
||||
<Form.Item
|
||||
name="name"
|
||||
label="Menu Name"
|
||||
rules={[{ required: true, message: 'Menu name is required!' }]}
|
||||
>
|
||||
<Input className="input" placeholder="e.g. Overview or User Management" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
name="path_url"
|
||||
label="Path URL"
|
||||
rules={[{ required: true, message: 'Path URL is required!' }]}
|
||||
>
|
||||
<Input className="input font-mono" placeholder="e.g. /administration/user" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item name="menu_parent_id" label="Parent Menu" tooltip="Select parent menu or leave as Root menu (null)">
|
||||
<Select placeholder="Root Menu (No Parent)" allowClear
|
||||
optionFilterProp="children" getPopupContainer={(triggerNode: any) => triggerNode.parentNode}
|
||||
showSearch={{ filterOption: (input, option) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase()) }}
|
||||
options={[
|
||||
{ label: '— Root Menu (None) —', value: null as any },
|
||||
...validParentOptions.map(p => ({
|
||||
label: `${p.label} ${p.isAdmin ? ' (Admin)' : ''}`,
|
||||
value: p.value,
|
||||
})),
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
name="icon"
|
||||
label={
|
||||
<span className="flex items-center gap-2">
|
||||
Icon (Tabler)
|
||||
{selectedIcon && (
|
||||
<span className="inline-flex items-center justify-center w-5 h-5 rounded bg-zinc-100 dark:bg-zinc-800 text-his">
|
||||
<i className={selectedIcon} />
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
}
|
||||
>
|
||||
<Select placeholder="Select Tabler Icon" allowClear
|
||||
optionFilterProp="children" getPopupContainer={(triggerNode: any) => triggerNode.parentNode}
|
||||
onChange={(val) => setSelectedIcon(val || '')}
|
||||
options={TABLER_ICON_OPTIONS.map(opt => ({
|
||||
label: (
|
||||
<div className="flex items-center gap-2 py-0.5">
|
||||
<i className={`${opt.value} text-base text-zinc-600 dark:text-zinc-300 w-5 text-center`} />
|
||||
<span>{opt.label}</span>
|
||||
<span className="text-xs text-muted-foreground ml-auto font-mono">{opt.value}</span>
|
||||
</div>
|
||||
),
|
||||
value: opt.value,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<div className="p-3 rounded-lg border border-zinc-200 dark:border-zinc-800 bg-zinc-50/50 dark:bg-zinc-900/40 flex items-center justify-between">
|
||||
<div>
|
||||
<span className="text-sm font-medium text-zinc-900 dark:text-zinc-100 block">
|
||||
Admin Panel Menu
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground block mt-0.5">
|
||||
When enabled, this menu is treated as part of the Admin Panel and governed by Allow Admin Panel permission.
|
||||
</span>
|
||||
</div>
|
||||
<Form.Item name="is_admin_menu" valuePropName="checked" className="mb-0">
|
||||
<Switch />
|
||||
</Form.Item>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Form.Item name="action" label="Action / Permissions" tooltip="Select which action permissions are available on this menu" className="w-full">
|
||||
<Select mode="multiple" allowClear loading={permissionLoading} options={availablePermissions.map(p => ({ label: p, value: p }))}
|
||||
showSearch={{ filterOption: (input, option) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase()) }}
|
||||
placeholder={permissionLoading ? "Loading permissions..." : "Assign permissions to this menu..."}
|
||||
className="h-max"
|
||||
optionFilterProp="children" getPopupContainer={(triggerNode: any) => triggerNode.parentNode}
|
||||
tagRender={(props) => {
|
||||
const { value, closable, onClose } = props;
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 mr-1.5 my-0.5">
|
||||
<RbacBadge permission={String(value)} size="sm" />
|
||||
{closable && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="text-xs text-muted-foreground hover:text-rose-500 ml-0.5"
|
||||
>
|
||||
<X size={10} />
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Button variant='outline' className="mt-6" title="Add Permission" type="button" onClick={() => setShowPermissionForm(true)}><Plus /></Button>
|
||||
</div>
|
||||
|
||||
<Form.Item name="description" label="Description">
|
||||
<Input.TextArea className="input" id="description" rows={3} placeholder="Describe the purpose of this menu" />
|
||||
</Form.Item>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="mt-6">
|
||||
<Button variant="outline" type="button" onClick={onCancel} disabled={isLoading}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={isLoading}>
|
||||
{isLoading && (
|
||||
<Icons.spinner className="mr-1 h-4 w-4 animate-spin" />
|
||||
)}
|
||||
Save Menu
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
|
||||
{showPermissionForm ?
|
||||
<PermissionForm
|
||||
isUpdate={false}
|
||||
onCancel={() => { setShowPermissionForm(false); mutate() }}
|
||||
/>
|
||||
: null
|
||||
}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
'use client';
|
||||
|
||||
import { ChangeEvent, FC, useEffect, useMemo, useState } from 'react';
|
||||
import { MoreHorizontalIcon } from 'lucide-react';
|
||||
import { Table } from 'antd';
|
||||
import { TableProps, type ColumnsType } from 'antd/es/table';
|
||||
import { PlusCircledIcon } from '@radix-ui/react-icons';
|
||||
import useAxiosAuth from '@/lib/axios/useAxiosAuth';
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { AlertDialog, AlertDialogTrigger } from '@/components/ui/alert-dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Dialog } from '@/components/ui/dialog';
|
||||
import MenuForm from './Form';
|
||||
import ConfirmAsync from './ConfirmAsync';
|
||||
import { type IMenu } from './type';
|
||||
import RbacBadge from '@/components/ui/rbac-badge';
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
type Props = {
|
||||
data: IMenu[];
|
||||
};
|
||||
|
||||
// Transform flat menu list into hierarchical tree for Antd Table
|
||||
function buildMenuTree(items: IMenu[]): IMenu[] {
|
||||
const itemMap = new Map<number, IMenu>();
|
||||
const roots: IMenu[] = [];
|
||||
|
||||
// Clone all items and add empty children
|
||||
items.forEach(item => {
|
||||
if (item.id !== undefined) {
|
||||
itemMap.set(item.id, { ...item, children: [] });
|
||||
}
|
||||
});
|
||||
|
||||
// Wire parents and children
|
||||
items.forEach(item => {
|
||||
if (item.id === undefined) return;
|
||||
const mappedItem = itemMap.get(item.id)!;
|
||||
if (item.menu_parent_id && itemMap.has(item.menu_parent_id)) {
|
||||
const parent = itemMap.get(item.menu_parent_id)!;
|
||||
if (!parent.children) parent.children = [];
|
||||
parent.children.push(mappedItem);
|
||||
} else {
|
||||
roots.push(mappedItem);
|
||||
}
|
||||
});
|
||||
|
||||
// Remove empty children arrays so Antd doesn't render expand icons on leaf nodes
|
||||
function cleanupEmptyChildren(list: IMenu[]) {
|
||||
list.forEach(node => {
|
||||
if (node.children && node.children.length === 0) {
|
||||
delete node.children;
|
||||
} else if (node.children && node.children.length > 0) {
|
||||
cleanupEmptyChildren(node.children);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
cleanupEmptyChildren(roots);
|
||||
return roots;
|
||||
}
|
||||
|
||||
const ComponentMenuPage: FC<Props> = ({ data }) => {
|
||||
const [rawMenus, setRawMenus] = useState<IMenu[]>([]);
|
||||
const [filterData, setFilterData] = useState<IMenu[]>([]);
|
||||
const [selectedData, setSelectedData] = useState<IMenu | undefined>(undefined);
|
||||
const [showFormDialog, setShowFormDialog] = useState(false);
|
||||
const [searchText, setSearchText] = useState('');
|
||||
|
||||
const axios = useAxiosAuth();
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
if (data && Array.isArray(data)) {
|
||||
setRawMenus(data);
|
||||
setFilterData(data);
|
||||
} else {
|
||||
setRawMenus([]);
|
||||
setFilterData([]);
|
||||
}
|
||||
}, [data]);
|
||||
|
||||
const handleDelete = async (id: string | number) => {
|
||||
return await axios.delete(`/menu/${id}`).then((res) => res.data);
|
||||
};
|
||||
|
||||
const handleResetForm = () => {
|
||||
setSelectedData(undefined);
|
||||
setShowFormDialog(false);
|
||||
};
|
||||
|
||||
const handleSearch = (e: ChangeEvent<HTMLInputElement>) => {
|
||||
const text = e.target.value;
|
||||
setSearchText(text);
|
||||
if (text && rawMenus.length > 0) {
|
||||
const lower = text.toLowerCase();
|
||||
const filtered = rawMenus.filter(
|
||||
(item) =>
|
||||
item.name?.toLowerCase().includes(lower) ||
|
||||
item.path_url?.toLowerCase().includes(lower) ||
|
||||
item.description?.toLowerCase().includes(lower) ||
|
||||
item.icon?.toLowerCase().includes(lower) ||
|
||||
(item.action && item.action.some(act => act.toLowerCase().includes(lower)))
|
||||
);
|
||||
setFilterData(filtered);
|
||||
} else {
|
||||
setFilterData(rawMenus);
|
||||
}
|
||||
};
|
||||
|
||||
// If searching, display flat filtered items; otherwise display structured tree
|
||||
const displayDataSource = useMemo(() => {
|
||||
if (searchText.trim().length > 0) {
|
||||
return filterData;
|
||||
}
|
||||
return buildMenuTree(rawMenus);
|
||||
}, [searchText, filterData, rawMenus]);
|
||||
|
||||
const columns: ColumnsType<IMenu> = [
|
||||
{
|
||||
title: 'Menu Name',
|
||||
dataIndex: 'name',
|
||||
key: 'name',
|
||||
render: (text: string, record: IMenu) => (
|
||||
<div className="inline-flex items-center gap-2">
|
||||
{record.icon ? (
|
||||
<span className="inline-flex items-center justify-center w-6 h-6 rounded bg-zinc-100 dark:bg-zinc-800 text-zinc-700 dark:text-zinc-200 text-sm">
|
||||
<i className={record.icon} />
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex items-center justify-center w-6 h-6 rounded bg-zinc-50 dark:bg-zinc-900 text-zinc-400 text-xs font-mono">
|
||||
#
|
||||
</span>
|
||||
)}
|
||||
<span className="font-semibold text-zinc-900 dark:text-zinc-100">
|
||||
{text}
|
||||
</span>
|
||||
{record.menu_parent_id && searchText && (
|
||||
<span className="text-[10px] text-muted-foreground bg-zinc-100 dark:bg-zinc-800 px-1.5 py-0.5 rounded">
|
||||
child
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'Path URL',
|
||||
dataIndex: 'path_url',
|
||||
key: 'path_url',
|
||||
render: (path: string) => (
|
||||
<span className="font-mono text-xs text-zinc-600 dark:text-zinc-300">
|
||||
{path || '/'}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'Type',
|
||||
dataIndex: 'is_admin_menu',
|
||||
key: 'is_admin_menu',
|
||||
width: 120,
|
||||
align: 'center',
|
||||
render: (isAdmin?: boolean) => (
|
||||
isAdmin ? (
|
||||
<span className="inline-flex items-center px-2 py-0.5 rounded-sm text-[11px] font-semibold bg-indigo-500/10 text-indigo-600 border border-indigo-500/20 dark:bg-indigo-500/20 dark:text-indigo-300 dark:border-indigo-500/30">
|
||||
Admin Panel
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex items-center px-2 py-0.5 rounded-sm text-[11px] font-semibold bg-zinc-500/10 text-zinc-600 border border-zinc-500/20 dark:bg-zinc-500/20 dark:text-zinc-400 dark:border-zinc-500/30">
|
||||
General
|
||||
</span>
|
||||
)
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'Actions / Permissions',
|
||||
dataIndex: 'action',
|
||||
key: 'action',
|
||||
render: (actions?: string[]) => {
|
||||
if (!actions || actions.length === 0) {
|
||||
return <span className="text-xs text-muted-foreground italic">No action assigned</span>;
|
||||
}
|
||||
return (
|
||||
<div className="flex flex-wrap gap-1 max-w-md">
|
||||
{actions.map((act) => (
|
||||
<RbacBadge key={act} permission={act} size="sm" />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: 'Description',
|
||||
dataIndex: 'description',
|
||||
key: 'description',
|
||||
render: (desc: string) => (
|
||||
<span className="text-xs text-muted-foreground line-clamp-2 max-w-xs">
|
||||
{desc || '-'}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'Action',
|
||||
key: 'row_action',
|
||||
width: 80,
|
||||
align: 'center',
|
||||
render: (_, record) => (
|
||||
<AlertDialog>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8">
|
||||
<MoreHorizontalIcon className="h-4 w-4" />
|
||||
<span className="sr-only">Menu Actions</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
setSelectedData(record);
|
||||
setShowFormDialog(true);
|
||||
}}
|
||||
>
|
||||
Edit Menu
|
||||
</DropdownMenuItem>
|
||||
<AlertDialogTrigger asChild>
|
||||
<DropdownMenuItem className="text-rose-600 dark:text-rose-400">
|
||||
Delete Menu
|
||||
</DropdownMenuItem>
|
||||
</AlertDialogTrigger>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<ConfirmAsync
|
||||
title="Delete Menu?"
|
||||
description={`Are you sure you want to delete menu "${record.name}"? If this menu has child menus or permissions assigned, access may be affected.`}
|
||||
onConfirm={() => handleDelete(record.id!)}
|
||||
onOkSuccess={() => router.refresh()}
|
||||
/>
|
||||
</AlertDialog>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const tableProps: TableProps<IMenu> = {
|
||||
bordered: false,
|
||||
size: 'small',
|
||||
showHeader: true,
|
||||
pagination: searchText ? {
|
||||
pageSizeOptions: [10, 20, 50],
|
||||
defaultPageSize: 10,
|
||||
showSizeChanger: true,
|
||||
size: 'middle' as any,
|
||||
} : false, // In tree mode, keep full tree expanded/visible for clear hierarchy
|
||||
scroll: { x: 'max-content' },
|
||||
tableLayout: 'auto',
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col space-y-4">
|
||||
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
|
||||
<div className="flex flex-1 items-center space-x-2 w-full sm:w-auto">
|
||||
<Input
|
||||
placeholder="Search menu, path, or permissions..."
|
||||
className="h-8 w-full sm:w-64"
|
||||
value={searchText}
|
||||
onChange={handleSearch}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-8 text-his hover:text-his hover:bg-his/10 font-semibold"
|
||||
onClick={() => {
|
||||
setSelectedData(undefined);
|
||||
setShowFormDialog(true);
|
||||
}}
|
||||
>
|
||||
<PlusCircledIcon className="mr-2 h-4 w-4" />
|
||||
Create New Menu
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Table
|
||||
{...tableProps}
|
||||
rowKey="id"
|
||||
columns={columns}
|
||||
dataSource={displayDataSource}
|
||||
locale={{
|
||||
emptyText: (
|
||||
<div className="py-8 text-center text-muted-foreground">
|
||||
<i className="ti ti-category text-3xl mb-2 text-zinc-400 block" />
|
||||
<p className="text-sm font-medium">No menus registered</p>
|
||||
<p className="text-xs text-zinc-400 mt-1">
|
||||
{searchText ? 'No menu matching your search.' : 'Click "Create New Menu" to register your first navigation menu.'}
|
||||
</p>
|
||||
</div>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Dialog
|
||||
open={showFormDialog}
|
||||
onOpenChange={(state) => {
|
||||
if (!state) setSelectedData(undefined);
|
||||
setShowFormDialog(state);
|
||||
}}
|
||||
>
|
||||
<MenuForm
|
||||
data={selectedData}
|
||||
menuList={rawMenus}
|
||||
isUpdate={selectedData !== undefined}
|
||||
onCancel={handleResetForm}
|
||||
/>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default ComponentMenuPage;
|
||||
@@ -0,0 +1,7 @@
|
||||
import { type IMenu, type IPermission } from "@/types/rbac";
|
||||
|
||||
export type { IMenu, IPermission };
|
||||
|
||||
export interface IMenuAction extends IMenu {
|
||||
children?: IMenuAction[];
|
||||
}
|
||||
Reference in New Issue
Block a user