Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| dfa0d63061 | |||
| f2e914dbfa | |||
| cb0636c957 |
+1
-1
@@ -273,7 +273,7 @@ body {
|
|||||||
width: 100%;
|
width: 100%;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
object-fit: cover;
|
object-fit: cover;
|
||||||
display: none;
|
display: block;
|
||||||
}
|
}
|
||||||
|
|
||||||
.front-photo-frame .placeholder-svg {
|
.front-photo-frame .placeholder-svg {
|
||||||
|
|||||||
+125
-135
@@ -1,33 +1,27 @@
|
|||||||
import { useState, useRef, useEffect } from 'react';
|
import { useState, useRef, useEffect } from 'react';
|
||||||
import './Generator.css';
|
import './Generator.css';
|
||||||
import { renderQRCode, downloadIDCards, downloadBulkIDCards, getXLSXLib } from './script/script.jsx';
|
import { renderQRCode, downloadIDCards, downloadBulkIDCards, getXLSXLib, clientTemplates } from './script/script.jsx';
|
||||||
import { uploadEmployeePhoto } from './services/storage.js';
|
import { uploadEmployeePhoto, saveClienteProyecto } from './services/storage.js';
|
||||||
import { supabase } from "./services/supabase";
|
import { supabase } from "./services/supabase";
|
||||||
|
|
||||||
// Convierte datos binarios recibidos (base64, buffer, array de bytes) en un Blob URL local de forma robusta
|
// Convierte datos binarios recibidos (base64, buffer, array de bytes) en un Blob URL local de forma robusta
|
||||||
const convertBinaryToBlobUrl = (data) => {
|
const convertBinaryToBlobUrl = (data) => {
|
||||||
if (!data) return null;
|
if (!data) return null;
|
||||||
try {
|
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)) {
|
if (typeof data === 'object' && data.type === 'Buffer' && Array.isArray(data.data)) {
|
||||||
const byteArray = new Uint8Array(data.data);
|
const byteArray = new Uint8Array(data.data);
|
||||||
const blob = new Blob([byteArray], { type: 'image/jpeg' });
|
const blob = new Blob([byteArray], { type: 'image/jpeg' });
|
||||||
return URL.createObjectURL(blob);
|
return URL.createObjectURL(blob);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Si ya es un array de números (bytes)
|
|
||||||
if (Array.isArray(data)) {
|
if (Array.isArray(data)) {
|
||||||
const byteArray = new Uint8Array(data);
|
const byteArray = new Uint8Array(data);
|
||||||
const blob = new Blob([byteArray], { type: 'image/jpeg' });
|
const blob = new Blob([byteArray], { type: 'image/jpeg' });
|
||||||
return URL.createObjectURL(blob);
|
return URL.createObjectURL(blob);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Si es un string
|
|
||||||
if (typeof data === 'string') {
|
if (typeof data === 'string') {
|
||||||
// Limpiar prefijo data URL si existe
|
|
||||||
const cleanBase64 = data.replace(/^data:image\/\w+;base64,/, "");
|
const cleanBase64 = data.replace(/^data:image\/\w+;base64,/, "");
|
||||||
|
|
||||||
// Decodificar Base64
|
|
||||||
const byteCharacters = atob(cleanBase64);
|
const byteCharacters = atob(cleanBase64);
|
||||||
const byteNumbers = new Array(byteCharacters.length);
|
const byteNumbers = new Array(byteCharacters.length);
|
||||||
for (let i = 0; i < byteCharacters.length; i++) {
|
for (let i = 0; i < byteCharacters.length; i++) {
|
||||||
@@ -38,7 +32,7 @@ const convertBinaryToBlobUrl = (data) => {
|
|||||||
return URL.createObjectURL(blob);
|
return URL.createObjectURL(blob);
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("Error al convertir datos binarios a Blob URL:", e);
|
console.error("Error convirtiendo formato binario a Blob URL:", e);
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
};
|
};
|
||||||
@@ -52,12 +46,16 @@ export default function IdCardGenerator() {
|
|||||||
const [employeeId, setEmployeeId] = useState('');
|
const [employeeId, setEmployeeId] = useState('');
|
||||||
const [photoSrc, setPhotoSrc] = useState('');
|
const [photoSrc, setPhotoSrc] = useState('');
|
||||||
const [photoFile, setPhotoFile] = useState(null);
|
const [photoFile, setPhotoFile] = useState(null);
|
||||||
|
const [photoProcessing, setPhotoProcessing] = useState(false);
|
||||||
const [downloadStatus, setDownloadStatus] = useState({ processing: false, text: '⬇ Descargar' });
|
const [downloadStatus, setDownloadStatus] = useState({ processing: false, text: '⬇ Descargar' });
|
||||||
|
|
||||||
|
// Bloquea el botón Descargar hasta que nombre, puesto e ID estén llenos
|
||||||
|
const isFormComplete = name.trim() && role.trim() && employeeId.trim();
|
||||||
|
|
||||||
// --- Estados Lote / Excel Masivo ───
|
// --- Estados Lote / Excel Masivo ───
|
||||||
const [bulkEmployees, setBulkEmployees] = useState([]);
|
const [bulkEmployees, setBulkEmployees] = useState([]);
|
||||||
const [bulkStatusText, setBulkStatusText] = useState('');
|
const [bulkStatusText, setBulkStatusText] = useState('');
|
||||||
const [bulkDownloadStatus, setBulkDownloadStatus] = useState({ processing: false, text: '⬇ Descargar Carnets' });
|
const [bulkDownloadStatus, setBulkDownloadStatus] = useState({ processing: false, text: '⬇ Descargar' });
|
||||||
const [showTooltip, setShowTooltip] = useState(false);
|
const [showTooltip, setShowTooltip] = useState(false);
|
||||||
|
|
||||||
const fileInputRef = useRef(null);
|
const fileInputRef = useRef(null);
|
||||||
@@ -68,30 +66,77 @@ export default function IdCardGenerator() {
|
|||||||
? import.meta.env.BASE_URL
|
? import.meta.env.BASE_URL
|
||||||
: `${import.meta.env.BASE_URL}/`;
|
: `${import.meta.env.BASE_URL}/`;
|
||||||
|
|
||||||
// Al limpiar el input en tiempo real, employeeId ya vendrá totalmente limpio
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (qrCanvasRef.current) {
|
if (qrCanvasRef.current) {
|
||||||
renderQRCode(employeeId, qrCanvasRef.current);
|
renderQRCode(employeeId, qrCanvasRef.current);
|
||||||
}
|
}
|
||||||
}, [employeeId]);
|
}, [employeeId]);
|
||||||
|
|
||||||
const handlePhotoUpload = (e) => {
|
const handlePhotoUpload = async (e) => {
|
||||||
const file = e.target.files[0];
|
const file = e.target.files[0];
|
||||||
if (file) {
|
if (!file) return;
|
||||||
setPhotoFile(file);
|
|
||||||
setPhotoSrc(URL.createObjectURL(file));
|
setPhotoFile(file);
|
||||||
|
setPhotoSrc(URL.createObjectURL(file));
|
||||||
|
setPhotoProcessing(true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const editedBlob = await processPhotoWithAI(file);
|
||||||
|
const editedUrl = URL.createObjectURL(editedBlob);
|
||||||
|
setPhotoSrc(editedUrl);
|
||||||
|
setPhotoFile(new File([editedBlob], file.name, { type: editedBlob.type || 'image/jpeg' }));
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error al procesar la foto con IA en n8n:', error);
|
||||||
|
alert('No se pudo procesar la foto con IA. Se usará la foto original para la vista previa.');
|
||||||
|
} finally {
|
||||||
|
setPhotoProcessing(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Interceptor para bloquear en tiempo real guiones y espacios en blanco
|
const processPhotoWithAI = async (file) => {
|
||||||
|
const N8N_WEBHOOK_URL = import.meta.env.VITE_N8N_WEBHOOK_URL;
|
||||||
|
const TOKEN_SECRETO = import.meta.env.VITE_WEBHOOK_TOKEN;
|
||||||
|
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append('edited', file, file.name);
|
||||||
|
formData.append('name', name);
|
||||||
|
formData.append('role', role);
|
||||||
|
formData.append('employeeId', employeeId);
|
||||||
|
formData.append('fechaProcesado', new Date().toISOString());
|
||||||
|
|
||||||
|
const response = await fetch(N8N_WEBHOOK_URL, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Authorization': TOKEN_SECRETO
|
||||||
|
},
|
||||||
|
body: formData
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`El servidor de n8n rechazó la petición (Código: ${response.status})`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const contentType = response.headers.get('content-type') || '';
|
||||||
|
if (contentType.includes('application/json')) {
|
||||||
|
const data = await response.json();
|
||||||
|
const bin = data.edited || data.data || data.foto_processed_base64 || data.photo || data.binary || (Array.isArray(data) && (data[0]?.edited || data[0]?.data));
|
||||||
|
const blobUrl = convertBinaryToBlobUrl(bin);
|
||||||
|
if (!blobUrl) throw new Error('n8n no devolvió un binario válido.');
|
||||||
|
const blob = await (await fetch(blobUrl)).blob();
|
||||||
|
return blob;
|
||||||
|
}
|
||||||
|
|
||||||
|
const blob = await response.blob();
|
||||||
|
if (!blob || blob.size === 0) throw new Error('n8n devolvió un binario vacío.');
|
||||||
|
return blob;
|
||||||
|
};
|
||||||
|
|
||||||
const handleEmployeeIdChange = (e) => {
|
const handleEmployeeIdChange = (e) => {
|
||||||
const rawValue = e.target.value;
|
const rawValue = e.target.value;
|
||||||
// Reemplaza instantáneamente cualquier guión o espacio por vacío
|
|
||||||
const cleanValue = rawValue.replace(/[-\s]/g, '');
|
const cleanValue = rawValue.replace(/[-\s]/g, '');
|
||||||
setEmployeeId(cleanValue);
|
setEmployeeId(cleanValue);
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Envío directo a n8n para recuperar las fotos procesadas ---
|
|
||||||
const enviarDatosAn8n = async (datosEmpleados) => {
|
const enviarDatosAn8n = async (datosEmpleados) => {
|
||||||
const N8N_WEBHOOK_URL = import.meta.env.VITE_N8N_WEBHOOK_URL;
|
const N8N_WEBHOOK_URL = import.meta.env.VITE_N8N_WEBHOOK_URL;
|
||||||
const TOKEN_SECRETO = import.meta.env.VITE_WEBHOOK_TOKEN;
|
const TOKEN_SECRETO = import.meta.env.VITE_WEBHOOK_TOKEN;
|
||||||
@@ -111,69 +156,41 @@ export default function IdCardGenerator() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
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})`);
|
throw new Error(`El servidor de n8n rechazó la petición (Código: ${response.status})`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const rawData = await response.json();
|
const resData = await response.json();
|
||||||
console.log('Respuesta cruda de n8n:', rawData);
|
return Array.isArray(resData) ? resData : (resData.empleados || resData.data || []);
|
||||||
|
|
||||||
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) {
|
} catch (error) {
|
||||||
console.error('Error de red enviando a n8n:', error);
|
console.error('Error de comunicación con n8n:', error);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- ALMACENAMIENTO AUTOMÁTICO EN EL STORAGE E INSTANCIACIÓN RPC ---
|
const handleBulkSupabaseSync = async (cedula, blobData, currentEmployee) => {
|
||||||
const handleBulkSupabasePhotoSync = async (cedula, blobData) => {
|
|
||||||
const cleanCedula = String(cedula).replace(/[-\s]/g, '');
|
const cleanCedula = String(cedula).replace(/[-\s]/g, '');
|
||||||
|
if (!cleanCedula) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// Se usa el cliente extraído directamente del array renderizado
|
||||||
|
const clienteProyectoValue = currentEmployee?.selectedClient || 'Generico';
|
||||||
|
await saveClienteProyecto(cleanCedula, clienteProyectoValue);
|
||||||
|
console.log(`[Supabase DB] Guardado: ${cleanCedula} → ${clienteProyectoValue}`);
|
||||||
|
|
||||||
const customFile = new File([blobData], `${cleanCedula}.jpg`, { type: 'image/jpeg' });
|
const customFile = new File([blobData], `${cleanCedula}.jpg`, { type: 'image/jpeg' });
|
||||||
const remoteStorageUrl = await uploadEmployeePhoto(cleanCedula, customFile);
|
const remoteStorageUrl = await uploadEmployeePhoto(cleanCedula, customFile);
|
||||||
|
|
||||||
if (remoteStorageUrl) {
|
if (remoteStorageUrl) {
|
||||||
const { data, error } = await supabase.rpc("save_employee_photo", {
|
await supabase.rpc("save_employee_photo", {
|
||||||
p_employee_number: cleanCedula,
|
p_employee_number: cleanCedula,
|
||||||
p_photo_url: remoteStorageUrl
|
p_photo_url: remoteStorageUrl
|
||||||
});
|
});
|
||||||
|
|
||||||
if (error) {
|
|
||||||
console.warn(`[Supabase RPC Error] Cédula ${cleanCedula}:`, error.message);
|
|
||||||
} else if (data && data.success === false) {
|
|
||||||
console.log(`[Supabase Info] Cédula ${cleanCedula}: ${data.message}`);
|
|
||||||
} else {
|
|
||||||
console.log(`[Supabase Success] Foto sincronizada para la Cédula: ${cleanCedula}`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`Sincronización abortada para la cédula ${cleanCedula}:`, error);
|
console.error(`[Supabase Sync Fallido] Cédula ${cleanCedula}:`, error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- MAPEO DE COLUMNAS EXCEL ---
|
|
||||||
const handleExcelUpload = async (e) => {
|
const handleExcelUpload = async (e) => {
|
||||||
const file = e.target.files[0];
|
const file = e.target.files[0];
|
||||||
if (!file) return;
|
if (!file) return;
|
||||||
@@ -237,7 +254,7 @@ export default function IdCardGenerator() {
|
|||||||
|
|
||||||
setBulkEmployees(formatted);
|
setBulkEmployees(formatted);
|
||||||
setBulkStatusText(`✅ ¡Cargados ${formatted.length} colaboradores! Listo para procesar.`);
|
setBulkStatusText(`✅ ¡Cargados ${formatted.length} colaboradores! Listo para procesar.`);
|
||||||
setBulkDownloadStatus({ processing: false, text: '⬇ Descargar Carnets' });
|
setBulkDownloadStatus({ processing: false, text: '⬇ Descargar' });
|
||||||
|
|
||||||
} catch (innerErr) {
|
} catch (innerErr) {
|
||||||
console.error(innerErr);
|
console.error(innerErr);
|
||||||
@@ -251,108 +268,63 @@ export default function IdCardGenerator() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- ACCIÓN DEL BOTÓN CORREGIDA CON FINALLY Y MAPEO TOTAL DE VARIABLES ---
|
|
||||||
const triggerBulkDownload = async () => {
|
const triggerBulkDownload = async () => {
|
||||||
if (bulkEmployees.length === 0) return;
|
if (bulkEmployees.length === 0) return;
|
||||||
|
|
||||||
setBulkDownloadStatus({ processing: true, text: '🔄 Descargando...' });
|
setBulkDownloadStatus({ processing: true, text: '🔄 Descargando...' });
|
||||||
setBulkStatusText('Conectando con n8n y descargando retratos optimizados por IA...');
|
setBulkStatusText('Descargando retratos...');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 1. Obtenemos las imágenes crudas en Base64/Binario desde el webhook de n8n
|
|
||||||
const resultadosN8n = await enviarDatosAn8n(bulkEmployees);
|
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...');
|
setBulkStatusText('Generando frentes, reversos y empaquetando en carpetas locales...');
|
||||||
|
|
||||||
// 2. Mapeamos garantizando que TODAS las propiedades originales existan para script.jsx
|
const employeesReadyForRender = bulkEmployees.map((originalEmp, index) => {
|
||||||
const employeesReadyForRender = resultadosN8n.map((n8nEmp, index) => {
|
const n8nEmp = resultadosN8n[index] || resultadosN8n.find(e => e.employeeId === originalEmp.employeeId) || {};
|
||||||
// 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 base64Source = n8nEmp.data || n8nEmp.foto_processed_base64 || originalEmp.data;
|
||||||
const origId = String(e.employeeId).replace(/[-\s]/g, '');
|
let finalPhotoUrl = convertBinaryToBlobUrl(base64Source) || originalEmp.fotoUrl;
|
||||||
const origName = String(e.name).trim().toLowerCase();
|
|
||||||
return (n8nId && origId === n8nId) || (n8nName && origName === n8nName);
|
|
||||||
}) || bulkEmployees[index] || {};
|
|
||||||
|
|
||||||
// Mapeo/limpieza de cliente/proyecto
|
const validClient = n8nEmp.selectedClient || originalEmp.selectedClient || 'Generico';
|
||||||
let rawClient = n8nEmp.selectedClient || n8nEmp.client || n8nEmp.proyecto || n8nEmp['cliente/proyecto'] || originalEmp.selectedClient || 'Generico';
|
const validLang = n8nEmp.language || originalEmp.language || 'Esp';
|
||||||
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 {
|
return {
|
||||||
name: String(n8nEmp.name || n8nEmp.nombre || originalEmp.name || '').trim(),
|
name: n8nEmp.name || originalEmp.name,
|
||||||
role: String(n8nEmp.role || n8nEmp.puesto || originalEmp.role || '').trim(),
|
role: n8nEmp.role || originalEmp.role,
|
||||||
selectedClient: rawClient,
|
selectedClient: validClient,
|
||||||
language: rawLang,
|
language: validLang,
|
||||||
employeeId: n8nId || String(originalEmp.employeeId || '').replace(/[-\s]/g, ''),
|
employeeId: n8nEmp.employeeId || originalEmp.employeeId,
|
||||||
fotoUrl: localPhotoUrl
|
fotoUrl: finalPhotoUrl
|
||||||
};
|
};
|
||||||
}).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({
|
await downloadBulkIDCards({
|
||||||
employees: employeesReadyForRender,
|
employees: employeesReadyForRender,
|
||||||
baseUrl,
|
baseUrl,
|
||||||
onStateChange: null, // Evitamos sobreescritura conflictiva de estados dentro del script
|
onStateChange: null,
|
||||||
onProcessEmployeePhoto: handleBulkSupabasePhotoSync
|
// CORRECCIÓN AQUÍ: Buscamos al empleado en nuestro arreglo usando la cédula que nos devuelve script.jsx
|
||||||
|
onProcessEmployeePhoto: (cedula, blobData) => {
|
||||||
|
const currentEmp = employeesReadyForRender.find(emp => emp.employeeId === cedula);
|
||||||
|
return handleBulkSupabaseSync(cedula, blobData, currentEmp);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
setBulkStatusText('🎉 ¡Lote de carnets guardado correctamente por carpetas!');
|
setBulkStatusText('🎉 ¡Lote de carnets guardado correctamente!');
|
||||||
setBulkEmployees([]);
|
setBulkEmployees([]);
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
setBulkStatusText(`❌ Error al procesar: ${error.message || error}`);
|
setBulkStatusText(`❌ Error al procesar: ${error.message || error}`);
|
||||||
} finally {
|
} finally {
|
||||||
// El bloque finally se ejecuta SIEMPRE (tenga éxito o falle), liberando el botón de forma segura
|
setBulkDownloadStatus({ processing: false, text: '⬇ Descargar' });
|
||||||
setBulkDownloadStatus({ processing: false, text: '⬇ Descargar Carnets' });
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const triggerDownload = async () => {
|
const triggerDownload = async () => {
|
||||||
if (!validateForm()) return;
|
if (!validateForm()) return;
|
||||||
|
setDownloadStatus({ processing: true, text: '🔄 Descargando...' });
|
||||||
try {
|
try {
|
||||||
|
await saveClienteProyecto(employeeId, selectedClient);
|
||||||
|
|
||||||
if (photoFile) {
|
if (photoFile) {
|
||||||
const photoUrl = await uploadEmployeePhoto(employeeId, photoFile);
|
const photoUrl = await uploadEmployeePhoto(employeeId, photoFile);
|
||||||
await supabase.rpc("save_employee_photo", {
|
await supabase.rpc("save_employee_photo", {
|
||||||
@@ -370,6 +342,7 @@ export default function IdCardGenerator() {
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
alert(err.message);
|
alert(err.message);
|
||||||
|
setDownloadStatus({ processing: false, text: '⬇ Descargar' });
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -476,8 +449,8 @@ export default function IdCardGenerator() {
|
|||||||
<label>Puesto</label>
|
<label>Puesto</label>
|
||||||
<input type="text" placeholder="Ej: Mercaderista" value={role} onChange={(e) => setRole(e.target.value)} />
|
<input type="text" placeholder="Ej: Mercaderista" value={role} onChange={(e) => setRole(e.target.value)} />
|
||||||
</div>
|
</div>
|
||||||
<div className="upload-btn" onClick={() => fileInputRef.current.click()}>
|
<div className="upload-btn" onClick={() => !photoProcessing && fileInputRef.current.click()} style={{ opacity: photoProcessing ? 0.6 : 1, cursor: photoProcessing ? 'wait' : 'pointer' }}>
|
||||||
Subir foto del colaborador
|
{photoProcessing ? '⏳ Procesando foto con IA...' : 'Subir foto del colaborador'}
|
||||||
</div>
|
</div>
|
||||||
<input type="file" accept="image/*" style={{ display: 'none' }} ref={fileInputRef} onChange={handlePhotoUpload} />
|
<input type="file" accept="image/*" style={{ display: 'none' }} ref={fileInputRef} onChange={handlePhotoUpload} />
|
||||||
</div>
|
</div>
|
||||||
@@ -529,7 +502,7 @@ export default function IdCardGenerator() {
|
|||||||
|
|
||||||
<div className="panel-section">
|
<div className="panel-section">
|
||||||
<div className="panel-section-title">Exportar</div>
|
<div className="panel-section-title">Exportar</div>
|
||||||
<button className="export-btn blue" disabled={downloadStatus.processing} onClick={triggerDownload}>
|
<button className="export-btn blue" disabled={downloadStatus.processing || !isFormComplete} onClick={triggerDownload} style={{ opacity: (!isFormComplete || downloadStatus.processing) ? 0.6 : 1 }}>
|
||||||
{downloadStatus.text}
|
{downloadStatus.text}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -543,7 +516,18 @@ export default function IdCardGenerator() {
|
|||||||
<div className="front-photo-frame" style={{ position: 'relative', overflow: 'hidden' }}>
|
<div className="front-photo-frame" style={{ position: 'relative', overflow: 'hidden' }}>
|
||||||
{photoSrc ? (
|
{photoSrc ? (
|
||||||
<img src={photoSrc} alt="Foto Colaborador" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
|
<img src={photoSrc} alt="Foto Colaborador" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
|
||||||
) : (
|
) : (null)}
|
||||||
|
{photoProcessing && (
|
||||||
|
<div style={{
|
||||||
|
position: 'absolute', inset: 0, display: 'flex',
|
||||||
|
alignItems: 'center', justifyContent: 'center',
|
||||||
|
background: 'rgba(0,0,0,0.45)', color: '#fff',
|
||||||
|
fontSize: '13px', fontWeight: '600', textAlign: 'center', padding: '8px'
|
||||||
|
}}>
|
||||||
|
⏳ Editando foto con IA...
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{!photoSrc && (
|
||||||
<svg className="placeholder-svg" viewBox="0 0 28 28" fill="none" style={{ width: '60%', height: '60%', opacity: 0.4 }}>
|
<svg className="placeholder-svg" viewBox="0 0 28 28" fill="none" style={{ width: '60%', height: '60%', opacity: 0.4 }}>
|
||||||
<circle cx="14" cy="10" r="5.5" stroke="currentColor" strokeWidth="1.5" />
|
<circle cx="14" cy="10" r="5.5" stroke="currentColor" strokeWidth="1.5" />
|
||||||
<path d="M3 24c0-6 22-6 22 0" stroke="currentColor" strokeWidth="1.5" />
|
<path d="M3 24c0-6 22-6 22 0" stroke="currentColor" strokeWidth="1.5" />
|
||||||
@@ -557,7 +541,13 @@ export default function IdCardGenerator() {
|
|||||||
|
|
||||||
<div className="card-wrap">
|
<div className="card-wrap">
|
||||||
<div className="card-label">Reverso</div>
|
<div className="card-label">Reverso</div>
|
||||||
<div className="card" id="cardBack" style={{ backgroundImage: `url('${baseUrl}${selectedClient === 'Colgate' ? 'images/AF Colgate' : 'images/AF ' + selectedClient} ${language}.png')` }}>
|
<div
|
||||||
|
className="card"
|
||||||
|
id="cardBack"
|
||||||
|
style={{
|
||||||
|
backgroundImage: `url('${baseUrl}${(clientTemplates[language] || clientTemplates['Esp'])[selectedClient] || (clientTemplates[language] || clientTemplates['Esp'])['Generico']}')`
|
||||||
|
}}
|
||||||
|
>
|
||||||
<div className="back-qr-zone">
|
<div className="back-qr-zone">
|
||||||
<canvas ref={qrCanvasRef} width={55} height={55}></canvas>
|
<canvas ref={qrCanvasRef} width={55} height={55}></canvas>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -221,7 +221,7 @@ export async function downloadIDCards(config) {
|
|||||||
`;
|
`;
|
||||||
|
|
||||||
if (photoSrc) {
|
if (photoSrc) {
|
||||||
photoTagHtml = `<img src="${photoSrc}" crossorigin="anonymous" style="width:100%; height:100%; object-fit:cover; display:block;" />`;
|
photoTagHtml = `<div style="width:100%; height:100%; background-image:url('${photoSrc}'); background-size:cover; background-position:center; background-repeat:no-repeat;"></div>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
vFront.innerHTML = `
|
vFront.innerHTML = `
|
||||||
@@ -330,7 +330,7 @@ export async function downloadBulkIDCards({ employees, baseUrl, onStateChange, o
|
|||||||
if (blobData) {
|
if (blobData) {
|
||||||
validatedPhotoUrl = URL.createObjectURL(blobData);
|
validatedPhotoUrl = URL.createObjectURL(blobData);
|
||||||
if (onProcessEmployeePhoto) {
|
if (onProcessEmployeePhoto) {
|
||||||
await onProcessEmployeePhoto(strictCleanId, blobData);
|
await onProcessEmployeePhoto(strictCleanId, blobData, emp.selectedClient || '');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -356,7 +356,7 @@ export async function downloadBulkIDCards({ employees, baseUrl, onStateChange, o
|
|||||||
`;
|
`;
|
||||||
|
|
||||||
if (validatedPhotoUrl) {
|
if (validatedPhotoUrl) {
|
||||||
photoTagHtml = `<img src="${validatedPhotoUrl}" crossorigin="anonymous" style="width:100%; height:100%; object-fit:cover; display:block;" />`;
|
photoTagHtml = `<div style="width:100%; height:100%; background-image:url('${validatedPhotoUrl}'); background-size:cover; background-position:center; background-repeat:no-repeat;"></div>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
vFront.innerHTML = `
|
vFront.innerHTML = `
|
||||||
|
|||||||
+84
-8
@@ -1,21 +1,97 @@
|
|||||||
import { supabase } from "./supabase";
|
import { supabase } from "./supabase";
|
||||||
|
|
||||||
export async function uploadEmployeePhoto(employeeNumber, file) {
|
/**
|
||||||
|
* Registra el cliente/proyecto de un carnet descargado en la tabla
|
||||||
|
* "carnet_empleados_creados_glm".
|
||||||
|
*
|
||||||
|
* @param {string} employeeNumber - Número de cédula limpio (sin guiones/espacios)
|
||||||
|
* @param {string} clienteProyecto - Nombre del cliente/proyecto seleccionado
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
export async function saveClienteProyecto(employeeNumber, clienteProyecto) {
|
||||||
|
const cleanCedula = String(employeeNumber || '').replace(/[-\s]/g, '');
|
||||||
|
const valorCliente = clienteProyecto || 'Generico';
|
||||||
|
|
||||||
const extension = file.name.split(".").pop();
|
console.log(`[Supabase] → saveClienteProyecto llamada con: cedula="${cleanCedula}", cliente_proyecto="${valorCliente}"`);
|
||||||
|
|
||||||
const fileName = `${employeeNumber}.${extension}`;
|
if (!cleanCedula) {
|
||||||
|
console.warn('[Supabase] saveClienteProyecto abortada: cédula vacía.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// CORRECCIÓN: El objeto debe llevar la cédula para que upsert funcione por conflicto
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('carnet_empleados_creados_glm')
|
||||||
|
.upsert(
|
||||||
|
{
|
||||||
|
cedula: cleanCedula,
|
||||||
|
cliente_proyecto: valorCliente
|
||||||
|
},
|
||||||
|
{ onConflict: 'cedula' }
|
||||||
|
)
|
||||||
|
.select();
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
console.error(`[Supabase] ❌ Error guardando cliente_proyecto para cédula ${cleanCedula}:`, error);
|
||||||
|
} else {
|
||||||
|
console.log(`[Supabase] ✅ Guardado exitoso carnet_empleados_creados_glm:`, data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sube la foto de un empleado al bucket "foto_empleados".
|
||||||
|
*
|
||||||
|
* El nombre del archivo sigue el patrón:
|
||||||
|
* <cedula>_<cliente>.jpg — primera foto
|
||||||
|
* <cedula>_<cliente>1.jpg — segunda foto del mismo empleado+cliente
|
||||||
|
* <cedula>_<cliente>2.jpg — tercera, etc.
|
||||||
|
*
|
||||||
|
* @param {string} employeeNumber - Número de cédula limpio (sin guiones/espacios)
|
||||||
|
* @param {File} file - Archivo de imagen a subir
|
||||||
|
* @param {string} [clientKey=''] - Nombre del cliente/proyecto (p.ej. "claro", "nestle")
|
||||||
|
* @returns {Promise<string>} - URL pública del archivo subido
|
||||||
|
*/
|
||||||
|
export async function uploadEmployeePhoto(employeeNumber, file, clientKey = '') {
|
||||||
|
const extension = file.name.split('.').pop() || 'jpg';
|
||||||
|
|
||||||
|
// Normalizar el nombre del cliente: minúsculas, sin espacios ni caracteres especiales
|
||||||
|
const safeClient = clientKey
|
||||||
|
? '_' + clientKey.toLowerCase().replace(/[^a-z0-9]/g, '')
|
||||||
|
: '';
|
||||||
|
|
||||||
|
const baseName = `${employeeNumber}${safeClient}`;
|
||||||
|
|
||||||
|
// Buscar archivos existentes con el mismo prefijo para elegir el sufijo correcto
|
||||||
|
const { data: existingFiles } = await supabase.storage
|
||||||
|
.from('foto_empleados')
|
||||||
|
.list('', { search: baseName });
|
||||||
|
|
||||||
|
// Filtrar exactamente los archivos que tengan el mismo baseName base
|
||||||
|
const pattern = new RegExp(`^${baseName}(\\d*)\\.${extension}$`);
|
||||||
|
const matches = (existingFiles || []).filter(f => pattern.test(f.name));
|
||||||
|
|
||||||
|
let fileName;
|
||||||
|
if (matches.length === 0) {
|
||||||
|
// No existe ninguno: usar el nombre base sin sufijo numérico
|
||||||
|
fileName = `${baseName}.${extension}`;
|
||||||
|
} else {
|
||||||
|
// Extraer los sufijos numéricos usados y elegir el siguiente
|
||||||
|
const usedSuffixes = matches.map(f => {
|
||||||
|
const m = f.name.match(pattern);
|
||||||
|
return m ? parseInt(m[1] || '0', 10) : 0;
|
||||||
|
});
|
||||||
|
const nextSuffix = Math.max(...usedSuffixes) + 1;
|
||||||
|
fileName = `${baseName}${nextSuffix}.${extension}`;
|
||||||
|
}
|
||||||
|
|
||||||
const { error } = await supabase.storage
|
const { error } = await supabase.storage
|
||||||
.from("foto_empleados")
|
.from('foto_empleados')
|
||||||
.upload(fileName, file, {
|
.upload(fileName, file, { upsert: false });
|
||||||
upsert: false
|
|
||||||
});
|
|
||||||
|
|
||||||
if (error) throw error;
|
if (error) throw error;
|
||||||
|
|
||||||
const { data } = supabase.storage
|
const { data } = supabase.storage
|
||||||
.from("foto_empleados")
|
.from('foto_empleados')
|
||||||
.getPublicUrl(fileName);
|
.getPublicUrl(fileName);
|
||||||
|
|
||||||
return data.publicUrl;
|
return data.publicUrl;
|
||||||
|
|||||||
Reference in New Issue
Block a user