feat: implement core ID card generation interface with photo upload and bulk data processing support
This commit is contained in:
+75
-42
@@ -44,27 +44,45 @@ export const getXLSXLib = () => loadScript('https://cdnjs.cloudflare.com/ajax/li
|
||||
|
||||
export 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]}`;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
// Descarga la imagen evadiendo las restricciones CORS de Google Drive usando un CDN/Proxy transparente
|
||||
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 {
|
||||
// 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 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:", e);
|
||||
console.error("Error haciendo fetch con bypass CORS a la imagen externa:", e);
|
||||
try {
|
||||
// Intento secundario fallback por si falla el proxy
|
||||
const response = await fetch(url, { mode: 'cors' });
|
||||
return await response.blob();
|
||||
} catch (err) {
|
||||
@@ -79,19 +97,24 @@ function preloadImage(src) {
|
||||
const img = new Image();
|
||||
img.crossOrigin = 'anonymous';
|
||||
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;
|
||||
});
|
||||
}
|
||||
|
||||
// ── GENERADOR DE QR NATIVO ──
|
||||
// ── GENERADOR DE QR NATIVO (Garantiza ID limpio en URL) ──
|
||||
export async function renderQRCode(employeeId, canvasElement) {
|
||||
if (!canvasElement) return;
|
||||
const text = (employeeId || '').trim();
|
||||
const cleanId = (employeeId || '').replace(/[-\s]/g, '');
|
||||
const ctx = canvasElement.getContext('2d');
|
||||
ctx.clearRect(0, 0, canvasElement.width, canvasElement.height);
|
||||
|
||||
if (text.length <= 2) return;
|
||||
if (cleanId.length <= 2) return;
|
||||
|
||||
const QRCodeLib = await getQRLib();
|
||||
const tmp = document.createElement('div');
|
||||
@@ -99,7 +122,7 @@ export async function renderQRCode(employeeId, canvasElement) {
|
||||
document.body.appendChild(tmp);
|
||||
|
||||
new QRCodeLib(tmp, {
|
||||
text: `http://localhost:5173/employee/${text}`,
|
||||
text: `http://localhost:5173/employee/${cleanId}`,
|
||||
width: 55,
|
||||
height: 55,
|
||||
colorDark: '#000000',
|
||||
@@ -181,22 +204,19 @@ export async function downloadIDCards(config) {
|
||||
vFront.style.cssText = cardStyleBase;
|
||||
vFront.style.backgroundImage = `url('${frontBgUrl}')`;
|
||||
|
||||
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>`;
|
||||
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 (photoSrc) {
|
||||
photoStyleHtml = `
|
||||
background-image: url('${photoSrc}') !important;
|
||||
background-size: cover !important;
|
||||
background-position: center center !important;
|
||||
background-repeat: no-repeat !important;
|
||||
`;
|
||||
innerPhotoContent = '';
|
||||
photoTagHtml = `<img src="${photoSrc}" 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; ${photoStyleHtml}">
|
||||
${innerPhotoContent}
|
||||
<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;">
|
||||
${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 }) {
|
||||
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 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);
|
||||
let validatedPhotoUrl = null;
|
||||
|
||||
// --- PROCESAMIENTO E INYECCIÓN BINARIA A SUPABASE ---
|
||||
if (onProcessEmployeePhoto && directDriveUrl && emp.employeeId) {
|
||||
if (directDriveUrl && strictCleanId) {
|
||||
try {
|
||||
const blobData = await fetchImageAsBlob(directDriveUrl);
|
||||
if (blobData) {
|
||||
await onProcessEmployeePhoto(emp.employeeId, blobData);
|
||||
validatedPhotoUrl = URL.createObjectURL(blobData);
|
||||
if (onProcessEmployeePhoto) {
|
||||
await onProcessEmployeePhoto(strictCleanId, blobData);
|
||||
}
|
||||
}
|
||||
} 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 ---
|
||||
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>`;
|
||||
// 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) {
|
||||
photoStyleHtml = `
|
||||
background-image: url('${validatedPhotoUrl}') !important;
|
||||
background-size: cover !important;
|
||||
background-position: center center !important;
|
||||
background-repeat: no-repeat !important;
|
||||
`;
|
||||
innerPhotoContent = '';
|
||||
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; ${photoStyleHtml}">
|
||||
${innerPhotoContent}
|
||||
<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()}
|
||||
@@ -361,6 +387,9 @@ export async function downloadBulkIDCards({ employees, baseUrl, onStateChange, o
|
||||
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];
|
||||
@@ -370,6 +399,10 @@ export async function downloadBulkIDCards({ employees, baseUrl, onStateChange, o
|
||||
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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user