diff --git a/src/Generator.jsx b/src/Generator.jsx index ce28998..a5e5c04 100644 --- a/src/Generator.jsx +++ b/src/Generator.jsx @@ -25,7 +25,6 @@ export default function IdCardGenerator() { const excelInputRef = useRef(null); const qrCanvasRef = useRef(null); - // Determinar la URL base de Vite de forma segura (Solo una declaración única aquí) const baseUrl = import.meta.env.BASE_URL.endsWith('/') ? import.meta.env.BASE_URL : `${import.meta.env.BASE_URL}/`; @@ -44,7 +43,36 @@ export default function IdCardGenerator() { } }; - // --- MAPEO DE COLUMNAS CORREGIDO --- + // --- ALMACENAMIENTO AUTOMÁTICO EN EL STORAGE E INSTANCIACIÓN RPC --- + const handleBulkSupabasePhotoSync = async (cedula, blobData) => { + try { + // Creamos un archivo sintáctico válido con tipo explícito image/jpeg + const customFile = new File([blobData], `${cedula}.jpg`, { type: 'image/jpeg' }); + + // Subida al Storage Bucket + const remoteStorageUrl = await uploadEmployeePhoto(cedula, customFile); + + if (remoteStorageUrl) { + // LLamado a tu función RPC nativa + const { data, error } = await supabase.rpc("save_employee_photo", { + p_employee_number: cedula, + p_photo_url: remoteStorageUrl + }); + + if (error) { + console.warn(`[Supabase RPC Error] Cédula ${cedula}:`, error.message); + } else if (data && data.success === false) { + console.log(`[Supabase Info] Cédula ${cedula}: ${data.message}`); + } else { + console.log(`[Supabase Success] Foto sincronizada para la Cédula: ${cedula}`); + } + } + } catch (error) { + console.error(`Sincronización abortada para la cédula ${cedula}:`, error); + } + }; + + // --- MAPEO DE COLUMNAS EXCEL CORREGIDO --- const handleExcelUpload = async (e) => { const file = e.target.files[0]; if (!file) return; @@ -68,7 +96,6 @@ export default function IdCardGenerator() { } const formatted = jsonRows.map((row) => { - // 1. Normalizar Idioma (ES/Español -> Esp, EN/Inglés -> Ing) let rawLang = String(row.lenguaje || 'Esp').trim().toLowerCase(); if (rawLang.includes('es') || rawLang.includes('esp')) { rawLang = 'Esp'; @@ -78,14 +105,13 @@ export default function IdCardGenerator() { rawLang = 'Esp'; } - // 2. CORRECCIÓN: Leer la columna exacta "cliente/proyecto" por separado let rawClient = String(row['cliente/proyecto'] || 'Generico') .trim() .normalize("NFD") - .replace(/[\u0300-\u036f]/g, ""); // Convierte "Nestlé" en "Nestle" + .replace(/[\u0300-\u036f]/g, ""); - // Mapear nombres específicos para asegurar coincidencia exacta con las llaves de script.jsx const lowerClient = rawClient.toLowerCase(); + // CORRECCIÓN ESENCIAL: Dejar las llaves igual a script.jsx (Claro, Nestle, Whirlpool) sin .toUpperCase() if (lowerClient.includes('nestle')) rawClient = 'Nestle'; else if (lowerClient.includes('claro')) rawClient = 'Claro'; else if (lowerClient.includes('colgate')) rawClient = 'Colgate'; @@ -102,7 +128,7 @@ export default function IdCardGenerator() { role: String(row.puesto || '').trim(), selectedClient: rawClient, language: rawLang, - employeeId: String(row.cedula || '').trim(), // CORRECCIÓN: Columna individual 'cedula' + employeeId: String(row.cedula || '').trim(), fotoUrl: String(row.foto_url || '').trim() }; }).filter(emp => emp.name && emp.role); @@ -127,9 +153,10 @@ export default function IdCardGenerator() { await downloadBulkIDCards({ employees: bulkEmployees, baseUrl, - onStateChange: setBulkDownloadStatus + onStateChange: setBulkDownloadStatus, + onProcessEmployeePhoto: handleBulkSupabasePhotoSync }); - setBulkStatusText('🎉 ¡Lote procesado y guardado!'); + setBulkStatusText('🎉 ¡Lote guardado y sincronizado con Supabase!'); } catch (error) { console.error(error); alert("Error procesando las imágenes remotas."); @@ -176,7 +203,7 @@ export default function IdCardGenerator() {