Files
hats-app/app/(dashboard)/work-permit/components/index.tsx
T
2025-12-19 13:57:55 +07:00

214 lines
10 KiB
TypeScript

"use client"
import { FC, useState } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { DatePicker, Form, Input, Select } from 'antd';
import dayjs from 'dayjs';
import type { RangePickerProps } from 'antd/es/date-picker';
import { Separator } from '@/components/ui/separator';
import { Button } from '@/components/ui/button';
import { Icons } from '@/components/Icons';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog';
import useAxiosAuth from '@/lib/axios/useAxiosAuth';
import { toast } from 'sonner';
import { Label } from '@/components/ui/label';
const OPTION_TAGS_PERMIT = [
{ label: 'Izin', value: 'permit' },
{ label: 'Bedrest', value: 'bedrest' },
{ label: 'Dirumah', value: 'dirumah' },
{ label: 'Haji / Umrah', value: 'haji/umrah' },
{ label: 'Travelling', value: 'travelling' },
]
const OPTION_TAGS_SICK = [
{ label: 'Sakit', value: 'sick' },
{ label: 'Bedrest', value: 'bedrest' },
{ label: 'Dirumah', value: 'dirumah' },
{ label: 'Covid', value: 'covid' },
]
const PERMIT_TYPE = [
{ lable: 'Permission', value: 'I', icon: 'ti ti-license' },
{ lable: 'Sick', value: 'S', icon: 'ti ti-stethoscope' },
]
type Props = {
TL_LIST?: any[]
};
const Component: FC<Props> = ({ TL_LIST }) => {
const [permitType, setPermitType] = useState<string>('')
const [isLoading, setIsLoading] = useState(false)
const [leavePeriod, setLeavePeriod] = useState<any>([])
const [showConfirm, setShowConfirm] = useState(false)
const router = useRouter()
const [form] = Form.useForm();
const { data: session } = useSession()
const axios = useAxiosAuth()
const handleSubmit = async () => {
setIsLoading(true)
try {
const formData = form.getFieldsValue()
if (!permitType) return handleError('Leave type cannot be empty!')
const payload = {
"nik": session?.user.detail.nik,
"send_to": 9,
// "send_to": 1,
"cc": formData['cc'],
"category": permitType,
"start_date": dayjs(formData['start_date'][0]).format('YYYY-MM-DD'),
"end_date": dayjs(formData['start_date'][1]).format('YYYY-MM-DD'),
"return_to_work_date": dayjs(formData['return_to_work_date']).format('YYYY-MM-DD'),
"contact_street": formData['contact_street'],
"contact_city": formData['contact_city'],
"contact_phone_number": session?.user.detail.phone_number,
"note": formData['note'],
"tags": formData["tags"],
"image": ""
}
console.log(payload)
const { data } = await axios.post('/application-form', payload)
handleSuccess(data?.message)
} catch (error: any) {
console.log(error)
handleError(`Fail to apply for leave, (${error.response?.data?.code || error.response?.status || '-'}) ${error.response?.data?.message || error.response?.statusText || error.message}`, true)
}
}
const handleSuccess = (message: string) => {
toast.success(message)
router.replace('/')
router.refresh()
}
const handleError = (message: string, action?: boolean) => {
toast.error("Oops! Something went wrong.", {
description: message,
action: action ? <Button variant='outline' onClick={handleSubmit}>Try again</Button> : undefined,
})
setIsLoading(false)
}
// DISABLE DATE BEFORE 18 SEP 2023
// eslint-disable-next-line arrow-body-style
const disabledDate: RangePickerProps['disabledDate'] = (current) => {
const disabledDate = new Date('2023-09-18');
disabledDate.setHours(0, 0, 0, 0);
const disabledTimestamp = disabledDate.getTime();
const selectedTimestamp = current ? current.valueOf() : 0;
return selectedTimestamp < disabledTimestamp;
}
// eslint-disable-next-line arrow-body-style
const disabledDateKembaliKerja: RangePickerProps['disabledDate'] = (current) => {
if (leavePeriod && leavePeriod.length === 2 && leavePeriod[1]) {
return current && current < dayjs(leavePeriod[1]).endOf('day');
}
return false
};
return (
<>
<Form form={form} onFinish={() => setShowConfirm(true)} scrollToFirstError layout="vertical" size='small' requiredMark={false}>
<div className='space-y-3 flex flex-col items-center mb-5'>
<Label>Permit Type</Label>
<div className='flex items-center flex-wrap space-x-5 text-sm'>
{PERMIT_TYPE && PERMIT_TYPE.length > 0 ?
PERMIT_TYPE.map((item, key) =>
<div className='flex flex-col items-center space-y-1' key={key}>
<button type='button' className={`rounded-xl w-20 h-20 ${permitType === item.value ? 'bg-zinc-200 dark:bg-zinc-700 ' : 'btn-outline'}`} onClick={() => setPermitType(item.value)}>
<i className={`${item.icon} icon text-2xl`}></i>
</button>
<p className='text-center'>{item.lable}</p>
</div>
) :
<div>
Working status not available, please contact administrator.
</div>
}
</div>
</div>
<div className='grid grid-cols-1 font-medium gap-y-0'>
<Form.Item label='Start-End Date' name='start_date' rules={[{ required: true }]} >
<DatePicker.RangePicker onChange={val => setLeavePeriod(val)} format={'MMM DD, YYYY'} size='small' className='input' disabledDate={disabledDate} />
</Form.Item>
<Form.Item label='Return to Work Date' name='return_to_work_date' rules={[{ required: true }]} initialValue={leavePeriod && leavePeriod.length === 2 && dayjs(leavePeriod[1]).endOf('day')}>
<DatePicker disabledDate={disabledDateKembaliKerja} format={'MMMM DD, YYYY'} size='small' className='input' disabled={leavePeriod?.length !== 2} />
</Form.Item>
<Form.Item label='Address' name='contact_street' rules={[{ required: true }]}>
<Input.TextArea className='input' placeholder='Please write address..' maxLength={255} rootClassName='px-3! py-2!' />
</Form.Item>
<Form.Item label='City' name='contact_city' rules={[{ required: true, max: 50 }]}>
<Input className='input' placeholder='Please write city' maxLength={50} />
</Form.Item>
<Form.Item label='Note' name='note'>
<Input.TextArea className='input' placeholder='Reason note...' maxLength={255} rootClassName='px-3! py-2!' />
</Form.Item>
<Form.Item label='Tags' name='tags'>
<Select mode="multiple" allowClear placeholder="Select relate tags" options={permitType === 'S' ? OPTION_TAGS_SICK : OPTION_TAGS_PERMIT} size='large'
optionFilterProp="children"
filterOption={(input, option) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase())}
/>
</Form.Item>
<Form.Item label='Send to' name='send_to' initialValue='Stevanus Akbar Alexander'>
<Input className='input' disabled readOnly />
</Form.Item>
<Form.Item label='Mentions to' name='cc' >
<Select mode="multiple" allowClear placeholder="Add mentions to Team Leader" size='large'
options={TL_LIST?.length! > 0 ? TL_LIST?.map(item => { return { value: item.id, label: item.fullname } }) : []}
optionFilterProp="children"
filterOption={(input, option) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase())}
/>
</Form.Item>
<Separator />
</div>
<Separator />
<div className='flex flex-col space-y-2'>
<Button type="submit" disabled={isLoading}>
{isLoading && (
<Icons.spinner className="mr-1 h-4 w-4 animate-spin" />
)}
Submit
</Button>
<Button type='reset' variant='outline' onClick={() => router.back()} disabled={isLoading} >Cancel</Button>
</div>
</Form>
{showConfirm &&
<AlertDialog open={true}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
<AlertDialogDescription>
This data will be stored on our server, you can change it whenever you want later.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isLoading} onClick={() => setShowConfirm(false)}>Cancel</AlertDialogCancel>
<AlertDialogAction disabled={isLoading} onClick={handleSubmit}>
{isLoading && (
<Icons.spinner className="mr-1 h-4 w-4 animate-spin" />
)}
Continue
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
}
</>
);
}
export default Component;