Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4b4685675c | |||
| 4ea71b7300 | |||
| 710045ee11 |
+5
-4
@@ -45,6 +45,7 @@ body {
|
|||||||
justify-content: center;
|
justify-content: center;
|
||||||
align-items: flex-start;
|
align-items: flex-start;
|
||||||
flex-direction: row;
|
flex-direction: row;
|
||||||
|
margin-top: 30px
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ── CONTROLS PANEL ── */
|
/* ── CONTROLS PANEL ── */
|
||||||
@@ -255,11 +256,11 @@ body {
|
|||||||
/* ── FRONT DYNAMIC OVERLAYS ── */
|
/* ── FRONT DYNAMIC OVERLAYS ── */
|
||||||
.front-photo-frame {
|
.front-photo-frame {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
top: 99px;
|
top: 98.5px;
|
||||||
left: 50%;
|
left: 49.9%;
|
||||||
transform: translateX(-50%);
|
transform: translateX(-50%);
|
||||||
width: 145px;
|
width: 145.5px;
|
||||||
height: 145px;
|
height: 145.5px;
|
||||||
border-radius: 50%;
|
border-radius: 50%;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
display: flex;
|
display: flex;
|
||||||
|
|||||||
+236
-190
@@ -1,28 +1,35 @@
|
|||||||
import React, { useState, useRef, useEffect } from 'react';
|
import React, { useState, useRef, useEffect } from 'react';
|
||||||
import './App.css';
|
import './App.css';
|
||||||
// Importamos las funciones lógicas nativas desde el archivo portado script.jsx
|
import { renderQRCode, downloadIDCards, downloadBulkIDCards, getXLSXLib } from './script/script.jsx';
|
||||||
import { renderQRCode, downloadIDCards } from './script/script.jsx';
|
|
||||||
import { uploadEmployeePhoto } from './services/storage.js';
|
import { uploadEmployeePhoto } from './services/storage.js';
|
||||||
import { supabase } from "./services/supabase";
|
import { supabase } from "./services/supabase";
|
||||||
|
|
||||||
export default function IdCardGenerator() {
|
export default function IdCardGenerator() {
|
||||||
// --- Estados para manejar la lógica en tiempo real ───
|
// --- Estados formulario individual ───
|
||||||
const [name, setName] = useState('');
|
const [name, setName] = useState('');
|
||||||
const [role, setRole] = useState('');
|
const [role, setRole] = useState('');
|
||||||
const [language, setLanguage] = useState('Esp'); // 'Esp' o 'Ing'
|
const [language, setLanguage] = useState('Esp');
|
||||||
const [selectedClient, setSelectedClient] = useState('Generico'); // Sin tildes de forma interna
|
const [selectedClient, setSelectedClient] = useState('Generico');
|
||||||
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);
|
||||||
|
|
||||||
// Estado para controlar la UI del botón de descarga mientras procesa
|
|
||||||
const [downloadStatus, setDownloadStatus] = useState({ processing: false, text: '⬇ Descargar' });
|
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 fileInputRef = useRef(null);
|
||||||
|
const excelInputRef = useRef(null);
|
||||||
const qrCanvasRef = useRef(null);
|
const qrCanvasRef = useRef(null);
|
||||||
|
|
||||||
// EFECTO AUTOMÁTICO: Renderiza el QR en tiempo real mientras escribes mediante referencias
|
const baseUrl = import.meta.env.BASE_URL.endsWith('/')
|
||||||
|
? 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);
|
||||||
@@ -31,112 +38,166 @@ export default function IdCardGenerator() {
|
|||||||
|
|
||||||
const handlePhotoUpload = (e) => {
|
const handlePhotoUpload = (e) => {
|
||||||
const file = e.target.files[0];
|
const file = e.target.files[0];
|
||||||
|
|
||||||
if (file) {
|
if (file) {
|
||||||
setPhotoFile(file);
|
setPhotoFile(file);
|
||||||
|
setPhotoSrc(URL.createObjectURL(file));
|
||||||
const localUrl = URL.createObjectURL(file);
|
|
||||||
setPhotoSrc(localUrl);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleLanguageChange = (lang) => {
|
// Interceptor para bloquear en tiempo real guiones y espacios en blanco
|
||||||
setLanguage(lang);
|
const handleEmployeeIdChange = (e) => {
|
||||||
|
const rawValue = e.target.value;
|
||||||
|
// Reemplaza instantáneamente cualquier guión o espacio por vacío
|
||||||
|
const cleanValue = rawValue.replace(/[-\s]/g, '');
|
||||||
|
setEmployeeId(cleanValue);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleClientChange = (e) => {
|
// --- ALMACENAMIENTO AUTOMÁTICO EN EL STORAGE E INSTANCIACIÓN RPC ---
|
||||||
setSelectedClient(e.target.value);
|
const handleBulkSupabasePhotoSync = async (cedula, blobData) => {
|
||||||
};
|
const cleanCedula = String(cedula).replace(/[-\s]/g, '');
|
||||||
|
try {
|
||||||
|
const customFile = new File([blobData], `${cleanCedula}.jpg`, { type: 'image/jpeg' });
|
||||||
|
const remoteStorageUrl = await uploadEmployeePhoto(cleanCedula, customFile);
|
||||||
|
|
||||||
// Forzar generación del QR manualmente si se desea mediante el botón verde
|
if (remoteStorageUrl) {
|
||||||
const triggerGenerateQR = () => {
|
const { data, error } = await supabase.rpc("save_employee_photo", {
|
||||||
if (qrCanvasRef.current) {
|
p_employee_number: cleanCedula,
|
||||||
renderQRCode(employeeId, qrCanvasRef.current);
|
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) {
|
||||||
|
console.error(`Sincronización abortada para la cédula ${cleanCedula}:`, error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Disparador del motor de renderizado ULTRA MAX QUALITY en sandbox
|
// --- MAPEO DE COLUMNAS EXCEL CON LIMPIEZA DE CÉDULA ---
|
||||||
const triggerDownload = async () => {
|
const handleExcelUpload = async (e) => {
|
||||||
if (!validateForm()) {
|
const file = e.target.files[0];
|
||||||
|
if (!file) return;
|
||||||
|
|
||||||
|
setBulkStatusText('Leyendo documento...');
|
||||||
|
try {
|
||||||
|
const XLSXLib = await getXLSXLib();
|
||||||
|
const reader = new FileReader();
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
||||||
|
if (jsonRows.length === 0) {
|
||||||
|
setBulkStatusText('❌ El archivo está vacío.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const formatted = jsonRows.map((row) => {
|
||||||
|
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';
|
||||||
|
}
|
||||||
|
|
||||||
|
let rawClient = String(row['cliente/proyecto'] || 'Generico')
|
||||||
|
.trim()
|
||||||
|
.normalize("NFD")
|
||||||
|
.replace(/[\u0300-\u036f]/g, "");
|
||||||
|
|
||||||
|
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';
|
||||||
|
|
||||||
|
const cleanedCedula = String(row.cedula || '').replace(/[-\s]/g, '');
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: String(row.nombre || '').trim(),
|
||||||
|
role: String(row.puesto || '').trim(),
|
||||||
|
selectedClient: rawClient,
|
||||||
|
language: rawLang,
|
||||||
|
employeeId: cleanedCedula,
|
||||||
|
fotoUrl: String(row.foto_url || '').trim()
|
||||||
|
};
|
||||||
|
}).filter(emp => emp.name && emp.role && emp.employeeId);
|
||||||
|
|
||||||
|
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 {
|
try {
|
||||||
|
await downloadBulkIDCards({
|
||||||
|
employees: bulkEmployees,
|
||||||
|
baseUrl,
|
||||||
|
onStateChange: setBulkDownloadStatus,
|
||||||
|
onProcessEmployeePhoto: handleBulkSupabasePhotoSync
|
||||||
|
});
|
||||||
|
setBulkStatusText('🎉 ¡Lote 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) {
|
if (photoFile) {
|
||||||
|
const photoUrl = await uploadEmployeePhoto(employeeId, photoFile);
|
||||||
const photoUrl = await uploadEmployeePhoto(
|
await supabase.rpc("save_employee_photo", {
|
||||||
employeeId,
|
|
||||||
photoFile
|
|
||||||
);
|
|
||||||
|
|
||||||
console.log("Foto subida:", photoUrl);
|
|
||||||
|
|
||||||
const { data, error } = await supabase.rpc(
|
|
||||||
"save_employee_photo",
|
|
||||||
{
|
|
||||||
p_employee_number: employeeId,
|
p_employee_number: employeeId,
|
||||||
p_photo_url: photoUrl
|
p_photo_url: photoUrl
|
||||||
}
|
});
|
||||||
);
|
|
||||||
|
|
||||||
if (error) {
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!data.success) {
|
|
||||||
console.warn(data.message);
|
|
||||||
} else {
|
|
||||||
console.log(data.message);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await downloadIDCards({
|
await downloadIDCards({
|
||||||
name,
|
name, role, selectedClient, language, photoSrc,
|
||||||
role,
|
baseUrl,
|
||||||
selectedClient,
|
|
||||||
language,
|
|
||||||
photoSrc,
|
|
||||||
baseUrl: import.meta.env.BASE_URL.endsWith('/')
|
|
||||||
? import.meta.env.BASE_URL
|
|
||||||
: `${import.meta.env.BASE_URL}/`,
|
|
||||||
qrCanvas: qrCanvasRef.current,
|
qrCanvas: qrCanvasRef.current,
|
||||||
onStateChange: setDownloadStatus
|
onStateChange: setDownloadStatus
|
||||||
});
|
});
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
alert(err.message);
|
alert(err.message);
|
||||||
}
|
}
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const baseUrl = import.meta.env.BASE_URL.endsWith('/')
|
|
||||||
? import.meta.env.BASE_URL
|
|
||||||
: `${import.meta.env.BASE_URL}/`;
|
|
||||||
|
|
||||||
const validateForm = () => {
|
const validateForm = () => {
|
||||||
if (!name.trim()) {
|
if (!name.trim()) { alert("Debe ingresar el nombre."); return false; }
|
||||||
alert("Debe ingresar el nombre.");
|
if (!role.trim()) { alert("Debe ingresar el puesto."); return false; }
|
||||||
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 (!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;
|
return true;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -147,83 +208,111 @@ export default function IdCardGenerator() {
|
|||||||
<p>GomezLee Marketing · Carnet Corporativo CR80</p>
|
<p>GomezLee Marketing · Carnet Corporativo CR80</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="main-container">
|
<div className="main-container" style={{ display: 'flex', gap: '20px', alignItems: 'flex-start' }}>
|
||||||
<div className="panel">
|
{/* FORMULARIO MASIVO EXCEL */}
|
||||||
|
<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 />
|
||||||
|
</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 */}
|
||||||
|
<div className="panel">
|
||||||
<div className="preview-badge">
|
<div className="preview-badge">
|
||||||
<div className="dot"></div>
|
<div className="dot"></div>
|
||||||
<span>Vista previa en tiempo real</span>
|
<span>Vista previa en tiempo real</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Sección Colaborador */}
|
|
||||||
<div className="panel-section">
|
<div className="panel-section">
|
||||||
<div className="panel-section-title">Colaborador</div>
|
<div className="panel-section-title">Colaborador</div>
|
||||||
|
|
||||||
<div className="field">
|
<div className="field">
|
||||||
<label>Nombre</label>
|
<label>Nombre</label>
|
||||||
<input
|
<input type="text" placeholder="Ej: Alexi Zabala" value={name} onChange={(e) => setName(e.target.value)} />
|
||||||
type="text"
|
|
||||||
id="inputName"
|
|
||||||
placeholder="Ej: Alexi Zabala"
|
|
||||||
value={name}
|
|
||||||
onChange={(e) => setName(e.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="field">
|
<div className="field">
|
||||||
<label>Puesto</label>
|
<label>Puesto</label>
|
||||||
<input
|
<input type="text" placeholder="Ej: Mercaderista" value={role} onChange={(e) => setRole(e.target.value)} />
|
||||||
type="text"
|
|
||||||
id="inputRole"
|
|
||||||
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={() => 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
|
Subir foto del colaborador
|
||||||
</div>
|
</div>
|
||||||
<input
|
<input type="file" accept="image/*" style={{ display: 'none' }} ref={fileInputRef} onChange={handlePhotoUpload} />
|
||||||
type="file"
|
|
||||||
id="photoInput"
|
|
||||||
accept="image/*"
|
|
||||||
style={{ display: 'none' }}
|
|
||||||
ref={fileInputRef}
|
|
||||||
onChange={handlePhotoUpload}
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="divider"></div>
|
<div className="divider"></div>
|
||||||
|
|
||||||
{/* Sección Cliente / Proyecto */}
|
|
||||||
<div className="panel-section">
|
<div className="panel-section">
|
||||||
<div className="panel-section-title">Cliente / Proyecto</div>
|
<div className="panel-section-title">Cliente / Proyecto</div>
|
||||||
|
|
||||||
<div className="lang-container">
|
<div className="lang-container">
|
||||||
<button
|
<button type="button" className={`lang-btn ${language === 'Esp' ? 'active' : ''}`} onClick={() => setLanguage('Esp')}>Español</button>
|
||||||
type="button"
|
<button type="button" className={`lang-btn ${language === 'Ing' ? 'active' : ''}`} onClick={() => setLanguage('Ing')}>Inglés</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>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="field">
|
<div className="field">
|
||||||
<label>Seleccionar Cliente</label>
|
<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="Generico">Genérico (Por defecto)</option>
|
||||||
<option value="Claro">Claro</option>
|
<option value="Claro">Claro</option>
|
||||||
<option value="Colgate">Colgate</option>
|
<option value="Colgate">Colgate</option>
|
||||||
@@ -240,103 +329,60 @@ export default function IdCardGenerator() {
|
|||||||
|
|
||||||
<div className="divider"></div>
|
<div className="divider"></div>
|
||||||
|
|
||||||
{/* Sección Código QR */}
|
|
||||||
<div className="panel-section">
|
<div className="panel-section">
|
||||||
<div className="panel-section-title">Código QR</div>
|
<div className="panel-section-title">Código QR</div>
|
||||||
<div className="field">
|
<div className="field">
|
||||||
<label>ID del empleado</label>
|
<label>ID del empleado / Cédula</label>
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
id="inputQR"
|
placeholder="Ej: 123456789 (Sin guiones ni espacios)"
|
||||||
placeholder="Ej: 12345"
|
|
||||||
value={employeeId}
|
value={employeeId}
|
||||||
onChange={(e) => setEmployeeId(e.target.value)}
|
onChange={handleEmployeeIdChange}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<button
|
<button className="export-btn" style={{ background: '#6CC24A', marginTop: '2px' }} onClick={() => renderQRCode(employeeId, qrCanvasRef.current)}>
|
||||||
className="export-btn"
|
|
||||||
style={{ background: '#6CC24A', marginTop: '2px' }}
|
|
||||||
onClick={triggerGenerateQR}
|
|
||||||
>
|
|
||||||
⟳ Generar QR
|
⟳ Generar QR
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="divider"></div>
|
<div className="divider"></div>
|
||||||
|
|
||||||
{/* Sección Exportar */}
|
|
||||||
<div className="panel-section">
|
<div className="panel-section">
|
||||||
<div className="panel-section-title">Exportar</div>
|
<div className="panel-section-title">Exportar</div>
|
||||||
<button
|
<button className="export-btn blue" disabled={downloadStatus.processing} onClick={triggerDownload}>
|
||||||
className="export-btn blue"
|
|
||||||
id="btnDownload"
|
|
||||||
disabled={downloadStatus.processing}
|
|
||||||
onClick={triggerDownload}
|
|
||||||
>
|
|
||||||
{downloadStatus.text}
|
{downloadStatus.text}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* --- STAGE: Vista previa de las tarjetas ─── */}
|
{/* VISTA PREVIA */}
|
||||||
<div className="stage">
|
<div className="stage">
|
||||||
|
|
||||||
{/* Frente */}
|
|
||||||
<div className="card-wrap">
|
<div className="card-wrap">
|
||||||
<div className="card-label">Frente</div>
|
<div className="card-label">Frente</div>
|
||||||
<div
|
<div className="card" id="cardFront" style={{ backgroundImage: `url('${baseUrl}images/AF GLM Frente.png')` }}>
|
||||||
className="card"
|
<div className="front-photo-frame" style={{ position: 'relative', overflow: 'hidden' }}>
|
||||||
id="cardFront"
|
|
||||||
style={{ backgroundImage: `url('${baseUrl}images/AF GLM Frente.png')` }}
|
|
||||||
>
|
|
||||||
<div className="front-photo-frame" id="photoFrame" style={{ position: 'relative', overflow: 'hidden' }}>
|
|
||||||
{photoSrc ? (
|
{photoSrc ? (
|
||||||
<img
|
<img src={photoSrc} alt="Foto Colaborador" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
|
||||||
id="photoImg"
|
|
||||||
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" />
|
<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" />
|
||||||
</svg>
|
</svg>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
<div className="front-dynamic-name">{name ? name.toUpperCase() : 'NOMBRE APELLIDO'}</div>
|
||||||
<div className="front-dynamic-name" id="displayName">
|
<div className="front-dynamic-role">{role ? role.toUpperCase() : 'PUESTO'}</div>
|
||||||
{name ? name.toUpperCase() : 'NOMBRE APELLIDO'}
|
|
||||||
</div>
|
|
||||||
<div className="front-dynamic-role" id="displayRole">
|
|
||||||
{role ? role.toUpperCase() : 'PUESTO'}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Reverso */}
|
|
||||||
<div className="card-wrap">
|
<div className="card-wrap">
|
||||||
<div className="card-label">Reverso</div>
|
<div className="card-label">Reverso</div>
|
||||||
<div
|
<div className="card" id="cardBack" style={{ backgroundImage: `url('${baseUrl}${selectedClient === 'Colgate' ? 'images/AF Colgate' : 'images/AF ' + selectedClient} ${language}.png')` }}>
|
||||||
className="card"
|
|
||||||
id="cardBack"
|
|
||||||
style={{
|
|
||||||
backgroundImage: `url('${baseUrl}${selectedClient === 'Colgate' ? 'images/GLM Colgate' : 'images/AF ' + selectedClient} ${language}.png')`
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<div className="back-qr-zone">
|
<div className="back-qr-zone">
|
||||||
{/* Asignamos la referencia de React para un control de pixeles seguro */}
|
<canvas ref={qrCanvasRef} width={55} height={55}></canvas>
|
||||||
<canvas ref={qrCanvasRef} width="55" height="55"></canvas>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
|
|||||||
+254
-49
@@ -3,7 +3,7 @@ export const clientTemplates = {
|
|||||||
'Esp': {
|
'Esp': {
|
||||||
'Generico': 'images/AF Generico Esp.png',
|
'Generico': 'images/AF Generico Esp.png',
|
||||||
'Claro': 'images/AF Claro 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',
|
'KitchenAid': 'images/AF KitchenAid Esp.png',
|
||||||
'Kraft': 'images/AF Kraft Esp.png',
|
'Kraft': 'images/AF Kraft Esp.png',
|
||||||
'Motorola': 'images/AF Motorola Esp.png',
|
'Motorola': 'images/AF Motorola Esp.png',
|
||||||
@@ -15,7 +15,7 @@ export const clientTemplates = {
|
|||||||
'Ing': {
|
'Ing': {
|
||||||
'Generico': 'images/AF Generico Ing.png',
|
'Generico': 'images/AF Generico Ing.png',
|
||||||
'Claro': 'images/AF Claro 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',
|
'KitchenAid': 'images/AF KitchenAid Ing.png',
|
||||||
'Kraft': 'images/AF Kraft Ing.png',
|
'Kraft': 'images/AF Kraft Ing.png',
|
||||||
'Motorola': 'images/AF Motorola Ing.png',
|
'Motorola': 'images/AF Motorola Ing.png',
|
||||||
@@ -37,17 +37,84 @@ 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');
|
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) ──
|
export function convertDriveUrlToDirect(url) {
|
||||||
|
if (!url) return '';
|
||||||
|
|
||||||
|
if (!url.includes('drive.google.com') && !url.includes('docs.google.com')) {
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const regExp = /(?:https?:\/\/)?(?:drive\.google\.com\/)(?:file\/d\/|open\?id=)([\w-]+)/;
|
||||||
|
const match = url.match(regExp);
|
||||||
|
if (match && match[1]) {
|
||||||
|
// Endpoint optimizado para saltar bloqueos pesados de descargas directas anónimas
|
||||||
|
return `https://drive.google.com/thumbnail?id=${match[1]}&sz=w1000`;
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Error convirtiendo la URL de Drive:", e);
|
||||||
|
}
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchImageAsBlob(url) {
|
||||||
|
if (!url) return null;
|
||||||
|
|
||||||
|
if (url.includes('drive.google.com') || url.includes('docs.google.com')) {
|
||||||
|
try {
|
||||||
|
const response = await fetch(url);
|
||||||
|
if (response.ok) return await response.blob();
|
||||||
|
} catch (e) {
|
||||||
|
console.warn("No se pudo obtener el Blob directo de Drive debido a restricciones CORS.");
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const proxyUrl = `https://images.weserv.nl/?url=${encodeURIComponent(url)}&default=${encodeURIComponent(url)}`;
|
||||||
|
const response = await fetch(proxyUrl);
|
||||||
|
if (!response.ok) throw new Error("Error en respuesta de red proxy");
|
||||||
|
return await response.blob();
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Error haciendo fetch con bypass CORS a la imagen externa:", e);
|
||||||
|
try {
|
||||||
|
const response = await fetch(url, { mode: 'cors' });
|
||||||
|
return await response.blob();
|
||||||
|
} catch (err) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 = () => {
|
||||||
|
const retryImg = new Image();
|
||||||
|
retryImg.onload = () => resolve(src);
|
||||||
|
retryImg.onerror = () => resolve(null);
|
||||||
|
retryImg.src = src;
|
||||||
|
};
|
||||||
|
img.src = src;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── GENERADOR DE QR NATIVO (Garantiza ID limpio en URL) ──
|
||||||
export async function renderQRCode(employeeId, canvasElement) {
|
export async function renderQRCode(employeeId, canvasElement) {
|
||||||
if (!canvasElement) return;
|
if (!canvasElement) return;
|
||||||
const text = (employeeId || '').trim();
|
const cleanId = (employeeId || '').replace(/[-\s]/g, '');
|
||||||
const ctx = canvasElement.getContext('2d');
|
const ctx = canvasElement.getContext('2d');
|
||||||
ctx.clearRect(0, 0, canvasElement.width, canvasElement.height);
|
ctx.clearRect(0, 0, canvasElement.width, canvasElement.height);
|
||||||
|
|
||||||
if (text.length <= 2) return;
|
if (cleanId.length <= 2) return;
|
||||||
|
|
||||||
const QRCodeLib = await getQRLib();
|
const QRCodeLib = await getQRLib();
|
||||||
const tmp = document.createElement('div');
|
const tmp = document.createElement('div');
|
||||||
@@ -55,7 +122,7 @@ export async function renderQRCode(employeeId, canvasElement) {
|
|||||||
document.body.appendChild(tmp);
|
document.body.appendChild(tmp);
|
||||||
|
|
||||||
new QRCodeLib(tmp, {
|
new QRCodeLib(tmp, {
|
||||||
text: `http://localhost:5173/employee/${text}`,
|
text: `http://localhost:5173/employee/${cleanId}`,
|
||||||
width: 55,
|
width: 55,
|
||||||
height: 55,
|
height: 55,
|
||||||
colorDark: '#000000',
|
colorDark: '#000000',
|
||||||
@@ -63,32 +130,42 @@ export async function renderQRCode(employeeId, canvasElement) {
|
|||||||
correctLevel: QRCodeLib.CorrectLevel.M
|
correctLevel: QRCodeLib.CorrectLevel.M
|
||||||
});
|
});
|
||||||
|
|
||||||
setTimeout(() => {
|
await new Promise((resolve) => setTimeout(resolve, 60));
|
||||||
|
|
||||||
const img = tmp.querySelector('img') || tmp.querySelector('canvas');
|
const img = tmp.querySelector('img') || tmp.querySelector('canvas');
|
||||||
|
|
||||||
const drawIt = (src) => {
|
const drawIt = (src) => {
|
||||||
|
return new Promise((res) => {
|
||||||
const i = new Image();
|
const i = new Image();
|
||||||
i.onload = () => {
|
i.onload = () => {
|
||||||
ctx.fillStyle = '#ffffff';
|
ctx.fillStyle = '#ffffff';
|
||||||
ctx.fillRect(0, 0, 55, 55);
|
ctx.fillRect(0, 0, 55, 55);
|
||||||
ctx.drawImage(i, 0, 0, 55, 55);
|
ctx.drawImage(i, 0, 0, 55, 55);
|
||||||
if (tmp.parentNode) document.body.removeChild(tmp);
|
if (tmp.parentNode) document.body.removeChild(tmp);
|
||||||
|
res();
|
||||||
};
|
};
|
||||||
i.src = src;
|
i.src = src;
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
if (img && img.tagName === 'CANVAS') {
|
if (img && img.tagName === 'CANVAS') {
|
||||||
drawIt(img.toDataURL());
|
await drawIt(img.toDataURL());
|
||||||
} else if (img) {
|
} else if (img) {
|
||||||
if (img.complete) drawIt(img.src);
|
if (img.complete) await drawIt(img.src);
|
||||||
else img.onload = () => drawIt(img.src);
|
else {
|
||||||
|
await new Promise((res) => {
|
||||||
|
img.onload = async () => {
|
||||||
|
await drawIt(img.src);
|
||||||
|
res();
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
if (tmp.parentNode) document.body.removeChild(tmp);
|
if (tmp.parentNode) document.body.removeChild(tmp);
|
||||||
}
|
}
|
||||||
}, 50);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── ENGINE DE PROCESAMIENTO ULTRA MAX QUALITY (650x1004) ──
|
// ── ENGINE DE PROCESAMIENTO INDIVIDUAL ──
|
||||||
export async function downloadIDCards(config) {
|
export async function downloadIDCards(config) {
|
||||||
const { name, role, selectedClient, language, photoSrc, baseUrl, qrCanvas, onStateChange } = config;
|
const { name, role, selectedClient, language, photoSrc, baseUrl, qrCanvas, onStateChange } = config;
|
||||||
|
|
||||||
@@ -97,13 +174,11 @@ export async function downloadIDCards(config) {
|
|||||||
const html2canvasLib = await getHtml2Canvas();
|
const html2canvasLib = await getHtml2Canvas();
|
||||||
const cleanName = name.trim().replace(/\s+/g, '') || 'Empleado';
|
const cleanName = name.trim().replace(/\s+/g, '') || 'Empleado';
|
||||||
|
|
||||||
// Resolver rutas absolutas
|
|
||||||
const frontBgUrl = `${baseUrl}images/AF GLM Frente.png`;
|
const frontBgUrl = `${baseUrl}images/AF GLM Frente.png`;
|
||||||
const currentGroup = clientTemplates[language] || clientTemplates['Esp'];
|
const currentGroup = clientTemplates[language] || clientTemplates['Esp'];
|
||||||
const backBgFile = currentGroup[selectedClient] || 'images/AF Generico Esp.png';
|
const backBgFile = currentGroup[selectedClient] || 'images/AF Generico Esp.png';
|
||||||
const backBgUrl = `${baseUrl}${backBgFile}`;
|
const backBgUrl = `${baseUrl}${backBgFile}`;
|
||||||
|
|
||||||
// Sandbox virtual aislado
|
|
||||||
const sandbox = document.createElement('div');
|
const sandbox = document.createElement('div');
|
||||||
sandbox.style.position = 'fixed';
|
sandbox.style.position = 'fixed';
|
||||||
sandbox.style.top = '-9999px';
|
sandbox.style.top = '-9999px';
|
||||||
@@ -125,27 +200,23 @@ export async function downloadIDCards(config) {
|
|||||||
font-family: Arial, Helvetica, sans-serif;
|
font-family: Arial, Helvetica, sans-serif;
|
||||||
`;
|
`;
|
||||||
|
|
||||||
// 1. Frente Virtual en tamaño real
|
|
||||||
const vFront = document.createElement('div');
|
const vFront = document.createElement('div');
|
||||||
vFront.style.cssText = cardStyleBase;
|
vFront.style.cssText = cardStyleBase;
|
||||||
vFront.style.backgroundImage = `url('${frontBgUrl}')`;
|
vFront.style.backgroundImage = `url('${frontBgUrl}')`;
|
||||||
|
|
||||||
let photoStyleHtml = `background: #e1e9ee; display: flex; align-items: center; justify-content: center;`;
|
let photoTagHtml = `
|
||||||
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>`;
|
<div style="width:100%; height:100%; background:#e1e9ee; display:flex; align-items:center; justify-content: center;">
|
||||||
|
<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>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
if (photoSrc) {
|
if (photoSrc) {
|
||||||
photoStyleHtml = `
|
photoTagHtml = `<img src="${photoSrc}" crossorigin="anonymous" style="width:100%; height:100%; object-fit:cover; display:block;" />`;
|
||||||
background-image: url('${photoSrc}') !important;
|
|
||||||
background-size: cover !important;
|
|
||||||
background-position: center center !important;
|
|
||||||
background-repeat: no-repeat !important;
|
|
||||||
`;
|
|
||||||
innerPhotoContent = '';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
vFront.innerHTML = `
|
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}">
|
<div style="position:absolute; top:260.5px; left:131.5px; width:384px; height:384px; border-radius:50%; overflow:hidden; z-index:5;">
|
||||||
${innerPhotoContent}
|
${photoTagHtml}
|
||||||
</div>
|
</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;">
|
<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;">
|
||||||
${name.toUpperCase() || 'NOMBRE APELLIDO'}
|
${name.toUpperCase() || 'NOMBRE APELLIDO'}
|
||||||
@@ -155,24 +226,12 @@ export async function downloadIDCards(config) {
|
|||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
// 2. Reverso Virtual en tamaño real
|
|
||||||
const vBack = document.createElement('div');
|
const vBack = document.createElement('div');
|
||||||
vBack.style.cssText = cardStyleBase;
|
vBack.style.cssText = cardStyleBase;
|
||||||
vBack.style.backgroundImage = `url('${backBgUrl}')`;
|
vBack.style.backgroundImage = `url('${backBgUrl}')`;
|
||||||
|
|
||||||
const vQRZone = document.createElement('div');
|
const vQRZone = document.createElement('div');
|
||||||
vQRZone.style.cssText = `
|
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;`;
|
||||||
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');
|
const vQRCanvas = document.createElement('canvas');
|
||||||
vQRCanvas.width = 149;
|
vQRCanvas.width = 149;
|
||||||
@@ -191,15 +250,7 @@ export async function downloadIDCards(config) {
|
|||||||
sandbox.appendChild(vFront);
|
sandbox.appendChild(vFront);
|
||||||
sandbox.appendChild(vBack);
|
sandbox.appendChild(vBack);
|
||||||
|
|
||||||
const renderOpts = {
|
const renderOpts = { scale: 1, useCORS: true, allowTaint: false, backgroundColor: null, logging: false, width: 650, height: 1004 };
|
||||||
scale: 1,
|
|
||||||
useCORS: true,
|
|
||||||
allowTaint: false,
|
|
||||||
backgroundColor: null,
|
|
||||||
logging: false,
|
|
||||||
width: 650,
|
|
||||||
height: 1004
|
|
||||||
};
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const frontCanvas = await html2canvasLib(vFront, renderOpts);
|
const frontCanvas = await html2canvasLib(vFront, renderOpts);
|
||||||
@@ -215,6 +266,160 @@ export async function downloadIDCards(config) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── ENGINE MASIVO CON SOLUCIÓN TOTAL POR INYECCIÓN DE IMG CORS NATIVA ──
|
||||||
|
export async function downloadBulkIDCards({ employees, baseUrl, onStateChange, onProcessEmployeePhoto }) {
|
||||||
|
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 currentClient = emp.selectedClient || 'Generico';
|
||||||
|
const cleanName = emp.name.trim().replace(/\s+/g, '') || `Empleado_${i + 1}`;
|
||||||
|
const folderName = `${cleanName}_${currentClient}`;
|
||||||
|
|
||||||
|
const strictCleanId = String(emp.employeeId || '').replace(/[-\s]/g, '');
|
||||||
|
|
||||||
|
await renderQRCode(strictCleanId, hiddenQRCanvas);
|
||||||
|
|
||||||
|
const directDriveUrl = convertDriveUrlToDirect(emp.fotoUrl);
|
||||||
|
let validatedPhotoUrl = null;
|
||||||
|
|
||||||
|
if (directDriveUrl && strictCleanId) {
|
||||||
|
try {
|
||||||
|
const blobData = await fetchImageAsBlob(directDriveUrl);
|
||||||
|
if (blobData) {
|
||||||
|
validatedPhotoUrl = URL.createObjectURL(blobData);
|
||||||
|
if (onProcessEmployeePhoto) {
|
||||||
|
await onProcessEmployeePhoto(strictCleanId, blobData);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`Error guardando foto en Supabase para Cédula: ${strictCleanId}`, err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!validatedPhotoUrl && directDriveUrl) {
|
||||||
|
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')`;
|
||||||
|
|
||||||
|
// CAMBIO ESTRATÉGICO AQUÍ: Usamos una etiqueta <img> HTML real con crossorigin explícito,
|
||||||
|
// esto destruye el bloqueo "Anti-Taint" de los lienzos y obliga a html2canvas a procesar la foto de Drive.
|
||||||
|
let photoTagHtml = `
|
||||||
|
<div style="width:100%; height:100%; background:#e1e9ee; display:flex; align-items:center; justify-content: center;">
|
||||||
|
<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>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
if (validatedPhotoUrl) {
|
||||||
|
photoTagHtml = `<img src="${validatedPhotoUrl}" crossorigin="anonymous" style="width:100%; height:100%; object-fit:cover; display:block;" />`;
|
||||||
|
}
|
||||||
|
|
||||||
|
vFront.innerHTML = `
|
||||||
|
<div style="position:absolute; top:260.5px; left:131.5px; width:384px; height:384px; border-radius:50%; overflow:hidden; z-index:5;">
|
||||||
|
${photoTagHtml}
|
||||||
|
</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 ---
|
||||||
|
const currentGroup = clientTemplates[emp.language] || clientTemplates['Esp'];
|
||||||
|
const backBgFile = currentGroup[currentClient] || currentGroup['Generico'];
|
||||||
|
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);
|
||||||
|
|
||||||
|
// Forzar un retraso mínimo de microsegundos para asegurar el render interno
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 30));
|
||||||
|
|
||||||
|
// Capturas gráficas del ZIP
|
||||||
|
const frontCanvas = await html2canvasLib(vFront, renderOpts);
|
||||||
|
const frontData = frontCanvas.toDataURL('image/png').split(',')[1];
|
||||||
|
zip.file(`${folderName}/${cleanName}_${currentClient}_Frente.png`, frontData, { base64: true });
|
||||||
|
|
||||||
|
const backCanvas = await html2canvasLib(vBack, renderOpts);
|
||||||
|
const backData = backCanvas.toDataURL('image/png').split(',')[1];
|
||||||
|
zip.file(`${folderName}/${cleanName}_${currentClient}_Reverso.png`, backData, { base64: true });
|
||||||
|
|
||||||
|
if (validatedPhotoUrl && validatedPhotoUrl.startsWith('blob:')) {
|
||||||
|
URL.revokeObjectURL(validatedPhotoUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {
|
function executeFileDownload(dataUrl, fileName) {
|
||||||
const link = document.createElement('a');
|
const link = document.createElement('a');
|
||||||
link.href = dataUrl;
|
link.href = dataUrl;
|
||||||
|
|||||||
Reference in New Issue
Block a user