mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-05 10:46:29 +00:00
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
This commit is contained in:
+1
-1
@@ -19,4 +19,4 @@ FIREBASE_APP_ID = "1:422528660020:web:db16e1cba4d357e32f1061"
|
||||
DEVICE_CODE = "40001"
|
||||
NEXT_PUBLIC_HATS_SUPPORT_NAME = "Amalia"
|
||||
NEXT_PUBLIC_HATS_SUPPORT_PHONE = "6285214074002"
|
||||
NEXT_PUBLIC_APP_VERSION = "v1.1.1"
|
||||
NEXT_PUBLIC_APP_VERSION = "v1.1.2"
|
||||
+3
-1
@@ -38,4 +38,6 @@ yarn-error.log*
|
||||
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
next-env.d.ts
|
||||
|
||||
*.log
|
||||
@@ -58,7 +58,7 @@ export default async function DashboardPage() {
|
||||
{lastPresence.is_checkin && lastPresence.device_code !== '11001' &&
|
||||
<Link href='/iam-here'>
|
||||
<Button variant='ghost' title="I'am Here">
|
||||
<span className='animatecss animatecss-tada animatecss-infinite text-2xl'>👋🏻</span>
|
||||
<span className='animated-tada tada text-2xl'>👋🏻</span>
|
||||
</Button>
|
||||
</Link>
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useEffect } from "react"
|
||||
import Image from "next/image"
|
||||
import Link from "next/link"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { clientLogger } from "@/lib/logger-client"
|
||||
|
||||
export default function Error({
|
||||
error,
|
||||
@@ -15,6 +16,7 @@ export default function Error({
|
||||
|
||||
useEffect(() => {
|
||||
console.log({ name: error.name, cause: error.cause, message: error.message, stack: error.stack })
|
||||
clientLogger.error(error.stack!)
|
||||
}, [error])
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client"
|
||||
|
||||
import { useMemo } from "react"
|
||||
import { useMemo, useState } from "react"
|
||||
import dayjs from "dayjs"
|
||||
import { useSearchParams } from "next/navigation"
|
||||
|
||||
@@ -12,7 +12,19 @@ import Pagination from "@/components/pagination"
|
||||
import { getVariantWorkingStatus } from "@/lib/helper"
|
||||
import SortFilter from "../components/SortFilter"
|
||||
import { type ILeaveSickPermit } from "../components/type"
|
||||
import { ResponseData } from "@/types/types"
|
||||
import { IProfile } from "../../profile/components/type"
|
||||
import { PDFDocument } from 'pdf-lib';
|
||||
import { toast } from "sonner"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Download, Eye, Loader2 } from "lucide-react"
|
||||
import useAxiosAuth from "@/lib/axios/useAxiosAuth"
|
||||
|
||||
import relativeTime from "dayjs/plugin/relativeTime";
|
||||
import customParseFormat from 'dayjs/plugin/customParseFormat';
|
||||
|
||||
import "dayjs/locale/id";
|
||||
dayjs.extend(customParseFormat);
|
||||
|
||||
type Props = {
|
||||
data: ILeaveSickPermit[]
|
||||
@@ -20,10 +32,13 @@ type Props = {
|
||||
|
||||
export default function DataTable({ data }: Props) {
|
||||
const searchParams = useSearchParams();
|
||||
const [isPreviewLoading, setIsPreviewLoading] = useState(false)
|
||||
const [isDownLoading, setIsDownLoading] = useState(false)
|
||||
|
||||
const currentPage = Number(searchParams!.get('page') as string) || 1;
|
||||
const pageSize = Number(searchParams!.get('limit') as string) || 10;
|
||||
const savedSort = searchParams!.get('sort') as string || ''
|
||||
const axios = useAxiosAuth()
|
||||
|
||||
const currentTableData = useMemo(() => {
|
||||
const newData = [...data]
|
||||
@@ -35,9 +50,137 @@ export default function DataTable({ data }: Props) {
|
||||
|
||||
const firstPageIndex = (currentPage - 1) * pageSize;
|
||||
const lastPageIndex = firstPageIndex + pageSize;
|
||||
|
||||
return newData.slice(firstPageIndex, lastPageIndex);
|
||||
}, [currentPage, pageSize, savedSort, data]);
|
||||
|
||||
const handlePreviewOrSubmit = async (dataCuti: ILeaveSickPermit, preview?: boolean) => {
|
||||
if (preview) setIsPreviewLoading(true)
|
||||
else setIsDownLoading(true)
|
||||
|
||||
dayjs.locale("id");
|
||||
dayjs.extend(relativeTime);
|
||||
|
||||
try {
|
||||
const { data } = await axios.post('/user/profile', {})
|
||||
const { data: profile }: ResponseData<IProfile> = data
|
||||
|
||||
const url = '/files/form_cuti_empty.pdf'
|
||||
const existingPdfBytes = await fetch(url).then(res => res.arrayBuffer())
|
||||
|
||||
const pdfDoc = await PDFDocument.load(existingPdfBytes)
|
||||
// const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica)
|
||||
|
||||
const pages = pdfDoc.getPages()
|
||||
const firstPage = pages[0]
|
||||
|
||||
firstPage.drawText(profile.division?.name || '', { x: 165, y: 672, size: 11 }) // DEPARTMENT
|
||||
firstPage.drawText(new Date().getFullYear().toString(), { x: 500, y: 672, size: 11 }) // YEAR
|
||||
firstPage.drawText('Stevanus Akbar Alexander', { x: 243, y: 646, size: 11 }) // MGR DEPARTMENT
|
||||
firstPage.drawText(profile.fullname, { x: 243, y: 628, size: 11 }) // NAME
|
||||
firstPage.drawText(profile.position?.name || '', { x: 243, y: 608, size: 11 }) // Positiion
|
||||
/* CUTI TAHUNAN */
|
||||
if (dataCuti.category_code === 'CT') {
|
||||
firstPage.drawText('x', { x: 244, y: 582, size: 16 })
|
||||
}
|
||||
/* CUTI BESAR */
|
||||
if (dataCuti.category_code === 'CB') {
|
||||
firstPage.drawText('x', { x: 244, y: 555, size: 16 })
|
||||
}
|
||||
/* CUTI MELAHIRKAN */
|
||||
if (dataCuti.category_code === 'CM') {
|
||||
firstPage.drawText('x', { x: 374, y: 582, size: 16 })
|
||||
}
|
||||
/* LAINNYA */
|
||||
if (dataCuti.category_code === 'CL') {
|
||||
firstPage.drawText('x', { x: 374, y: 555, size: 16 })
|
||||
// firstPage.drawText(otherLeave, { x: 443, y: 558, size: 10 })
|
||||
}
|
||||
|
||||
firstPage.drawText(dayjs(dataCuti.start_date[0]).format('dddd'), { x: 340, y: 506, size: 11 })
|
||||
firstPage.drawText(dayjs(dataCuti.start_date[0]).format('DD').split('')[0] + ' ' + dayjs(dataCuti.start_date[0]).format('DD').split('')[1], { x: 416, y: 505, size: 13 })
|
||||
firstPage.drawText(dayjs(dataCuti.start_date[0]).format('MM').split('')[0] + ' ' + dayjs(dataCuti.start_date[0]).format('MM').split('')[1], { x: 471, y: 505, size: 13 })
|
||||
firstPage.drawText(dayjs(dataCuti.start_date[0]).format('YY').split('')[0] + ' ' + dayjs(dataCuti.start_date[0]).format('YY').split('')[1], { x: 522, y: 505, size: 13 })
|
||||
|
||||
firstPage.drawText(dayjs(dataCuti.end_date[1]).format('dddd'), { x: 340, y: 483, size: 11 })
|
||||
firstPage.drawText(dayjs(dataCuti.end_date[1]).format('DD').split('')[0] + ' ' + dayjs(dataCuti.end_date[1]).format('DD').split('')[1], { x: 416, y: 482, size: 13 })
|
||||
firstPage.drawText(dayjs(dataCuti.end_date[1]).format('MM').split('')[0] + ' ' + dayjs(dataCuti.end_date[1]).format('MM').split('')[1], { x: 471, y: 482, size: 13 })
|
||||
firstPage.drawText(dayjs(dataCuti.end_date[1]).format('YY').split('')[0] + ' ' + dayjs(dataCuti.end_date[1]).format('YY').split('')[1], { x: 522, y: 482, size: 13 })
|
||||
|
||||
firstPage.drawText(dayjs(dataCuti.return_to_work_date).format('dddd'), { x: 340, y: 461, size: 11 })
|
||||
firstPage.drawText(dayjs(dataCuti.return_to_work_date).format('DD').split('')[0] + ' ' + dayjs(dataCuti.return_to_work_date).format('DD').split('')[1], { x: 416, y: 460, size: 13 })
|
||||
firstPage.drawText(dayjs(dataCuti.return_to_work_date).format('MM').split('')[0] + ' ' + dayjs(dataCuti.return_to_work_date).format('MM').split('')[1], { x: 471, y: 460, size: 13 })
|
||||
firstPage.drawText(dayjs(dataCuti.return_to_work_date).format('YY').split('')[0] + ' ' + dayjs(dataCuti.return_to_work_date).format('YY').split('')[1], { x: 522, y: 460, size: 13 })
|
||||
|
||||
|
||||
firstPage.drawText(dataCuti.contact_street, { x: 285, y: 428, size: 10 })
|
||||
firstPage.drawText(dataCuti.contact_city, { x: 285, y: 406, size: 11 })
|
||||
firstPage.drawText(profile.phone_number || '', { x: 285, y: 384, size: 11 })
|
||||
|
||||
|
||||
// firstPage.drawText(session?.user.detail.fullname!, { x: 167, y: 350, size: 10 })
|
||||
firstPage.drawText(dayjs(dataCuti.created_at).format('DD MMMM YYYY'), { x: 167, y: 323, size: 10 })
|
||||
|
||||
firstPage.drawText('(' + profile.fullname.substring(0, 21) + ')', { x: 54, y: 230, size: 9 })
|
||||
firstPage.drawText('(' + 'Stevanus Akbar Alexander'.substring(0, 21) + ')', { x: 161, y: 230, size: 9 })
|
||||
|
||||
|
||||
const fileName = `Form Cuti ${profile.fullname} ${dayjs(dataCuti.start_date).format('YYYYMMDD')} - ${dayjs(dataCuti.end_date).format('YYYYMMDD')}`
|
||||
|
||||
await pdfDoc.setTitle(fileName)
|
||||
await pdfDoc.setSubject('SURAT PERMOHONAN FORM CUTI KARYAWAN')
|
||||
await pdfDoc.setKeywords(['form cuti', 'hats', 'super apps', 'his', 'nutech'])
|
||||
await pdfDoc.setCreator(profile.fullname)
|
||||
await pdfDoc.setAuthor('H.I.S Dev Super Team 😎')
|
||||
await pdfDoc.setProducer('H.A.T.s')
|
||||
await pdfDoc.setCreationDate(new Date())
|
||||
await pdfDoc.setModificationDate(new Date())
|
||||
|
||||
const pdfBase64 = await pdfDoc.saveAsBase64({ dataUri: true })
|
||||
|
||||
if (!preview) {
|
||||
const downloadLink = window.document.createElement('a');
|
||||
downloadLink.style.display = "none";
|
||||
downloadLink.href = pdfBase64;
|
||||
downloadLink.download = fileName;
|
||||
window.document.body.appendChild(downloadLink);
|
||||
downloadLink.click();
|
||||
window.document.body.removeChild(downloadLink);
|
||||
|
||||
toast.success('Download successfull', { description: `File "${fileName}.pdf" successfully downloaded` })
|
||||
} else {
|
||||
// Create a new window
|
||||
const newWindow: any = window.open("", "_blank", "width=800,height=600");
|
||||
|
||||
// Create an HTML document with an embedded data URL
|
||||
const htmlDocument = `
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>PDF Preview</title>
|
||||
</head>
|
||||
<body style="margin: 0; height: 100vh;">
|
||||
<embed src="${pdfBase64}" type="application/pdf" width="100%" height="100%" style="display: block;">
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
|
||||
// Write the HTML document to the new window
|
||||
newWindow.document.open();
|
||||
newWindow.document.write(htmlDocument);
|
||||
newWindow.document.close();
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.log(error)
|
||||
toast.error(`Fail to get the file`, { description: `(${error.response?.data?.code || error.response?.status || '-'}) ${error.response?.data?.message || error.response?.statusText || error.message}` })
|
||||
} finally {
|
||||
setIsPreviewLoading(false)
|
||||
setIsDownLoading(false)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="w-full pt-2">
|
||||
<SortFilter data={data} />
|
||||
@@ -56,6 +199,7 @@ export default function DataTable({ data }: Props) {
|
||||
<TableHead>Approval Status</TableHead>
|
||||
<TableHead>Approval by</TableHead>
|
||||
<TableHead>Approval at</TableHead>
|
||||
<TableHead>Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
@@ -85,6 +229,20 @@ export default function DataTable({ data }: Props) {
|
||||
dayjs(row.approved_at).format('YYYY-MM-DD HH:mm') : row.rejected_at ? dayjs(row.rejected_at).format('YYYY-MM-DD HH:mm') : null
|
||||
}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{row.category_code === 'I' || row.category_code === 'S' ?
|
||||
null
|
||||
:
|
||||
<div className="flex items-center">
|
||||
<Button size='icon' variant='ghost' onClick={() => handlePreviewOrSubmit(row, true)} disabled={isPreviewLoading}>
|
||||
{isPreviewLoading ? <Loader2 className="animate-spin" /> : <Eye />}
|
||||
</Button>
|
||||
<Button size='icon' variant='ghost' onClick={() => handlePreviewOrSubmit(row, false)} disabled={isDownLoading}>
|
||||
{isDownLoading ? <Loader2 className="animate-spin" /> : <Download />}
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
) : (
|
||||
|
||||
@@ -1,20 +1,26 @@
|
||||
"use client"
|
||||
|
||||
import { FC, useEffect, useState } from 'react';
|
||||
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 { FormDescription, FormLabel } from '@/components/ui/form';
|
||||
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
|
||||
@@ -32,20 +38,34 @@ const FormComponent: FC<Props> = () => {
|
||||
const router = useRouter()
|
||||
const axios = useAxiosAuth()
|
||||
|
||||
const options: PositionOptions = {
|
||||
enableHighAccuracy: false,
|
||||
timeout: 10000,
|
||||
maximumAge: 0
|
||||
};
|
||||
// 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)
|
||||
}
|
||||
}, []);
|
||||
|
||||
const successCallback = (position: GeolocationPosition) => {
|
||||
// 2. Wrap successCallback in useCallback
|
||||
const successCallback = useCallback((position: GeolocationPosition) => {
|
||||
const x = position.coords.latitude;
|
||||
const y = position.coords.longitude;
|
||||
setLatitude(x); setLongitude(y)
|
||||
setLatitude(x);
|
||||
setLongitude(y);
|
||||
displayLocation(x, y);
|
||||
};
|
||||
}, [displayLocation]); // Depends on displayLocation
|
||||
|
||||
const errorCallback = (error: GeolocationPositionError) => {
|
||||
// 3. Wrap errorCallback in useCallback
|
||||
const errorCallback = useCallback((error: GeolocationPositionError) => {
|
||||
let errorMessage = 'Unknown error';
|
||||
switch (error.code) {
|
||||
case 1:
|
||||
@@ -58,28 +78,19 @@ const FormComponent: FC<Props> = () => {
|
||||
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, options);
|
||||
}, [successCallback])
|
||||
|
||||
|
||||
const displayLocation = async (latitude: number, longitude: number) => {
|
||||
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 {
|
||||
alert(`${res.status} ${res.statusText}`)
|
||||
}
|
||||
};
|
||||
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')
|
||||
@@ -149,14 +160,14 @@ const FormComponent: FC<Props> = () => {
|
||||
|
||||
<div className='flex flex-col items-center space-y-3 w-full'>
|
||||
<div className=' w-full space-y-2'>
|
||||
<FormLabel>Note</FormLabel>
|
||||
<Label>Note</Label>
|
||||
<Textarea
|
||||
placeholder="Tell us a little bit about your presence"
|
||||
className="resize-none" value={note} onChange={(e) => setNote(e.target.value)}
|
||||
/>
|
||||
<FormDescription>
|
||||
<p className='text-xs sm:text-sm text-muted-foreground'>
|
||||
Tambahkan catatan kehadiran jika diperlukan
|
||||
</FormDescription>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
import { FC, Suspense, lazy } from 'react';
|
||||
import { type Metadata } from 'next';
|
||||
import { redirect } from 'next/navigation';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import PageLoading from '@/components/loader/PageLoading';
|
||||
import { fetchDataWithPost } from '@/lib/fetchData';
|
||||
import { getServerSession } from 'next-auth';
|
||||
import { authOptions } from '@/pages/api/auth/[...nextauth]';
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
const FormComponent = lazy(() => import('./components/FormComponent'))
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Update your current work location (I'am Here) - HIS Attendance Task System (H.A.T.s)",
|
||||
title: "Update Your Current Work Location and Condition (I'am Here) - HIS Attendance Task System (H.A.T.s)",
|
||||
}
|
||||
|
||||
type Props = {};
|
||||
@@ -35,7 +35,7 @@ const IamHerePage: FC<Props> = async () => {
|
||||
<CardHeader>
|
||||
<div className='flex justify-center items-center flex-col'>
|
||||
<CardTitle className="text-lg font-medium">I'am Here</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">Update your presence information with the latest data.</p>
|
||||
<p className="text-sm text-muted-foreground text-center sm:px-20">Update your presence information (location, condition or other necessary information) with the latest data.</p>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<Separator className='w-10/12 xl:w-11/12 mx-auto' />
|
||||
|
||||
@@ -19,12 +19,12 @@ import { Switch } from '@/components/ui/switch';
|
||||
import { type IProfile } from '../../profile/components/type';
|
||||
import { type ResponseData } from '@/types/types';
|
||||
import { type RangePickerProps } from 'antd/es/date-picker';
|
||||
import { toast } from 'sonner';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import relativeTime from "dayjs/plugin/relativeTime";
|
||||
import customParseFormat from 'dayjs/plugin/customParseFormat';
|
||||
import { toast } from 'sonner';
|
||||
import "dayjs/locale/id";
|
||||
import { Label } from '@/components/ui/label';
|
||||
|
||||
import "dayjs/locale/id";
|
||||
dayjs.extend(customParseFormat);
|
||||
|
||||
|
||||
@@ -134,10 +134,10 @@ const Component: FC<Props> = ({ TL_LIST }) => {
|
||||
|
||||
await pdfDoc.setTitle(`Form Cuti ${profile.fullname} - ${dayjs().format('YYYYMMDD')}`)
|
||||
await pdfDoc.setSubject('SURAT PERMOHONAN FORM CUTI KARYAWAN')
|
||||
await pdfDoc.setKeywords(['form cuti', 'super apps', 'his', 'nutech'])
|
||||
await pdfDoc.setKeywords(['form cuti', 'hats', 'super apps', 'his', 'nutech'])
|
||||
await pdfDoc.setCreator(profile.fullname)
|
||||
await pdfDoc.setAuthor('H.I.S Dev Super Team 😎')
|
||||
await pdfDoc.setProducer('Super Apps')
|
||||
await pdfDoc.setProducer('H.A.T.s')
|
||||
await pdfDoc.setCreationDate(new Date())
|
||||
await pdfDoc.setModificationDate(new Date())
|
||||
|
||||
|
||||
@@ -15,6 +15,17 @@ interface ReleaseNote {
|
||||
}
|
||||
|
||||
const releaseNotes: ReleaseNote[] = [
|
||||
{
|
||||
version: "v1.1.2",
|
||||
date: "20 February 2026",
|
||||
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" },
|
||||
]
|
||||
},
|
||||
{
|
||||
version: "v1.1.1",
|
||||
date: "09 February 2026",
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
"use server";
|
||||
|
||||
import { serverApiCall } from "@/lib/server-api";
|
||||
import { logger } from "@/lib/logger";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import dayjs from "dayjs";
|
||||
|
||||
export async function importBatchAttendanceAction(rawExcelData: any[][]) {
|
||||
// 1. Remove the first row (headers) and keep only the data rows
|
||||
const dataRows = rawExcelData.slice(1);
|
||||
|
||||
logger.info(`Starting batch import for ${dataRows.length} rows`);
|
||||
|
||||
try {
|
||||
// 2. Map through the arrays using their specific index
|
||||
const importPromises = dataRows.map((row) => {
|
||||
// Based on your array structure:
|
||||
// row[0] = null
|
||||
// row[1] = nik
|
||||
// row[2] = working_status
|
||||
// row[3] = working_hours_start
|
||||
// row[4] = working_hours_end
|
||||
// row[5] = note
|
||||
|
||||
// Skip completely empty rows if they accidentally got parsed
|
||||
if (!row[1]) return Promise.resolve({ success: false, message: "Empty NIK" });
|
||||
|
||||
const payload = {
|
||||
nik: String(row[1]), // Ensure it is a string
|
||||
working_status: row[2],
|
||||
working_hours_start: dayjs(row[3]).format('YYYY-MM-DD HH:mm:ss'),
|
||||
working_hours_end: row[4] ? dayjs(row[4]).format('YYYY-MM-DD HH:mm:ss') : null, // Fallback to null if empty
|
||||
note: row[5] || "",
|
||||
|
||||
// Hardcoded requirements
|
||||
area_code: row[2] === 'WFO' ? "A01" : undefined,
|
||||
create_checkout: Boolean(row[4]) // true if working_hours_end has a value
|
||||
};
|
||||
|
||||
// Call your backend API
|
||||
return serverApiCall('POST', '/presence/manual', payload);
|
||||
});
|
||||
|
||||
// 3. Execute all promises concurrently
|
||||
const results = await Promise.allSettled(importPromises);
|
||||
|
||||
// 4. Analyze the results
|
||||
let successCount = 0;
|
||||
let failedCount = 0;
|
||||
|
||||
results.forEach((result, index) => {
|
||||
if (result.status === "fulfilled" && result.value.success) {
|
||||
successCount++;
|
||||
} else {
|
||||
failedCount++;
|
||||
logger.error(`Row ${index + 2} (NIK: ${dataRows[index][1]}) failed to import`, {
|
||||
reason: result.status === "fulfilled" ? (result.value as any)?.message : result.reason
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
logger.info(`Batch import finished. Success: ${successCount}, Failed: ${failedCount}`);
|
||||
revalidatePath('/admin/report/history');
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: `Import process finished.`,
|
||||
stats: {
|
||||
total: dataRows.length,
|
||||
successCount,
|
||||
failedCount
|
||||
}
|
||||
};
|
||||
|
||||
} catch (error: any) {
|
||||
logger.error("Critical failure during batch import", error);
|
||||
return { success: false, message: "A critical server error occurred during import." };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// actions/logger.ts
|
||||
"use server";
|
||||
|
||||
import { logger } from "@/lib/logger";
|
||||
|
||||
export type LogLevel = 'INFO' | 'WARN' | 'ERROR' | 'DEBUG' | 'API_REQ' | 'API_RES';
|
||||
|
||||
// This function receives the log from the browser and writes it to the server file
|
||||
export async function sendLogToServer(level: LogLevel, message: string, data?: any) {
|
||||
try {
|
||||
// Route the log to the correct method in your existing server logger
|
||||
switch (level) {
|
||||
case 'INFO': logger.info(`[CLIENT] ${message}`, data); break;
|
||||
case 'WARN': logger.warn(`[CLIENT] ${message}`, data); break;
|
||||
case 'ERROR': logger.error(`[CLIENT] ${message}`, data); break;
|
||||
case 'DEBUG': logger.debug(`[CLIENT] ${message}`, data); break;
|
||||
case 'API_REQ': logger.apiReq(`[CLIENT] ${message}`, data); break;
|
||||
case 'API_RES': logger.apiRes(`[CLIENT] ${message}`, data); break;
|
||||
default: logger.info(`[CLIENT] ${message}`, data); break;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to write client log to server:", error);
|
||||
}
|
||||
}
|
||||
@@ -148,7 +148,7 @@ const ComponentAreaPage: FC<Props> = ({ data }) => {
|
||||
defaultPageSize: 10,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
// size: 'default'
|
||||
size: 'default'
|
||||
},
|
||||
scroll: { x: 'max-content' },
|
||||
tableLayout: 'auto',
|
||||
|
||||
@@ -172,7 +172,7 @@ const ComponentCompanyPage: FC<Props> = ({ data }) => {
|
||||
defaultPageSize: 10,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
// size: 'default',
|
||||
size: 'default',
|
||||
},
|
||||
scroll: { x: 'max-content' },
|
||||
tableLayout: 'auto',
|
||||
|
||||
@@ -145,7 +145,7 @@ const ComponentPage: FC<Props> = ({ data }) => {
|
||||
defaultPageSize: 10,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
// size: 'default'
|
||||
size: 'default'
|
||||
},
|
||||
scroll: { x: 'max-content' },
|
||||
tableLayout: 'auto',
|
||||
|
||||
@@ -186,7 +186,7 @@ const ComponentPage: FC<Props> = ({ data }) => {
|
||||
defaultPageSize: 10,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
// size: 'default'
|
||||
size: 'default'
|
||||
},
|
||||
scroll: { x: 'max-content' },
|
||||
tableLayout: 'auto',
|
||||
|
||||
@@ -151,7 +151,7 @@ const ComponentPage: FC<Props> = ({ data }) => {
|
||||
defaultPageSize: 10,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
// size: 'default'
|
||||
size: 'default'
|
||||
},
|
||||
scroll: { x: 'max-content' },
|
||||
tableLayout: 'auto',
|
||||
|
||||
@@ -166,6 +166,7 @@ const ComponentPage: FC<Props> = ({ data }) => {
|
||||
rowKey='id'
|
||||
columns={Columns}
|
||||
dataSource={filterData || []}
|
||||
pagination={{ size: 'default' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -151,7 +151,7 @@ const ComponentPage: FC<Props> = ({ data }) => {
|
||||
defaultPageSize: 10,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
// size: 'default'
|
||||
size: 'default'
|
||||
},
|
||||
scroll: { x: 'max-content' },
|
||||
tableLayout: 'auto',
|
||||
|
||||
@@ -151,7 +151,7 @@ const ComponentPage: FC<Props> = ({ data }) => {
|
||||
defaultPageSize: 10,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
// size: 'default'
|
||||
size: 'default'
|
||||
},
|
||||
scroll: { x: 'max-content' },
|
||||
tableLayout: 'auto',
|
||||
|
||||
+3
-1
@@ -4,6 +4,7 @@ import { useEffect } from "react"
|
||||
import Image from "next/image"
|
||||
import Link from "next/link"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { clientLogger } from "@/lib/logger-client"
|
||||
|
||||
export default function Error({
|
||||
error,
|
||||
@@ -15,12 +16,13 @@ export default function Error({
|
||||
|
||||
useEffect(() => {
|
||||
console.log({ name: error.name, cause: error.cause, message: error.message, stack: error.stack })
|
||||
clientLogger.error(error.stack!)
|
||||
}, [error])
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="h-[85vh] flex flex-col justify-center items-center overflow-x-hidden overflow-y-auto py-5">
|
||||
<Image alt='ilustrations' height={0} width={0} quality={70} src='/assets/illustrations/maintenance.svg' className='w-80 md:w-[28rem] 2xl:w-[40rem] shadow-sm rounded-full object-cover' />
|
||||
<Image alt='ilustrations' height={0} width={0} quality={70} src='/assets/illustrations/maintenance.svg' className='w-80 md:w-md 2xl:w-160 shadow-sm rounded-full object-cover' />
|
||||
<h2 className="text-xl sm:text-2xl font-semibold tracking-tight text-center">Oopps.. something went wrong!</h2>
|
||||
<span className="text-center mt-1 mb-6 text-zinc-600 dark:text-zinc-400 md:w-9/12 break-all px-2 sm:px-0">{error.message || 'Sorry, system error has occurred'}</span>
|
||||
<div className="flex items-center space-x-2">
|
||||
|
||||
@@ -160,7 +160,7 @@ const ComponentPage: FC<Props> = ({ data }) => {
|
||||
defaultPageSize: 10,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
// size: 'default'
|
||||
size: 'default'
|
||||
},
|
||||
scroll: { x: 'max-content' },
|
||||
tableLayout: 'auto',
|
||||
|
||||
@@ -92,7 +92,7 @@ const ComponentRolePage: FC<Props> = ({ data }) => {
|
||||
defaultPageSize: 10,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
// size: 'default'
|
||||
size: 'default'
|
||||
},
|
||||
scroll: { x: 'max-content' },
|
||||
tableLayout: 'auto',
|
||||
|
||||
@@ -63,7 +63,7 @@ const ComponentRolePage: FC<Props> = ({ data }) => {
|
||||
defaultPageSize: 10,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
// size: 'default'
|
||||
size: 'default'
|
||||
},
|
||||
scroll: { x: 'max-content' },
|
||||
tableLayout: 'auto',
|
||||
|
||||
@@ -92,7 +92,7 @@ const ComponentRolePage: FC<Props> = ({ data }) => {
|
||||
defaultPageSize: 10,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
// size: 'default'
|
||||
size: 'default'
|
||||
},
|
||||
scroll: { x: 'max-content' },
|
||||
tableLayout: 'auto',
|
||||
|
||||
@@ -134,7 +134,7 @@ const ComponentRolePage: FC<Props> = ({ data }) => {
|
||||
defaultPageSize: 10,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
// size: 'default'
|
||||
size: 'default'
|
||||
},
|
||||
scroll: { x: 'max-content' },
|
||||
tableLayout: 'auto',
|
||||
|
||||
@@ -63,7 +63,7 @@ const ComponentRolePage: FC<Props> = ({ data }) => {
|
||||
defaultPageSize: 10,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
// size: 'default'
|
||||
size: 'default'
|
||||
},
|
||||
scroll: { x: 'max-content' },
|
||||
tableLayout: 'auto',
|
||||
|
||||
@@ -96,7 +96,7 @@ const ComponentPage: FC<Props> = ({ data }) => {
|
||||
defaultPageSize: 15,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
// size: 'default'
|
||||
size: 'default'
|
||||
},
|
||||
scroll: { x: 'max-content' },
|
||||
tableLayout: 'auto',
|
||||
|
||||
@@ -106,7 +106,7 @@ const ComponentPage: FC<Props> = ({ data }) => {
|
||||
defaultPageSize: 15,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
// size: 'default'
|
||||
size: 'default'
|
||||
},
|
||||
scroll: { x: 'max-content' },
|
||||
tableLayout: 'auto',
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
"use client"
|
||||
|
||||
import ExcelJS from 'exceljs';
|
||||
import { useCallback, useRef, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import {
|
||||
AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle
|
||||
} from "@/components/ui/alert-dialog"
|
||||
import { FileSpreadsheet, ImageIcon, Loader2, UploadIcon } from "lucide-react"
|
||||
import Dropzone from 'react-dropzone';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
|
||||
} from "@/components/ui/table"
|
||||
import dayjs from 'dayjs';
|
||||
import { importBatchAttendanceAction } from '@/app/actions/attendance';
|
||||
import PageLoading from '@/components/loader/PageLoading';
|
||||
import Link from 'next/link';
|
||||
|
||||
export default function ImportExcel() {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [fullLoading, setFullLoading] = useState(false);
|
||||
const [rowData, setRowData] = useState<any>([])
|
||||
const [showModal, setShowModal] = useState(false)
|
||||
|
||||
const dropzoneRef = useRef<any>(null);
|
||||
|
||||
const maxSizeMB = 5
|
||||
|
||||
const openDialog = () => {
|
||||
// Note that the ref is set async,
|
||||
// so it might be null at some point
|
||||
if (dropzoneRef.current) {
|
||||
dropzoneRef.current.open();
|
||||
}
|
||||
};
|
||||
|
||||
const onDrop = useCallback((acceptedFiles: any[]) => {
|
||||
acceptedFiles.forEach(async (file: any) => {
|
||||
const reader = new FileReader();
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
|
||||
reader.onabort = () => console.log('file reading was aborted');
|
||||
reader.onerror = () => console.log('file reading has failed');
|
||||
reader.onload = async (e: any) => {
|
||||
try {
|
||||
const arrayBuffer = e.target.result;
|
||||
await workbook.xlsx.load(arrayBuffer);
|
||||
|
||||
const worksheet = workbook.worksheets[0]; // Get the first worksheet
|
||||
if (!worksheet) {
|
||||
toast.error('Worksheet not found');
|
||||
return;
|
||||
}
|
||||
|
||||
const rows: any[] = [];
|
||||
|
||||
worksheet.eachRow((row, rowNumber) => {
|
||||
rows.push(row.values);
|
||||
});
|
||||
|
||||
setRowData(rows)
|
||||
console.log(rows);
|
||||
} catch (error: any) {
|
||||
toast.error('Failed to read the file. Please ensure it is a valid Excel file.', { description: error.message });
|
||||
} finally {
|
||||
setFullLoading(false);
|
||||
}
|
||||
};
|
||||
reader.readAsArrayBuffer(file);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleSaveFile = async () => {
|
||||
if (!rowData) return
|
||||
|
||||
setIsLoading(true)
|
||||
|
||||
const res = await importBatchAttendanceAction(rowData)
|
||||
|
||||
if (res.success) {
|
||||
toast.info(res.message, {
|
||||
description: JSON.stringify(res.stats),
|
||||
action: <Link href='/admin/report/history'><Button variant='outline'>See Results</Button></Link>
|
||||
})
|
||||
setRowData(null); setShowModal(false)
|
||||
} else {
|
||||
toast.error('Fail batch import', { description: res.message })
|
||||
}
|
||||
|
||||
setIsLoading(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button variant='outline' onClick={() => setShowModal(true)}><FileSpreadsheet />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`}>
|
||||
<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">
|
||||
{/* Drop area */}
|
||||
<Dropzone ref={dropzoneRef} onDrop={onDrop} multiple={false} noClick noKeyboard
|
||||
accept={{
|
||||
'application/vnd.ms-excel': ['.xls'],
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ['.xlsx'],
|
||||
}}
|
||||
>
|
||||
{/* @ts-ignore */}
|
||||
{({ getRootProps, getInputProps, acceptedFiles }) => {
|
||||
return (
|
||||
<div {...getRootProps()}
|
||||
className="border-input data-[dragging=true]:bg-accent/50 has-[input:focus]:border-ring has-[input:focus]:ring-ring/50 relative flex min-h-52 flex-col items-center overflow-hidden rounded-xl border border-dashed p-4 transition-colors not-data-files:justify-center has-[input:focus]:ring-[3px]"
|
||||
>
|
||||
<input {...getInputProps()} className="sr-only" aria-label="Upload image file" />
|
||||
|
||||
{rowData && rowData.length > 0 ? (
|
||||
<>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
{rowData[0]?.slice(0, rowData[0].length).map((item: any, key: number) =>
|
||||
<TableHead key={key}>{item}</TableHead>
|
||||
)}
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{rowData?.slice(1, rowData?.length).map((item: any, key: number) =>
|
||||
<TableRow key={key}>
|
||||
{item.slice(0, item.length).map((item1: any, key1: number) => {
|
||||
const renderText = typeof item1 === 'object' ? dayjs(item1).isValid() ? dayjs().format('dddd, DD MMM YYYY') : JSON.stringify(item1) : item1
|
||||
return <TableCell key={key1}>{renderText}</TableCell>
|
||||
}
|
||||
)}
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</>
|
||||
) : (
|
||||
<div className="flex flex-col items-center justify-center px-4 py-3 text-center">
|
||||
<div className="bg-background mb-2 flex size-11 shrink-0 items-center justify-center rounded-full border" aria-hidden="true">
|
||||
<ImageIcon className="size-4 opacity-60" />
|
||||
</div>
|
||||
<p className="mb-1.5 text-sm font-medium">Drop your files here</p>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
.XLSX or XLS (max. {maxSizeMB}MB)
|
||||
</p>
|
||||
<Button variant="outline" className="mt-4" onClick={openDialog}>
|
||||
<UploadIcon className="-ms-1 opacity-60" aria-hidden="true" />
|
||||
Browse file
|
||||
</Button>
|
||||
<Link href="/files/hats-batching-import.xlsx" download="H.A.T.s Batching Import.xlsx" className='text-xs text-his underline hover:text-blue-500 duration-200 mt-4 font-medium'>
|
||||
Download example file
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
|
||||
</div>
|
||||
);
|
||||
}}
|
||||
</Dropzone>
|
||||
</div>
|
||||
|
||||
{rowData && rowData.length > 0 ?
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel onClick={() => { setRowData(null); setShowModal(false) }}>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={handleSaveFile} disabled={isLoading}>{isLoading ? <Loader2 className='animate-spin' /> : null} Save</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
:
|
||||
<AlertDialogAction onClick={() => { setRowData(null); setShowModal(false) }}>Close</AlertDialogAction>
|
||||
}
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
: null
|
||||
}
|
||||
|
||||
{fullLoading ?
|
||||
<PageLoading className='bg-opacity-40 dark:bg-opacity-20 z-999' />
|
||||
:
|
||||
null
|
||||
}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/com
|
||||
import LazyLoading from '@/components/loader/LazyLoading';
|
||||
import fetchData from '@/lib/fetchData';
|
||||
|
||||
const ImportExcel = lazy(() => import('./component/ImportExcel'));
|
||||
const ComponentPage = lazy(() => import('./component'));
|
||||
|
||||
export const metadata: Metadata = {
|
||||
@@ -22,9 +23,18 @@ const ManualPresencePage: FC<Props> = async () => {
|
||||
<>
|
||||
<div className="flex flex-col">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
{/* <CardHeader>
|
||||
<CardTitle>Manual Attendance</CardTitle>
|
||||
<CardDescription>Only create a manual attendance <strong>if the FR system has problems !</strong></CardDescription>
|
||||
</CardHeader> */}
|
||||
<CardHeader className='flex flex-col md:flex-row justify-between'>
|
||||
<div className='space-y-1'>
|
||||
<CardTitle>Manual Attendance</CardTitle>
|
||||
<CardDescription>Only create a manual attendance <strong>if the FR system has problems !</strong></CardDescription>
|
||||
</div>
|
||||
<Suspense fallback={<LazyLoading />}>
|
||||
<ImportExcel />
|
||||
</Suspense>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Suspense fallback={<LazyLoading />}>
|
||||
|
||||
@@ -173,7 +173,7 @@ const ComponentPage: FC<Props> = ({ data }) => {
|
||||
defaultPageSize: 10,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
// size: 'default'
|
||||
size: 'default'
|
||||
},
|
||||
scroll: { x: 'max-content' },
|
||||
tableLayout: 'auto',
|
||||
|
||||
@@ -651,7 +651,7 @@ const ComponentPage: FC<Props> = ({ data }) => {
|
||||
defaultPageSize: 15,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
// size: 'default'
|
||||
size: 'default'
|
||||
},
|
||||
scroll: { x: 'max-content' },
|
||||
tableLayout: 'auto',
|
||||
|
||||
@@ -21,6 +21,7 @@ const ColumnsHistory: ColumnsType<IHistory> = [
|
||||
{
|
||||
title: 'Working Status',
|
||||
dataIndex: 'working_status',
|
||||
align: 'center',
|
||||
filters: [
|
||||
{
|
||||
text: 'WFO',
|
||||
@@ -50,6 +51,7 @@ const ColumnsHistory: ColumnsType<IHistory> = [
|
||||
{
|
||||
title: 'Approval',
|
||||
dataIndex: 'status',
|
||||
align: 'center',
|
||||
filters: [
|
||||
{
|
||||
text: 'Approved',
|
||||
@@ -204,6 +206,7 @@ const ColumnsHistory: ColumnsType<IHistory> = [
|
||||
{
|
||||
title: 'Auto Checkout',
|
||||
dataIndex: 'autocheckout',
|
||||
align: 'center',
|
||||
filters: [
|
||||
{
|
||||
text: 'Auto Checkout',
|
||||
@@ -216,11 +219,13 @@ const ColumnsHistory: ColumnsType<IHistory> = [
|
||||
{
|
||||
title: 'Clear AutoChekout',
|
||||
dataIndex: 'status',
|
||||
align: 'center',
|
||||
render: (val, record) => record?.is_clear_auto_checkout === false ? <Badge>need to be approve</Badge> : record.is_clear_auto_checkout === true ? <Badge variant='secondary'>approved</Badge> : undefined
|
||||
},
|
||||
{
|
||||
title: 'Manual Presence',
|
||||
dataIndex: 'manual_presence',
|
||||
align: 'center',
|
||||
render: (val, record) => val ? <i className="ti ti-check text-xl text-green-500"></i> : null
|
||||
},
|
||||
];
|
||||
|
||||
@@ -47,7 +47,7 @@ const ComponentPage: FC<Props> = ({ data }) => {
|
||||
defaultPageSize: 15,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
// size: 'default'
|
||||
size: 'default'
|
||||
},
|
||||
scroll: { x: 'max-content' },
|
||||
tableLayout: 'auto',
|
||||
@@ -65,15 +65,9 @@ const ComponentPage: FC<Props> = ({ data }) => {
|
||||
</div>
|
||||
<Table
|
||||
{...tableProps}
|
||||
onRow={(record, rowIndex) => {
|
||||
return {
|
||||
onClick: event => { console.log(record.face_image); }, // click row
|
||||
};
|
||||
}}
|
||||
rowKey='presence_checkin_code'
|
||||
columns={ColumnsHistory}
|
||||
dataSource={filterData || []}
|
||||
style={{ cursor: "pointer" }}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
|
||||
@@ -111,7 +111,7 @@ const ComponentPage: FC<Props> = ({ data }) => {
|
||||
defaultPageSize: 15,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
// size: 'default'
|
||||
size: 'default'
|
||||
},
|
||||
scroll: { x: 'max-content' },
|
||||
tableLayout: 'auto',
|
||||
|
||||
@@ -47,6 +47,9 @@ const ExportComponent: FC<Props> = ({ data }) => {
|
||||
{ header: 'Working Hours', key: 'working_hours', style: { numFmt: '0;[Red]0' } },
|
||||
{ header: 'Total Working Hours', key: 'total_working_hours', style: { numFmt: '0;[Red]0' } },
|
||||
{ header: 'Delta Working Hours', key: 'delta_working_hours', style: { numFmt: '0;[Red]0' } },
|
||||
{ header: 'WFO', key: 'total_wfo', width: 10, style: { numFmt: '0;[Red]0' } },
|
||||
{ header: 'WFH', key: 'total_wfh', width: 10, style: { numFmt: '0;[Red]0' } },
|
||||
{ header: 'WFS', key: 'total_wfs', width: 10, style: { numFmt: '0;[Red]0' } },
|
||||
{ header: 'Leave', key: 'total_cuti', width: 10, style: { numFmt: '0;[Red]0' } },
|
||||
{ header: 'Sick', key: 'total_sakit', width: 10, style: { numFmt: '0;[Red]0' } },
|
||||
{ header: 'Permission', key: 'total_izin', width: 10, style: { numFmt: '0;[Red]0' } },
|
||||
|
||||
@@ -3,11 +3,10 @@
|
||||
import { ChangeEvent, FC, useEffect, useState } from 'react';
|
||||
import { Table } from 'antd';
|
||||
import { TableProps, type ColumnsType } from 'antd/es/table';
|
||||
import { MixerHorizontalIcon } from '@radix-ui/react-icons';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { type IMonthlyReport } from './type';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
type Props = {
|
||||
data: IMonthlyReport[]
|
||||
@@ -17,6 +16,9 @@ const ComponentPage: FC<Props> = ({ data }) => {
|
||||
const [filterData, setFilterData] = useState<IMonthlyReport[]>([])
|
||||
|
||||
const router = useRouter()
|
||||
const searchParams = useSearchParams();
|
||||
const startDate = searchParams!.get('start_date') as string || dayjs().subtract(1, 'day').subtract(1, 'month')
|
||||
const endDate = searchParams!.get('end_date') as string || dayjs().subtract(1, 'day')
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
@@ -66,6 +68,24 @@ const ComponentPage: FC<Props> = ({ data }) => {
|
||||
sorter: (a, b) => a.delta_working_hours - b.delta_working_hours,
|
||||
render: (val) => val ? val.toFixed(2) : 0
|
||||
},
|
||||
{
|
||||
title: 'WFO',
|
||||
dataIndex: 'total_wfo',
|
||||
sorter: (a, b) => a.total_wfo - b.total_wfo,
|
||||
align: 'center'
|
||||
},
|
||||
{
|
||||
title: 'WFH',
|
||||
dataIndex: 'total_wfh',
|
||||
sorter: (a, b) => a.total_wfh - b.total_wfh,
|
||||
align: 'center'
|
||||
},
|
||||
{
|
||||
title: 'WFS',
|
||||
dataIndex: 'total_wfs',
|
||||
sorter: (a, b) => a.total_wfs - b.total_wfs,
|
||||
align: 'center'
|
||||
},
|
||||
{
|
||||
title: 'Leave',
|
||||
dataIndex: 'total_cuti',
|
||||
@@ -115,7 +135,7 @@ const ComponentPage: FC<Props> = ({ data }) => {
|
||||
defaultPageSize: 30,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
// size: 'default'
|
||||
size: 'default'
|
||||
},
|
||||
scroll: { x: 'max-content' },
|
||||
tableLayout: 'auto',
|
||||
@@ -136,7 +156,7 @@ const ComponentPage: FC<Props> = ({ data }) => {
|
||||
dataSource={filterData || []}
|
||||
onRow={(record, rowIndex) => {
|
||||
return {
|
||||
onClick: (e) => router.push(`/performance/${record.user_id}`)
|
||||
onClick: (e) => router.push(`/performance/${record.user_id}?start_date=${dayjs(startDate).format('YYYY-MM-DD')}&end_date=${dayjs(endDate).format('YYYY-MM-DD')}`)
|
||||
};
|
||||
}}
|
||||
style={{ cursor: "pointer" }}
|
||||
|
||||
@@ -8,6 +8,9 @@ export interface IMonthlyReport {
|
||||
"total_working_hours": number,
|
||||
delta_working_hours: number,
|
||||
"working_hours": number,
|
||||
"total_wfo": number,
|
||||
"total_wfh": number,
|
||||
"total_wfs": number,
|
||||
"total_cuti": number,
|
||||
"total_sakit": number,
|
||||
"total_izin": number,
|
||||
|
||||
@@ -38,9 +38,7 @@ const SummaryAttendancePage: FC<Props> = async ({ searchParams }) => {
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Suspense fallback={<LazyLoading />}>
|
||||
<ComponentPage
|
||||
data={data.report}
|
||||
/>
|
||||
<ComponentPage data={data.report} />
|
||||
</Suspense>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
+3
-1
@@ -4,6 +4,7 @@ import { useEffect } from "react"
|
||||
import Image from "next/image"
|
||||
import Link from "next/link"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { clientLogger } from "@/lib/logger-client"
|
||||
|
||||
export default function Error({
|
||||
error,
|
||||
@@ -15,12 +16,13 @@ export default function Error({
|
||||
|
||||
useEffect(() => {
|
||||
console.log({ name: error.name, cause: error.cause, message: error.message, stack: error.stack })
|
||||
clientLogger.error(error.stack!)
|
||||
}, [error])
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="h-[90vh] flex flex-col justify-center items-center overflow-x-hidden overflow-y-auto py-5">
|
||||
<Image alt='ilustrations' height={0} width={0} quality={70} src='/assets/illustrations/maintenance.svg' className='w-80 md:w-[28rem] 2xl:w-[40rem] shadow-sm rounded-full object-cover' />
|
||||
<Image alt='ilustrations' height={0} width={0} quality={70} src='/assets/illustrations/maintenance.svg' className='w-80 md:w-md 2xl:w-160 shadow-sm rounded-full object-cover' />
|
||||
<h2 className="text-xl sm:text-2xl font-semibold tracking-tight text-center">Oopps.. something went wrong!</h2>
|
||||
<span className="text-center mt-1 mb-6 text-zinc-600 dark:text-zinc-400 md:w-9/12 break-all px-2 sm:px-0">{error.message || 'Sorry, system error has occurred'}</span>
|
||||
<div className="flex items-center space-x-2">
|
||||
|
||||
+34
-1
@@ -294,4 +294,37 @@
|
||||
visibility: hidden;
|
||||
translate: -50% -50%;
|
||||
}
|
||||
/*** END MODAL STYLE ***/
|
||||
/*** END MODAL STYLE ***/
|
||||
|
||||
|
||||
|
||||
.animated-tada {
|
||||
animation-duration: 1.5s;
|
||||
animation-iteration-count: infinite;
|
||||
}
|
||||
|
||||
@keyframes tada {
|
||||
0% {
|
||||
transform: scale3d(1.2, 1.2, 1.2);
|
||||
}
|
||||
|
||||
10%, 20% {
|
||||
transform: scale3d(.9, .9, .9) rotate3d(0, 0, 1, -3deg);
|
||||
}
|
||||
|
||||
30%, 50%, 70%, 90% {
|
||||
transform: scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, 3deg);
|
||||
}
|
||||
|
||||
40%, 60%, 80% {
|
||||
transform: scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, -3deg);
|
||||
}
|
||||
|
||||
100% {
|
||||
transform: scale3d(1.2, 1.2, 1.2);
|
||||
}
|
||||
}
|
||||
|
||||
.tada {
|
||||
animation-name: tada;
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
"use client"
|
||||
|
||||
import { useState, type FC } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
} from '@/components/ui/dialog';
|
||||
import { CalendarX2, AlertTriangle, Calendar, ChevronRight, X, UserX, Eye } from 'lucide-react';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { format, getMonth, getYear, parseISO } from 'date-fns';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
type Props = {
|
||||
alphaData: any[]
|
||||
};
|
||||
|
||||
const monthColors: Record<number, { bg: string; text: string; border: string; dot: string }> = {
|
||||
0: { bg: 'bg-primary/10', text: 'text-primary', border: 'border-primary/20', dot: 'bg-primary' },
|
||||
1: { bg: 'bg-destructive/10', text: 'text-destructive', border: 'border-destructive/20', dot: 'bg-destructive' },
|
||||
};
|
||||
|
||||
const EmployeeAlpha: FC<Props> = ({ alphaData }) => {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
// Group by month
|
||||
const grouped = alphaData.reduce<Record<string, typeof alphaData>>((acc, item) => {
|
||||
const d = parseISO(item.date);
|
||||
const key = `${getYear(d)}-${String(getMonth(d)).padStart(2, '0')}`;
|
||||
if (!acc[key]) acc[key] = [];
|
||||
acc[key].push(item);
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
const sortedMonths = Object.keys(grouped).sort();
|
||||
|
||||
return (
|
||||
<>
|
||||
<Eye size={20} onClick={() => setOpen(true)} className='text-emerald-600 hover:text-his duration-200 cursor-pointer' />
|
||||
|
||||
{/* Modal */}
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent className="sm:max-w-lg p-0 gap-0 overflow-hidden border-border/50 bg-card">
|
||||
{/* Modal Header */}
|
||||
<div className="relative bg-destructive/5 border-b border-destructive/10 px-6 pt-6 pb-5">
|
||||
<div className="absolute -top-8 -right-8 w-24 h-24 rounded-full bg-destructive/10 blur-xl" />
|
||||
<DialogHeader className="relative">
|
||||
<div className="flex items-center gap-3 mb-2">
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-destructive/10 border border-destructive/20">
|
||||
<CalendarX2 className="h-5 w-5 text-destructive" />
|
||||
</div>
|
||||
<div>
|
||||
<DialogTitle className="text-lg font-semibold text-foreground">
|
||||
Absence Records
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-sm text-muted-foreground mt-0.5">
|
||||
{alphaData.length} days without check-in
|
||||
</DialogDescription>
|
||||
</div>
|
||||
</div>
|
||||
</DialogHeader>
|
||||
</div>
|
||||
|
||||
{/* Modal Body */}
|
||||
<div className="px-6 py-5 max-h-[60vh] overflow-y-auto space-y-5">
|
||||
{sortedMonths.map((monthKey, mIdx) => {
|
||||
const dates = grouped[monthKey];
|
||||
const sampleDate = parseISO(dates[0].date);
|
||||
const monthLabel = format(sampleDate, 'MMMM yyyy');
|
||||
const colorIdx = mIdx % 2;
|
||||
const colors = monthColors[colorIdx];
|
||||
|
||||
return (
|
||||
<div key={monthKey} className="animate-fade-in" style={{ animationDelay: `${mIdx * 80}ms` }}>
|
||||
{/* Month Header */}
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className={`h-2 w-2 rounded-full ${colors.dot}`} />
|
||||
<span className="text-sm font-semibold text-foreground">{monthLabel}</span>
|
||||
</div>
|
||||
<Badge variant="secondary" className="text-xs font-mono">
|
||||
{dates.length} day{dates.length > 1 ? 's' : ''}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{/* Date Items */}
|
||||
<div className="space-y-2">
|
||||
{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 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>
|
||||
</div>
|
||||
<Badge variant="outline" className={`${colors.text} ${colors.border} ${colors.bg} text-xs`}>
|
||||
Alpha
|
||||
</Badge>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Modal Footer */}
|
||||
<div className="border-t border-border px-6 py-4 bg-muted/30">
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Total: <span className="font-semibold font-mono text-foreground">{alphaData.length}</span> absence records
|
||||
</p>
|
||||
<Button variant="outline" size="sm" onClick={() => setOpen(false)}>
|
||||
Close
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default EmployeeAlpha;
|
||||
@@ -47,7 +47,7 @@ const TableAttendanceHistory: FC<Props> = ({ data }) => {
|
||||
defaultPageSize: 15,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
// size: 'default'
|
||||
size: 'default'
|
||||
},
|
||||
scroll: { x: 'max-content' },
|
||||
tableLayout: 'auto',
|
||||
@@ -63,15 +63,9 @@ const TableAttendanceHistory: FC<Props> = ({ data }) => {
|
||||
</div>
|
||||
<Table
|
||||
{...tableProps}
|
||||
onRow={(record, rowIndex) => {
|
||||
return {
|
||||
onClick: event => { console.log(record.face_image); }, // click row
|
||||
};
|
||||
}}
|
||||
rowKey='presence_checkin_code'
|
||||
columns={ColumnsHistory}
|
||||
dataSource={filterData || []}
|
||||
style={{ cursor: "pointer" }}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
|
||||
@@ -7,14 +7,13 @@ import { Card, Card900, CardContent, CardDescription, CardHeader, CardTitle } fr
|
||||
import LazyLoading from '@/components/loader/LazyLoading';
|
||||
import fetchData, { fetchDataWithPost } from '@/lib/fetchData';
|
||||
import { generateHourMinutes } from '@/lib/helper';
|
||||
import { type IUser } from '@/app/admin/administration/user/component/type';
|
||||
import { type IPerformace } from './type';
|
||||
import ViewAvatar from '@/components/ViewAvatar';
|
||||
|
||||
const DonutChart = lazy(() => import('./DonutChart'));
|
||||
const AreaChart = lazy(() => import('./AreaChart'))
|
||||
const TableAttendanceHistory = lazy(() => import('./Table'))
|
||||
const ExportComponent = lazy(() => import('./Export'))
|
||||
const EmployeeAlpha = lazy(() => import('./EmployeeAlpha'));
|
||||
|
||||
type Props = {
|
||||
id: string | undefined
|
||||
@@ -35,11 +34,13 @@ const PerformanceComponent: FC<Props> = async ({ id, start_date, end_date }) =>
|
||||
}
|
||||
}
|
||||
|
||||
const fetchUser: IUser = await fetchData(`/user/${id}`)
|
||||
const fetchPerformace: IPerformace = await fetchDataWithPost('/dashboard/user/' + id, { start_date: start_date || dayjs().subtract(1, 'day').subtract(1, 'month'), end_date: end_date || dayjs().subtract(1, 'day').format('YYYY-MM-DD') })
|
||||
const fetchUser = fetchData(`/user/${id}`)
|
||||
const fetchPerformace = fetchDataWithPost('/dashboard/user/' + id, { start_date: start_date || dayjs().subtract(1, 'day').subtract(1, 'month'), end_date: end_date || dayjs().subtract(1, 'day').format('YYYY-MM-DD') })
|
||||
const fetchAlpha = fetchDataWithPost(`/presence/report/absent`, { user_id: Number(id), start_date: start_date || dayjs().subtract(1, 'day').subtract(1, 'month'), end_date: end_date || dayjs().subtract(1, 'day').format('YYYY-MM-DD') })
|
||||
|
||||
const [user, performance] = await Promise.all([fetchUser, fetchPerformace])
|
||||
const [user, performance, alpha] = await Promise.all([fetchUser, fetchPerformace, fetchAlpha])
|
||||
|
||||
console.log(alpha)
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -104,18 +105,33 @@ const PerformanceComponent: FC<Props> = async ({ id, start_date, end_date }) =>
|
||||
</Card900>
|
||||
<Card900>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Total OvertIme</CardTitle>
|
||||
<i className="ti ti-clock-play icon h-4 w-4 text-his text-xl"></i>
|
||||
<CardTitle className="text-sm font-medium">Average <span className='text-green-500 font-semibold'>Check IN</span> | <span className='text-rose-500 font-semibold'>Check OUT</span></CardTitle>
|
||||
<i className="ti ti-clock-24 icon h-4 w-4 text-his text-xl"></i>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{generateHourMinutes(performance.presence?.total_overtime)}</div>
|
||||
<div className="text-2xl font-bold"><span className='text-green-500'>{performance.presence.check_in_mod}:00</span> | <span className='text-rose-500'>{performance.presence.check_out_mod}:00</span></div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
in {start_date ? `${dayjs(start_date).format('MMM DD')} - ${dayjs(end_date).format('MMM DD')}` : 'the Past 30 Days'} (Weekend Only)
|
||||
in {start_date ? `${dayjs(start_date).format('MMM DD')} - ${dayjs(end_date).format('MMM DD')}` : 'the Past 30 Days'}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card900>
|
||||
</div>
|
||||
<div className='space-y-3'>
|
||||
<Card900>
|
||||
<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} />
|
||||
</div>
|
||||
<i className="ti ti-clock-play icon h-4 w-4 text-his text-xl"></i>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{alpha && alpha.length ? alpha.length : 0}</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
in {start_date ? `${dayjs(start_date).format('MMM DD')} - ${dayjs(end_date).format('MMM DD')}` : 'the Past 30 Days'} (Weekend Only)
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card900>
|
||||
<Card900 className='relative'>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Total <span className='text-cyan-500 font-semibold'>Task</span> | <span className='text-amber-500 font-semibold'>On Progress</span> | <span className='text-lime-500 font-semibold'>Done</span></CardTitle>
|
||||
@@ -131,18 +147,6 @@ const PerformanceComponent: FC<Props> = async ({ id, start_date, end_date }) =>
|
||||
<p className='animate-pulse'>Coming soon</p>
|
||||
</div>
|
||||
</Card900>
|
||||
<Card900>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Average <span className='text-green-500 font-semibold'>Check IN</span> | <span className='text-rose-500 font-semibold'>Check OUT</span></CardTitle>
|
||||
<i className="ti ti-clock-24 icon h-4 w-4 text-his text-xl"></i>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold"><span className='text-green-500'>{performance.presence.check_in_mod}:00</span> | <span className='text-rose-500'>{performance.presence.check_out_mod}:00</span></div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
in {start_date ? `${dayjs(start_date).format('MMM DD')} - ${dayjs(end_date).format('MMM DD')}` : 'the Past 30 Days'}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card900>
|
||||
</div>
|
||||
<Card900>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-0">
|
||||
@@ -151,9 +155,15 @@ const PerformanceComponent: FC<Props> = async ({ id, start_date, end_date }) =>
|
||||
</CardHeader>
|
||||
<CardContent className='pb-0'>
|
||||
<p className="text-xs text-muted-foreground">in {start_date ? `${dayjs(start_date).format('MMM DD')} - ${dayjs(end_date).format('MMM DD')}` : 'the Past 30 Days'}</p>
|
||||
<Suspense fallback={<LazyLoading />}>
|
||||
<DonutChart data={[performance.presence?.total_ct01, performance.presence?.total_skt, performance.presence?.total_iz01]} labels={['Leave', 'Sick', 'Permit']} colors={['#8b5cf6', '#eab308', '#06b6d4']} />
|
||||
</Suspense>
|
||||
{performance.presence?.total_ct01 || performance.presence?.total_skt || performance.presence?.total_iz01 ?
|
||||
<Suspense fallback={<LazyLoading />}>
|
||||
<DonutChart data={[performance.presence?.total_ct01, performance.presence?.total_skt, performance.presence?.total_iz01]} labels={['Leave', 'Sick', 'Permit']} colors={['#8b5cf6', '#eab308', '#06b6d4']} />
|
||||
</Suspense>
|
||||
:
|
||||
<div className='flex items-center justify-center h-40 text-sm font-medium'>
|
||||
No Data.
|
||||
</div>
|
||||
}
|
||||
</CardContent>
|
||||
</Card900>
|
||||
<Card900>
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect } from "react"
|
||||
import Image from "next/image"
|
||||
import Link from "next/link"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { clientLogger } from "@/lib/logger-client"
|
||||
|
||||
export default function Error({
|
||||
error,
|
||||
reset,
|
||||
}: {
|
||||
error: Error
|
||||
reset: () => void
|
||||
}) {
|
||||
|
||||
useEffect(() => {
|
||||
console.log({ name: error.name, cause: error.cause, message: error.message, stack: error.stack })
|
||||
clientLogger.error(error.stack!)
|
||||
}, [error])
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="h-[90vh] flex flex-col justify-center items-center overflow-x-hidden overflow-y-auto py-5">
|
||||
<Image alt='ilustrations' height={0} width={0} quality={70} src='/assets/illustrations/maintenance.svg' className='w-80 md:w-md 2xl:w-160 shadow-sm rounded-full object-cover' />
|
||||
<h2 className="text-xl sm:text-2xl font-semibold tracking-tight text-center">Oopps.. something went wrong!</h2>
|
||||
<span className="text-center mt-1 mb-6 text-zinc-600 dark:text-zinc-400 md:w-9/12 break-all px-2 sm:px-0">{error.message || 'Sorry, system error has occurred'}</span>
|
||||
<div className="flex items-center space-x-2">
|
||||
<Button onClick={() => window.location.reload()} variant='secondary' className="w-28">Try Again</Button>
|
||||
<Link href='/auth'>
|
||||
<Button variant='outline' className="w-28">Login</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -2,9 +2,9 @@ import { FC, Suspense, lazy } from 'react';
|
||||
import LazyLoading from '@/components/loader/LazyLoading';
|
||||
import DateRangePicker from './components/DateRangePicker';
|
||||
import { Metadata } from 'next';
|
||||
import { getServerSession } from 'next-auth';
|
||||
import { authOptions } from '@/pages/api/auth/[...nextauth]';
|
||||
import dayjs from 'dayjs';
|
||||
import fetchData from '@/lib/fetchData';
|
||||
import { IUser } from '@/app/admin/administration/user/component/type';
|
||||
|
||||
const Header = lazy(() => import('@/app/(dashboard)/components/Header'))
|
||||
const PerformanceComponent = lazy(() => import('./components'))
|
||||
@@ -15,15 +15,17 @@ type Props = {
|
||||
};
|
||||
|
||||
|
||||
export async function generateMetadata({ searchParams }: any): Promise<Metadata> {
|
||||
const session = await getServerSession(authOptions)
|
||||
export async function generateMetadata({ params, searchParams }: any): Promise<Metadata> {
|
||||
const id = (await params).id
|
||||
const start_date = (await searchParams)!.start_date
|
||||
const end_date = (await searchParams)!.end_date
|
||||
|
||||
const fetchUser: IUser = await fetchData(`/user/${id}`)
|
||||
|
||||
const date = start_date && end_date ? `from ${dayjs(start_date).format('MMM DD, YYYY')} to ${dayjs(end_date).format('MMM DD, YYYY')}` : 'the last 30 days'
|
||||
|
||||
return {
|
||||
title: `${session?.user?.detail.fullname || 'User'}'s Performance in ${date} - HIS Attendance Task System (H.A.T.s)`,
|
||||
title: `${fetchUser.fullname || 'User'}'s Performance in ${date} - HIS Attendance Task System (H.A.T.s)`,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
import { FC } from 'react';
|
||||
import { LazyLoadImage } from 'react-lazy-load-image-component';
|
||||
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from './ui/dialog';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
@@ -29,7 +28,7 @@ const ViewAvatar: FC<Props> = ({ avatar, className, isPresence }) => {
|
||||
src={`${process.env.BASE_URL_IMG}${avatar}`}
|
||||
effect="blur"
|
||||
wrapperClassName="w-full h-full"
|
||||
className="w-full h-full rounded-full object-cover shadow-sm border border-border cursor-pointer hover:scale-110 duration-200"
|
||||
className="w-full h-full rounded-full object-cover shadow-sm border border-border cursor-pointer hover:scale-110 duration-300"
|
||||
/>
|
||||
</span>
|
||||
</DialogTrigger>
|
||||
|
||||
@@ -2,6 +2,7 @@ import { getServerSession } from "next-auth"
|
||||
import { authOptions } from "@/pages/api/auth/[...nextauth]"
|
||||
import { redirect } from "next/navigation"
|
||||
import { ResponseData } from "@/types/types"
|
||||
import { logger } from "./logger"
|
||||
|
||||
export default async function fetchData(url: string = '/', cache: "default" | "force-cache" | "no-cache" | "no-store" | "only-if-cached" | "reload" = 'default', next?: NextFetchRequestConfig) {
|
||||
const { BASE_URL_API } = process.env
|
||||
@@ -20,6 +21,8 @@ export default async function fetchData(url: string = '/', cache: "default" | "f
|
||||
|
||||
// Recommendation: handle errors
|
||||
if (!res.ok) {
|
||||
logger.error(`ERROR FETCH DATA. http error: ${JSON.stringify(res)}. detail error: ${data}`);
|
||||
|
||||
console.log("FETCH ERROR DATA :", res.status, data)
|
||||
if (res.status === 401 || res.status === 403) return redirect(`/auth?error=Session error or has expired !`)
|
||||
// This will activate the closest `error.js` Error Boundary
|
||||
@@ -56,6 +59,8 @@ export async function fetchDataWithPost(url: string = '/', payload: any = {}, ca
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
logger.error(`ERROR FETCH DATA. http error: ${JSON.stringify(res)}. detail error: ${data}`);
|
||||
|
||||
console.log("FETCH ERROR DATA :", res.status, data)
|
||||
if (res.status === 401 || res.status === 403) redirect(`/auth?error=Session error or has expired !`);
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
// lib/client-logger.ts
|
||||
import { sendLogToServer } from "@/app/actions/logger";
|
||||
|
||||
// We wrap the server action call so it behaves identically to the server logger.
|
||||
// We DO NOT await these calls, so it acts as "fire and forget" and doesn't slow down the UI.
|
||||
export const clientLogger = {
|
||||
info: (message: string, data?: any) => { sendLogToServer('INFO', message, data); },
|
||||
warn: (message: string, data?: any) => { sendLogToServer('WARN', message, data); },
|
||||
error: (message: string, data?: any) => { sendLogToServer('ERROR', message, data); },
|
||||
debug: (message: string, data?: any) => { sendLogToServer('DEBUG', message, data); },
|
||||
|
||||
apiReq: (message: string, data?: any) => { sendLogToServer('API_REQ', message, data); },
|
||||
apiRes: (message: string, data?: any) => { sendLogToServer('API_RES', message, data); },
|
||||
};
|
||||
+56
-4
@@ -35,16 +35,68 @@ export const writeLog = (type: 'REQUEST' | 'RESPONSE' | 'ERROR', title: string,
|
||||
logProcess();
|
||||
};
|
||||
|
||||
// Helper to handle circular references in JSON (common in Axios error objects)
|
||||
|
||||
// Added standard log levels alongside our custom API ones
|
||||
type LogLevel = 'INFO' | 'WARN' | 'ERROR' | 'DEBUG' | 'API_REQ' | 'API_RES';
|
||||
|
||||
// Helper to handle circular references safely
|
||||
const getCircularReplacer = () => {
|
||||
const seen = new WeakSet();
|
||||
return (key: any, value: any) => {
|
||||
if (typeof value === "object" && value !== null) {
|
||||
if (seen.has(value)) {
|
||||
return "[Circular]";
|
||||
}
|
||||
if (seen.has(value)) return "[Circular]";
|
||||
seen.add(value);
|
||||
}
|
||||
return value;
|
||||
};
|
||||
};
|
||||
|
||||
// Core write function (Runs in the background)
|
||||
const writeToFile = (level: LogLevel, message: string, data?: any) => {
|
||||
const logProcess = async () => {
|
||||
try {
|
||||
const now = new Date();
|
||||
const dateStr = now.toISOString().split('T')[0];
|
||||
const fileName = `${dateStr}.log`;
|
||||
const logDir = path.join(process.cwd(), 'logs');
|
||||
|
||||
// Check folder exists
|
||||
if (!fs.existsSync(logDir)) {
|
||||
fs.mkdirSync(logDir);
|
||||
}
|
||||
|
||||
const timestamp = now.toISOString();
|
||||
|
||||
// Only stringify data if it was actually provided
|
||||
let dataString = '';
|
||||
if (data !== undefined) {
|
||||
dataString = typeof data === 'object'
|
||||
? `\n${JSON.stringify(data, getCircularReplacer(), 2)}`
|
||||
: `\n${data}`;
|
||||
}
|
||||
|
||||
const logEntry = `[${timestamp}] [${level}] ${message}${dataString}\n${'-'.repeat(50)}\n`;
|
||||
|
||||
fs.appendFile(path.join(logDir, fileName), logEntry, (err) => {
|
||||
if (err) console.error('Writing log failed:', err);
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Logger internal error:', error);
|
||||
}
|
||||
};
|
||||
|
||||
logProcess(); // Fire and forget
|
||||
};
|
||||
|
||||
// 🌟 Exported Logger Object for easy use anywhere!
|
||||
export const logger = {
|
||||
info: (message: string, data?: any) => writeToFile('INFO', message, data),
|
||||
warn: (message: string, data?: any) => writeToFile('WARN', message, data),
|
||||
error: (message: string, data?: any) => writeToFile('ERROR', message, data),
|
||||
debug: (message: string, data?: any) => writeToFile('DEBUG', message, data),
|
||||
|
||||
// Specific methods for your API helper to keep things organized
|
||||
apiReq: (message: string, data?: any) => writeToFile('API_REQ', message, data),
|
||||
apiRes: (message: string, data?: any) => writeToFile('API_RES', message, data),
|
||||
};
|
||||
@@ -29,6 +29,7 @@ export async function serverApiCall<T>(
|
||||
let response;
|
||||
switch (method) {
|
||||
case 'POST':
|
||||
// response = await axios.post(`http://localhost:2709${url}`, payload, config);
|
||||
response = await axios.post(url, payload, config);
|
||||
break;
|
||||
case 'PUT':
|
||||
|
||||
Generated
+41
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "hats-app",
|
||||
"version": "0.1.0",
|
||||
"version": "1.1.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "hats-app",
|
||||
"version": "0.1.0",
|
||||
"version": "1.1.0",
|
||||
"dependencies": {
|
||||
"@bprogress/next": "^3.2.12",
|
||||
"@hookform/resolvers": "^5.2.2",
|
||||
@@ -45,6 +45,7 @@
|
||||
"react-apexcharts": "^1.9.0",
|
||||
"react-day-picker": "^9.12.0",
|
||||
"react-dom": "^19.2.3",
|
||||
"react-dropzone": "^15.0.0",
|
||||
"react-easy-crop": "^5.5.6",
|
||||
"react-hook-form": "^7.68.0",
|
||||
"react-lazy-load-image-component": "^1.6.3",
|
||||
@@ -5539,6 +5540,15 @@
|
||||
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/attr-accept": {
|
||||
"version": "2.2.5",
|
||||
"resolved": "https://registry.npmjs.org/attr-accept/-/attr-accept-2.2.5.tgz",
|
||||
"integrity": "sha512-0bDNnY/u6pPwHDMoF0FieU354oBi0a8rD9FcsLwzcGWbc8KS8KPIi7y+s13OlVY+gMWc/9xEMUgNE6Qm8ZllYQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/available-typed-arrays": {
|
||||
"version": "1.0.7",
|
||||
"resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz",
|
||||
@@ -7067,6 +7077,18 @@
|
||||
"node": ">=16.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/file-selector": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/file-selector/-/file-selector-2.1.2.tgz",
|
||||
"integrity": "sha512-QgXo+mXTe8ljeqUFaX3QVHc5osSItJ/Km+xpocx0aSqWGMSCf6qYs/VnzZgS864Pjn5iceMRFigeAV7AfTlaig==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tslib": "^2.7.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 12"
|
||||
}
|
||||
},
|
||||
"node_modules/fill-range": {
|
||||
"version": "7.1.1",
|
||||
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
|
||||
@@ -9726,6 +9748,23 @@
|
||||
"react": "^19.2.3"
|
||||
}
|
||||
},
|
||||
"node_modules/react-dropzone": {
|
||||
"version": "15.0.0",
|
||||
"resolved": "https://registry.npmjs.org/react-dropzone/-/react-dropzone-15.0.0.tgz",
|
||||
"integrity": "sha512-lGjYV/EoqEjEWPnmiSvH4v5IoIAwQM2W4Z1C0Q/Pw2xD0eVzKPS359BQTUMum+1fa0kH2nrKjuavmTPOGhpLPg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"attr-accept": "^2.2.4",
|
||||
"file-selector": "^2.1.0",
|
||||
"prop-types": "^15.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 10.13"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">= 16.8 || 18.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/react-easy-crop": {
|
||||
"version": "5.5.6",
|
||||
"resolved": "https://registry.npmjs.org/react-easy-crop/-/react-easy-crop-5.5.6.tgz",
|
||||
|
||||
+2
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "hats-app",
|
||||
"description": "H.I.S Super Apps (smart absence, task management, work permit and leave mangement, etc).",
|
||||
"version": "1.1.0",
|
||||
"version": "1.1.2",
|
||||
"private": true,
|
||||
"author": "ichsankurnia",
|
||||
"repository": {
|
||||
@@ -58,6 +58,7 @@
|
||||
"react-apexcharts": "^1.9.0",
|
||||
"react-day-picker": "^9.12.0",
|
||||
"react-dom": "^19.2.3",
|
||||
"react-dropzone": "^15.0.0",
|
||||
"react-easy-crop": "^5.5.6",
|
||||
"react-hook-form": "^7.68.0",
|
||||
"react-lazy-load-image-component": "^1.6.3",
|
||||
|
||||
Binary file not shown.
Reference in New Issue
Block a user