mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-05 10:56:28 +00:00
751b28fab2
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.
322 lines
15 KiB
TypeScript
322 lines
15 KiB
TypeScript
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
|
|
}
|
|
</>
|
|
);
|
|
}
|