Files
hats-app/app/(dashboard)/components/NeedApproval.tsx
T
Ichsan Kurniawan 7d6549f892 Enforce page and action-based permissions
Use RBAC permissions to guard dashboard pages and control approval and export actions. Reuse cached sessions and refine permission badges and available icons.
2026-11-10 16:32:15 +07:00

290 lines
16 KiB
TypeScript

'use client'
import { FC, lazy, Suspense, useEffect, useState } from 'react';
import { Badge } from '@/components/ui/badge';
import { ScrollArea } from '@/components/ui/scroll-area';
import dayjs from 'dayjs';
import FilterDataDashboard from './FilterDataDashboard';
import { cn } from '@/lib/utils';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog';
import { Icons } from '@/components/Icons';
import { Button } from '@/components/ui/button';
import useAxiosAuth from '@/lib/axios/useAxiosAuth';
import PageLoading from '@/components/loader/PageLoading';
import { useRouter } from 'next/navigation';
import { toast } from 'sonner';
import FallbackAvatar from '@/components/loader/FallbackAvatar';
const ViewAvatar = lazy(() => import('@/components/ViewAvatar'));
const Avatar = lazy(() => import('@/components/ViewAvatar').then(mod => ({ default: mod.Avatar })));
type Props = {
data: any
isAllowApprove?: boolean
className?: string
};
const sortBy = 'presence_date'
const filterBy = ['fullname', 'position_name', 'working_status']
const NeedApproval: FC<Props> = ({ data, isAllowApprove, className }) => {
const [isLoading, setIsLoading] = useState(false)
const [isFullLoading, setIsFullLoading] = useState(false)
const [showDialog, setShowDialog] = useState(false)
const [showConfirm, setShowConfirm] = useState(false)
const [isApproval, setIsApproval] = useState(false)
const [dataPresence, setDataPresence] = useState<any>(null)
const [presenceId, setPresenceId] = useState(0)
const [dataFilter, setDataFilter] = useState<any[]>([])
const [search, setSearch] = useState('')
const [sort, setSort] = useState('desc')
const axios = useAxiosAuth()
const router = useRouter()
useEffect(() => {
let newData = [...data.list]
if (!search) {
newData = [...data.list]
} else {
newData = [...data.list].filter(item => (
filterBy.some(key => {
const value = item[key]?.toLowerCase();
return value && value.includes(search.toLowerCase());
})
))
}
if (sort === 'asc') {
newData.sort((a, b) => (dayjs(a[sortBy]).isAfter(dayjs(b[sortBy])) ? 1 : -1))
} else {
newData.sort((b, a) => (dayjs(a[sortBy]).isAfter(dayjs(b[sortBy])) ? 1 : -1))
}
setDataFilter(newData)
}, [data.list, search, sort])
const handleFetchPresenceByID = async (presenceId: number) => {
try {
setPresenceId(presenceId)
setIsFullLoading(true)
const { data: res } = await axios.get('/presence/approval/info/' + presenceId)
// console.log(res)
setDataPresence(res.data)
setShowDialog(true)
} catch (error: any) {
toast.error(`Failed to get detail attendance`, {
description: `(${error.response.data.code || error.response.status || '-'}) ${error.response.data.message || error.response.statusText || error.message}`
})
} finally {
setIsFullLoading(false)
}
}
const handleApproval = async () => {
try {
setIsLoading(true)
const { data: res } = await axios.put('/presence/approval/' + presenceId, {
"approve_status": isApproval
})
toast.success(isApproval ? 'Success Approval' : 'Success Decline', {
description: res.message,
action: <Button variant='outline' onClick={() => router.push('/admin/manual/approval')}>See approval</Button>,
})
setShowDialog(false)
setShowConfirm(false)
router.refresh()
} catch (error: any) {
toast.error(`Failed approval`, {
description: `(${error.response.data.code || error.response.status || '-'}) ${error.response.data.message || error.response.statusText || error.message}`
})
} finally {
setIsLoading(false)
}
}
return (
<>
<FilterDataDashboard search={search} onSearch={e => setSearch(e.target.value)} sort={sort} onSortChange={val => setSort(val)} />
<ScrollArea className={cn("hidden sm:block px-6", className)} height='max-h-[325px]'>
<div className="space-y-8">
{data && data.list?.length > 0 ?
dataFilter.map((item: any, key: number) =>
<div className="grid grid-cols-8" key={key}>
<div className="flex items-center col-span-4">
<Suspense fallback={<FallbackAvatar />}>
<ViewAvatar avatar={item.avatar} />
</Suspense>
<div className="ml-4 space-y-0.5 max-w-[70%] 2xl:max-w-[80%]">
<p className="text-xs sm:text-sm font-medium leading-none">{item.fullname}</p>
<p className="text-xs md:text-sm text-muted-foreground">
{item.position_name || '--'}
</p>
</div>
</div>
<div className='col-span-2 flex items-center text-2xl'>
<i className="ti ti-window-maximize text-his cursor-pointer hover:opacity-70 duration-300" onClick={() => handleFetchPresenceByID(item.presence_id)} title='Approval Attendance'></i>
</div>
<div className="col-span-2 text-xs text-right space-y-1">
{item.working_status === 'WFH' ?
<Badge variant='secondary' className="text-[11px]">{item.working_status}</Badge>
:
item.working_status === 'WFS' ?
<Badge className="text-[11px]">{item.working_status}</Badge>
:
item.working_status === 'SKT' ?
<Badge variant='destructive' className="text-[11px]">{item.working_status}</Badge>
:
<Badge variant='outline' className="text-[11px]">{item.working_status}</Badge>
}
<p className="font-semibold">{dayjs(item.working_hours_start).format('YYYY-MM-DD HH:mm')}</p>
</div>
</div>
)
:
<div className="h-32 w-full flex justify-center items-center" >
No results.
</div>
}
</div>
</ScrollArea>
{/* MOBILE VIEW */}
<div className={cn("overflow-y-auto block sm:hidden max-h-[325px] px-6", className)}>
<div className="w-full -mt-2">
{data && data.list?.length > 0 ?
dataFilter.map((item: any, key: number) =>
<div className="flex justify-between border-b border-zinc-300 dark:border-zinc-800 pt-3 pb-3.5" key={key} onClick={() => handleFetchPresenceByID(item.presence_id)}>
<div className='flex'>
<Suspense fallback={<FallbackAvatar />}>
<Avatar avatar={item.avatar} className='w-10 h-10' />
</Suspense>
<div className="ml-4 space-y-0.5">
<p className="text-sm font-medium leading-none">{item.fullname}</p>
<p className="text-xs text-muted-foreground pb-2">
{item.position_name || '--'}
</p>
<p className="text-xs font-semibold text-muted-foreground border-t border-zinc-300 dark:border-zinc-800 pt-1 w-max">{dayjs(item.working_hours_start).format('ddd, DD MMM YYYY HH:mm')}</p>
</div>
</div>
<div className="text-xs space-y-1">
{item.working_status === 'WFH' ?
<Badge variant='secondary' className="text-[11px]">{item.working_status}</Badge>
:
item.working_status === 'WFS' ?
<Badge className="text-[11px]">{item.working_status}</Badge>
:
item.working_status === 'SKT' ?
<Badge variant='destructive' className="text-[11px]">{item.working_status}</Badge>
:
<Badge variant='outline' className="text-[11px]">{item.working_status}</Badge>
}
</div>
</div>
)
:
<div className="h-32 w-full flex justify-center items-center" >
No results.
</div>
}
</div>
</div>
{showDialog &&
<AlertDialog open={true}>
<AlertDialogContent className='max-w-full md:max-w-[760px] py-6 md:px-10 overflow-y-auto max-h-[95vh]'>
<AlertDialogHeader className='flex flex-row justify-between'>
<div>
<AlertDialogTitle>Detail Attendance</AlertDialogTitle>
<AlertDialogDescription>
This action cannot be undone. This will permanently approve or decline this presence.
</AlertDialogDescription>
</div>
<Button variant='outline' size='icon' disabled={isLoading} onClick={() => setShowDialog(false)}><i className="ti ti-x text-xl"></i ></Button>
</AlertDialogHeader>
<div className='grid grid-cols-1 md:grid-cols-5 text-center md:text-left text-sm md:text-base md:my-3'>
<div className='col-span-2 flex flex-col items-center md:items-start'>
<Suspense fallback={<FallbackAvatar className='w-52 h-52 rounded-xl' />}>
<ViewAvatar isPresence avatar={dataPresence.face_image} className='w-52 h-52 sm:w-52 sm:h-52 rounded-xl shadow' />
</Suspense>
<span className='text-base font-semibold mt-2'>{dataPresence.user.fullname}</span>
<span className='text-muted-foreground'>{dataPresence?.user?.position?.name || dataPresence?.user.nickname}</span>
</div>
<div className='col-span-3 space-y-4 mt-5 md:mt-0'>
<div className='flex flex-col items-center md:items-start'>
<p className='text-muted-foreground text-xs md:text-sm font-medium'>Presence information :</p>
<div className='flex items-center space-x-2'>
<p><span className='font-semibold'>{dayjs(dataPresence.working_hours_start).format('dddd, DD MMMM YYYY')}</span></p>
<Badge>{dataPresence.working_status}</Badge>
</div>
</div>
<div>
<p className='text-muted-foreground text-xs md:text-sm font-medium'>Check-in time :</p>
<p>{dayjs(dataPresence.working_hours_start).format('HH:mm A')}</p>
</div>
<div className='flex flex-col'>
<p className='text-muted-foreground text-xs md:text-sm font-medium'>Location :</p>
<p className='font-medium text-xs'>{dataPresence.latitude}, {dataPresence.longitude}</p>
<div>
{dataPresence.location_name || '-'}
</div>
</div>
<div>
<p className='text-muted-foreground text-xs md:text-sm font-medium'>Device :</p>
<p className='wrap-break-word'>{dataPresence.device.name || '-'}</p>
</div>
<div>
<p className='text-muted-foreground text-xs md:text-sm font-medium'>Notes :</p>
<p className='wrap-break-word'>{dataPresence.note || '-'}</p>
</div>
<div>
<p className='text-muted-foreground text-xs md:text-sm font-medium'>Check-out time :</p>
<p>{dataPresence?.presence_checkout?.working_hours_start ? dayjs(dataPresence?.presence_checkout?.working_hours_end).format('HH:mm A') : 'Not check-out yet'}</p>
</div>
</div>
</div>
{isAllowApprove &&
<AlertDialogFooter>
<AlertDialogCancel disabled={isLoading} onClick={() => { setIsApproval(false); setShowConfirm(true) }} className='text-red-500 font-semibold'>
Decline
</AlertDialogCancel>
<AlertDialogAction disabled={isLoading} onClick={() => { setIsApproval(true); setShowConfirm(true) }}>
{isLoading && (
<Icons.spinner className="mr-1 h-4 w-4 animate-spin" />
)}
Approve
</AlertDialogAction>
</AlertDialogFooter>
}
</AlertDialogContent>
</AlertDialog>
}
{showConfirm &&
<AlertDialog open={true}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Approval Confirmation</AlertDialogTitle>
<AlertDialogDescription>
This action cannot be undone. This will permanently <span className='font-bold'>{isApproval ? 'Approve' : 'Decline'}</span> this presence.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isLoading} onClick={() => setShowConfirm(false)} className='text-red-500 font-semibold'>
Cancel
</AlertDialogCancel>
<AlertDialogAction disabled={isLoading} onClick={handleApproval}>
{isLoading && (
<Icons.spinner className="mr-1 h-4 w-4 animate-spin" />
)}
Continue
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
}
{isFullLoading && <PageLoading className='bg-opacity-40 dark:bg-opacity-20 z-999' />}
</>
);
}
export default NeedApproval;