"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." }; } }