mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-05 10:56:28 +00:00
1b37ff65f5
Gate administration actions by role permissions, centralize cached session access for data fetching, and return forbidden responses for unauthorized pages. Also lazy-load user exports and adjust search field sizing.
356 lines
17 KiB
TypeScript
356 lines
17 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 { Plus, X } from "lucide-react";
|
|
import PermissionForm from "../../action-permissions/component/Form";
|
|
import RbacBadge from "@/components/ui/rbac-badge";
|
|
|
|
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 [isAdminMenu, setIsAdminMenu] = useState<boolean>(false);
|
|
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: Boolean(item.is_admin_menu),
|
|
};
|
|
});
|
|
}, [menuList, isUpdate, data]);
|
|
|
|
useEffect(() => {
|
|
if (data) {
|
|
const adminStatus = Boolean(data.is_admin_menu);
|
|
setIsAdminMenu(adminStatus);
|
|
form.setFieldsValue({
|
|
...data,
|
|
menu_parent_id: data.menu_parent_id ?? null,
|
|
is_menu_admin: adminStatus,
|
|
action: data.action ?? [],
|
|
});
|
|
setSelectedIcon(data.icon || '');
|
|
} else {
|
|
form.resetFields();
|
|
setIsAdminMenu(false);
|
|
form.setFieldsValue({
|
|
is_menu_admin: 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(isAdminMenu),
|
|
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 created successfully.');
|
|
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 updated successfully.');
|
|
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 Menu'}
|
|
</DialogTitle>
|
|
<DialogDescription>
|
|
Configure menu routing, hierarchy, 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="Menu Path"
|
|
rules={[{ required: true, message: 'Menu path 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 (None)"
|
|
>
|
|
<Select placeholder="Root Menu (None)" allowClear
|
|
showSearch={{ filterOption: (input, option) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase()) }}
|
|
getPopupContainer={(triggerNode: any) => triggerNode.parentNode}
|
|
options={[
|
|
{ label: '(None) - Root Menu', 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 showSearch
|
|
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>
|
|
|
|
{/* Admin Menu Switch with HIS Primary Color */}
|
|
<div className="p-3.5 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-semibold text-zinc-900 dark:text-zinc-100 block">
|
|
Admin Menu
|
|
</span>
|
|
<span className="text-xs text-muted-foreground block mt-0.5">
|
|
When enabled, this menu belongs to the Admin Panel and requires admin panel privileges.
|
|
</span>
|
|
</div>
|
|
<Form.Item name="is_menu_admin" valuePropName="checked" className="mb-0">
|
|
<Switch
|
|
checked={isAdminMenu}
|
|
onChange={(checked) => {
|
|
setIsAdminMenu(checked);
|
|
form.setFieldValue('is_menu_admin', checked);
|
|
}}
|
|
style={{
|
|
backgroundColor: isAdminMenu ? '#EA512C' : undefined,
|
|
}}
|
|
className="[&.ant-switch-checked]:bg-[#EA512C]! [&.ant-switch-checked:hover]:bg-[#EA512C]/90!"
|
|
/>
|
|
</Form.Item>
|
|
</div>
|
|
|
|
{/* Action / Permissions Multi-select Container */}
|
|
<div className="flex items-center gap-2">
|
|
<Form.Item name="action" label="Action Permissions"
|
|
tooltip="Select action permissions available on this menu"
|
|
className="w-full"
|
|
// rules={[{ required: true, message: 'Please add aleast one action!' }]}
|
|
>
|
|
<Select mode="multiple" allowClear loading={permissionLoading} options={availablePermissions.map(p => ({ label: p, value: p }))}
|
|
placeholder={permissionLoading ? "Loading permissions..." : "Select permissions..."}
|
|
showSearch={{ filterOption: (input, option) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase()) }}
|
|
className="w-full min-h-[42px] [&_.ant-select-selector]:min-h-[42px]! [&_.ant-select-selector]:h-auto! [&_.ant-select-selector]:max-h-40! [&_.ant-select-selector]:overflow-y-auto! [&_.ant-select-selector]:p-1.5!"
|
|
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-1">
|
|
<RbacBadge permission={String(value)} size="sm" />
|
|
{closable && (
|
|
<button
|
|
type="button"
|
|
onClick={onClose}
|
|
aria-label={`Remove permission ${value}`}
|
|
className="text-xs text-muted-foreground hover:text-rose-500 rounded p-0.5 hover:bg-rose-50 dark:hover:bg-rose-950/40 transition-colors"
|
|
>
|
|
<X size={11} />
|
|
</button>
|
|
)}
|
|
</span>
|
|
);
|
|
}}
|
|
/>
|
|
</Form.Item>
|
|
<div className="pt-6">
|
|
<Button variant='outline' size='icon' type="button" onClick={() => setShowPermissionForm(true)}><Plus /></Button>
|
|
</div>
|
|
</div>
|
|
|
|
<Form.Item name="description" label="Description" className="mb-0">
|
|
<Input.TextArea
|
|
className="input"
|
|
id="description"
|
|
rows={3}
|
|
placeholder="Describe the purpose and scope 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} className="bg-his hover:bg-his/90 text-white font-medium">
|
|
{isLoading && (
|
|
<Icons.spinner className="mr-1.5 h-4 w-4 animate-spin" />
|
|
)}
|
|
{isUpdate ? 'Save Changes' : 'Save'}
|
|
</Button>
|
|
</DialogFooter>
|
|
</Form>
|
|
</DialogContent>
|
|
|
|
{showPermissionForm && (
|
|
<PermissionForm
|
|
isUpdate={false}
|
|
onCancel={() => {
|
|
setShowPermissionForm(false);
|
|
mutate();
|
|
}}
|
|
/>
|
|
)}
|
|
</>
|
|
);
|
|
}
|