Files
hats-app/app/admin/manual/manual-presence/component/ImportExcel.tsx
T
Ichsan Kurniawan 7d18e9f38f Add CreateAttendance and update UI/hooks
Add a new CreateAttendance component to allow admins to create manual attendance (Alpha) with confirmation dialog and server API call. Lazy-load the CreateAttendance component in EmployeeAlpha and wrap usages with Suspense plus a loading fallback to reduce initial bundle size. Update Performance page to use a centered Suspense fallback. Improve ImportExcel UX by showing a full-loading state, tweaking button/icon styles, and fixing modal sizing/scroll behavior. Enhance useFetchWithAxios to accept nullable URLs and SWR options, adjust the fetcher signature, and return the nested data payload. Add a "use server" directive and imports in lib/server-api, and apply small type/formatting tweaks (table size cast and minor UI/text refinements).
2026-02-22 23:33:15 +07:00

192 lines
10 KiB
TypeScript

"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) => {
setFullLoading(true);
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 className='text-muted-foreground' />Import Excel</Button>
{showModal ?
<AlertDialog open={true}>
<AlertDialogContent className={`max-h-[95vh] overflow-y-hidden duration-300 min-w-full ${rowData && rowData.length > 0 ? 'min-w-[90vw]' : 'sm:min-w-[600px]'}`}>
<AlertDialogHeader>
<AlertDialogTitle>{rowData && rowData.length > 0 ? "Review Your Data" : "Upload Excel File"}</AlertDialogTitle>
<AlertDialogDescription>
{rowData && rowData.length > 0 ? "Please review attendance data first before saving!" : "Please attach your excel file for batching import"}
</AlertDialogDescription>
</AlertDialogHeader>
<div className="flex flex-col gap-2 max-h-[65vh] md:max-h-[70vh] 2xl:max-h-[75vh] overflow-y-auto">
{/* Drop area */}
<Dropzone ref={dropzoneRef} onDrop={onDrop} multiple={false} noClick noKeyboard
accept={{
'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
}
</>
);
}