Files
hats-app/app/(dashboard)/presence-v2/components/FormComponent.tsx
T
Ichsan Kurniawan d09799068d Update member IDs and refactor geolocation
Adjust team data and improve geolocation handling. In app/(dashboard)/hats-team/page.tsx several TeamMember IDs were updated and a new member (Teddy Setiawan) was added; pastMembers IDs were also adjusted. In app/(dashboard)/presence-v2/components/FormComponent.tsx geolocation logic was refactored: moved PositionOptions constant outside the component, added useCallback for displayLocation, successCallback, and errorCallback, fixed useEffect dependencies to use stable callbacks, reduced noisy toasts on non-critical errors, and corrected an error-toast formatting issue. Also added useCallback to imports and minor formatting cleanups.
2026-02-09 23:41:21 +07:00

249 lines
10 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 dayjs from 'dayjs';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import CameraV2 from './CameraV2';
import { Separator } from '@/components/ui/separator';
import useAxiosAuth from '@/lib/axios/useAxiosAuth';
import { Icons } from '@/components/Icons';
import { toast } from 'sonner';
import { Label } from '@/components/ui/label';
// Move options OUTSIDE the component so it doesn't recreate on every render
const GEOLOCATION_OPTIONS: PositionOptions = {
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 0
};
type Props = {
isCheckout?: boolean
workingStatusList: any[]
};
const FormComponent: FC<Props> = ({ isCheckout, workingStatusList }) => {
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 [workingStatus, setWorkingStatus] = useState('')
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 (!isCheckout) {
if (!workingStatus) {
toast.error('Please select your working status first!')
return
}
}
if (!photo) {
toast.error('Photo is required!')
return
}
if (!note) {
toast.error('Please add a little notes!')
return
}
const title = isCheckout ? 'Check-Out' : 'Check-In'
const endpoint = isCheckout ? '/presence/check-out' : '/presence/check-in'
setIsLoading(true)
const payload = {
nik: session?.user.detail.nik,
datetime: null,
working_status: workingStatus,
image: photo ? photo.replace('data:image/jpeg;base64,', '').replace('data:image/png;base64,', '') : '',
location_name: locationName,
latitude,
longitude,
area_code: null,
device_code: process.env.DEVICE_CODE || "40001",
manual_presence: true,
note: note ? note : isCheckout ? '' : ''
}
console.log(payload)
axios.post(endpoint, payload).then(res => {
toast.info(`${title} success`)
router.replace('/')
router.refresh()
}).catch(error => {
setIsLoading(false)
toast.error(`${title} failed`, { description: `(${error.response?.data?.code || error.response?.status || '-'}) ${error.response?.data?.message || error.response?.statusText || error.message}` })
})
}
const getIcon = (code: string) => {
switch (code) {
case 'WFH':
return 'ti ti-home'
case 'WFS':
return 'ti ti-building-community'
case 'SKT':
return 'ti ti-stethoscope'
case 'CT01':
return 'ti ti-speedboat'
default:
return 'ti ti-speedboat'
}
}
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-1 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 className='flex items-center text-sm space-x-2'>
<p className='text-muted-foreground'>{isCheckout ? 'Check-out' : 'Check-in'} time: </p>
<p>{dayjs().format('HH:mm')}</p>
</div>
</div>
<Separator />
<div className='flex flex-col items-center space-y-3 w-full'>
{!isCheckout &&
<div className='space-y-2 flex flex-col items-center'>
<Label>Working status</Label>
<p className='text-xs sm:text-sm text-muted-foreground'>Status kerja pada saat absensi</p>
<div className='flex items-center flex-wrap space-x-5 text-sm'>
{workingStatusList && workingStatusList.length > 0 ?
workingStatusList.map((item, key) =>
<div className='flex flex-col items-center space-y-1' key={key}>
<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={`${getIcon(item.code)} icon text-2xl`}></i>
</button>
<p className='text-center'>{item.name}</p>
</div>
) :
<div>
Working status not available, please contact administrator.
</div>
}
</div>
</div>
}
<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="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;