Files
hats-app/app/performance/[id]/components/CreateAttendance.tsx
T
Ichsan Kurniawan 7d18e9f38f Add CreateAttendance and update UI/hooks
Add a new CreateAttendance component to allow admins to create manual attendance (Alpha) with confirmation dialog and server API call. Lazy-load the CreateAttendance component in EmployeeAlpha and wrap usages with Suspense plus a loading fallback to reduce initial bundle size. Update Performance page to use a centered Suspense fallback. Improve ImportExcel UX by showing a full-loading state, tweaking button/icon styles, and fixing modal sizing/scroll behavior. Enhance useFetchWithAxios to accept nullable URLs and SWR options, adjust the fetcher signature, and return the nested data payload. Add a "use server" directive and imports in lib/server-api, and apply small type/formatting tweaks (table size cast and minor UI/text refinements).
2026-02-22 23:33:15 +07:00

204 lines
11 KiB
TypeScript

"use client"
import { useState, type FC } from 'react';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog';
import { DatePicker, Form, Input, Radio } from 'antd';
import { Button } from '@/components/ui/button';
import { CirclePlus, Loader2 } from 'lucide-react';
import dayjs from 'dayjs';
import { Label } from '@/components/ui/label';
import { getIconWorkingStatus } from '@/lib/helper';
import { useRouter } from 'next/navigation';
import useMobileView from '@/hooks/useMobileView';
import { useFetchWithAxios } from '@/lib/axios/useFetch';
import { serverApiCall } from '@/lib/server-api';
import { toast } from 'sonner';
import { useSession } from 'next-auth/react';
type Props = {
user: any
date: string
};
const CreateAttendance: FC<Props> = ({ user, date }) => {
const [isLoading, setIsLoading] = useState(false)
const [showDialog, setShowDialog] = useState(false)
const [showConfirm, setShowConfirm] = useState(false)
const [workingStatus, setWorkingStatus] = useState('')
const [isCreateCheckout, setIsCreateCheckout] = useState<any>(undefined)
const [checkinTime, setCheckInTime] = useState<any>('')
const [checkoutTime, setCheckoutTime] = useState<any>('')
const { data: session } = useSession()
const router = useRouter()
const [form] = Form.useForm();
const { isMobile } = useMobileView()
const { data: resWorkingStatusList } = useFetchWithAxios('/presence/list-status')
const workingStatusList = resWorkingStatusList?.working_status || []
const handleSubmit = async () => {
setIsLoading(true)
const data = form.getFieldsValue()
const payload = {
"nik": user.nik,
"working_status": workingStatus,
"area_code": workingStatus === 'WFO' ? "A01" : undefined,
"working_hours_start": `${dayjs(date).format('YYYY-MM-DD')} ${checkinTime}:00`,
"create_checkout": isCreateCheckout,
"working_hours_end": isCreateCheckout ? `${dayjs(date).format('YYYY-MM-DD')} ${checkoutTime}:00` : undefined,
"note": data['note']
}
const res = await serverApiCall('POST', '/presence/manual', payload)
if (res.success) {
toast.success('Attendance created successfully', {
description: 'Create manual attendance successfully!',
action: <Button variant='outline' onClick={() => router.push('/admin/report/history')}>See attendance</Button>,
})
handleClose()
router.refresh()
} else {
toast.error(`Fail to create attendance`, { description: `(${res.code || '-'}) ${res.message}` })
}
setIsLoading(false)
}
const handleClose = () => {
setShowDialog(false)
setShowConfirm(false)
setCheckInTime('')
setCheckoutTime('')
form.resetFields()
}
return (
<>
{session?.user.detail.role.allow_admin_panel ?
<Button size='icon' variant='outline' className='h-9 w-9 cursor-pointer' title='Create attendance' onClick={() => setShowDialog(true)}>
<CirclePlus className='text-teal-500 h-4 w-4' />
</Button>
: null
}
{showDialog &&
<AlertDialog open={true}>
<AlertDialogContent className='overflow-y-auto max-h-[95vh]'>
<AlertDialogHeader className='flex flex-row justify-between'>
<div>
<AlertDialogTitle>Create Attendance</AlertDialogTitle>
<AlertDialogDescription>
Create manual attendance for <strong>{user?.fullname}</strong> on <strong>{dayjs(date).format('dddd, DD MMMM YYYY')}</strong>.
</AlertDialogDescription>
</div>
</AlertDialogHeader>
<Form form={form} onFinish={() => setShowConfirm(true)} scrollToFirstError layout="vertical" size='small' requiredMark={false}>
<div className='grid grid-cols-1 font-medium gap-y-0'>
<div className='space-y-2 pb-5'>
<Label>Working status</Label>
<div className='flex items-center flex-wrap justify-center gap-5 text-sm'>
<div className='flex flex-col items-center space-y-1'>
<button type='button' className={`rounded-xl w-20 h-20 ${workingStatus === 'WFO' ? 'bg-zinc-200 dark:bg-zinc-700 ' : 'btn-outline'}`} onClick={() => setWorkingStatus('WFO')}>
<i className='ti ti-building icon text-2xl'></i>
</button>
<p className='text-center text-muted-foreground'>Work From Office</p>
</div>
{workingStatusList && workingStatusList.length > 0 ?
workingStatusList.map((item: any, key: number) =>
<div className='flex flex-col items-center space-y-1' key={key}>
<button type='button' className={`rounded-xl w-20 h-20 ${workingStatus === item.code ? 'bg-zinc-200 dark:bg-zinc-700 ' : 'btn-outline'}`} onClick={() => setWorkingStatus(item.code)}>
<i className={`${getIconWorkingStatus(item.code)} icon text-2xl`}></i>
</button>
<p className='text-center text-muted-foreground'>{item.name}</p>
</div>
) :
<div>
Working status not available, please contact administrator.
</div>
}
</div>
</div>
<Form.Item label='Check-in time' name='working_hours_start' rules={[{ required: true }]}>
{isMobile ?
<input className='input w-full' type='time' value={checkinTime} onChange={(e) => setCheckInTime(e.target.value)} />
:
<DatePicker.TimePicker placeholder='Select check-in time'
onChange={val => setCheckInTime(dayjs(val).format('HH:mm'))}
className='input w-full' format='HH:mm'
getPopupContainer={(triggerNode: any) => triggerNode.parentNode}
showNow={false}
/>
}
</Form.Item>
<Form.Item label='Create Check-out' name='create_checkout'>
<Radio.Group onChange={e => setIsCreateCheckout(e.target.value)}>
<Radio value={true}>Yes</Radio>
<Radio value={false}>No</Radio>
</Radio.Group>
</Form.Item>
{isCreateCheckout &&
<Form.Item label='Check-out Time' name='working_hours_end'>
{isMobile ?
<input className='input w-full' type='time' value={checkoutTime} onChange={(e) => setCheckoutTime(e.target.value)} />
:
<DatePicker.TimePicker placeholder='Select check-out time'
onChange={val => setCheckoutTime(dayjs(val).format('HH:mm'))}
className='input w-full' format='HH:mm'
getPopupContainer={(triggerNode: any) => triggerNode.parentNode}
showNow={false}
/>
}
</Form.Item>
}
<Form.Item label='Note' name='note'>
<Input.TextArea className='w-full input' rootClassName='px-3! py-2!' placeholder='Enter a little attendance notes...' />
</Form.Item>
</div>
<AlertDialogFooter>
<AlertDialogCancel disabled={isLoading} onClick={handleClose} >
Cancel
</AlertDialogCancel>
<AlertDialogAction disabled={isLoading} onClick={() => { setShowConfirm(true) }} type='submit'>
{isLoading && (
<Loader2 size={20} className="animate-spin" />
)}
Save Attendance
</AlertDialogAction>
</AlertDialogFooter>
</Form>
</AlertDialogContent>
</AlertDialog>
}
{showConfirm &&
<AlertDialog open={true}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
<AlertDialogDescription>
This action will be create a manual attendance for <strong>{user?.fullname}</strong> on <strong>{dayjs(date).format('dddd, DD MMMM YYYY')}</strong>. This data will be stored on our server, you can't change it when you done.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isLoading} onClick={() => setShowConfirm(false)}>Cancel</AlertDialogCancel>
<AlertDialogAction disabled={isLoading} onClick={handleSubmit}>
{isLoading && (
<Loader2 size={20} className="animate-spin" />
)}
Continue
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
}
</>
);
}
export default CreateAttendance;