feat: implement ID card generator with bulk upload, Excel parsing, Supabase and n8n integration
This commit is contained in:
+190
-10
@@ -1,9 +1,48 @@
|
||||
import React, { useState, useRef, useEffect } from 'react';
|
||||
import './App.css';
|
||||
import { useState, useRef, useEffect } from 'react';
|
||||
import './Generator.css';
|
||||
import { renderQRCode, downloadIDCards, downloadBulkIDCards, getXLSXLib } from './script/script.jsx';
|
||||
import { uploadEmployeePhoto } from './services/storage.js';
|
||||
import { supabase } from "./services/supabase";
|
||||
|
||||
// Convierte datos binarios recibidos (base64, buffer, array de bytes) en un Blob URL local de forma robusta
|
||||
const convertBinaryToBlobUrl = (data) => {
|
||||
if (!data) return null;
|
||||
try {
|
||||
// Si es un objeto tipo Buffer de Node.js/n8n (p. ej., { type: 'Buffer', data: [...] })
|
||||
if (typeof data === 'object' && data.type === 'Buffer' && Array.isArray(data.data)) {
|
||||
const byteArray = new Uint8Array(data.data);
|
||||
const blob = new Blob([byteArray], { type: 'image/jpeg' });
|
||||
return URL.createObjectURL(blob);
|
||||
}
|
||||
|
||||
// Si ya es un array de números (bytes)
|
||||
if (Array.isArray(data)) {
|
||||
const byteArray = new Uint8Array(data);
|
||||
const blob = new Blob([byteArray], { type: 'image/jpeg' });
|
||||
return URL.createObjectURL(blob);
|
||||
}
|
||||
|
||||
// Si es un string
|
||||
if (typeof data === 'string') {
|
||||
// Limpiar prefijo data URL si existe
|
||||
const cleanBase64 = data.replace(/^data:image\/\w+;base64,/, "");
|
||||
|
||||
// Decodificar Base64
|
||||
const byteCharacters = atob(cleanBase64);
|
||||
const byteNumbers = new Array(byteCharacters.length);
|
||||
for (let i = 0; i < byteCharacters.length; i++) {
|
||||
byteNumbers[i] = byteCharacters.charCodeAt(i);
|
||||
}
|
||||
const byteArray = new Uint8Array(byteNumbers);
|
||||
const blob = new Blob([byteArray], { type: 'image/jpeg' });
|
||||
return URL.createObjectURL(blob);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Error al convertir datos binarios a Blob URL:", e);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
export default function IdCardGenerator() {
|
||||
// --- Estados formulario individual ───
|
||||
const [name, setName] = useState('');
|
||||
@@ -18,7 +57,7 @@ export default function IdCardGenerator() {
|
||||
// --- Estados Lote / Excel Masivo ───
|
||||
const [bulkEmployees, setBulkEmployees] = useState([]);
|
||||
const [bulkStatusText, setBulkStatusText] = useState('');
|
||||
const [bulkDownloadStatus, setBulkDownloadStatus] = useState({ processing: false, text: '⬇ Descargar' });
|
||||
const [bulkDownloadStatus, setBulkDownloadStatus] = useState({ processing: false, text: '⬇ Descargar Carnets' });
|
||||
const [showTooltip, setShowTooltip] = useState(false);
|
||||
|
||||
const fileInputRef = useRef(null);
|
||||
@@ -52,6 +91,62 @@ export default function IdCardGenerator() {
|
||||
setEmployeeId(cleanValue);
|
||||
};
|
||||
|
||||
// --- Envío directo a n8n para recuperar las fotos procesadas ---
|
||||
const enviarDatosAn8n = async (datosEmpleados) => {
|
||||
const N8N_WEBHOOK_URL = import.meta.env.VITE_N8N_WEBHOOK_URL;
|
||||
const TOKEN_SECRETO = import.meta.env.VITE_WEBHOOK_TOKEN;
|
||||
|
||||
try {
|
||||
const response = await fetch(N8N_WEBHOOK_URL, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': TOKEN_SECRETO
|
||||
},
|
||||
body: JSON.stringify({
|
||||
empleados: datosEmpleados,
|
||||
total: datosEmpleados.length,
|
||||
fechaProcesado: new Date().toISOString()
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.error('Error en n8n:', response.status);
|
||||
throw new Error(`El servidor de n8n rechazó la petición (Código: ${response.status})`);
|
||||
}
|
||||
|
||||
const rawData = await response.json();
|
||||
console.log('Respuesta cruda de n8n:', rawData);
|
||||
|
||||
let dataArray = [];
|
||||
if (Array.isArray(rawData)) {
|
||||
dataArray = rawData;
|
||||
} else if (rawData && typeof rawData === 'object') {
|
||||
const keys = ['empleados', 'data', 'result', 'employees', 'items', 'output'];
|
||||
for (const key of keys) {
|
||||
if (Array.isArray(rawData[key])) {
|
||||
dataArray = rawData[key];
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (dataArray.length === 0 && (rawData.name || rawData.employeeId || rawData.data || rawData.json)) {
|
||||
dataArray = [rawData];
|
||||
}
|
||||
}
|
||||
|
||||
// Normalizar el envoltorio `{ json: ... }` si viene de n8n
|
||||
return dataArray.map(item => {
|
||||
if (item && item.json && typeof item.json === 'object') {
|
||||
return item.json;
|
||||
}
|
||||
return item;
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error de red enviando a n8n:', error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
// --- ALMACENAMIENTO AUTOMÁTICO EN EL STORAGE E INSTANCIACIÓN RPC ---
|
||||
const handleBulkSupabasePhotoSync = async (cedula, blobData) => {
|
||||
const cleanCedula = String(cedula).replace(/[-\s]/g, '');
|
||||
@@ -78,7 +173,7 @@ export default function IdCardGenerator() {
|
||||
}
|
||||
};
|
||||
|
||||
// --- MAPEO DE COLUMNAS EXCEL CON LIMPIEZA DE CÉDULA ---
|
||||
// --- MAPEO DE COLUMNAS EXCEL ---
|
||||
const handleExcelUpload = async (e) => {
|
||||
const file = e.target.files[0];
|
||||
if (!file) return;
|
||||
@@ -88,7 +183,7 @@ export default function IdCardGenerator() {
|
||||
const XLSXLib = await getXLSXLib();
|
||||
const reader = new FileReader();
|
||||
|
||||
reader.onload = (evt) => {
|
||||
reader.onload = async (evt) => {
|
||||
try {
|
||||
const bstr = evt.target.result;
|
||||
const wb = XLSXLib.read(bstr, { type: 'binary' });
|
||||
@@ -141,7 +236,9 @@ export default function IdCardGenerator() {
|
||||
}).filter(emp => emp.name && emp.role && emp.employeeId);
|
||||
|
||||
setBulkEmployees(formatted);
|
||||
setBulkStatusText(`✅ ¡Cargados ${formatted.length} colaboradores con éxito!`);
|
||||
setBulkStatusText(`✅ ¡Cargados ${formatted.length} colaboradores! Listo para procesar.`);
|
||||
setBulkDownloadStatus({ processing: false, text: '⬇ Descargar Carnets' });
|
||||
|
||||
} catch (innerErr) {
|
||||
console.error(innerErr);
|
||||
setBulkStatusText('❌ Error de lectura. Revisa el formato de columnas.');
|
||||
@@ -154,19 +251,102 @@ export default function IdCardGenerator() {
|
||||
}
|
||||
};
|
||||
|
||||
// --- ACCIÓN DEL BOTÓN CORREGIDA CON FINALLY Y MAPEO TOTAL DE VARIABLES ---
|
||||
const triggerBulkDownload = async () => {
|
||||
if (bulkEmployees.length === 0) return;
|
||||
|
||||
setBulkDownloadStatus({ processing: true, text: '🔄 Descargando...' });
|
||||
setBulkStatusText('Conectando con n8n y descargando retratos optimizados por IA...');
|
||||
|
||||
try {
|
||||
// 1. Obtenemos las imágenes crudas en Base64/Binario desde el webhook de n8n
|
||||
const resultadosN8n = await enviarDatosAn8n(bulkEmployees);
|
||||
|
||||
if (!resultadosN8n || resultadosN8n.length === 0) {
|
||||
throw new Error('No se recibieron colaboradores procesados desde n8n.');
|
||||
}
|
||||
|
||||
setBulkStatusText('Generando frentes, reversos y empaquetando en carpetas locales...');
|
||||
|
||||
// 2. Mapeamos garantizando que TODAS las propiedades originales existan para script.jsx
|
||||
const employeesReadyForRender = resultadosN8n.map((n8nEmp, index) => {
|
||||
// Buscamos la fila correspondiente en el Excel original (por employeeId o nombre) para mantener cliente
|
||||
const n8nId = String(n8nEmp.employeeId || n8nEmp.employee_id || n8nEmp.cedula || n8nEmp.id || '').replace(/[-\s]/g, '');
|
||||
const n8nName = String(n8nEmp.name || n8nEmp.nombre || '').trim().toLowerCase();
|
||||
|
||||
const originalEmp = bulkEmployees.find(e => {
|
||||
const origId = String(e.employeeId).replace(/[-\s]/g, '');
|
||||
const origName = String(e.name).trim().toLowerCase();
|
||||
return (n8nId && origId === n8nId) || (n8nName && origName === n8nName);
|
||||
}) || bulkEmployees[index] || {};
|
||||
|
||||
// Mapeo/limpieza de cliente/proyecto
|
||||
let rawClient = n8nEmp.selectedClient || n8nEmp.client || n8nEmp.proyecto || n8nEmp['cliente/proyecto'] || originalEmp.selectedClient || 'Generico';
|
||||
const lowerClient = String(rawClient).toLowerCase();
|
||||
if (lowerClient.includes('nestle')) rawClient = 'Nestle';
|
||||
else if (lowerClient.includes('claro')) rawClient = 'Claro';
|
||||
else if (lowerClient.includes('colgate')) rawClient = 'Colgate';
|
||||
else if (lowerClient.includes('kitchenaid') || lowerClient.includes('kitchen')) rawClient = 'KitchenAid';
|
||||
else if (lowerClient.includes('kraft')) rawClient = 'Kraft';
|
||||
else if (lowerClient.includes('motorola')) rawClient = 'Motorola';
|
||||
else if (lowerClient.includes('p&g') || lowerClient.includes('p y g')) rawClient = 'P&G';
|
||||
else if (lowerClient.includes('philip') || lowerClient.includes('morris')) rawClient = 'Philip Morris';
|
||||
else if (lowerClient.includes('whirlpool')) rawClient = 'Whirlpool';
|
||||
else rawClient = 'Generico';
|
||||
|
||||
// Mapeo/conversión de la imagen del empleado
|
||||
let localPhotoUrl = originalEmp.fotoUrl || '';
|
||||
const imageData = n8nEmp.data || n8nEmp.foto_processed_base64 || n8nEmp.binary || n8nEmp.image || originalEmp.data;
|
||||
|
||||
if (imageData) {
|
||||
const blobUrl = convertBinaryToBlobUrl(imageData);
|
||||
if (blobUrl) {
|
||||
localPhotoUrl = blobUrl;
|
||||
}
|
||||
}
|
||||
|
||||
// Normalización de idioma
|
||||
let rawLang = String(n8nEmp.language || n8nEmp.lenguaje || n8nEmp.idioma || originalEmp.language || 'Esp').trim().toLowerCase();
|
||||
if (rawLang.includes('es') || rawLang.includes('esp')) {
|
||||
rawLang = 'Esp';
|
||||
} else if (rawLang.includes('en') || rawLang.includes('ing')) {
|
||||
rawLang = 'Ing';
|
||||
} else {
|
||||
rawLang = 'Esp';
|
||||
}
|
||||
|
||||
// Inyectamos las claves exactas que script.jsx desestructura
|
||||
return {
|
||||
name: String(n8nEmp.name || n8nEmp.nombre || originalEmp.name || '').trim(),
|
||||
role: String(n8nEmp.role || n8nEmp.puesto || originalEmp.role || '').trim(),
|
||||
selectedClient: rawClient,
|
||||
language: rawLang,
|
||||
employeeId: n8nId || String(originalEmp.employeeId || '').replace(/[-\s]/g, ''),
|
||||
fotoUrl: localPhotoUrl
|
||||
};
|
||||
}).filter(emp => emp.name && emp.employeeId);
|
||||
|
||||
if (employeesReadyForRender.length === 0) {
|
||||
throw new Error('Ningún colaborador posee datos válidos de nombre e identificación para procesar.');
|
||||
}
|
||||
|
||||
// 3. Ejecutamos tu motor original en script.jsx que procesará los diseños de Claro, Nestle, etc.
|
||||
await downloadBulkIDCards({
|
||||
employees: bulkEmployees,
|
||||
employees: employeesReadyForRender,
|
||||
baseUrl,
|
||||
onStateChange: setBulkDownloadStatus,
|
||||
onStateChange: null, // Evitamos sobreescritura conflictiva de estados dentro del script
|
||||
onProcessEmployeePhoto: handleBulkSupabasePhotoSync
|
||||
});
|
||||
setBulkStatusText('🎉 ¡Lote guardado!');
|
||||
|
||||
setBulkStatusText('🎉 ¡Lote de carnets guardado correctamente por carpetas!');
|
||||
setBulkEmployees([]);
|
||||
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
alert("Error procesando las imágenes remotas.");
|
||||
setBulkStatusText(`❌ Error al procesar: ${error.message || error}`);
|
||||
} finally {
|
||||
// El bloque finally se ejecuta SIEMPRE (tenga éxito o falle), liberando el botón de forma segura
|
||||
setBulkDownloadStatus({ processing: false, text: '⬇ Descargar Carnets' });
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user