feat: add IdCardGenerator component with bulk upload and Supabase sync support
This commit is contained in:
+43
-13
@@ -42,7 +42,7 @@ const getHtml2Canvas = () => loadScript('https://cdnjs.cloudflare.com/ajax/libs/
|
||||
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');
|
||||
|
||||
function convertDriveUrlToDirect(url) {
|
||||
export function convertDriveUrlToDirect(url) {
|
||||
if (!url) return '';
|
||||
const regExp = /(?:https?:\/\/)?(?:drive\.google\.com\/)(?:file\/d\/|open\?id=)([\w-]+)/;
|
||||
const match = url.match(regExp);
|
||||
@@ -52,6 +52,27 @@ function convertDriveUrlToDirect(url) {
|
||||
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;
|
||||
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);
|
||||
try {
|
||||
// Intento secundario fallback por si falla el proxy
|
||||
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);
|
||||
@@ -226,7 +247,7 @@ export async function downloadIDCards(config) {
|
||||
}
|
||||
|
||||
// ── ENGINE MASIVO CON CORRESPONDENCIA DINÁMICA DE REVERSO POR IDIOMA ──
|
||||
export async function downloadBulkIDCards({ employees, baseUrl, onStateChange }) {
|
||||
export async function downloadBulkIDCards({ employees, baseUrl, onStateChange, onProcessEmployeePhoto }) {
|
||||
if (onStateChange) onStateChange({ processing: true, text: 'Descargando...' });
|
||||
|
||||
const html2canvasLib = await getHtml2Canvas();
|
||||
@@ -261,14 +282,26 @@ export async function downloadBulkIDCards({ employees, baseUrl, onStateChange })
|
||||
|
||||
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 cleanClient = emp.selectedClient.trim().replace(/\s+/g, '') || 'Generico';
|
||||
|
||||
const folderName = `${cleanName}_${cleanClient}`;
|
||||
const folderName = `${cleanName}_${currentClient}`;
|
||||
|
||||
await renderQRCode(emp.employeeId, hiddenQRCanvas);
|
||||
|
||||
const directDriveUrl = convertDriveUrlToDirect(emp.fotoUrl);
|
||||
|
||||
// --- PROCESAMIENTO E INYECCIÓN BINARIA A SUPABASE ---
|
||||
if (onProcessEmployeePhoto && directDriveUrl && emp.employeeId) {
|
||||
try {
|
||||
const blobData = await fetchImageAsBlob(directDriveUrl);
|
||||
if (blobData) {
|
||||
await onProcessEmployeePhoto(emp.employeeId, blobData);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`Error guardando foto en Supabase para Cédula: ${emp.employeeId}`, err);
|
||||
}
|
||||
}
|
||||
|
||||
const validatedPhotoUrl = await preloadImage(directDriveUrl);
|
||||
|
||||
// --- Renderizar Frente Virtual ---
|
||||
@@ -302,12 +335,9 @@ export async function downloadBulkIDCards({ employees, baseUrl, onStateChange })
|
||||
`;
|
||||
sandbox.appendChild(vFront);
|
||||
|
||||
// --- Renderizar Reverso Virtual (Asignación exacta e idéntica según cliente e idioma) ───
|
||||
// --- Renderizar Reverso Virtual ---
|
||||
const currentGroup = clientTemplates[emp.language] || clientTemplates['Esp'];
|
||||
|
||||
// Comprobación robusta de la existencia de la propiedad mapeada del cliente
|
||||
const clientKey = currentGroup.hasOwnProperty(emp.selectedClient) ? emp.selectedClient : 'Generico';
|
||||
const backBgFile = currentGroup[clientKey];
|
||||
const backBgFile = currentGroup[currentClient] || currentGroup['Generico'];
|
||||
const backBgUrl = `${baseUrl}${backBgFile}`;
|
||||
|
||||
const vBack = document.createElement('div');
|
||||
@@ -331,14 +361,14 @@ export async function downloadBulkIDCards({ employees, baseUrl, onStateChange })
|
||||
vBack.appendChild(vQRZone);
|
||||
sandbox.appendChild(vBack);
|
||||
|
||||
// Captura de datos gráficos
|
||||
// Capturas gráficas del ZIP
|
||||
const frontCanvas = await html2canvasLib(vFront, renderOpts);
|
||||
const frontData = frontCanvas.toDataURL('image/png').split(',')[1];
|
||||
zip.file(`${folderName}/${cleanName}_${cleanClient}_Frente.png`, frontData, { base64: true });
|
||||
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}_${cleanClient}_Reverso.png`, backData, { base64: true });
|
||||
zip.file(`${folderName}/${cleanName}_${currentClient}_Reverso.png`, backData, { base64: true });
|
||||
|
||||
sandbox.removeChild(vFront);
|
||||
sandbox.removeChild(vBack);
|
||||
|
||||
Reference in New Issue
Block a user