mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-06 20:46:29 +00:00
initial commit for new hats app
This commit is contained in:
@@ -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<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)
|
||||
|
||||
console.log(res)
|
||||
if (!res) return
|
||||
|
||||
if (res.code === '00') {
|
||||
showSuccess()
|
||||
} else {
|
||||
showError(res.message)
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.log(error)
|
||||
setIsloading(false)
|
||||
showError(error?.message)
|
||||
}
|
||||
}
|
||||
|
||||
const showSuccess = () => {
|
||||
router.refresh()
|
||||
toast.success(contentSuccess || 'Data successfully removed.' as string)
|
||||
onOkSuccess!()
|
||||
};
|
||||
|
||||
const showError = (message?: string) => {
|
||||
toast.error(message)
|
||||
};
|
||||
|
||||
return (
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{title || 'Are you absolutely sure?'}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{description || 'This action cannot be undone. This will permanently delete this data and remove from our servers.'}
|
||||
</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,155 @@
|
||||
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 (
|
||||
<DialogContent>
|
||||
<Form form={form} onFinish={handleSubmit} layout='vertical'>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="dark:text-white">{isUpdate ? 'Update menu' : 'Create menu'}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Add a new team to manage products and customers
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid mt-8">
|
||||
<Form.Item name='name' label='Menu name' rules={[{ required: true, message: 'This field is required!' }]} >
|
||||
<Input className="input" id="name" placeholder="Dashboard" />
|
||||
</Form.Item>
|
||||
<div className="grid grid-cols-3 gap-x-4">
|
||||
<Form.Item name='menu_parent_id' label='Parent Menu' className="col-span-2" >
|
||||
<Select placeholder='Select parent' showSearch allowClear
|
||||
optionFilterProp="children"
|
||||
filterOption={(input, option) => option!.children!.toString().toLowerCase().indexOf(input.toLowerCase()) >= 0}
|
||||
getPopupContainer={(triggerNode: any) => triggerNode.parentNode}
|
||||
>
|
||||
<Select.Option value=''>-</Select.Option>
|
||||
{menuList.map((item =>
|
||||
<Select.Option key={item.id} value={item.id}>({item.id}) {item.name}</Select.Option>
|
||||
))}
|
||||
</Select>
|
||||
</Form.Item>
|
||||
<Form.Item name='icon' label='Icon' >
|
||||
<Select placeholder='Select icon' showSearch allowClear
|
||||
optionFilterProp="children"
|
||||
filterOption={(input, option) => option!.children!.toString().toLowerCase().indexOf(input.toLowerCase()) >= 0}
|
||||
getPopupContainer={(triggerNode: any) => triggerNode.parentNode}
|
||||
>
|
||||
<Select.Option value=''>-</Select.Option>
|
||||
<Select.Option value='ti ti-layout-dashboard'>
|
||||
<i className="ti ti-layout-dashboard icon"></i>
|
||||
</Select.Option>
|
||||
|
||||
<Select.Option value='ti ti-database'>
|
||||
<i className="ti ti-database icon"></i>
|
||||
</Select.Option>
|
||||
|
||||
<Select.Option value='ti ti-devices-2'>
|
||||
<i className="ti ti-devices-2 icon"></i>
|
||||
</Select.Option>
|
||||
</Select>
|
||||
</Form.Item>
|
||||
</div>
|
||||
<Form.Item name='path_url' label='Path URL' rules={[{ required: true, message: 'This field is required!' }]} >
|
||||
<Input className="input" id="path_url" placeholder="dashboard" />
|
||||
</Form.Item>
|
||||
<Form.Item name='hidden_data' label='Hidden Data' >
|
||||
<Radio.Group>
|
||||
<Radio value={true}>Hidden</Radio>
|
||||
<Radio value={false}>Visible</Radio>
|
||||
</Radio.Group>
|
||||
</Form.Item>
|
||||
<Form.Item name='description' label='Description'>
|
||||
<Input.TextArea className="input" id="description" placeholder="Halaman dashboard" />
|
||||
</Form.Item>
|
||||
</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>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
'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<Props> = ({ data }) => {
|
||||
const [filterData, setFilterData] = useState<IMenu[]>([])
|
||||
const [selectedData, setSelectedData] = useState<IMenu | undefined>(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<HTMLInputElement>) => {
|
||||
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<IMenu> = [
|
||||
{
|
||||
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) => (
|
||||
<div className='flex justify-center text-white font-semibold text-xs'>
|
||||
{record.status.code === 'A' ?
|
||||
<div className="px-2 py-1.5 rounded-full bg-green-500 w-24">{record.status.name}</div>
|
||||
:
|
||||
<div className="px-2 py-1.5 rounded-full bg-rose-500 w-24">{record.status.name}</div>
|
||||
}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
{
|
||||
title: 'Description',
|
||||
dataIndex: 'description',
|
||||
},
|
||||
{
|
||||
title: 'Action',
|
||||
key: 'action',
|
||||
render: (_, record) => (
|
||||
<AlertDialog>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant='ghost' size="icon">
|
||||
<MoreHorizontalIcon />
|
||||
<span className="sr-only">Action Button</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => { }}>View</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => { setShowFormDialog(true); setSelectedData(record) }} >Edit</DropdownMenuItem>
|
||||
<AlertDialogTrigger asChild>
|
||||
<DropdownMenuItem>Delete</DropdownMenuItem>
|
||||
</AlertDialogTrigger>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<ConfirmAsync
|
||||
onConfirm={() => handleDelete(record.id)}
|
||||
onOkSuccess={() => { }}
|
||||
/>
|
||||
</AlertDialog>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const tableProps: TableProps<IMenu> = {
|
||||
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: 'default'
|
||||
},
|
||||
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 space-y-2 sm:space-y-0">
|
||||
<div className="flex flex-1 items-center space-x-2">
|
||||
<Input placeholder="Search menu..." className="h-8 w-full sm:w-[250px]" onChange={handleSearch} />
|
||||
</div>
|
||||
<Button size="sm" variant='ghost' className="ml-auto h-8 w-full sm:w-max text-his" onClick={() => setShowFormDialog(true)}>
|
||||
<PlusCircledIcon className="mr-2 h-4 w-4" />
|
||||
Create New Menu
|
||||
</Button>
|
||||
</div>
|
||||
<Table
|
||||
{...tableProps}
|
||||
rowKey='id'
|
||||
columns={Columns}
|
||||
dataSource={filterData || []}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Dialog open={showFormDialog} onOpenChange={(state) => {
|
||||
if (state === false) setSelectedData(undefined)
|
||||
setShowFormDialog(state)
|
||||
}}>
|
||||
<ComponentForm
|
||||
data={selectedData}
|
||||
menuList={data}
|
||||
isUpdate={selectedData !== undefined}
|
||||
onCancel={handleResetForm}
|
||||
/>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default ComponentPage;
|
||||
@@ -0,0 +1,21 @@
|
||||
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[]
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
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 (
|
||||
<>
|
||||
<div className="flex flex-col">
|
||||
<Card>
|
||||
<CardHeader className='flex flex-row items-center justify-between space-y-2 sm:space-y-0'>
|
||||
<div>
|
||||
<CardTitle>Menu</CardTitle>
|
||||
<CardDescription>Here's a list of menus that have been registered!</CardDescription>
|
||||
</div>
|
||||
<div>
|
||||
<Button className="sm:hidden" size={'icon'}><Download size={20} /></Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Suspense fallback={<LazyLoading />}>
|
||||
<ComponentPage
|
||||
data={data.menu}
|
||||
/>
|
||||
</Suspense>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user