feat: implement core ID card generation interface with photo upload and bulk data processing support
This commit is contained in:
+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;
|
||||||
|
|||||||
+31
-22
@@ -29,6 +29,7 @@ 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);
|
||||||
@@ -43,36 +44,41 @@ export default function IdCardGenerator() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Interceptor para bloquear en tiempo real guiones y espacios en blanco
|
||||||
|
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);
|
||||||
|
};
|
||||||
|
|
||||||
// --- ALMACENAMIENTO AUTOMÁTICO EN EL STORAGE E INSTANCIACIÓN RPC ---
|
// --- ALMACENAMIENTO AUTOMÁTICO EN EL STORAGE E INSTANCIACIÓN RPC ---
|
||||||
const handleBulkSupabasePhotoSync = async (cedula, blobData) => {
|
const handleBulkSupabasePhotoSync = async (cedula, blobData) => {
|
||||||
|
const cleanCedula = String(cedula).replace(/[-\s]/g, '');
|
||||||
try {
|
try {
|
||||||
// Creamos un archivo sintáctico válido con tipo explícito image/jpeg
|
const customFile = new File([blobData], `${cleanCedula}.jpg`, { type: 'image/jpeg' });
|
||||||
const customFile = new File([blobData], `${cedula}.jpg`, { type: 'image/jpeg' });
|
const remoteStorageUrl = await uploadEmployeePhoto(cleanCedula, customFile);
|
||||||
|
|
||||||
// Subida al Storage Bucket
|
|
||||||
const remoteStorageUrl = await uploadEmployeePhoto(cedula, customFile);
|
|
||||||
|
|
||||||
if (remoteStorageUrl) {
|
if (remoteStorageUrl) {
|
||||||
// LLamado a tu función RPC nativa
|
|
||||||
const { data, error } = await supabase.rpc("save_employee_photo", {
|
const { data, error } = await supabase.rpc("save_employee_photo", {
|
||||||
p_employee_number: cedula,
|
p_employee_number: cleanCedula,
|
||||||
p_photo_url: remoteStorageUrl
|
p_photo_url: remoteStorageUrl
|
||||||
});
|
});
|
||||||
|
|
||||||
if (error) {
|
if (error) {
|
||||||
console.warn(`[Supabase RPC Error] Cédula ${cedula}:`, error.message);
|
console.warn(`[Supabase RPC Error] Cédula ${cleanCedula}:`, error.message);
|
||||||
} else if (data && data.success === false) {
|
} else if (data && data.success === false) {
|
||||||
console.log(`[Supabase Info] Cédula ${cedula}: ${data.message}`);
|
console.log(`[Supabase Info] Cédula ${cleanCedula}: ${data.message}`);
|
||||||
} else {
|
} else {
|
||||||
console.log(`[Supabase Success] Foto sincronizada para la Cédula: ${cedula}`);
|
console.log(`[Supabase Success] Foto sincronizada para la Cédula: ${cleanCedula}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`Sincronización abortada para la cédula ${cedula}:`, error);
|
console.error(`Sincronización abortada para la cédula ${cleanCedula}:`, error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- MAPEO DE COLUMNAS EXCEL CORREGIDO ---
|
// --- MAPEO DE COLUMNAS EXCEL CON LIMPIEZA DE CÉDULA ---
|
||||||
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;
|
||||||
@@ -111,7 +117,6 @@ export default function IdCardGenerator() {
|
|||||||
.replace(/[\u0300-\u036f]/g, "");
|
.replace(/[\u0300-\u036f]/g, "");
|
||||||
|
|
||||||
const lowerClient = rawClient.toLowerCase();
|
const lowerClient = rawClient.toLowerCase();
|
||||||
// CORRECCIÓN ESENCIAL: Dejar las llaves igual a script.jsx (Claro, Nestle, Whirlpool) sin .toUpperCase()
|
|
||||||
if (lowerClient.includes('nestle')) rawClient = 'Nestle';
|
if (lowerClient.includes('nestle')) rawClient = 'Nestle';
|
||||||
else if (lowerClient.includes('claro')) rawClient = 'Claro';
|
else if (lowerClient.includes('claro')) rawClient = 'Claro';
|
||||||
else if (lowerClient.includes('colgate')) rawClient = 'Colgate';
|
else if (lowerClient.includes('colgate')) rawClient = 'Colgate';
|
||||||
@@ -123,15 +128,17 @@ export default function IdCardGenerator() {
|
|||||||
else if (lowerClient.includes('whirlpool')) rawClient = 'Whirlpool';
|
else if (lowerClient.includes('whirlpool')) rawClient = 'Whirlpool';
|
||||||
else rawClient = 'Generico';
|
else rawClient = 'Generico';
|
||||||
|
|
||||||
|
const cleanedCedula = String(row.cedula || '').replace(/[-\s]/g, '');
|
||||||
|
|
||||||
return {
|
return {
|
||||||
name: String(row.nombre || '').trim(),
|
name: String(row.nombre || '').trim(),
|
||||||
role: String(row.puesto || '').trim(),
|
role: String(row.puesto || '').trim(),
|
||||||
selectedClient: rawClient,
|
selectedClient: rawClient,
|
||||||
language: rawLang,
|
language: rawLang,
|
||||||
employeeId: String(row.cedula || '').trim(),
|
employeeId: cleanedCedula,
|
||||||
fotoUrl: String(row.foto_url || '').trim()
|
fotoUrl: String(row.foto_url || '').trim()
|
||||||
};
|
};
|
||||||
}).filter(emp => emp.name && emp.role);
|
}).filter(emp => emp.name && emp.role && emp.employeeId);
|
||||||
|
|
||||||
setBulkEmployees(formatted);
|
setBulkEmployees(formatted);
|
||||||
setBulkStatusText(`✅ ¡Cargados ${formatted.length} colaboradores con éxito!`);
|
setBulkStatusText(`✅ ¡Cargados ${formatted.length} colaboradores con éxito!`);
|
||||||
@@ -156,7 +163,7 @@ export default function IdCardGenerator() {
|
|||||||
onStateChange: setBulkDownloadStatus,
|
onStateChange: setBulkDownloadStatus,
|
||||||
onProcessEmployeePhoto: handleBulkSupabasePhotoSync
|
onProcessEmployeePhoto: handleBulkSupabasePhotoSync
|
||||||
});
|
});
|
||||||
setBulkStatusText('🎉 ¡Lote guardado y sincronizado con Supabase!');
|
setBulkStatusText('🎉 ¡Lote guardado!');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
alert("Error procesando las imágenes remotas.");
|
alert("Error procesando las imágenes remotas.");
|
||||||
@@ -202,7 +209,6 @@ export default function IdCardGenerator() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="main-container" style={{ display: 'flex', gap: '20px', alignItems: 'flex-start' }}>
|
<div className="main-container" style={{ display: 'flex', gap: '20px', alignItems: 'flex-start' }}>
|
||||||
|
|
||||||
{/* FORMULARIO MASIVO EXCEL */}
|
{/* FORMULARIO MASIVO EXCEL */}
|
||||||
<div className="panel" style={{ minWidth: '320px' }}>
|
<div className="panel" style={{ minWidth: '320px' }}>
|
||||||
<div className="preview-badge" style={{ background: '#FFF3E0', color: '#E65100' }}>
|
<div className="preview-badge" style={{ background: '#FFF3E0', color: '#E65100' }}>
|
||||||
@@ -236,7 +242,6 @@ export default function IdCardGenerator() {
|
|||||||
}}>
|
}}>
|
||||||
Formato de columnas requeridas en el Excel: <br />
|
Formato de columnas requeridas en el Excel: <br />
|
||||||
<b style={{ color: '#6CC24A' }}>nombre, puesto, cliente/proyecto, cedula, lenguaje, foto_url</b>.<br />
|
<b style={{ color: '#6CC24A' }}>nombre, puesto, cliente/proyecto, cedula, lenguaje, foto_url</b>.<br />
|
||||||
Las imágenes se guardarán automáticamente en Supabase si no tienen una previa asignada.
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -327,8 +332,13 @@ export default function IdCardGenerator() {
|
|||||||
<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 type="text" placeholder="Ej: 12345" value={employeeId} onChange={(e) => setEmployeeId(e.target.value)} />
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="Ej: 123456789 (Sin guiones ni espacios)"
|
||||||
|
value={employeeId}
|
||||||
|
onChange={handleEmployeeIdChange}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<button className="export-btn" style={{ background: '#6CC24A', marginTop: '2px' }} onClick={() => renderQRCode(employeeId, qrCanvasRef.current)}>
|
<button className="export-btn" style={{ background: '#6CC24A', marginTop: '2px' }} onClick={() => renderQRCode(employeeId, qrCanvasRef.current)}>
|
||||||
⟳ Generar QR
|
⟳ Generar QR
|
||||||
@@ -369,12 +379,11 @@ export default function IdCardGenerator() {
|
|||||||
<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}${selectedClient === 'Colgate' ? 'images/AF Colgate' : 'images/AF ' + selectedClient} ${language}.png')` }}>
|
||||||
<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>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|||||||
+75
-42
@@ -44,27 +44,45 @@ export const getXLSXLib = () => loadScript('https://cdnjs.cloudflare.com/ajax/li
|
|||||||
|
|
||||||
export function convertDriveUrlToDirect(url) {
|
export function convertDriveUrlToDirect(url) {
|
||||||
if (!url) return '';
|
if (!url) return '';
|
||||||
const regExp = /(?:https?:\/\/)?(?:drive\.google\.com\/)(?:file\/d\/|open\?id=)([\w-]+)/;
|
|
||||||
const match = url.match(regExp);
|
if (!url.includes('drive.google.com') && !url.includes('docs.google.com')) {
|
||||||
if (match && match[1]) {
|
return url;
|
||||||
return `https://docs.google.com/uc?export=download&id=${match[1]}`;
|
}
|
||||||
|
|
||||||
|
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;
|
return url;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Descarga la imagen evadiendo las restricciones CORS de Google Drive usando un CDN/Proxy transparente
|
|
||||||
export async function fetchImageAsBlob(url) {
|
export async function fetchImageAsBlob(url) {
|
||||||
if (!url) return null;
|
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 {
|
try {
|
||||||
// Codificamos la URL directa de drive y la pasamos por el proxy weserv.nl para saltar el CORS de manera segura
|
|
||||||
const proxyUrl = `https://images.weserv.nl/?url=${encodeURIComponent(url)}&default=${encodeURIComponent(url)}`;
|
const proxyUrl = `https://images.weserv.nl/?url=${encodeURIComponent(url)}&default=${encodeURIComponent(url)}`;
|
||||||
const response = await fetch(proxyUrl);
|
const response = await fetch(proxyUrl);
|
||||||
if (!response.ok) throw new Error("Error en respuesta de red proxy");
|
if (!response.ok) throw new Error("Error en respuesta de red proxy");
|
||||||
return await response.blob();
|
return await response.blob();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("Error haciendo fetch con bypass CORS a la imagen:", e);
|
console.error("Error haciendo fetch con bypass CORS a la imagen externa:", e);
|
||||||
try {
|
try {
|
||||||
// Intento secundario fallback por si falla el proxy
|
|
||||||
const response = await fetch(url, { mode: 'cors' });
|
const response = await fetch(url, { mode: 'cors' });
|
||||||
return await response.blob();
|
return await response.blob();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -79,19 +97,24 @@ function preloadImage(src) {
|
|||||||
const img = new Image();
|
const img = new Image();
|
||||||
img.crossOrigin = 'anonymous';
|
img.crossOrigin = 'anonymous';
|
||||||
img.onload = () => resolve(src);
|
img.onload = () => resolve(src);
|
||||||
img.onerror = () => resolve(null);
|
img.onerror = () => {
|
||||||
|
const retryImg = new Image();
|
||||||
|
retryImg.onload = () => resolve(src);
|
||||||
|
retryImg.onerror = () => resolve(null);
|
||||||
|
retryImg.src = src;
|
||||||
|
};
|
||||||
img.src = src;
|
img.src = src;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── GENERADOR DE QR NATIVO ──
|
// ── 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');
|
||||||
@@ -99,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',
|
||||||
@@ -181,22 +204,19 @@ export async function downloadIDCards(config) {
|
|||||||
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'}
|
||||||
@@ -246,7 +266,7 @@ export async function downloadIDCards(config) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── ENGINE MASIVO CON CORRESPONDENCIA DINÁMICA DE REVERSO POR IDIOMA ──
|
// ── ENGINE MASIVO CON SOLUCIÓN TOTAL POR INYECCIÓN DE IMG CORS NATIVA ──
|
||||||
export async function downloadBulkIDCards({ employees, baseUrl, onStateChange, onProcessEmployeePhoto }) {
|
export async function downloadBulkIDCards({ employees, baseUrl, onStateChange, onProcessEmployeePhoto }) {
|
||||||
if (onStateChange) onStateChange({ processing: true, text: 'Descargando...' });
|
if (onStateChange) onStateChange({ processing: true, text: 'Descargando...' });
|
||||||
|
|
||||||
@@ -286,45 +306,51 @@ export async function downloadBulkIDCards({ employees, baseUrl, onStateChange, o
|
|||||||
const cleanName = emp.name.trim().replace(/\s+/g, '') || `Empleado_${i + 1}`;
|
const cleanName = emp.name.trim().replace(/\s+/g, '') || `Empleado_${i + 1}`;
|
||||||
const folderName = `${cleanName}_${currentClient}`;
|
const folderName = `${cleanName}_${currentClient}`;
|
||||||
|
|
||||||
await renderQRCode(emp.employeeId, hiddenQRCanvas);
|
const strictCleanId = String(emp.employeeId || '').replace(/[-\s]/g, '');
|
||||||
|
|
||||||
|
await renderQRCode(strictCleanId, hiddenQRCanvas);
|
||||||
|
|
||||||
const directDriveUrl = convertDriveUrlToDirect(emp.fotoUrl);
|
const directDriveUrl = convertDriveUrlToDirect(emp.fotoUrl);
|
||||||
|
let validatedPhotoUrl = null;
|
||||||
|
|
||||||
// --- PROCESAMIENTO E INYECCIÓN BINARIA A SUPABASE ---
|
if (directDriveUrl && strictCleanId) {
|
||||||
if (onProcessEmployeePhoto && directDriveUrl && emp.employeeId) {
|
|
||||||
try {
|
try {
|
||||||
const blobData = await fetchImageAsBlob(directDriveUrl);
|
const blobData = await fetchImageAsBlob(directDriveUrl);
|
||||||
if (blobData) {
|
if (blobData) {
|
||||||
await onProcessEmployeePhoto(emp.employeeId, blobData);
|
validatedPhotoUrl = URL.createObjectURL(blobData);
|
||||||
|
if (onProcessEmployeePhoto) {
|
||||||
|
await onProcessEmployeePhoto(strictCleanId, blobData);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(`Error guardando foto en Supabase para Cédula: ${emp.employeeId}`, err);
|
console.error(`Error guardando foto en Supabase para Cédula: ${strictCleanId}`, err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const validatedPhotoUrl = await preloadImage(directDriveUrl);
|
if (!validatedPhotoUrl && directDriveUrl) {
|
||||||
|
validatedPhotoUrl = await preloadImage(directDriveUrl);
|
||||||
|
}
|
||||||
|
|
||||||
// --- Renderizar Frente Virtual ---
|
// --- Renderizar Frente Virtual ---
|
||||||
const vFront = document.createElement('div');
|
const vFront = document.createElement('div');
|
||||||
vFront.style.cssText = cardStyleBase;
|
vFront.style.cssText = cardStyleBase;
|
||||||
vFront.style.backgroundImage = `url('${baseUrl}images/AF GLM Frente.png')`;
|
vFront.style.backgroundImage = `url('${baseUrl}images/AF GLM Frente.png')`;
|
||||||
|
|
||||||
let photoStyleHtml = `background: #e1e9ee; display: flex; align-items: center; justify-content: center;`;
|
// CAMBIO ESTRATÉGICO AQUÍ: Usamos una etiqueta <img> HTML real con crossorigin explícito,
|
||||||
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>`;
|
// 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) {
|
if (validatedPhotoUrl) {
|
||||||
photoStyleHtml = `
|
photoTagHtml = `<img src="${validatedPhotoUrl}" crossorigin="anonymous" style="width:100%; height:100%; object-fit:cover; display:block;" />`;
|
||||||
background-image: url('${validatedPhotoUrl}') !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;">
|
||||||
${emp.name.toUpperCase()}
|
${emp.name.toUpperCase()}
|
||||||
@@ -361,6 +387,9 @@ export async function downloadBulkIDCards({ employees, baseUrl, onStateChange, o
|
|||||||
vBack.appendChild(vQRZone);
|
vBack.appendChild(vQRZone);
|
||||||
sandbox.appendChild(vBack);
|
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
|
// Capturas gráficas del ZIP
|
||||||
const frontCanvas = await html2canvasLib(vFront, renderOpts);
|
const frontCanvas = await html2canvasLib(vFront, renderOpts);
|
||||||
const frontData = frontCanvas.toDataURL('image/png').split(',')[1];
|
const frontData = frontCanvas.toDataURL('image/png').split(',')[1];
|
||||||
@@ -370,6 +399,10 @@ export async function downloadBulkIDCards({ employees, baseUrl, onStateChange, o
|
|||||||
const backData = backCanvas.toDataURL('image/png').split(',')[1];
|
const backData = backCanvas.toDataURL('image/png').split(',')[1];
|
||||||
zip.file(`${folderName}/${cleanName}_${currentClient}_Reverso.png`, backData, { base64: true });
|
zip.file(`${folderName}/${cleanName}_${currentClient}_Reverso.png`, backData, { base64: true });
|
||||||
|
|
||||||
|
if (validatedPhotoUrl && validatedPhotoUrl.startsWith('blob:')) {
|
||||||
|
URL.revokeObjectURL(validatedPhotoUrl);
|
||||||
|
}
|
||||||
|
|
||||||
sandbox.removeChild(vFront);
|
sandbox.removeChild(vFront);
|
||||||
sandbox.removeChild(vBack);
|
sandbox.removeChild(vBack);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user