Files
hats-app/app/(dashboard)/iam-here/components/FormComponent.tsx
T
Ichsan Kurniawan 5a3629badf update performance, manual attendance, redownload leave form
Added the ability to view and re-download leave application forms in the Employee History page (Leave, Permit, and Sick tabs)
Added employee alpha stats and employee alpha detail in Employee Performance Page
Added total WFO, WFH and WFS in Admin Summary Report
Added batch import from Excel files in Admin Manual Attendance
2026-02-20 15:19:42 +07:00

190 lines
7.6 KiB
TypeScript

"use client"
import { FC, useCallback, useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useSession } from 'next-auth/react';
import { Camera as CameraIcon } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Separator } from '@/components/ui/separator';
import useAxiosAuth from '@/lib/axios/useAxiosAuth';
import { Icons } from '@/components/Icons';
import CameraV2 from '../../presence-v2/components/CameraV2';
import { toast } from 'sonner';
import { Label } from '@/components/ui/label';
type Props = {};
const GEOLOCATION_OPTIONS: PositionOptions = {
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 0
};
const FormComponent: FC<Props> = () => {
const OFFICE_PEJATEN_LATTITUDE = -6.27831622506824
const OFFICE_PEJATEN_LONGITUDE = 106.82955901443484
const [showCamera, setShowCamera] = useState(true)
const [photo, setPhoto] = useState('')
const [locationName, setLocationName] = useState('')
const [latitude, setLatitude] = useState(OFFICE_PEJATEN_LATTITUDE)
const [longitude, setLongitude] = useState(OFFICE_PEJATEN_LONGITUDE)
const [note, setNote] = useState('')
const [isLoading, setIsLoading] = useState(false)
const [orientation, setOrientation] = useState<'portrait' | 'landscape' | 'square'>('portrait')
const { data: session } = useSession()
const router = useRouter()
const axios = useAxiosAuth()
// 1. Wrap displayLocation in useCallback
const displayLocation = useCallback(async (latitude: number, longitude: number) => {
try {
const res = await fetch(`https://nominatim.openstreetmap.org/reverse?lat=${latitude}&lon=${longitude}&format=jsonv2&zoom=13`)
if (res.ok) {
const data = await res.json()
console.log(data?.display_name)
setLocationName(data?.display_name)
} else {
// Optional: Reduce noise by not toasting on minor network errors during typing
console.warn(`${res.status} ${res.statusText}`)
}
} catch (error) {
console.error("Error fetching location name", error)
}
}, []);
// 2. Wrap successCallback in useCallback
const successCallback = useCallback((position: GeolocationPosition) => {
const x = position.coords.latitude;
const y = position.coords.longitude;
setLatitude(x);
setLongitude(y);
displayLocation(x, y);
}, [displayLocation]); // Depends on displayLocation
// 3. Wrap errorCallback in useCallback
const errorCallback = useCallback((error: GeolocationPositionError) => {
let errorMessage = 'Unknown error';
switch (error.code) {
case 1:
errorMessage = 'Permission denied';
break;
case 2:
errorMessage = 'Position unavailable';
break;
case 3:
errorMessage = 'Timeout';
break;
}
// Only toast if it's a serious permission issue, or throttle it
toast.warning("Failed to fetch geolocation, reason: " + errorMessage)
}, []);
// 4. Update useEffect dependencies
useEffect(() => {
if (!navigator.geolocation) {
toast.warning('Geolocation not available in your apps')
return
}
navigator.geolocation.getCurrentPosition(successCallback, errorCallback, GEOLOCATION_OPTIONS);
}, [successCallback, errorCallback]); // Now these dependencies are stable
const handleReceivePhoto = (photo: string, landscape?: boolean, w?: number, h?: number) => {
setOrientation(w! > h! ? 'landscape' : w === h ? 'square' : 'portrait')
setPhoto(photo)
setShowCamera(false)
}
const handleSubmit = () => {
if (!photo) {
toast.error('Photo is required!')
return
}
if (!note) {
toast.error('Please add a little notes!')
return
}
setIsLoading(true)
const payload = {
nik: session?.user.detail.nik,
location_name: locationName,
latitude,
longitude,
device_code: "40001",
note: note,
image: photo ? photo.replace('data:image/jpeg;base64,', '').replace('data:image/png;base64,', '') : '',
}
console.log(payload)
axios.post('/presence/check-in/i-am-here', payload).then(res => {
toast.info(`Update Presence success`)
router.replace('/')
router.refresh()
}).catch(error => {
setIsLoading(false)
toast.error(`Update Presence failed`, { description: `(${error.response?.data?.code || error.response?.status || '-'}) ${error.response?.data?.message || error.response?.statusText || error.message}` })
})
}
return (
<>
<div className='space-y-8'>
<div className='flex flex-col justify-center items-center space-y-5'>
{photo ?
<img alt='' src={photo} className={`btn-outline ${orientation === 'portrait' ? 'w-36 h-48' : orientation === 'landscape' ? 'w-48 h-36' : 'w-48 h-48'} rounded-xl object-cover shadow`} />
:
<div className='btn-outline w-36 h-48 rounded-xl flex items-center justify-center bg-zinc-200 dark:bg-zinc-800'></div>
}
<Button variant='outline' onClick={() => setShowCamera(true)}>
<CameraIcon className='mr-2 w-4 h-4' />Retake photo
</Button>
<div className='space-y-2 flex flex-col items-center'>
<div className='flex items-center space-x-2 text-xs sm:text-sm text-muted-foreground'>
<i className="ti ti-map-pin icon text-xl"></i>
<p>{OFFICE_PEJATEN_LATTITUDE}, {OFFICE_PEJATEN_LONGITUDE}</p>
</div>
<div className='flex items-center text-sm text-center w-full md:w-9/12'>
<p>{locationName}</p>
</div>
</div>
</div>
<Separator />
<div className='flex flex-col items-center space-y-3 w-full'>
<div className=' w-full space-y-2'>
<Label>Note</Label>
<Textarea
placeholder="Tell us a little bit about your presence"
className="resize-none" value={note} onChange={(e) => setNote(e.target.value)}
/>
<p className='text-xs sm:text-sm text-muted-foreground'>
Tambahkan catatan kehadiran jika diperlukan
</p>
</div>
</div>
<div className='flex flex-col space-y-2'>
<Button type="submit" disabled={isLoading} onClick={handleSubmit}>
{isLoading && (
<Icons.spinner className="mr-1 h-4 w-4 animate-spin" />
)}
Submit
</Button>
<Button variant='outline' onClick={() => router.back()} disabled={isLoading} >Cancel</Button>
</div>
</div>
{showCamera && <CameraV2 onClose={() => setShowCamera(false)} onSubmit={handleReceivePhoto} />}
</>
);
}
export default FormComponent;