mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-05 10:56:28 +00:00
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).
This commit is contained in:
@@ -21,9 +21,10 @@ const releaseNotes: ReleaseNote[] = [
|
||||
type: "minor",
|
||||
changes: [
|
||||
{ category: "feature", description: "Added the ability to view and re-download leave application forms in the Employee History page (Leave, Permit, and Sick tabs)" },
|
||||
{ category: "feature", description: "Added employee alpha stats and employee alpha detail in Employee Performance Page" },
|
||||
{ category: "feature", description: "Added total WFO, WFH and WFS in Admin Summary Report" },
|
||||
{ category: "feature", description: "Added batch import from Excel files in Admin Manual Attendance" },
|
||||
{ category: "feature", description: "Added Alpha statistics and detailed Alpha records on the Employee Performance page" },
|
||||
{ category: "feature", description: "Added the ability to create manual attendance records for Alpha status on the Employee Performance page" },
|
||||
{ category: "feature", description: "Added total counts for WFO, WFH, and WFS in the Admin Summary Report" },
|
||||
{ category: "feature", description: "Added batch import functionality from Excel files in Admin Manual Attendance" },
|
||||
]
|
||||
},
|
||||
{
|
||||
|
||||
@@ -37,6 +37,7 @@ export default function ImportExcel() {
|
||||
|
||||
const onDrop = useCallback((acceptedFiles: any[]) => {
|
||||
acceptedFiles.forEach(async (file: any) => {
|
||||
setFullLoading(true);
|
||||
const reader = new FileReader();
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
|
||||
@@ -93,18 +94,18 @@ export default function ImportExcel() {
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button variant='outline' onClick={() => setShowModal(true)}><FileSpreadsheet />Import Excel</Button>
|
||||
<Button variant='outline' onClick={() => setShowModal(true)}><FileSpreadsheet className='text-muted-foreground' />Import Excel</Button>
|
||||
|
||||
{showModal ?
|
||||
<AlertDialog open={true}>
|
||||
<AlertDialogContent className={`max-h-[90vh] duration-300 min-w-full ${rowData && rowData.length > 0 ? 'min-w-[90vw]' : 'sm:min-w-[600px]'} overflow-y-auto`}>
|
||||
<AlertDialogContent className={`max-h-[95vh] overflow-y-hidden duration-300 min-w-full ${rowData && rowData.length > 0 ? 'min-w-[90vw]' : 'sm:min-w-[600px]'}`}>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{rowData && rowData.length > 0 ? "Review Your Data" : "Upload Excel File"}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{rowData && rowData.length > 0 ? "Please review attendance data first before saving!" : "Please attach your excel file for batching import"}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex flex-col gap-2 max-h-[65vh] md:max-h-[70vh] 2xl:max-h-[75vh] overflow-y-auto">
|
||||
{/* Drop area */}
|
||||
<Dropzone ref={dropzoneRef} onDrop={onDrop} multiple={false} noClick noKeyboard
|
||||
accept={{
|
||||
|
||||
@@ -111,7 +111,7 @@ const ComponentPage: FC<Props> = ({ data }) => {
|
||||
defaultPageSize: 15,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
size: 'middle'
|
||||
size: 'middle' as any
|
||||
},
|
||||
scroll: { x: 'max-content' },
|
||||
tableLayout: 'auto',
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
"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;
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client"
|
||||
|
||||
import { useState, type FC } from 'react';
|
||||
import { lazy, Suspense, useState, type FC } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@@ -8,12 +8,16 @@ import {
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
} from '@/components/ui/dialog';
|
||||
import { CalendarX2, AlertTriangle, Calendar, ChevronRight, X, UserX, Eye } from 'lucide-react';
|
||||
import { CalendarX2, Calendar, Eye } from 'lucide-react';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { format, getMonth, getYear, parseISO } from 'date-fns';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import LazyLoading from '@/components/loader/LazyLoading';
|
||||
|
||||
const CreateAttendance = lazy(() => import('./CreateAttendance'));
|
||||
|
||||
type Props = {
|
||||
user: any
|
||||
alphaData: any[]
|
||||
};
|
||||
|
||||
@@ -22,7 +26,7 @@ const monthColors: Record<number, { bg: string; text: string; border: string; do
|
||||
1: { bg: 'bg-destructive/10', text: 'text-destructive', border: 'border-destructive/20', dot: 'bg-destructive' },
|
||||
};
|
||||
|
||||
const EmployeeAlpha: FC<Props> = ({ alphaData }) => {
|
||||
const EmployeeAlpha: FC<Props> = ({ alphaData, user }) => {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
// Group by month
|
||||
@@ -90,25 +94,18 @@ const EmployeeAlpha: FC<Props> = ({ alphaData }) => {
|
||||
{dates.map((item, idx) => {
|
||||
const d = parseISO(item.date);
|
||||
return (
|
||||
<div
|
||||
key={item.date}
|
||||
className={`flex items-center gap-3 rounded-xl border ${colors.border} ${colors.bg} px-4 py-3 transition-all duration-200 hover:scale-[1.01]`}
|
||||
style={{ animationDelay: `${(mIdx * 4 + idx) * 50}ms` }}
|
||||
>
|
||||
<div key={item.date} className={`flex items-center gap-3 rounded-xl border ${colors.border} ${colors.bg} px-4 py-3 transition-all duration-200 hover:scale-[1.01]`} style={{ animationDelay: `${(mIdx * 4 + idx) * 50}ms` }}>
|
||||
<div className={`flex h-9 w-9 items-center justify-center rounded-lg bg-card border ${colors.border}`}>
|
||||
<Calendar className={`h-4 w-4 ${colors.text}`} />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium text-foreground">
|
||||
{format(d, 'EEEE')}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground font-mono">
|
||||
{format(d, 'dd MMMM yyyy')}
|
||||
</p>
|
||||
<p className="text-sm font-medium text-foreground">{format(d, 'EEEE')}</p>
|
||||
<p className="text-xs text-muted-foreground font-mono">{format(d, 'dd MMMM yyyy')}</p>
|
||||
</div>
|
||||
<Badge variant="outline" className={`${colors.text} ${colors.border} ${colors.bg} text-xs`}>
|
||||
Alpha
|
||||
</Badge>
|
||||
<Badge variant="outline" className={`${colors.text} ${colors.border} ${colors.bg} text-xs`}>Alpha</Badge>
|
||||
<Suspense fallback={<LazyLoading />}>
|
||||
<CreateAttendance user={user} date={format(d, 'yyyy-MM-dd')} />
|
||||
</Suspense>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -40,8 +40,6 @@ const PerformanceComponent: FC<Props> = async ({ id, start_date, end_date }) =>
|
||||
|
||||
const [user, performance, alpha] = await Promise.all([fetchUser, fetchPerformace, fetchAlpha])
|
||||
|
||||
console.log(alpha)
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className='gap-4 space-y-7 w-full mx-auto mt-6'>
|
||||
@@ -121,7 +119,9 @@ const PerformanceComponent: FC<Props> = async ({ id, start_date, end_date }) =>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<div className='flex gap-2'>
|
||||
<CardTitle className="text-sm font-medium">Total Alpha</CardTitle>
|
||||
<EmployeeAlpha alphaData={alpha} />
|
||||
<Suspense fallback={<LazyLoading />}>
|
||||
<EmployeeAlpha user={user} alphaData={alpha} />
|
||||
</Suspense>
|
||||
</div>
|
||||
<i className="ti ti-clock-play icon h-4 w-4 text-his text-xl"></i>
|
||||
</CardHeader>
|
||||
|
||||
@@ -48,7 +48,7 @@ const PerformancePage: FC<Props> = async ({ params, searchParams }) => {
|
||||
</div>
|
||||
<DateRangePicker />
|
||||
</div>
|
||||
<Suspense key={`${start_date}${end_date}`} fallback={<LazyLoading />}>
|
||||
<Suspense key={`${start_date}${end_date}`} fallback={<div className='w-full h-[70vh] flex justify-center items-center'><LazyLoading /></div>}>
|
||||
<PerformanceComponent id={id} start_date={start_date as string} end_date={end_date as string} />
|
||||
</Suspense>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import useSWR from 'swr'
|
||||
import useSWR, { type SWRConfiguration } from 'swr'
|
||||
import { useSession } from 'next-auth/react';
|
||||
import { type ResponseData } from '@/types/types';
|
||||
import useAxiosAuth from './useAxiosAuth';
|
||||
@@ -25,14 +25,17 @@ export default function useFetch(endpoint: string) {
|
||||
}
|
||||
|
||||
|
||||
export function useFetchWithAxios(url: string) {
|
||||
export function useFetchWithAxios(url: string | null, options?: SWRConfiguration) {
|
||||
const axios = useAxiosAuth();
|
||||
const fetcher = () => axios.get(url).then(res => res.data)
|
||||
|
||||
const { data, error, isLoading, mutate } = useSWR<ResponseData<any>>(url, fetcher)
|
||||
// Only define fetcher if url is present
|
||||
const fetcher = (url: string) => axios.get(url).then(res => res.data)
|
||||
|
||||
// Pass url directly. If it is null, SWR will pause.
|
||||
const { data, error, isLoading, mutate } = useSWR<ResponseData<any>>(url, fetcher, options)
|
||||
|
||||
return {
|
||||
data,
|
||||
data: data?.data,
|
||||
isLoading,
|
||||
error,
|
||||
mutate
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
"use server"
|
||||
|
||||
import { getServerSession } from "next-auth";
|
||||
import { authOptions } from "@/pages/api/auth/[...nextauth]"; // Adjust path as needed
|
||||
import axios from "@/lib/axios"; // Your axios instance
|
||||
|
||||
Reference in New Issue
Block a user