feat: implement core ID card generation interface with photo upload and bulk data processing support

This commit is contained in:
2026-07-03 15:02:47 -04:00
parent 4ea71b7300
commit 4b4685675c
3 changed files with 111 additions and 68 deletions
+5 -4
View File
@@ -45,6 +45,7 @@ body {
justify-content: center;
align-items: flex-start;
flex-direction: row;
margin-top: 30px
}
/* ── CONTROLS PANEL ── */
@@ -255,11 +256,11 @@ body {
/* ── FRONT DYNAMIC OVERLAYS ── */
.front-photo-frame {
position: absolute;
top: 99px;
left: 50%;
top: 98.5px;
left: 49.9%;
transform: translateX(-50%);
width: 145px;
height: 145px;
width: 145.5px;
height: 145.5px;
border-radius: 50%;
overflow: hidden;
display: flex;
+31 -22
View File
@@ -29,6 +29,7 @@ export default function IdCardGenerator() {
? import.meta.env.BASE_URL
: `${import.meta.env.BASE_URL}/`;
// Al limpiar el input en tiempo real, employeeId ya vendrá totalmente limpio
useEffect(() => {
if (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 ---
const handleBulkSupabasePhotoSync = async (cedula, blobData) => {
const cleanCedula = String(cedula).replace(/[-\s]/g, '');
try {
// Creamos un archivo sintáctico válido con tipo explícito image/jpeg
const customFile = new File([blobData], `${cedula}.jpg`, { type: 'image/jpeg' });
// Subida al Storage Bucket
const remoteStorageUrl = await uploadEmployeePhoto(cedula, customFile);
const customFile = new File([blobData], `${cleanCedula}.jpg`, { type: 'image/jpeg' });
const remoteStorageUrl = await uploadEmployeePhoto(cleanCedula, customFile);
if (remoteStorageUrl) {
// LLamado a tu función RPC nativa
const { data, error } = await supabase.rpc("save_employee_photo", {
p_employee_number: cedula,
p_employee_number: cleanCedula,
p_photo_url: remoteStorageUrl
});
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) {
console.log(`[Supabase Info] Cédula ${cedula}: ${data.message}`);
console.log(`[Supabase Info] Cédula ${cleanCedula}: ${data.message}`);
} 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) {
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 file = e.target.files[0];
if (!file) return;
@@ -111,7 +117,6 @@ export default function IdCardGenerator() {
.replace(/[\u0300-\u036f]/g, "");
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';
else if (lowerClient.includes('claro')) rawClient = 'Claro';
else if (lowerClient.includes('colgate')) rawClient = 'Colgate';
@@ -123,15 +128,17 @@ export default function IdCardGenerator() {
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: String(row.cedula || '').trim(),
employeeId: cleanedCedula,
fotoUrl: String(row.foto_url || '').trim()
};
}).filter(emp => emp.name && emp.role);
}).filter(emp => emp.name && emp.role && emp.employeeId);
setBulkEmployees(formatted);
setBulkStatusText(`✅ ¡Cargados ${formatted.length} colaboradores con éxito!`);
@@ -156,7 +163,7 @@ export default function IdCardGenerator() {
onStateChange: setBulkDownloadStatus,
onProcessEmployeePhoto: handleBulkSupabasePhotoSync
});
setBulkStatusText('🎉 ¡Lote guardado y sincronizado con Supabase!');
setBulkStatusText('🎉 ¡Lote guardado!');
} catch (error) {
console.error(error);
alert("Error procesando las imágenes remotas.");
@@ -202,7 +209,6 @@ export default function IdCardGenerator() {
</div>
<div className="main-container" style={{ display: 'flex', gap: '20px', alignItems: 'flex-start' }}>
{/* FORMULARIO MASIVO EXCEL */}
<div className="panel" style={{ minWidth: '320px' }}>
<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 />
<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>
@@ -327,8 +332,13 @@ export default function IdCardGenerator() {
<div className="panel-section">
<div className="panel-section-title">Código QR</div>
<div className="field">
<label>ID del empleado</label>
<input type="text" placeholder="Ej: 12345" value={employeeId} onChange={(e) => setEmployeeId(e.target.value)} />
<label>ID del empleado / Cédula</label>
<input
type="text"
placeholder="Ej: 123456789 (Sin guiones ni espacios)"
value={employeeId}
onChange={handleEmployeeIdChange}
/>
</div>
<button className="export-btn" style={{ background: '#6CC24A', marginTop: '2px' }} onClick={() => renderQRCode(employeeId, qrCanvasRef.current)}>
Generar QR
@@ -369,12 +379,11 @@ export default function IdCardGenerator() {
<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="back-qr-zone">
<canvas ref={qrCanvasRef} width="55" height="55"></canvas>
<canvas ref={qrCanvasRef} width={55} height={55}></canvas>
</div>
</div>
</div>
</div>
</div>
</>
);
+72 -39
View File
@@ -44,27 +44,45 @@ export const getXLSXLib = () => loadScript('https://cdnjs.cloudflare.com/ajax/li
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]) {
return `https://docs.google.com/uc?export=download&id=${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);
}