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

381 lines
19 KiB
TypeScript

"use client"
import { ChangeEvent, FC, FormEvent, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import { DatePicker } from 'antd';
import dayjs from 'dayjs';
import { PDFDocument } from 'pdf-lib';
import SignaturePad from "react-signature-canvas";
import useAxiosAuth from '@/lib/axios/useAxiosAuth';
import { readFile } from '@/lib/helper';
import { Textarea } from '@/components/ui/textarea';
import { Separator } from '@/components/ui/separator';
import { Input } from '@/components/ui/input';
import { Select as MultiSelect } from 'antd'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Button } from '@/components/ui/button';
import { Icons } from '@/components/Icons';
import { Switch } from '@/components/ui/switch';
import { type IProfile } from '../../profile/components/type';
import { type ResponseData } from '@/types/types';
import { type RangePickerProps } from 'antd/es/date-picker';
import relativeTime from "dayjs/plugin/relativeTime";
import customParseFormat from 'dayjs/plugin/customParseFormat';
import { toast } from 'sonner';
import "dayjs/locale/id";
import { Label } from '@/components/ui/label';
dayjs.extend(customParseFormat);
type Props = {
TL_LIST?: any[]
};
const Component: FC<Props> = ({ TL_LIST }) => {
const [isLoading, setIsLoading] = useState(false)
const [leaveType, setLeaveType] = useState('')
const [otherLeave, setOtherLeave] = useState('')
const [leavePeriod, setLeavePeriod] = useState<any>([])
const [leaveIn, setLeaveIn] = useState<any>(null)
const [address, setAddress] = useState('')
const [city, setCity] = useState('')
const [includeSign, setIncludeSign] = useState(false)
const [imgSign, setImgSign] = useState('')
const [signLabelUploaded, setSignLabelUploaded] = useState('Or upload your sign')
const [mentionsTo, setMentionsTo] = useState([])
const axios = useAxiosAuth()
const router = useRouter()
const signCanvas = useRef<SignaturePad>(null);
dayjs.locale("id");
dayjs.extend(relativeTime);
const handleSubmit = async (e: FormEvent<HTMLFormElement>, preview?: boolean) => {
e && e?.preventDefault()
setIsLoading(true)
try {
if (!leaveType) return handleError('Leave type cannot be empty!')
if (!leavePeriod || leavePeriod.length !== 2) return handleError('Leave period is not valid!')
if (!leaveIn) return handleError('Please select leave in first!')
if (!address) return handleError('Your data is not complete yet!')
if (!city) return handleError('Your data is not complete yet!')
const { data } = await axios.post('/user/profile', {})
const { data: profile }: ResponseData<IProfile> = data
const url = '/files/form_cuti_empty.pdf'
const existingPdfBytes = await fetch(url).then(res => res.arrayBuffer())
const pdfDoc = await PDFDocument.load(existingPdfBytes)
// const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica)
const pages = pdfDoc.getPages()
const firstPage = pages[0]
firstPage.drawText(profile.division?.name || '', { x: 165, y: 672, size: 11 }) // DEPARTMENT
firstPage.drawText(new Date().getFullYear().toString(), { x: 500, y: 672, size: 11 }) // YEAR
firstPage.drawText('Stevanus Akbar Alexander', { x: 243, y: 646, size: 11 }) // MGR DEPARTMENT
firstPage.drawText(profile.fullname, { x: 243, y: 628, size: 11 }) // NAME
firstPage.drawText(profile.position?.name || '', { x: 243, y: 608, size: 11 }) // Positiion
/* CUTI TAHUNAN */
if (leaveType === 'CT') {
firstPage.drawText('x', { x: 244, y: 582, size: 16 })
}
/* CUTI BESAR */
if (leaveType === 'CB') {
firstPage.drawText('x', { x: 244, y: 555, size: 16 })
}
/* CUTI MELAHIRKAN */
if (leaveType === 'CM') {
firstPage.drawText('x', { x: 374, y: 582, size: 16 })
}
/* LAINNYA */
if (leaveType === 'CL') {
firstPage.drawText('x', { x: 374, y: 555, size: 16 })
firstPage.drawText(otherLeave, { x: 443, y: 558, size: 10 })
}
firstPage.drawText(dayjs(leavePeriod[0]).format('dddd'), { x: 340, y: 506, size: 11 })
firstPage.drawText(dayjs(leavePeriod[0]).format('DD').split('')[0] + ' ' + dayjs(leavePeriod[0]).format('DD').split('')[1], { x: 416, y: 505, size: 13 })
firstPage.drawText(dayjs(leavePeriod[0]).format('MM').split('')[0] + ' ' + dayjs(leavePeriod[0]).format('MM').split('')[1], { x: 471, y: 505, size: 13 })
firstPage.drawText(dayjs(leavePeriod[0]).format('YY').split('')[0] + ' ' + dayjs(leavePeriod[0]).format('YY').split('')[1], { x: 522, y: 505, size: 13 })
firstPage.drawText(dayjs(leavePeriod[1]).format('dddd'), { x: 340, y: 483, size: 11 })
firstPage.drawText(dayjs(leavePeriod[1]).format('DD').split('')[0] + ' ' + dayjs(leavePeriod[1]).format('DD').split('')[1], { x: 416, y: 482, size: 13 })
firstPage.drawText(dayjs(leavePeriod[1]).format('MM').split('')[0] + ' ' + dayjs(leavePeriod[1]).format('MM').split('')[1], { x: 471, y: 482, size: 13 })
firstPage.drawText(dayjs(leavePeriod[1]).format('YY').split('')[0] + ' ' + dayjs(leavePeriod[1]).format('YY').split('')[1], { x: 522, y: 482, size: 13 })
firstPage.drawText(dayjs(leaveIn).format('dddd'), { x: 340, y: 461, size: 11 })
firstPage.drawText(dayjs(leaveIn).format('DD').split('')[0] + ' ' + dayjs(leaveIn).format('DD').split('')[1], { x: 416, y: 460, size: 13 })
firstPage.drawText(dayjs(leaveIn).format('MM').split('')[0] + ' ' + dayjs(leaveIn).format('MM').split('')[1], { x: 471, y: 460, size: 13 })
firstPage.drawText(dayjs(leaveIn).format('YY').split('')[0] + ' ' + dayjs(leaveIn).format('YY').split('')[1], { x: 522, y: 460, size: 13 })
firstPage.drawText(address, { x: 285, y: 428, size: 10 })
firstPage.drawText(city, { x: 285, y: 406, size: 11 })
firstPage.drawText(profile.phone_number || '', { x: 285, y: 384, size: 11 })
// firstPage.drawText(session?.user.detail.fullname!, { x: 167, y: 350, size: 10 })
firstPage.drawText(dayjs().format('DD MMMM YYYY'), { x: 167, y: 323, size: 10 })
firstPage.drawText('(' + profile.fullname.substring(0, 21) + ')', { x: 54, y: 230, size: 9 })
firstPage.drawText('(' + 'Stevanus Akbar Alexander'.substring(0, 21) + ')', { x: 161, y: 230, size: 9 })
if (includeSign && !signCanvas.current?.isEmpty()) {
const sign = await pdfDoc.embedPng(signCanvas.current?.getTrimmedCanvas().toDataURL('image/png', 1)!)
firstPage.drawImage(sign, { x: 54, y: 240, width: 100, height: 55 })
}
await pdfDoc.setTitle(`Form Cuti ${profile.fullname} - ${dayjs().format('YYYYMMDD')}`)
await pdfDoc.setSubject('SURAT PERMOHONAN FORM CUTI KARYAWAN')
await pdfDoc.setKeywords(['form cuti', 'super apps', 'his', 'nutech'])
await pdfDoc.setCreator(profile.fullname)
await pdfDoc.setAuthor('H.I.S Dev Super Team 😎')
await pdfDoc.setProducer('Super Apps')
await pdfDoc.setCreationDate(new Date())
await pdfDoc.setModificationDate(new Date())
const pdfBase64 = await pdfDoc.saveAsBase64({ dataUri: true })
if (!preview) {
const payload = {
"nik": profile.nik,
"send_to": 9,
// "send_to": 1,
"cc": mentionsTo,
"category": leaveType,
"start_date": dayjs(leavePeriod[0]).format('YYYY-MM-DD'),
"end_date": dayjs(leavePeriod[1]).format('YYYY-MM-DD'),
"return_to_work_date": dayjs(leaveIn).format('YYYY-MM-DD'),
"contact_street": address,
"contact_city": city,
"contact_phone_number": profile.phone_number
}
console.log(payload)
await axios.post('/application-form', payload)
const downloadLink = window.document.createElement('a');
downloadLink.style.display = "none";
downloadLink.href = pdfBase64;
downloadLink.download = `Form Cuti ${profile.fullname} - ${dayjs().format('YYYYMMDD')}`;
window.document.body.appendChild(downloadLink);
downloadLink.click();
window.document.body.removeChild(downloadLink);
handleSuccess('Apply for leave successfully, we generate E-Form for you')
} else {
// Create a new window
const newWindow: any = window.open("", "_blank", "width=800,height=600");
// Create an HTML document with an embedded data URL
const htmlDocument = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PDF Preview</title>
</head>
<body style="margin: 0; height: 100vh;">
<embed src="${pdfBase64}" type="application/pdf" width="100%" height="100%" style="display: block;">
</body>
</html>
`;
// Write the HTML document to the new window
newWindow.document.open();
newWindow.document.write(htmlDocument);
newWindow.document.close();
}
} 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}`)
} finally {
setIsLoading(false)
}
}
const handleSuccess = (message: string) => {
toast.info(message)
router.replace('/')
router.refresh()
}
const handleError = (message: string) => {
toast.error("Oops! Something went wrong.", {
description: message,
action: <Button variant='outline' onClick={() => handleSubmit('' as any)}>Try again</Button>,
})
setIsLoading(false)
}
const clearSignCanvas = () => {
signCanvas.current?.clear();
setSignLabelUploaded('Or upload your sign')
}
const saveSign = () => {
if (signCanvas.current?.isEmpty()) return
setImgSign(signCanvas.current?.getTrimmedCanvas().toDataURL('image/png', 1)!)
}
const importSign = async (e: ChangeEvent<HTMLInputElement>) => {
signCanvas.current?.clear()
const file = e.target.files![0]
setSignLabelUploaded(file.name)
const base64 = await readFile(file)
signCanvas.current?.fromDataURL(base64 as string)
}
// eslint-disable-next-line arrow-body-style
// const disabledDate: RangePickerProps['disabledDate'] = (current) => {
// // Can not select days before today and today
// return current && current < dayjs().endOf('day');
// };
// 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 onSubmit={handleSubmit} className='space-y-8'>
<div className='space-y-2'>
<Label>Leave Type</Label>
<Select value={leaveType} onValueChange={val => setLeaveType(val)}>
{/* <Select > */}
<SelectTrigger className='w-full'>
<SelectValue placeholder="Select the type of leave" />
</SelectTrigger>
<SelectContent>
<SelectItem value="CT">Cuti Tahunan</SelectItem>
<SelectItem value="CM">Cuti Melahirkan</SelectItem>
<SelectItem value="CB">Cuti Besar</SelectItem>
<SelectItem value="CL">Lainnya</SelectItem>
</SelectContent>
</Select>
<p className='text-muted-foreground text-sm'>Jenis cuti yang diambil, jika lainnya tuliskan alasan cuti tersebut</p>
{leaveType === 'CL' &&
<Input placeholder='Jelaskan alasan cuti...' value={otherLeave} onChange={e => setOtherLeave(e.target.value)} />
}
</div>
<Separator />
<div className='space-y-4'>
<div className='flex flex-col space-y-2'>
<Label>Leave Period</Label>
<DatePicker.RangePicker disabledDate={disabledDate} onChange={val => setLeavePeriod(val)} format={'MMM DD, YYYY'} size='small' className='px-3 py-2' />
</div>
<div className='flex flex-col space-y-2'>
<Label>Return to Work</Label>
<DatePicker disabledDate={disabledDateKembaliKerja} onChange={val => setLeaveIn(val)} defaultValue={leavePeriod && leavePeriod.length === 2 && dayjs(leavePeriod[1]).endOf('day')} format={'MMMM DD, YYYY'} size='small' className='px-3 py-2' disabled={leavePeriod?.length !== 2} />
</div>
<p className='text-muted-foreground text-sm'>Periode masa cuti dari mulai cuti sampai dengan kembali bekerja</p>
</div>
<Separator />
<div className='space-y-4'>
<div className='space-y-2'>
<Label>Address</Label>
<Textarea value={address} onChange={e => setAddress(e.target.value)} maxLength={255} />
</div>
<div className='space-y-2'>
<Label>City</Label>
<Input value={city} onChange={e => setCity(e.target.value)} maxLength={50} />
</div>
<p className='text-muted-foreground text-sm'>Alamat yang Dapat Dihubungi Ketika Cuti</p>
</div>
<Separator />
<div className='space-y-4'>
<div className='space-y-2'>
<Label>Send to</Label>
<Input defaultValue='Stevanus Akbar Alexander' disabled readOnly />
</div>
<div className='space-y-2'>
<Label>Mentions to</Label>
<MultiSelect mode="multiple" allowClear placeholder="Add mentions to Team Leader" size='large' className='w-full'
options={TL_LIST?.length! > 0 ? TL_LIST?.map(item => { return { value: item.id, label: item.fullname } }) : []} value={mentionsTo} onChange={(val) => setMentionsTo(val)}
optionFilterProp="children"
filterOption={(input, option) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase())}
/>
</div>
</div>
<div className='space-y-4'>
<div className='flex items-center space-x-3'>
<Switch checked={includeSign} onCheckedChange={setIncludeSign} />
<Label>Add Signature</Label>
</div>
{includeSign &&
<div className='space-y-3'>
<p className='text-muted-foreground text-sm'>Draw your signature on the canvas</p>
<div className='w-full h-64 sm:h-96 relative'>
<SignaturePad
ref={signCanvas} canvasProps={{
className: 'border border-gray-400 rounded-2xl shadow bg-white w-full h-full absolute'
}}
/>
</div>
<div className='flex flex-col sm:flex-row sm:items-center justify-between space-y-2 sm:space-y-0'>
{/* <input placeholder='or upload sign' type='file' className='input' accept='image/*' onChange={importSign} /> */}
<div className="flex flex-row items-center">
<input type="file" id="custom-input" onChange={importSign} hidden />
<label htmlFor="custom-input"
className="block text-sm bg-orange-200 dark:bg-orange-800 text-orange-900 dark:text-orange-50 mr-3 py-2 px-4 rounded-md border-0 font-semibold cursor-pointer"
>
Choose file
</label>
<label className="text-sm text-muted-foreground">{signLabelUploaded}</label>
</div>
{/* <Button type='button' onClick={() => console.log(signCanvas.current?.isEmpty())}>Save</Button> */}
<Button variant='destructive' type='button' onClick={clearSignCanvas}>Clear</Button>
</div>
{imgSign && <img alt='' src={imgSign} className='border-2 border-gray-300 shadow rounded-2xl' />}
</div>
}
</div>
<Separator />
<div className='flex flex-col space-y-2'>
<Button type='button' variant='secondary' disabled={isLoading} onClick={() => handleSubmit('' as any, true)}><i className="ti ti-eye icon pb-1 mr-2"></i>Preview</Button>
<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>
</>
);
}
export default Component;