mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-06 12:26:28 +00:00
386 lines
16 KiB
TypeScript
386 lines
16 KiB
TypeScript
import { useRouter } from "next/navigation"
|
|
import { FC, useEffect, useState } from "react"
|
|
import { Checkbox, Form, Input, Radio } from "antd"
|
|
import useAxiosAuth from "@/lib/axios/useAxiosAuth"
|
|
import { Button } from "@/components/ui/button"
|
|
import {
|
|
DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle,
|
|
} from "@/components/ui/dialog"
|
|
import { Label } from "@/components/ui/label"
|
|
import { Icons } from "@/components/Icons"
|
|
import { IMenuAction } from "@/app/admin/menu/component/type"
|
|
import { DUMMY_MENU_LIST, LIST_ACTION_DATA } from "@/lib/data"
|
|
import { cn } from "@/lib/utils"
|
|
import { type IRole } from "./type"
|
|
import { toast } from "sonner"
|
|
|
|
type Props = {
|
|
isUpdate?: boolean
|
|
data?: IRole
|
|
onCancel?: () => any
|
|
}
|
|
|
|
function createMenuTree(data: IMenuAction[], parentId: Number | null | undefined = null) {
|
|
const result = [];
|
|
|
|
// Filter items with the specified parentId
|
|
const filteredItems = data.filter(item => item.menu_parent_id === parentId);
|
|
|
|
// Iterate over the filtered items
|
|
for (const item of filteredItems) {
|
|
// Recursively call createMenuTree to build the children for the current item
|
|
const children = createMenuTree(data, item.id);
|
|
|
|
// Add the children array to the current item if there are children
|
|
if (children.length > 0) {
|
|
item.children = children;
|
|
}
|
|
|
|
// Add the current item to the result array
|
|
result.push(item);
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
|
|
function assignMenuLevel(menuList: IMenuAction[], existMenu: IMenuAction[], level: number = 1) {
|
|
for (const menu of menuList) {
|
|
if (menu.children && menu.children.length > 0) {
|
|
existMenu.push({ ...menu, menu_level: level, action: [] })
|
|
assignMenuLevel(menu.children, existMenu, level + 1);
|
|
} else {
|
|
existMenu.push({ ...menu, menu_level: level, action: [] })
|
|
}
|
|
}
|
|
|
|
return existMenu;
|
|
}
|
|
|
|
|
|
export default function ComponentForm({ data, isUpdate, onCancel }: Props) {
|
|
const [isLoading, setIsLoading] = useState(false)
|
|
const [allowAdmin, setAllowAdmin] = useState(false)
|
|
const [privilegeMenus, setPrivilegeMenus] = useState<IMenuAction[]>([])
|
|
|
|
const [form] = Form.useForm();
|
|
const router = useRouter()
|
|
const axios = useAxiosAuth()
|
|
// const { data: menuList } = useFetch('/menu')
|
|
|
|
useEffect(() => {
|
|
if (DUMMY_MENU_LIST && DUMMY_MENU_LIST.length > 0) {
|
|
// CREATE MENU TREE
|
|
const nestedMenuData = createMenuTree(DUMMY_MENU_LIST as IMenuAction[]);
|
|
// console.log(nestedMenuData)
|
|
|
|
// DESTRUCTURING MENU TREE INTO ONE LIST
|
|
const result: IMenuAction[] = []
|
|
const resultData = assignMenuLevel(nestedMenuData, result);
|
|
|
|
// REMOVE "children object"
|
|
const arrayMenu = resultData.map(({ children, ...rest }) => rest);
|
|
|
|
if (data && data.privilege) {
|
|
const existData = [...arrayMenu].map((item) => {
|
|
// FIND ACTION FROM EXISTING DATA AND SET IT
|
|
const findIdxAction = data.privilege.findIndex((menu: any) => menu.menu_id === item.id)
|
|
if (findIdxAction > -1) {
|
|
item.action = data.privilege[findIdxAction].action
|
|
}
|
|
return item
|
|
})
|
|
setPrivilegeMenus(existData)
|
|
} else {
|
|
setPrivilegeMenus(arrayMenu)
|
|
}
|
|
}
|
|
}, [DUMMY_MENU_LIST, data])
|
|
|
|
useEffect(() => {
|
|
if (data) {
|
|
if (data.allow_admin) setAllowAdmin(data.allow_admin)
|
|
form.setFieldsValue(data)
|
|
} else {
|
|
form.resetFields()
|
|
}
|
|
}, [data, form])
|
|
|
|
|
|
const handleSubmit = (value: any) => {
|
|
!isUpdate ? handleCreate(value) : handleUpdate(value)
|
|
}
|
|
|
|
const handleCreate = async (payload: IRole) => {
|
|
try {
|
|
setIsLoading(true)
|
|
// await axios.post('/dayoff', payload)
|
|
|
|
if (allowAdmin) {
|
|
// ONLY SUBMIT MENU THAT HAVE ACTION
|
|
const submitedPrivilegeMenus = privilegeMenus.filter(item => item.action?.length! > 0)
|
|
// REMOVE CHILD MENU DOES"NT HAVE A PARENT
|
|
const filterChildNotHaveParent = [...submitedPrivilegeMenus].filter((item) => {
|
|
if (item.menu_level > 1) {
|
|
const findParent = [...submitedPrivilegeMenus].find(menu => menu.id === item.menu_parent_id)
|
|
if (findParent) {
|
|
return true
|
|
}
|
|
return false
|
|
} else {
|
|
return true
|
|
}
|
|
}).map(item => {
|
|
return { menu_id: item.id, menu_name: item.name, action: item.action }
|
|
})
|
|
|
|
payload['privilege'] = filterChildNotHaveParent
|
|
} else {
|
|
payload['privilege'] = []
|
|
}
|
|
|
|
localStorage.setItem('role_test', JSON.stringify(payload))
|
|
|
|
handleSuccess('Data successfully created.')
|
|
} catch (error: any) {
|
|
handleError(`Data failed to create, (${error.response.data.code || error.response.status || '-'}) ${error.response.data.message || error.response.statusText || error.message}`)
|
|
}
|
|
}
|
|
|
|
const handleUpdate = async (payload: IRole) => {
|
|
try {
|
|
setIsLoading(true)
|
|
// await axios.put('/dayoff/' + data?.id, payload)
|
|
|
|
if (allowAdmin) {
|
|
// ONLY SUBMIT MENU THAT HAVE ACTION
|
|
const submitedPrivilegeMenus = privilegeMenus.filter(item => item.action?.length! > 0)
|
|
// REMOVE CHILD MENU DOES"NT HAVE A PARENT
|
|
const filterChildNotHaveParent = [...submitedPrivilegeMenus].filter((item) => {
|
|
if (item.menu_level > 1) {
|
|
const findParent = [...submitedPrivilegeMenus].find(menu => menu.id === item.menu_parent_id)
|
|
if (findParent) {
|
|
return true
|
|
}
|
|
return false
|
|
} else {
|
|
return true
|
|
}
|
|
}).map(item => {
|
|
return { menu_id: item.id, menu_name: item.name, action: item.action }
|
|
})
|
|
|
|
payload['privilege'] = filterChildNotHaveParent
|
|
} else {
|
|
payload['privilege'] = []
|
|
}
|
|
|
|
localStorage.setItem('role_test', JSON.stringify(payload))
|
|
|
|
handleSuccess('Data successfully updated.')
|
|
} catch (error: any) {
|
|
handleError(`Data failed to update, (${error.response.data.code || error.response.status || '-'}) ${error.response.data.message || error.response.statusText || error.message}`)
|
|
}
|
|
}
|
|
|
|
const handleSuccess = (message: string) => {
|
|
toast.success(message)
|
|
setIsLoading(false)
|
|
onCancel!()
|
|
router.refresh()
|
|
form.resetFields()
|
|
}
|
|
|
|
const handleError = (message: string) => {
|
|
toast.error(message)
|
|
setIsLoading(false)
|
|
}
|
|
|
|
const handleCheckAllAction = (action: typeof LIST_ACTION_DATA[0], isChecked: boolean) => {
|
|
console.log({ action, isChecked })
|
|
const existData = [...privilegeMenus]
|
|
|
|
if (isChecked) {
|
|
existData.map((item) => {
|
|
item.action?.push(action.id)
|
|
return item
|
|
})
|
|
} else {
|
|
existData.map((item) => {
|
|
const index = item.action?.indexOf(action.id);
|
|
if (index! > -1) {
|
|
item.action?.splice(index!, 1);
|
|
}
|
|
return item
|
|
})
|
|
}
|
|
setPrivilegeMenus(existData)
|
|
}
|
|
|
|
const handleCheckMenu = (menu: IMenuAction, isChecked: boolean) => {
|
|
console.log({ menu, isChecked })
|
|
const existData = [...privilegeMenus]
|
|
|
|
const findIndex = existData.findIndex(item => item.id === menu.id)
|
|
if (isChecked) {
|
|
existData[findIndex].action = LIST_ACTION_DATA.map(item => item.id)
|
|
} else {
|
|
existData[findIndex].action = []
|
|
|
|
// FIND CHILD AND ALSO REMOVE ACTION IN NESTED CHILD IF EXIST
|
|
const filterChild = existData.filter(item => item.menu_parent_id === menu.id)
|
|
if (filterChild.length > 0) {
|
|
for (const item of filterChild) {
|
|
handleCheckMenu(item, isChecked)
|
|
}
|
|
}
|
|
}
|
|
|
|
setPrivilegeMenus(existData)
|
|
}
|
|
|
|
const handleCheckAction = (menu: IMenuAction, action: number[]) => {
|
|
console.log({ menu, action })
|
|
const existData = [...privilegeMenus]
|
|
|
|
const findIndex = existData.findIndex(item => item.id === menu.id)
|
|
existData[findIndex].action = action as number[]
|
|
|
|
setPrivilegeMenus(existData)
|
|
}
|
|
|
|
const disableCheckAction = (menu: IMenuAction) => {
|
|
if (menu.menu_level > 1) {
|
|
const { menu_parent_id } = menu
|
|
const findParent = privilegeMenus.find(item => item.id === menu_parent_id)
|
|
if (findParent?.action?.length! <= 0) {
|
|
return true
|
|
}
|
|
}
|
|
|
|
return false
|
|
}
|
|
|
|
return (
|
|
<DialogContent className="lg:min-w-[90%] xl:min-w-[80%] 2xl:min-w-[60%] overflow-y-auto max-h-[90vh]">
|
|
<Form form={form} onFinish={handleSubmit} scrollToFirstError layout='vertical' size="small">
|
|
<DialogHeader>
|
|
<DialogTitle className="dark:text-white">{isUpdate ? 'Update role' : 'Create new role'}</DialogTitle>
|
|
<DialogDescription>
|
|
Add or update a role and adjust the privilege
|
|
</DialogDescription>
|
|
</DialogHeader>
|
|
<div className="grid mt-8">
|
|
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
|
<Form.Item name='code' label='Code' rules={[{ required: true, message: 'This field is required!' }]} >
|
|
<Input className="input" placeholder="EXT" />
|
|
</Form.Item>
|
|
<Form.Item name='name' label='Role Name' rules={[{ required: true, message: 'This field is required!' }]} >
|
|
<Input className="input" placeholder="ROLE NAME" />
|
|
</Form.Item>
|
|
</div>
|
|
<Form.Item name='description' label='Description' >
|
|
<Input.TextArea className="input" placeholder="" />
|
|
</Form.Item>
|
|
<Form.Item name='allow_admin' label='Allow Admin Panel' initialValue={false} >
|
|
<Radio.Group onChange={(e) => setAllowAdmin(e.target.value)}>
|
|
<Radio value={false}>Dissallow</Radio>
|
|
<Radio value={true}>Allow</Radio>
|
|
</Radio.Group>
|
|
</Form.Item>
|
|
</div>
|
|
|
|
{allowAdmin &&
|
|
<div className="w-full min-w-[1000px] overflow-x-auto flex flex-col mb-5 mt-2" >
|
|
<Label className="mb-4">User Privilege</Label>
|
|
{/* HEADER */}
|
|
<div className="grid grid-cols-8 bg-zinc-300 dark:bg-zinc-700 py-5">
|
|
<span className="col-span-2 pl-2">Menu Name</span>
|
|
{LIST_ACTION_DATA.map((action) =>
|
|
<div key={action.id}>
|
|
<Checkbox onChange={e => handleCheckAllAction(action, e.target.checked)}>
|
|
{action.name}
|
|
</Checkbox>
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
{/* BODY */}
|
|
{privilegeMenus.length > 0 && privilegeMenus.map((menu: IMenuAction, key: number) =>
|
|
// <ChildrenItem key={item.id} menu={item} onMenuChecked={handleCheckMenu} onActionChecked={handleCheckAction} />
|
|
<div className={`grid grid-cols-8 w-full border-b border-border py-3 ${menu.menu_level === 1 ? 'bg-zinc-100 dark:bg-zinc-900' : ''}`} key={key}>
|
|
<div className='col-span-2 flex items-center pl-2'>
|
|
<Checkbox className={`${!menu.menu_parent_id ? 'pl-2 bold' : 'pl-8'}`} style={{ paddingLeft: (menu.menu_level - 1) * 20 }}
|
|
checked={menu.action?.length! > 0} onChange={(e) => handleCheckMenu(menu, e.target.checked)} disabled={disableCheckAction(menu)}
|
|
>
|
|
{menu.name}
|
|
</Checkbox>
|
|
</div>
|
|
|
|
<div className="col-span-6">
|
|
<Checkbox.Group className="grid" style={{ gridTemplateColumns: `repeat(${LIST_ACTION_DATA.length}, minmax(0, 1fr))` }}
|
|
value={menu.action} onChange={(val) => handleCheckAction(menu, val)} disabled={disableCheckAction(menu)}
|
|
>
|
|
{LIST_ACTION_DATA?.length > 0 && LIST_ACTION_DATA.map((item: any, key: number) =>
|
|
<div key={key} className='item text-center border-l border-border'>
|
|
<Checkbox value={item.id} ></Checkbox>
|
|
</div>
|
|
)}
|
|
</Checkbox.Group>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
</div>
|
|
}
|
|
|
|
<DialogFooter>
|
|
<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
|
|
</Button>
|
|
</DialogFooter>
|
|
</Form>
|
|
</DialogContent>
|
|
)
|
|
}
|
|
|
|
type ChildrenProps = {
|
|
menu: IMenuAction
|
|
className?: string
|
|
onMenuChecked: (menu: IMenuAction, isChecked: boolean) => any
|
|
onActionChecked: (menu: IMenuAction, action: typeof LIST_ACTION_DATA[0], isChecked: boolean) => any
|
|
}
|
|
|
|
const ChildrenItem: FC<ChildrenProps> = ({ menu, className, onMenuChecked, onActionChecked }) => {
|
|
return (
|
|
<>
|
|
<div className={`grid grid-cols-8 w-full border-b border-border py-1 ${!menu.menu_parent_id ? 'bg-zinc-100 dark:bg-zinc-900' : ''}`} >
|
|
<div className={cn('col-span-2 flex items-center', className)}>
|
|
<Checkbox className={`${!menu.menu_parent_id ? 'pl-2 bold' : 'pl-8'}`} onChange={(e) => onMenuChecked(menu, e.target.checked)}>
|
|
{menu.name}
|
|
</Checkbox>
|
|
</div>
|
|
|
|
<Form.Item className="mb-0 mt-0 col-span-6" name={`menu_${menu.id}`}>
|
|
<Checkbox.Group className="grid" style={{ gridTemplateColumns: `repeat(${LIST_ACTION_DATA.length}, minmax(0, 1fr))` }} onChange={(e) => console.log(e)}>
|
|
{LIST_ACTION_DATA?.length > 0 && LIST_ACTION_DATA.map((item: any, key: number) =>
|
|
<div key={key} className='item text-center border-l border-border'>
|
|
<Checkbox value={item.id} onChange={(e) => onActionChecked(menu, item, e.target.checked)}></Checkbox>
|
|
</div>
|
|
)}
|
|
</Checkbox.Group>
|
|
</Form.Item>
|
|
</div>
|
|
|
|
{menu.children && menu.children.length > 0 && menu.children.map((item) =>
|
|
<ChildrenItem className="ml-8" key={item.id} menu={item} onMenuChecked={onMenuChecked} onActionChecked={onActionChecked} />
|
|
)}
|
|
</>
|
|
)
|
|
} |