feat: implement bulk ID card generation via Excel upload and individual form processing with Supabase storage integration
This commit is contained in:
+205
-195
@@ -1,28 +1,35 @@
|
||||
import React, { useState, useRef, useEffect } from 'react';
|
||||
import './App.css';
|
||||
// Importamos las funciones lógicas nativas desde el archivo portado script.jsx
|
||||
import { renderQRCode, downloadIDCards } from './script/script.jsx';
|
||||
import { renderQRCode, downloadIDCards, downloadBulkIDCards, getXLSXLib } from './script/script.jsx';
|
||||
import { uploadEmployeePhoto } from './services/storage.js';
|
||||
import { supabase } from "./services/supabase";
|
||||
|
||||
export default function IdCardGenerator() {
|
||||
// --- Estados para manejar la lógica en tiempo real ───
|
||||
// --- Estados formulario individual ───
|
||||
const [name, setName] = useState('');
|
||||
const [role, setRole] = useState('');
|
||||
const [language, setLanguage] = useState('Esp'); // 'Esp' o 'Ing'
|
||||
const [selectedClient, setSelectedClient] = useState('Generico'); // Sin tildes de forma interna
|
||||
const [language, setLanguage] = useState('Esp');
|
||||
const [selectedClient, setSelectedClient] = useState('Generico');
|
||||
const [employeeId, setEmployeeId] = useState('');
|
||||
const [photoSrc, setPhotoSrc] = useState('');
|
||||
const [photoFile, setPhotoFile] = useState(null);
|
||||
|
||||
// Estado para controlar la UI del botón de descarga mientras procesa
|
||||
const [downloadStatus, setDownloadStatus] = useState({ processing: false, text: '⬇ Descargar' });
|
||||
|
||||
// Referencias del DOM controladas por React
|
||||
// --- Estados Lote / Excel Masivo ───
|
||||
const [bulkEmployees, setBulkEmployees] = useState([]);
|
||||
const [bulkStatusText, setBulkStatusText] = useState('');
|
||||
const [bulkDownloadStatus, setBulkDownloadStatus] = useState({ processing: false, text: '⬇ Descargar' });
|
||||
const [showTooltip, setShowTooltip] = useState(false);
|
||||
|
||||
const fileInputRef = useRef(null);
|
||||
const excelInputRef = useRef(null);
|
||||
const qrCanvasRef = useRef(null);
|
||||
|
||||
// EFECTO AUTOMÁTICO: Renderiza el QR en tiempo real mientras escribes mediante referencias
|
||||
// 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}/`;
|
||||
|
||||
useEffect(() => {
|
||||
if (qrCanvasRef.current) {
|
||||
renderQRCode(employeeId, qrCanvasRef.current);
|
||||
@@ -31,112 +38,132 @@ export default function IdCardGenerator() {
|
||||
|
||||
const handlePhotoUpload = (e) => {
|
||||
const file = e.target.files[0];
|
||||
|
||||
if (file) {
|
||||
setPhotoFile(file);
|
||||
|
||||
const localUrl = URL.createObjectURL(file);
|
||||
setPhotoSrc(localUrl);
|
||||
setPhotoSrc(URL.createObjectURL(file));
|
||||
}
|
||||
};
|
||||
|
||||
const handleLanguageChange = (lang) => {
|
||||
setLanguage(lang);
|
||||
};
|
||||
// --- MAPEO DE COLUMNAS CORREGIDO ---
|
||||
const handleExcelUpload = async (e) => {
|
||||
const file = e.target.files[0];
|
||||
if (!file) return;
|
||||
|
||||
const handleClientChange = (e) => {
|
||||
setSelectedClient(e.target.value);
|
||||
};
|
||||
setBulkStatusText('Leyendo documento...');
|
||||
try {
|
||||
const XLSXLib = await getXLSXLib();
|
||||
const reader = new FileReader();
|
||||
|
||||
// Forzar generación del QR manualmente si se desea mediante el botón verde
|
||||
const triggerGenerateQR = () => {
|
||||
if (qrCanvasRef.current) {
|
||||
renderQRCode(employeeId, qrCanvasRef.current);
|
||||
}
|
||||
};
|
||||
reader.onload = (evt) => {
|
||||
try {
|
||||
const bstr = evt.target.result;
|
||||
const wb = XLSXLib.read(bstr, { type: 'binary' });
|
||||
const wsname = wb.SheetNames[0];
|
||||
const ws = wb.Sheets[wsname];
|
||||
const jsonRows = XLSXLib.utils.sheet_to_json(ws);
|
||||
|
||||
// Disparador del motor de renderizado ULTRA MAX QUALITY en sandbox
|
||||
const triggerDownload = async () => {
|
||||
if (!validateForm()) {
|
||||
if (jsonRows.length === 0) {
|
||||
setBulkStatusText('❌ El archivo está vacío.');
|
||||
return;
|
||||
}
|
||||
|
||||
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';
|
||||
} else if (rawLang.includes('en') || rawLang.includes('ing')) {
|
||||
rawLang = 'Ing';
|
||||
} else {
|
||||
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"
|
||||
|
||||
// Mapear nombres específicos para asegurar coincidencia exacta con las llaves de script.jsx
|
||||
const lowerClient = 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';
|
||||
|
||||
return {
|
||||
name: String(row.nombre || '').trim(),
|
||||
role: String(row.puesto || '').trim(),
|
||||
selectedClient: rawClient,
|
||||
language: rawLang,
|
||||
employeeId: String(row.cedula || '').trim(), // CORRECCIÓN: Columna individual 'cedula'
|
||||
fotoUrl: String(row.foto_url || '').trim()
|
||||
};
|
||||
}).filter(emp => emp.name && emp.role);
|
||||
|
||||
setBulkEmployees(formatted);
|
||||
setBulkStatusText(`✅ ¡Cargados ${formatted.length} colaboradores con éxito!`);
|
||||
} catch (innerErr) {
|
||||
console.error(innerErr);
|
||||
setBulkStatusText('❌ Error de lectura. Revisa el formato de columnas.');
|
||||
}
|
||||
};
|
||||
reader.readAsBinaryString(file);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
setBulkStatusText('❌ Error cargando el motor XLSX.');
|
||||
}
|
||||
};
|
||||
|
||||
const triggerBulkDownload = async () => {
|
||||
if (bulkEmployees.length === 0) return;
|
||||
try {
|
||||
await downloadBulkIDCards({
|
||||
employees: bulkEmployees,
|
||||
baseUrl,
|
||||
onStateChange: setBulkDownloadStatus
|
||||
});
|
||||
setBulkStatusText('🎉 ¡Lote procesado y guardado!');
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
alert("Error procesando las imágenes remotas.");
|
||||
}
|
||||
};
|
||||
|
||||
// Solo si el usuario seleccionó una foto
|
||||
const triggerDownload = async () => {
|
||||
if (!validateForm()) return;
|
||||
try {
|
||||
if (photoFile) {
|
||||
|
||||
const photoUrl = await uploadEmployeePhoto(
|
||||
employeeId,
|
||||
photoFile
|
||||
);
|
||||
|
||||
console.log("Foto subida:", photoUrl);
|
||||
|
||||
const { data, error } = await supabase.rpc(
|
||||
"save_employee_photo",
|
||||
{
|
||||
const photoUrl = await uploadEmployeePhoto(employeeId, photoFile);
|
||||
await supabase.rpc("save_employee_photo", {
|
||||
p_employee_number: employeeId,
|
||||
p_photo_url: photoUrl
|
||||
}
|
||||
);
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (!data.success) {
|
||||
console.warn(data.message);
|
||||
} else {
|
||||
console.log(data.message);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
await downloadIDCards({
|
||||
name,
|
||||
role,
|
||||
selectedClient,
|
||||
language,
|
||||
photoSrc,
|
||||
baseUrl: import.meta.env.BASE_URL.endsWith('/')
|
||||
? import.meta.env.BASE_URL
|
||||
: `${import.meta.env.BASE_URL}/`,
|
||||
name, role, selectedClient, language, photoSrc,
|
||||
baseUrl,
|
||||
qrCanvas: qrCanvasRef.current,
|
||||
onStateChange: setDownloadStatus
|
||||
});
|
||||
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
alert(err.message);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
const baseUrl = import.meta.env.BASE_URL.endsWith('/')
|
||||
? import.meta.env.BASE_URL
|
||||
: `${import.meta.env.BASE_URL}/`;
|
||||
|
||||
const validateForm = () => {
|
||||
if (!name.trim()) {
|
||||
alert("Debe ingresar el nombre.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!role.trim()) {
|
||||
alert("Debe ingresar el puesto.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!employeeId.trim()) {
|
||||
alert("Debe ingresar el ID del empleado.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!photoFile) {
|
||||
alert("Debe subir la foto del colaborador.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!name.trim()) { alert("Debe ingresar el nombre."); return false; }
|
||||
if (!role.trim()) { alert("Debe ingresar el puesto."); return false; }
|
||||
if (!employeeId.trim()) { alert("Debe ingresar el ID del empleado."); return false; }
|
||||
if (!photoFile) { alert("Debe subir la foto del colaborador."); return false; }
|
||||
return true;
|
||||
};
|
||||
|
||||
@@ -147,83 +174,113 @@ export default function IdCardGenerator() {
|
||||
<p>GomezLee Marketing · Carnet Corporativo CR80</p>
|
||||
</div>
|
||||
|
||||
<div className="main-container">
|
||||
<div className="panel">
|
||||
<div className="main-container" style={{ display: 'flex', gap: '20px', alignItems: 'flex-start' }}>
|
||||
|
||||
{/* FORMULARIO MASIVO EXCEL (IZQUIERDA) */}
|
||||
<div className="panel" style={{ minWidth: '320px' }}>
|
||||
<div className="preview-badge" style={{ background: '#FFF3E0', color: '#E65100' }}>
|
||||
<div className="dot" style={{ background: '#E65100' }}></div>
|
||||
<span>Módulo de Lotes Automáticos</span>
|
||||
</div>
|
||||
|
||||
<div className="panel-section">
|
||||
<div className="panel-section-title" style={{ display: 'flex', alignItems: 'center', gap: '6px', position: 'relative' }}>
|
||||
<span>Carga Masiva de Colaboradores</span>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
width: '16px', height: '16px', borderRadius: '50%',
|
||||
background: '#cbd5e1', color: '#334155', fontSize: '11px',
|
||||
fontWeight: 'bold', cursor: 'help', userSelect: 'none'
|
||||
}}
|
||||
onMouseEnter={() => setShowTooltip(true)}
|
||||
onMouseLeave={() => setShowTooltip(false)}
|
||||
>
|
||||
?
|
||||
</div>
|
||||
|
||||
{showTooltip && (
|
||||
<div style={{
|
||||
position: 'absolute', top: '24px', left: '0', right: '0',
|
||||
background: '#1e293b', color: '#ffffff', padding: '10px',
|
||||
borderRadius: '6px', fontSize: '11px', lineHeight: '1.4',
|
||||
zIndex: '99', boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)',
|
||||
fontWeight: 'normal', textTransform: 'none'
|
||||
}}>
|
||||
Formato de columnas requeridas en el Excel: <br />
|
||||
<b style={{ color: '#6CC24A' }}>nombre, puesto, cliente/proyecto, cedula, lenguaje, foto_url</b>.<br />
|
||||
Las imágenes se descargarán automáticamente desde los enlaces públicos de Google Drive.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="upload-btn" style={{ background: '#475569', marginTop: '12px' }} onClick={() => excelInputRef.current.click()}>
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
|
||||
<polyline points="14 2 14 8 20 8" />
|
||||
<line x1="16" y1="13" x2="8" y2="13" />
|
||||
<line x1="16" y1="17" x2="8" y2="17" />
|
||||
</svg>
|
||||
Seleccionar Archivo Excel
|
||||
</div>
|
||||
<input type="file" accept=".xlsx, .xls, .csv" style={{ display: 'none' }} ref={excelInputRef} onChange={handleExcelUpload} />
|
||||
|
||||
{bulkStatusText && (
|
||||
<div style={{ fontSize: '12px', marginTop: '8px', fontWeight: '500', color: '#475569' }}>
|
||||
{bulkStatusText}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="divider"></div>
|
||||
|
||||
<div className="panel-section">
|
||||
<div className="panel-section-title">Exportar Lote</div>
|
||||
<button
|
||||
className="export-btn blue"
|
||||
disabled={bulkDownloadStatus.processing || bulkEmployees.length === 0}
|
||||
onClick={triggerBulkDownload}
|
||||
style={{ opacity: bulkEmployees.length === 0 ? 0.6 : 1 }}
|
||||
>
|
||||
{bulkDownloadStatus.text}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* FORMULARIO INDIVIDUAL (CENTRO) */}
|
||||
<div className="panel">
|
||||
<div className="preview-badge">
|
||||
<div className="dot"></div>
|
||||
<span>Vista previa en tiempo real</span>
|
||||
</div>
|
||||
|
||||
{/* Sección Colaborador */}
|
||||
<div className="panel-section">
|
||||
<div className="panel-section-title">Colaborador</div>
|
||||
|
||||
<div className="field">
|
||||
<label>Nombre</label>
|
||||
<input
|
||||
type="text"
|
||||
id="inputName"
|
||||
placeholder="Ej: Alexi Zabala"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
<input type="text" placeholder="Ej: Alexi Zabala" value={name} onChange={(e) => setName(e.target.value)} />
|
||||
</div>
|
||||
|
||||
<div className="field">
|
||||
<label>Puesto</label>
|
||||
<input
|
||||
type="text"
|
||||
id="inputRole"
|
||||
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 className="upload-btn" onClick={() => fileInputRef.current.click()}>
|
||||
<svg width="14" height="14" viewBox="0 0 14 14" fill="none">
|
||||
<circle cx="7" cy="5" r="3" stroke="currentColor" strokeWidth="1.2" />
|
||||
<path d="M1 12c0-3.5 12-3.5 12 0" stroke="currentColor" strokeWidth="1.2" />
|
||||
</svg>
|
||||
Subir foto del colaborador
|
||||
</div>
|
||||
<input
|
||||
type="file"
|
||||
id="photoInput"
|
||||
accept="image/*"
|
||||
style={{ display: 'none' }}
|
||||
ref={fileInputRef}
|
||||
onChange={handlePhotoUpload}
|
||||
/>
|
||||
<input type="file" accept="image/*" style={{ display: 'none' }} ref={fileInputRef} onChange={handlePhotoUpload} />
|
||||
</div>
|
||||
|
||||
<div className="divider"></div>
|
||||
|
||||
{/* Sección Cliente / Proyecto */}
|
||||
<div className="panel-section">
|
||||
<div className="panel-section-title">Cliente / Proyecto</div>
|
||||
|
||||
<div className="lang-container">
|
||||
<button
|
||||
type="button"
|
||||
className={`lang-btn ${language === 'Esp' ? 'active' : ''}`}
|
||||
onClick={() => handleLanguageChange('Esp')}
|
||||
>
|
||||
Español
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`lang-btn ${language === 'Ing' ? 'active' : ''}`}
|
||||
onClick={() => handleLanguageChange('Ing')}
|
||||
>
|
||||
Inglés
|
||||
</button>
|
||||
<button type="button" className={`lang-btn ${language === 'Esp' ? 'active' : ''}`} onClick={() => setLanguage('Esp')}>Español</button>
|
||||
<button type="button" className={`lang-btn ${language === 'Ing' ? 'active' : ''}`} onClick={() => setLanguage('Ing')}>Inglés</button>
|
||||
</div>
|
||||
|
||||
<div className="field">
|
||||
<label>Seleccionar Cliente</label>
|
||||
<select id="selectClient" value={selectedClient} onChange={handleClientChange}>
|
||||
<select value={selectedClient} onChange={(e) => setSelectedClient(e.target.value)}>
|
||||
<option value="Generico">Genérico (Por defecto)</option>
|
||||
<option value="Claro">Claro</option>
|
||||
<option value="Colgate">Colgate</option>
|
||||
@@ -240,104 +297,57 @@ export default function IdCardGenerator() {
|
||||
|
||||
<div className="divider"></div>
|
||||
|
||||
{/* Sección Código QR */}
|
||||
<div className="panel-section">
|
||||
<div className="panel-section-title">Código QR</div>
|
||||
<div className="field">
|
||||
<label>ID del empleado</label>
|
||||
<input
|
||||
type="text"
|
||||
id="inputQR"
|
||||
placeholder="Ej: 12345"
|
||||
value={employeeId}
|
||||
onChange={(e) => setEmployeeId(e.target.value)}
|
||||
/>
|
||||
<input type="text" placeholder="Ej: 12345" value={employeeId} onChange={(e) => setEmployeeId(e.target.value)} />
|
||||
</div>
|
||||
<button
|
||||
className="export-btn"
|
||||
style={{ background: '#6CC24A', marginTop: '2px' }}
|
||||
onClick={triggerGenerateQR}
|
||||
>
|
||||
<button className="export-btn" style={{ background: '#6CC24A', marginTop: '2px' }} onClick={() => renderQRCode(employeeId, qrCanvasRef.current)}>
|
||||
⟳ Generar QR
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="divider"></div>
|
||||
|
||||
{/* Sección Exportar */}
|
||||
<div className="panel-section">
|
||||
<div className="panel-section-title">Exportar</div>
|
||||
<button
|
||||
className="export-btn blue"
|
||||
id="btnDownload"
|
||||
disabled={downloadStatus.processing}
|
||||
onClick={triggerDownload}
|
||||
>
|
||||
<button className="export-btn blue" disabled={downloadStatus.processing} onClick={triggerDownload}>
|
||||
{downloadStatus.text}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
{/* --- STAGE: Vista previa de las tarjetas ─── */}
|
||||
{/* VISTA PREVIA (DERECHA) */}
|
||||
<div className="stage">
|
||||
|
||||
{/* Frente */}
|
||||
<div className="card-wrap">
|
||||
<div className="card-label">Frente</div>
|
||||
<div
|
||||
className="card"
|
||||
id="cardFront"
|
||||
style={{ backgroundImage: `url('${baseUrl}images/AF GLM Frente.png')` }}
|
||||
>
|
||||
<div className="front-photo-frame" id="photoFrame" style={{ position: 'relative', overflow: 'hidden' }}>
|
||||
<div className="card" id="cardFront" style={{ backgroundImage: `url('${baseUrl}images/AF GLM Frente.png')` }}>
|
||||
<div className="front-photo-frame" style={{ position: 'relative', overflow: 'hidden' }}>
|
||||
{photoSrc ? (
|
||||
<img
|
||||
id="photoImg"
|
||||
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' }} />
|
||||
) : (
|
||||
<svg className="placeholder-svg" id="photoPlaceholder" 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" />
|
||||
<path d="M3 24c0-6 22-6 22 0" stroke="currentColor" strokeWidth="1.5" />
|
||||
</svg>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="front-dynamic-name" id="displayName">
|
||||
{name ? name.toUpperCase() : 'NOMBRE APELLIDO'}
|
||||
</div>
|
||||
<div className="front-dynamic-role" id="displayRole">
|
||||
{role ? role.toUpperCase() : 'PUESTO'}
|
||||
</div>
|
||||
<div className="front-dynamic-name">{name ? name.toUpperCase() : 'NOMBRE APELLIDO'}</div>
|
||||
<div className="front-dynamic-role">{role ? role.toUpperCase() : 'PUESTO'}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Reverso */}
|
||||
<div className="card-wrap">
|
||||
<div className="card-label">Reverso</div>
|
||||
<div
|
||||
className="card"
|
||||
id="cardBack"
|
||||
style={{
|
||||
backgroundImage: `url('${baseUrl}${selectedClient === 'Colgate' ? 'images/GLM Colgate' : 'images/AF ' + selectedClient} ${language}.png')`
|
||||
}}
|
||||
>
|
||||
<div className="card" id="cardBack" style={{ backgroundImage: `url('${baseUrl}${selectedClient === 'Colgate' ? 'images/AF Colgate' : 'images/AF ' + selectedClient} ${language}.png')` }}>
|
||||
<div className="back-qr-zone">
|
||||
{/* Asignamos la referencia de React para un control de pixeles seguro */}
|
||||
<canvas ref={qrCanvasRef} width="55" height="55"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
||||
+177
-35
@@ -3,7 +3,7 @@ export const clientTemplates = {
|
||||
'Esp': {
|
||||
'Generico': 'images/AF Generico Esp.png',
|
||||
'Claro': 'images/AF Claro Esp.png',
|
||||
'Colgate': 'images/GLM Colgate Esp.png',
|
||||
'Colgate': 'images/AF Colgate Esp.png',
|
||||
'KitchenAid': 'images/AF KitchenAid Esp.png',
|
||||
'Kraft': 'images/AF Kraft Esp.png',
|
||||
'Motorola': 'images/AF Motorola Esp.png',
|
||||
@@ -15,7 +15,7 @@ export const clientTemplates = {
|
||||
'Ing': {
|
||||
'Generico': 'images/AF Generico Ing.png',
|
||||
'Claro': 'images/AF Claro Ing.png',
|
||||
'Colgate': 'images/GLM Colgate Ing.png',
|
||||
'Colgate': 'images/AF Colgate Ing.png',
|
||||
'KitchenAid': 'images/AF KitchenAid Ing.png',
|
||||
'Kraft': 'images/AF Kraft Ing.png',
|
||||
'Motorola': 'images/AF Motorola Ing.png',
|
||||
@@ -37,10 +37,33 @@ function loadScript(src, globalKey) {
|
||||
});
|
||||
}
|
||||
|
||||
const getQRLib = () => loadScript('https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js', 'QRCode');
|
||||
export const getQRLib = () => loadScript('https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js', 'QRCode');
|
||||
const getHtml2Canvas = () => loadScript('https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js', 'html2canvas');
|
||||
export const getJSZip = () => loadScript('https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js', 'JSZip');
|
||||
export const getXLSXLib = () => loadScript('https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js', 'XLSX');
|
||||
|
||||
// ── GENERADOR DE QR NATIVO (REACT RENDERING) ──
|
||||
function convertDriveUrlToDirect(url) {
|
||||
if (!url) return '';
|
||||
const regExp = /(?:https?:\/\/)?(?:drive\.google\.com\/)(?:file\/d\/|open\?id=)([\w-]+)/;
|
||||
const match = url.match(regExp);
|
||||
if (match && match[1]) {
|
||||
return `https://docs.google.com/uc?export=download&id=${match[1]}`;
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
function preloadImage(src) {
|
||||
return new Promise((resolve) => {
|
||||
if (!src) return resolve(null);
|
||||
const img = new Image();
|
||||
img.crossOrigin = 'anonymous';
|
||||
img.onload = () => resolve(src);
|
||||
img.onerror = () => resolve(null);
|
||||
img.src = src;
|
||||
});
|
||||
}
|
||||
|
||||
// ── GENERADOR DE QR NATIVO ──
|
||||
export async function renderQRCode(employeeId, canvasElement) {
|
||||
if (!canvasElement) return;
|
||||
const text = (employeeId || '').trim();
|
||||
@@ -63,32 +86,42 @@ export async function renderQRCode(employeeId, canvasElement) {
|
||||
correctLevel: QRCodeLib.CorrectLevel.M
|
||||
});
|
||||
|
||||
setTimeout(() => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 60));
|
||||
|
||||
const img = tmp.querySelector('img') || tmp.querySelector('canvas');
|
||||
|
||||
const drawIt = (src) => {
|
||||
return new Promise((res) => {
|
||||
const i = new Image();
|
||||
i.onload = () => {
|
||||
ctx.fillStyle = '#ffffff';
|
||||
ctx.fillRect(0, 0, 55, 55);
|
||||
ctx.drawImage(i, 0, 0, 55, 55);
|
||||
if (tmp.parentNode) document.body.removeChild(tmp);
|
||||
res();
|
||||
};
|
||||
i.src = src;
|
||||
});
|
||||
};
|
||||
|
||||
if (img && img.tagName === 'CANVAS') {
|
||||
drawIt(img.toDataURL());
|
||||
await drawIt(img.toDataURL());
|
||||
} else if (img) {
|
||||
if (img.complete) drawIt(img.src);
|
||||
else img.onload = () => drawIt(img.src);
|
||||
if (img.complete) await drawIt(img.src);
|
||||
else {
|
||||
await new Promise((res) => {
|
||||
img.onload = async () => {
|
||||
await drawIt(img.src);
|
||||
res();
|
||||
};
|
||||
});
|
||||
}
|
||||
} else {
|
||||
if (tmp.parentNode) document.body.removeChild(tmp);
|
||||
}
|
||||
}, 50);
|
||||
}
|
||||
|
||||
// ── ENGINE DE PROCESAMIENTO ULTRA MAX QUALITY (650x1004) ──
|
||||
// ── ENGINE DE PROCESAMIENTO INDIVIDUAL ──
|
||||
export async function downloadIDCards(config) {
|
||||
const { name, role, selectedClient, language, photoSrc, baseUrl, qrCanvas, onStateChange } = config;
|
||||
|
||||
@@ -97,13 +130,11 @@ export async function downloadIDCards(config) {
|
||||
const html2canvasLib = await getHtml2Canvas();
|
||||
const cleanName = name.trim().replace(/\s+/g, '') || 'Empleado';
|
||||
|
||||
// Resolver rutas absolutas
|
||||
const frontBgUrl = `${baseUrl}images/AF GLM Frente.png`;
|
||||
const currentGroup = clientTemplates[language] || clientTemplates['Esp'];
|
||||
const backBgFile = currentGroup[selectedClient] || 'images/AF Generico Esp.png';
|
||||
const backBgUrl = `${baseUrl}${backBgFile}`;
|
||||
|
||||
// Sandbox virtual aislado
|
||||
const sandbox = document.createElement('div');
|
||||
sandbox.style.position = 'fixed';
|
||||
sandbox.style.top = '-9999px';
|
||||
@@ -125,7 +156,6 @@ export async function downloadIDCards(config) {
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
`;
|
||||
|
||||
// 1. Frente Virtual en tamaño real
|
||||
const vFront = document.createElement('div');
|
||||
vFront.style.cssText = cardStyleBase;
|
||||
vFront.style.backgroundImage = `url('${frontBgUrl}')`;
|
||||
@@ -155,24 +185,12 @@ export async function downloadIDCards(config) {
|
||||
</div>
|
||||
`;
|
||||
|
||||
// 2. Reverso Virtual en tamaño real
|
||||
const vBack = document.createElement('div');
|
||||
vBack.style.cssText = cardStyleBase;
|
||||
vBack.style.backgroundImage = `url('${backBgUrl}')`;
|
||||
|
||||
const vQRZone = document.createElement('div');
|
||||
vQRZone.style.cssText = `
|
||||
position: absolute;
|
||||
bottom: 27px;
|
||||
right: 27px;
|
||||
background: #ffffff;
|
||||
padding: 11px;
|
||||
border-radius: 16px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 5;
|
||||
`;
|
||||
vQRZone.style.cssText = `position: absolute; bottom: 27px; right: 27px; background: #ffffff; padding: 11px; border-radius: 16px; display: flex; align-items: center; justify-content: center; z-index: 5;`;
|
||||
|
||||
const vQRCanvas = document.createElement('canvas');
|
||||
vQRCanvas.width = 149;
|
||||
@@ -191,15 +209,7 @@ export async function downloadIDCards(config) {
|
||||
sandbox.appendChild(vFront);
|
||||
sandbox.appendChild(vBack);
|
||||
|
||||
const renderOpts = {
|
||||
scale: 1,
|
||||
useCORS: true,
|
||||
allowTaint: false,
|
||||
backgroundColor: null,
|
||||
logging: false,
|
||||
width: 650,
|
||||
height: 1004
|
||||
};
|
||||
const renderOpts = { scale: 1, useCORS: true, allowTaint: false, backgroundColor: null, logging: false, width: 650, height: 1004 };
|
||||
|
||||
try {
|
||||
const frontCanvas = await html2canvasLib(vFront, renderOpts);
|
||||
@@ -215,6 +225,138 @@ export async function downloadIDCards(config) {
|
||||
}
|
||||
}
|
||||
|
||||
// ── ENGINE MASIVO CON CORRESPONDENCIA DINÁMICA DE REVERSO POR IDIOMA ──
|
||||
export async function downloadBulkIDCards({ employees, baseUrl, onStateChange }) {
|
||||
if (onStateChange) onStateChange({ processing: true, text: 'Descargando...' });
|
||||
|
||||
const html2canvasLib = await getHtml2Canvas();
|
||||
const JSZipLib = await getJSZip();
|
||||
const zip = new JSZipLib();
|
||||
|
||||
const hiddenQRCanvas = document.createElement('canvas');
|
||||
hiddenQRCanvas.width = 55;
|
||||
hiddenQRCanvas.height = 55;
|
||||
|
||||
const sandbox = document.createElement('div');
|
||||
sandbox.style.position = 'fixed';
|
||||
sandbox.style.top = '-9999px';
|
||||
sandbox.style.left = '-9999px';
|
||||
sandbox.style.width = '1400px';
|
||||
document.body.appendChild(sandbox);
|
||||
|
||||
const cardStyleBase = `
|
||||
position: relative;
|
||||
width: 650px;
|
||||
height: 1004px;
|
||||
border-radius: 16px;
|
||||
background-size: cover;
|
||||
background-position: center;
|
||||
background-repeat: no-repeat;
|
||||
display: inline-block;
|
||||
overflow: hidden;
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
`;
|
||||
|
||||
const renderOpts = { scale: 1, useCORS: true, allowTaint: false, backgroundColor: null, logging: false, width: 650, height: 1004 };
|
||||
|
||||
for (let i = 0; i < employees.length; i++) {
|
||||
const emp = employees[i];
|
||||
const cleanName = emp.name.trim().replace(/\s+/g, '') || `Empleado_${i + 1}`;
|
||||
const cleanClient = emp.selectedClient.trim().replace(/\s+/g, '') || 'Generico';
|
||||
|
||||
const folderName = `${cleanName}_${cleanClient}`;
|
||||
|
||||
await renderQRCode(emp.employeeId, hiddenQRCanvas);
|
||||
|
||||
const directDriveUrl = convertDriveUrlToDirect(emp.fotoUrl);
|
||||
const validatedPhotoUrl = await preloadImage(directDriveUrl);
|
||||
|
||||
// --- Renderizar Frente Virtual ---
|
||||
const vFront = document.createElement('div');
|
||||
vFront.style.cssText = cardStyleBase;
|
||||
vFront.style.backgroundImage = `url('${baseUrl}images/AF GLM Frente.png')`;
|
||||
|
||||
let photoStyleHtml = `background: #e1e9ee; display: flex; align-items: center; justify-content: center;`;
|
||||
let innerPhotoContent = `<svg style="width:100px; height:100px; opacity:0.3; color:#4F758B;" viewBox="0 0 28 28" fill="none"><circle cx="14" cy="10" r="5.5" stroke="currentColor" stroke-width="1.5"/><path d="M3 24c0-6 22-6 22 0" stroke="currentColor" stroke-width="1.5"/></svg>`;
|
||||
|
||||
if (validatedPhotoUrl) {
|
||||
photoStyleHtml = `
|
||||
background-image: url('${validatedPhotoUrl}') !important;
|
||||
background-size: cover !important;
|
||||
background-position: center center !important;
|
||||
background-repeat: no-repeat !important;
|
||||
`;
|
||||
innerPhotoContent = '';
|
||||
}
|
||||
|
||||
vFront.innerHTML = `
|
||||
<div style="position:absolute; top:260.5px; left:131.5px; width:384px; height:384px; border-radius:50%; overflow:hidden; z-index:5; ${photoStyleHtml}">
|
||||
${innerPhotoContent}
|
||||
</div>
|
||||
<div style="position:absolute; top:715px; left:20px; right:20px; font-size:38px; font-weight:900; color:#FFFFFF; text-align:center; text-transform:uppercase; letter-spacing:1px; word-break:break-word; z-index:5;">
|
||||
${emp.name.toUpperCase()}
|
||||
</div>
|
||||
<div style="position:absolute; bottom:32px; right:15px; font-size:26px; font-weight:700; color:#6B8499; text-align:right; text-transform:uppercase; letter-spacing:1px; max-width:550px; white-space:nowrap; z-index:5;">
|
||||
${emp.role.toUpperCase()}
|
||||
</div>
|
||||
`;
|
||||
sandbox.appendChild(vFront);
|
||||
|
||||
// --- Renderizar Reverso Virtual (Asignación exacta e idéntica según cliente e idioma) ───
|
||||
const currentGroup = clientTemplates[emp.language] || clientTemplates['Esp'];
|
||||
|
||||
// Comprobación robusta de la existencia de la propiedad mapeada del cliente
|
||||
const clientKey = currentGroup.hasOwnProperty(emp.selectedClient) ? emp.selectedClient : 'Generico';
|
||||
const backBgFile = currentGroup[clientKey];
|
||||
const backBgUrl = `${baseUrl}${backBgFile}`;
|
||||
|
||||
const vBack = document.createElement('div');
|
||||
vBack.style.cssText = cardStyleBase;
|
||||
vBack.style.backgroundImage = `url('${backBgUrl}')`;
|
||||
|
||||
const vQRZone = document.createElement('div');
|
||||
vQRZone.style.cssText = `position: absolute; bottom: 27px; right: 27px; background: #ffffff; padding: 11px; border-radius: 16px; display: flex; align-items: center; justify-content: center; z-index: 5;`;
|
||||
|
||||
const vQRCanvas = document.createElement('canvas');
|
||||
vQRCanvas.width = 149;
|
||||
vQRCanvas.height = 149;
|
||||
vQRCanvas.style.width = '100px';
|
||||
vQRCanvas.style.height = '100px';
|
||||
const vQRContext = vQRCanvas.getContext('2d');
|
||||
if (vQRContext) {
|
||||
vQRContext.imageSmoothingEnabled = false;
|
||||
vQRContext.drawImage(hiddenQRCanvas, 0, 0, 149, 149);
|
||||
}
|
||||
vQRZone.appendChild(vQRCanvas);
|
||||
vBack.appendChild(vQRZone);
|
||||
sandbox.appendChild(vBack);
|
||||
|
||||
// Captura de datos gráficos
|
||||
const frontCanvas = await html2canvasLib(vFront, renderOpts);
|
||||
const frontData = frontCanvas.toDataURL('image/png').split(',')[1];
|
||||
zip.file(`${folderName}/${cleanName}_${cleanClient}_Frente.png`, frontData, { base64: true });
|
||||
|
||||
const backCanvas = await html2canvasLib(vBack, renderOpts);
|
||||
const backData = backCanvas.toDataURL('image/png').split(',')[1];
|
||||
zip.file(`${folderName}/${cleanName}_${cleanClient}_Reverso.png`, backData, { base64: true });
|
||||
|
||||
sandbox.removeChild(vFront);
|
||||
sandbox.removeChild(vBack);
|
||||
}
|
||||
|
||||
if (sandbox.parentNode) document.body.removeChild(sandbox);
|
||||
|
||||
const content = await zip.generateAsync({ type: 'blob' });
|
||||
const link = document.createElement('a');
|
||||
link.href = URL.createObjectURL(content);
|
||||
link.download = `Lote_Carnets_GLM.zip`;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
|
||||
if (onStateChange) onStateChange({ processing: false, text: '⬇ Descargar' });
|
||||
}
|
||||
|
||||
function executeFileDownload(dataUrl, fileName) {
|
||||
const link = document.createElement('a');
|
||||
link.href = dataUrl;
|
||||
|
||||
Reference in New Issue
Block a user