feat: add IdCardGenerator component with bulk upload and Supabase sync support
This commit is contained in:
+40
-13
@@ -25,7 +25,6 @@ export default function IdCardGenerator() {
|
||||
const excelInputRef = useRef(null);
|
||||
const qrCanvasRef = useRef(null);
|
||||
|
||||
// Determinar la URL base de Vite de forma segura (Solo una declaración única aquí)
|
||||
const baseUrl = import.meta.env.BASE_URL.endsWith('/')
|
||||
? import.meta.env.BASE_URL
|
||||
: `${import.meta.env.BASE_URL}/`;
|
||||
@@ -44,7 +43,36 @@ export default function IdCardGenerator() {
|
||||
}
|
||||
};
|
||||
|
||||
// --- MAPEO DE COLUMNAS CORREGIDO ---
|
||||
// --- ALMACENAMIENTO AUTOMÁTICO EN EL STORAGE E INSTANCIACIÓN RPC ---
|
||||
const handleBulkSupabasePhotoSync = async (cedula, blobData) => {
|
||||
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);
|
||||
|
||||
if (remoteStorageUrl) {
|
||||
// LLamado a tu función RPC nativa
|
||||
const { data, error } = await supabase.rpc("save_employee_photo", {
|
||||
p_employee_number: cedula,
|
||||
p_photo_url: remoteStorageUrl
|
||||
});
|
||||
|
||||
if (error) {
|
||||
console.warn(`[Supabase RPC Error] Cédula ${cedula}:`, error.message);
|
||||
} else if (data && data.success === false) {
|
||||
console.log(`[Supabase Info] Cédula ${cedula}: ${data.message}`);
|
||||
} else {
|
||||
console.log(`[Supabase Success] Foto sincronizada para la Cédula: ${cedula}`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Sincronización abortada para la cédula ${cedula}:`, error);
|
||||
}
|
||||
};
|
||||
|
||||
// --- MAPEO DE COLUMNAS EXCEL CORREGIDO ---
|
||||
const handleExcelUpload = async (e) => {
|
||||
const file = e.target.files[0];
|
||||
if (!file) return;
|
||||
@@ -68,7 +96,6 @@ export default function IdCardGenerator() {
|
||||
}
|
||||
|
||||
const formatted = jsonRows.map((row) => {
|
||||
// 1. Normalizar Idioma (ES/Español -> Esp, EN/Inglés -> Ing)
|
||||
let rawLang = String(row.lenguaje || 'Esp').trim().toLowerCase();
|
||||
if (rawLang.includes('es') || rawLang.includes('esp')) {
|
||||
rawLang = 'Esp';
|
||||
@@ -78,14 +105,13 @@ export default function IdCardGenerator() {
|
||||
rawLang = 'Esp';
|
||||
}
|
||||
|
||||
// 2. CORRECCIÓN: Leer la columna exacta "cliente/proyecto" por separado
|
||||
let rawClient = String(row['cliente/proyecto'] || 'Generico')
|
||||
.trim()
|
||||
.normalize("NFD")
|
||||
.replace(/[\u0300-\u036f]/g, ""); // Convierte "Nestlé" en "Nestle"
|
||||
.replace(/[\u0300-\u036f]/g, "");
|
||||
|
||||
// Mapear nombres específicos para asegurar coincidencia exacta con las llaves de script.jsx
|
||||
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';
|
||||
@@ -102,7 +128,7 @@ export default function IdCardGenerator() {
|
||||
role: String(row.puesto || '').trim(),
|
||||
selectedClient: rawClient,
|
||||
language: rawLang,
|
||||
employeeId: String(row.cedula || '').trim(), // CORRECCIÓN: Columna individual 'cedula'
|
||||
employeeId: String(row.cedula || '').trim(),
|
||||
fotoUrl: String(row.foto_url || '').trim()
|
||||
};
|
||||
}).filter(emp => emp.name && emp.role);
|
||||
@@ -127,9 +153,10 @@ export default function IdCardGenerator() {
|
||||
await downloadBulkIDCards({
|
||||
employees: bulkEmployees,
|
||||
baseUrl,
|
||||
onStateChange: setBulkDownloadStatus
|
||||
onStateChange: setBulkDownloadStatus,
|
||||
onProcessEmployeePhoto: handleBulkSupabasePhotoSync
|
||||
});
|
||||
setBulkStatusText('🎉 ¡Lote procesado y guardado!');
|
||||
setBulkStatusText('🎉 ¡Lote guardado y sincronizado con Supabase!');
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
alert("Error procesando las imágenes remotas.");
|
||||
@@ -176,7 +203,7 @@ export default function IdCardGenerator() {
|
||||
|
||||
<div className="main-container" style={{ display: 'flex', gap: '20px', alignItems: 'flex-start' }}>
|
||||
|
||||
{/* FORMULARIO MASIVO EXCEL (IZQUIERDA) */}
|
||||
{/* 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>
|
||||
@@ -209,7 +236,7 @@ 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 descargarán automáticamente desde los enlaces públicos de Google Drive.
|
||||
Las imágenes se guardarán automáticamente en Supabase si no tienen una previa asignada.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -247,7 +274,7 @@ export default function IdCardGenerator() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* FORMULARIO INDIVIDUAL (CENTRO) */}
|
||||
{/* FORMULARIO INDIVIDUAL */}
|
||||
<div className="panel">
|
||||
<div className="preview-badge">
|
||||
<div className="dot"></div>
|
||||
@@ -318,7 +345,7 @@ export default function IdCardGenerator() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* VISTA PREVIA (DERECHA) */}
|
||||
{/* VISTA PREVIA */}
|
||||
<div className="stage">
|
||||
<div className="card-wrap">
|
||||
<div className="card-label">Frente</div>
|
||||
|
||||
Reference in New Issue
Block a user