7 Commits

6 changed files with 1004 additions and 270 deletions
+222 -1
View File
@@ -9,9 +9,13 @@
"version": "0.0.0",
"dependencies": {
"@supabase/supabase-js": "^2.108.2",
"file-saver": "^2.0.5",
"jszip": "^3.10.1",
"lucide-react": "^1.23.0",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-router-dom": "^7.18.1"
"react-router-dom": "^7.18.1",
"xlsx": "^0.18.5"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
@@ -1039,6 +1043,15 @@
"acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
}
},
"node_modules/adler-32": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/adler-32/-/adler-32-1.3.1.tgz",
"integrity": "sha512-ynZ4w/nUUv5rrsR8UUGoe1VC9hZj6V5hU9Qw1HlMDJGEJw5S7TfTErWTjMys6M7vr0YWcPqs3qAr4ss0nDfP+A==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/ajv": {
"version": "6.15.0",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz",
@@ -1147,6 +1160,28 @@
],
"license": "CC-BY-4.0"
},
"node_modules/cfb": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/cfb/-/cfb-1.2.2.tgz",
"integrity": "sha512-KfdUZsSOw19/ObEWasvBP/Ac4reZvAGauZhs6S/gqNhXhI7cKwvlH7ulj+dOEYnca4bm4SGo8C1bTAQvnTjgQA==",
"license": "Apache-2.0",
"dependencies": {
"adler-32": "~1.3.0",
"crc-32": "~1.2.0"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/codepage": {
"version": "1.15.0",
"resolved": "https://registry.npmjs.org/codepage/-/codepage-1.15.0.tgz",
"integrity": "sha512-3g6NUTPd/YtuuGrhMnOMRjFc+LJw/bnMp3+0r/Wcz3IXUuCosKRJvMphm5+Q+bvTVGcJJuRvVLuYba+WojaFaA==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/convert-source-map": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
@@ -1167,6 +1202,24 @@
"url": "https://opencollective.com/express"
}
},
"node_modules/core-util-is": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",
"integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==",
"license": "MIT"
},
"node_modules/crc-32": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz",
"integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==",
"license": "Apache-2.0",
"bin": {
"crc32": "bin/crc32.njs"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
@@ -1491,6 +1544,12 @@
"node": ">=16.0.0"
}
},
"node_modules/file-saver": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/file-saver/-/file-saver-2.0.5.tgz",
"integrity": "sha512-P9bmyZ3h/PRG+Nzga+rbdI4OEpNDzAVyy74uVO9ATgzLK6VtAsYybF/+TOCvrc0MO793d6+42lLyZTw7/ArVzA==",
"license": "MIT"
},
"node_modules/find-up": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz",
@@ -1529,6 +1588,15 @@
"dev": true,
"license": "ISC"
},
"node_modules/frac": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/frac/-/frac-1.1.2.tgz",
"integrity": "sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/fsevents": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
@@ -1616,6 +1684,12 @@
"node": ">= 4"
}
},
"node_modules/immediate": {
"version": "3.0.6",
"resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz",
"integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==",
"license": "MIT"
},
"node_modules/imurmurhash": {
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz",
@@ -1626,6 +1700,12 @@
"node": ">=0.8.19"
}
},
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"license": "ISC"
},
"node_modules/is-extglob": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
@@ -1649,6 +1729,12 @@
"node": ">=0.10.0"
}
},
"node_modules/isarray": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
"integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==",
"license": "MIT"
},
"node_modules/isexe": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
@@ -1710,6 +1796,18 @@
"node": ">=6"
}
},
"node_modules/jszip": {
"version": "3.10.1",
"resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.1.tgz",
"integrity": "sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==",
"license": "(MIT OR GPL-3.0-or-later)",
"dependencies": {
"lie": "~3.3.0",
"pako": "~1.0.2",
"readable-stream": "~2.3.6",
"setimmediate": "^1.0.5"
}
},
"node_modules/keyv": {
"version": "4.5.4",
"resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
@@ -1734,6 +1832,15 @@
"node": ">= 0.8.0"
}
},
"node_modules/lie": {
"version": "3.3.0",
"resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz",
"integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==",
"license": "MIT",
"dependencies": {
"immediate": "~3.0.5"
}
},
"node_modules/lightningcss": {
"version": "1.32.0",
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz",
@@ -2033,6 +2140,15 @@
"yallist": "^3.0.2"
}
},
"node_modules/lucide-react": {
"version": "1.23.0",
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.23.0.tgz",
"integrity": "sha512-38BpJcD0JhFosxHApP/BYsBetLpQFRoTRzEzstM/XCc3jsAG7wqaY1lgVwxiUe3xqYE+lNxo2PkCmYwXWrwwIw==",
"license": "ISC",
"peerDependencies": {
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/minimatch": {
"version": "10.2.5",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz",
@@ -2142,6 +2258,12 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/pako": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz",
"integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==",
"license": "(MIT AND Zlib)"
},
"node_modules/path-exists": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
@@ -2221,6 +2343,12 @@
"node": ">= 0.8.0"
}
},
"node_modules/process-nextick-args": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
"integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",
"license": "MIT"
},
"node_modules/punycode": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
@@ -2290,6 +2418,21 @@
"react-dom": ">=18"
}
},
"node_modules/readable-stream": {
"version": "2.3.8",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
"integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
"license": "MIT",
"dependencies": {
"core-util-is": "~1.0.0",
"inherits": "~2.0.3",
"isarray": "~1.0.0",
"process-nextick-args": "~2.0.0",
"safe-buffer": "~5.1.1",
"string_decoder": "~1.1.1",
"util-deprecate": "~1.0.1"
}
},
"node_modules/rolldown": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.1.3.tgz",
@@ -2324,6 +2467,12 @@
"@rolldown/binding-win32-x64-msvc": "1.1.3"
}
},
"node_modules/safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
"license": "MIT"
},
"node_modules/scheduler": {
"version": "0.27.0",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",
@@ -2346,6 +2495,12 @@
"integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==",
"license": "MIT"
},
"node_modules/setimmediate": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz",
"integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==",
"license": "MIT"
},
"node_modules/shebang-command": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
@@ -2379,6 +2534,27 @@
"node": ">=0.10.0"
}
},
"node_modules/ssf": {
"version": "0.11.2",
"resolved": "https://registry.npmjs.org/ssf/-/ssf-0.11.2.tgz",
"integrity": "sha512-+idbmIXoYET47hH+d7dfm2epdOMUDjqcB4648sTZ+t2JwoyBFL/insLfB/racrDmsKB3diwsDA696pZMieAC5g==",
"license": "Apache-2.0",
"dependencies": {
"frac": "~1.1.2"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/string_decoder": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
"integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
"license": "MIT",
"dependencies": {
"safe-buffer": "~5.1.0"
}
},
"node_modules/tinyglobby": {
"version": "0.2.17",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
@@ -2456,6 +2632,12 @@
"punycode": "^2.1.0"
}
},
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
"license": "MIT"
},
"node_modules/vite": {
"version": "8.1.0",
"resolved": "https://registry.npmjs.org/vite/-/vite-8.1.0.tgz",
@@ -2550,6 +2732,24 @@
"node": ">= 8"
}
},
"node_modules/wmf": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wmf/-/wmf-1.0.2.tgz",
"integrity": "sha512-/p9K7bEh0Dj6WbXg4JG0xvLQmIadrner1bi45VMJTfnbVHsc7yIajZyoSoK60/dtVBs12Fm6WkUI5/3WAVsNMw==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/word": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/word/-/word-0.3.0.tgz",
"integrity": "sha512-OELeY0Q61OXpdUfTp+oweA/vtLVg5VDOXh+3he3PNzLGG/y0oylSOC1xRVj0+l4vQ3tj/bB1HVHv1ocXkQceFA==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/word-wrap": {
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",
@@ -2560,6 +2760,27 @@
"node": ">=0.10.0"
}
},
"node_modules/xlsx": {
"version": "0.18.5",
"resolved": "https://registry.npmjs.org/xlsx/-/xlsx-0.18.5.tgz",
"integrity": "sha512-dmg3LCjBPHZnQp5/F/+nnTa+miPJxUXB6vtk42YjBBKayDNagxGEeIdWApkYPOf3Z3pm3k62Knjzp7lMeTEtFQ==",
"license": "Apache-2.0",
"dependencies": {
"adler-32": "~1.3.0",
"cfb": "~1.2.1",
"codepage": "~1.15.0",
"crc-32": "~1.2.1",
"ssf": "~0.11.2",
"wmf": "~1.0.1",
"word": "~0.3.0"
},
"bin": {
"xlsx": "bin/xlsx.njs"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/yallist": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
+5 -1
View File
@@ -11,9 +11,13 @@
},
"dependencies": {
"@supabase/supabase-js": "^2.108.2",
"file-saver": "^2.0.5",
"jszip": "^3.10.1",
"lucide-react": "^1.23.0",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-router-dom": "^7.18.1"
"react-router-dom": "^7.18.1",
"xlsx": "^0.18.5"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
+6 -5
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;
@@ -272,7 +273,7 @@ body {
width: 100%;
height: 100%;
object-fit: cover;
display: none;
display: block;
}
.front-photo-frame .placeholder-svg {
+415 -199
View File
@@ -1,142 +1,356 @@
import React, { useState, useRef, useEffect } from 'react';
import './App.css';
// Importamos las funciones lógicas nativas desde el archivo portado script.jsx
import { renderQRCode, downloadIDCards } from './script/script.jsx';
import { uploadEmployeePhoto } from './services/storage.js';
import { useState, useRef, useEffect } from 'react';
import './Generator.css';
import { renderQRCode, downloadIDCards, downloadBulkIDCards, getXLSXLib, clientTemplates } from './script/script.jsx';
import { uploadEmployeePhoto, saveClienteProyecto } from './services/storage.js';
import { supabase } from "./services/supabase";
// Convierte datos binarios recibidos (base64, buffer, array de bytes) en un Blob URL local de forma robusta
const convertBinaryToBlobUrl = (data) => {
if (!data) return null;
try {
if (typeof data === 'object' && data.type === 'Buffer' && Array.isArray(data.data)) {
const byteArray = new Uint8Array(data.data);
const blob = new Blob([byteArray], { type: 'image/jpeg' });
return URL.createObjectURL(blob);
}
if (Array.isArray(data)) {
const byteArray = new Uint8Array(data);
const blob = new Blob([byteArray], { type: 'image/jpeg' });
return URL.createObjectURL(blob);
}
if (typeof data === 'string') {
const cleanBase64 = data.replace(/^data:image\/\w+;base64,/, "");
const byteCharacters = atob(cleanBase64);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray], { type: 'image/jpeg' });
return URL.createObjectURL(blob);
}
} catch (e) {
console.error("Error convirtiendo formato binario a Blob URL:", e);
}
return null;
};
export default function IdCardGenerator() {
// --- Estados para manejar la lógica en tiempo real ───
// --- Estados formulario individual ───
const [name, setName] = useState('');
const [role, setRole] = useState('');
const [language, setLanguage] = useState('Esp'); // 'Esp' o 'Ing'
const [selectedClient, setSelectedClient] = useState('Generico'); // Sin tildes de forma interna
const [language, setLanguage] = useState('Esp');
const [selectedClient, setSelectedClient] = useState('Generico');
const [employeeId, setEmployeeId] = useState('');
const [photoSrc, setPhotoSrc] = useState('');
const [photoFile, setPhotoFile] = useState(null);
// Estado para controlar la UI del botón de descarga mientras procesa
const [photoProcessing, setPhotoProcessing] = useState(false);
const [downloadStatus, setDownloadStatus] = useState({ processing: false, text: '⬇ Descargar' });
// Referencias del DOM controladas por React
// Bloquea el botón Descargar hasta que nombre, puesto e ID estén llenos
const isFormComplete = name.trim() && role.trim() && employeeId.trim();
// --- Estados Lote / Excel Masivo ───
const [bulkEmployees, setBulkEmployees] = useState([]);
const [bulkStatusText, setBulkStatusText] = useState('');
const [bulkDownloadStatus, setBulkDownloadStatus] = useState({ processing: false, text: '⬇ Descargar' });
const [showTooltip, setShowTooltip] = useState(false);
const fileInputRef = useRef(null);
const excelInputRef = useRef(null);
const qrCanvasRef = useRef(null);
// EFECTO AUTOMÁTICO: Renderiza el QR en tiempo real mientras escribes mediante referencias
const baseUrl = import.meta.env.BASE_URL.endsWith('/')
? import.meta.env.BASE_URL
: `${import.meta.env.BASE_URL}/`;
useEffect(() => {
if (qrCanvasRef.current) {
renderQRCode(employeeId, qrCanvasRef.current);
}
}, [employeeId]);
const handlePhotoUpload = (e) => {
const handlePhotoUpload = async (e) => {
const file = e.target.files[0];
if (!file) return;
if (file) {
setPhotoFile(file);
const localUrl = URL.createObjectURL(file);
setPhotoSrc(localUrl);
}
};
const handleLanguageChange = (lang) => {
setLanguage(lang);
};
const handleClientChange = (e) => {
setSelectedClient(e.target.value);
};
// Forzar generación del QR manualmente si se desea mediante el botón verde
const triggerGenerateQR = () => {
if (qrCanvasRef.current) {
renderQRCode(employeeId, qrCanvasRef.current);
}
};
// Disparador del motor de renderizado ULTRA MAX QUALITY en sandbox
const triggerDownload = async () => {
if (!validateForm()) {
return;
}
setPhotoFile(file);
setPhotoSrc(URL.createObjectURL(file));
setPhotoProcessing(true);
try {
const editedBlob = await processPhotoWithAI(file);
const editedUrl = URL.createObjectURL(editedBlob);
setPhotoSrc(editedUrl);
setPhotoFile(new File([editedBlob], file.name, { type: editedBlob.type || 'image/jpeg' }));
} catch (error) {
console.error('Error al procesar la foto con IA en n8n:', error);
alert('No se pudo procesar la foto con IA. Se usará la foto original para la vista previa.');
} finally {
setPhotoProcessing(false);
}
};
// Solo si el usuario seleccionó una foto
if (photoFile) {
const processPhotoWithAI = async (file) => {
const N8N_WEBHOOK_URL = import.meta.env.VITE_N8N_WEBHOOK_URL;
const TOKEN_SECRETO = import.meta.env.VITE_WEBHOOK_TOKEN;
const photoUrl = await uploadEmployeePhoto(
employeeId,
photoFile
);
const formData = new FormData();
formData.append('edited', file, file.name);
formData.append('name', name);
formData.append('role', role);
formData.append('employeeId', employeeId);
formData.append('fechaProcesado', new Date().toISOString());
console.log("Foto subida:", photoUrl);
const response = await fetch(N8N_WEBHOOK_URL, {
method: 'POST',
headers: {
'Authorization': TOKEN_SECRETO
},
body: formData
});
const { data, error } = await supabase.rpc(
"save_employee_photo",
{
p_employee_number: employeeId,
p_photo_url: photoUrl
if (!response.ok) {
throw new Error(`El servidor de n8n rechazó la petición (Código: ${response.status})`);
}
const contentType = response.headers.get('content-type') || '';
if (contentType.includes('application/json')) {
const data = await response.json();
const bin = data.edited || data.data || data.foto_processed_base64 || data.photo || data.binary || (Array.isArray(data) && (data[0]?.edited || data[0]?.data));
const blobUrl = convertBinaryToBlobUrl(bin);
if (!blobUrl) throw new Error('n8n no devolvió un binario válido.');
const blob = await (await fetch(blobUrl)).blob();
return blob;
}
const blob = await response.blob();
if (!blob || blob.size === 0) throw new Error('n8n devolvió un binario vacío.');
return blob;
};
const handleEmployeeIdChange = (e) => {
const rawValue = e.target.value;
const cleanValue = rawValue.replace(/[-\s]/g, '');
setEmployeeId(cleanValue);
};
const enviarDatosAn8n = async (datosEmpleados) => {
const N8N_WEBHOOK_URL = import.meta.env.VITE_N8N_WEBHOOK_URL;
const TOKEN_SECRETO = import.meta.env.VITE_WEBHOOK_TOKEN;
try {
const response = await fetch(N8N_WEBHOOK_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': TOKEN_SECRETO
},
body: JSON.stringify({
empleados: datosEmpleados,
total: datosEmpleados.length,
fechaProcesado: new Date().toISOString()
})
});
if (!response.ok) {
throw new Error(`El servidor de n8n rechazó la petición (Código: ${response.status})`);
}
const resData = await response.json();
return Array.isArray(resData) ? resData : (resData.empleados || resData.data || []);
} catch (error) {
console.error('Error de comunicación con n8n:', error);
throw error;
}
};
const handleBulkSupabaseSync = async (cedula, blobData, currentEmployee) => {
const cleanCedula = String(cedula).replace(/[-\s]/g, '');
if (!cleanCedula) return;
try {
// Se usa el cliente extraído directamente del array renderizado
const clienteProyectoValue = currentEmployee?.selectedClient || 'Generico';
await saveClienteProyecto(cleanCedula, clienteProyectoValue);
console.log(`[Supabase DB] Guardado: ${cleanCedula}${clienteProyectoValue}`);
const customFile = new File([blobData], `${cleanCedula}.jpg`, { type: 'image/jpeg' });
const remoteStorageUrl = await uploadEmployeePhoto(cleanCedula, customFile);
if (remoteStorageUrl) {
await supabase.rpc("save_employee_photo", {
p_employee_number: cleanCedula,
p_photo_url: remoteStorageUrl
});
}
} catch (error) {
console.error(`[Supabase Sync Fallido] Cédula ${cleanCedula}:`, error);
}
};
const handleExcelUpload = async (e) => {
const file = e.target.files[0];
if (!file) return;
setBulkStatusText('Leyendo documento...');
try {
const XLSXLib = await getXLSXLib();
const reader = new FileReader();
reader.onload = async (evt) => {
try {
const bstr = evt.target.result;
const wb = XLSXLib.read(bstr, { type: 'binary' });
const wsname = wb.SheetNames[0];
const ws = wb.Sheets[wsname];
const jsonRows = XLSXLib.utils.sheet_to_json(ws);
if (jsonRows.length === 0) {
setBulkStatusText('❌ El archivo está vacío.');
return;
}
);
if (error) {
throw error;
}
const formatted = jsonRows.map((row) => {
let rawLang = String(row.lenguaje || 'Esp').trim().toLowerCase();
if (rawLang.includes('es') || rawLang.includes('esp')) {
rawLang = 'Esp';
} else if (rawLang.includes('en') || rawLang.includes('ing')) {
rawLang = 'Ing';
} else {
rawLang = 'Esp';
}
if (!data.success) {
console.warn(data.message);
} else {
console.log(data.message);
let rawClient = String(row['cliente/proyecto'] || 'Generico')
.trim()
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "");
const lowerClient = rawClient.toLowerCase();
if (lowerClient.includes('nestle')) rawClient = 'Nestle';
else if (lowerClient.includes('claro')) rawClient = 'Claro';
else if (lowerClient.includes('colgate')) rawClient = 'Colgate';
else if (lowerClient.includes('kitchenaid') || lowerClient.includes('kitchen')) rawClient = 'KitchenAid';
else if (lowerClient.includes('kraft')) rawClient = 'Kraft';
else if (lowerClient.includes('motorola')) rawClient = 'Motorola';
else if (lowerClient.includes('p&g') || lowerClient.includes('p y g')) rawClient = 'P&G';
else if (lowerClient.includes('philip') || lowerClient.includes('morris')) rawClient = 'Philip Morris';
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: cleanedCedula,
fotoUrl: String(row.foto_url || '').trim()
};
}).filter(emp => emp.name && emp.role && emp.employeeId);
setBulkEmployees(formatted);
setBulkStatusText(`✅ ¡Cargados ${formatted.length} colaboradores! Listo para procesar.`);
setBulkDownloadStatus({ processing: false, text: '⬇ Descargar' });
} catch (innerErr) {
console.error(innerErr);
setBulkStatusText('❌ Error de lectura. Revisa el formato de columnas.');
}
};
reader.readAsBinaryString(file);
} catch (err) {
console.error(err);
setBulkStatusText('❌ Error cargando el motor XLSX.');
}
};
const triggerBulkDownload = async () => {
if (bulkEmployees.length === 0) return;
setBulkDownloadStatus({ processing: true, text: '🔄 Descargando...' });
setBulkStatusText('Descargando retratos...');
try {
const resultadosN8n = await enviarDatosAn8n(bulkEmployees);
setBulkStatusText('Generando frentes, reversos y empaquetando en carpetas locales...');
const employeesReadyForRender = bulkEmployees.map((originalEmp, index) => {
const n8nEmp = resultadosN8n[index] || resultadosN8n.find(e => e.employeeId === originalEmp.employeeId) || {};
const base64Source = n8nEmp.data || n8nEmp.foto_processed_base64 || originalEmp.data;
let finalPhotoUrl = convertBinaryToBlobUrl(base64Source) || originalEmp.fotoUrl;
const validClient = n8nEmp.selectedClient || originalEmp.selectedClient || 'Generico';
const validLang = n8nEmp.language || originalEmp.language || 'Esp';
return {
name: n8nEmp.name || originalEmp.name,
role: n8nEmp.role || originalEmp.role,
selectedClient: validClient,
language: validLang,
employeeId: n8nEmp.employeeId || originalEmp.employeeId,
fotoUrl: finalPhotoUrl
};
});
await downloadBulkIDCards({
employees: employeesReadyForRender,
baseUrl,
onStateChange: null,
// CORRECCIÓN AQUÍ: Buscamos al empleado en nuestro arreglo usando la cédula que nos devuelve script.jsx
onProcessEmployeePhoto: (cedula, blobData) => {
const currentEmp = employeesReadyForRender.find(emp => emp.employeeId === cedula);
return handleBulkSupabaseSync(cedula, blobData, currentEmp);
}
});
setBulkStatusText('🎉 ¡Lote de carnets guardado correctamente!');
setBulkEmployees([]);
} catch (error) {
console.error(error);
setBulkStatusText(`❌ Error al procesar: ${error.message || error}`);
} finally {
setBulkDownloadStatus({ processing: false, text: '⬇ Descargar' });
}
};
const triggerDownload = async () => {
if (!validateForm()) return;
setDownloadStatus({ processing: true, text: '🔄 Descargando...' });
try {
await saveClienteProyecto(employeeId, selectedClient);
if (photoFile) {
const photoUrl = await uploadEmployeePhoto(employeeId, photoFile);
await supabase.rpc("save_employee_photo", {
p_employee_number: employeeId,
p_photo_url: photoUrl
});
}
await downloadIDCards({
name,
role,
selectedClient,
language,
photoSrc,
baseUrl: import.meta.env.BASE_URL.endsWith('/')
? import.meta.env.BASE_URL
: `${import.meta.env.BASE_URL}/`,
name, role, selectedClient, language, photoSrc,
baseUrl,
qrCanvas: qrCanvasRef.current,
onStateChange: setDownloadStatus
});
} catch (err) {
console.error(err);
alert(err.message);
setDownloadStatus({ processing: false, text: '⬇ Descargar' });
}
};
const baseUrl = import.meta.env.BASE_URL.endsWith('/')
? import.meta.env.BASE_URL
: `${import.meta.env.BASE_URL}/`;
const validateForm = () => {
if (!name.trim()) {
alert("Debe ingresar el nombre.");
return false;
}
if (!role.trim()) {
alert("Debe ingresar el puesto.");
return false;
}
if (!employeeId.trim()) {
alert("Debe ingresar el ID del empleado.");
return false;
}
if (!photoFile) {
alert("Debe subir la foto del colaborador.");
return false;
}
if (!name.trim()) { alert("Debe ingresar el nombre."); return false; }
if (!role.trim()) { alert("Debe ingresar el puesto."); return false; }
if (!employeeId.trim()) { alert("Debe ingresar el ID del empleado."); return false; }
if (!photoFile) { alert("Debe subir la foto del colaborador."); return false; }
return true;
};
@@ -147,83 +361,111 @@ export default function IdCardGenerator() {
<p>GomezLee Marketing · Carnet Corporativo CR80</p>
</div>
<div className="main-container">
<div className="panel">
<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' }}>
<div className="dot" style={{ background: '#E65100' }}></div>
<span>Módulo de Lotes Automáticos</span>
</div>
<div className="panel-section">
<div className="panel-section-title" style={{ display: 'flex', alignItems: 'center', gap: '6px', position: 'relative' }}>
<span>Carga Masiva de Colaboradores</span>
<div
style={{
display: 'flex', alignItems: 'center', justifyContent: 'center',
width: '16px', height: '16px', borderRadius: '50%',
background: '#cbd5e1', color: '#334155', fontSize: '11px',
fontWeight: 'bold', cursor: 'help', userSelect: 'none'
}}
onMouseEnter={() => setShowTooltip(true)}
onMouseLeave={() => setShowTooltip(false)}
>
?
</div>
{showTooltip && (
<div style={{
position: 'absolute', top: '24px', left: '0', right: '0',
background: '#1e293b', color: '#ffffff', padding: '10px',
borderRadius: '6px', fontSize: '11px', lineHeight: '1.4',
zIndex: '99', boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)',
fontWeight: 'normal', textTransform: 'none'
}}>
Formato de columnas requeridas en el Excel: <br />
<b style={{ color: '#6CC24A' }}>nombre, puesto, cliente/proyecto, cedula, lenguaje, foto_url</b>.<br />
</div>
)}
</div>
<div className="upload-btn" style={{ background: '#475569', marginTop: '12px' }} onClick={() => excelInputRef.current.click()}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
<polyline points="14 2 14 8 20 8" />
<line x1="16" y1="13" x2="8" y2="13" />
<line x1="16" y1="17" x2="8" y2="17" />
</svg>
Seleccionar Archivo Excel
</div>
<input type="file" accept=".xlsx, .xls, .csv" style={{ display: 'none' }} ref={excelInputRef} onChange={handleExcelUpload} />
{bulkStatusText && (
<div style={{ fontSize: '12px', marginTop: '8px', fontWeight: '500', color: '#475569' }}>
{bulkStatusText}
</div>
)}
</div>
<div className="divider"></div>
<div className="panel-section">
<div className="panel-section-title">Exportar Lote</div>
<button
className="export-btn blue"
disabled={bulkDownloadStatus.processing || bulkEmployees.length === 0}
onClick={triggerBulkDownload}
style={{ opacity: bulkEmployees.length === 0 ? 0.6 : 1 }}
>
{bulkDownloadStatus.text}
</button>
</div>
</div>
{/* FORMULARIO INDIVIDUAL */}
<div className="panel">
<div className="preview-badge">
<div className="dot"></div>
<span>Vista previa en tiempo real</span>
</div>
{/* Sección Colaborador */}
<div className="panel-section">
<div className="panel-section-title">Colaborador</div>
<div className="field">
<label>Nombre</label>
<input
type="text"
id="inputName"
placeholder="Ej: Alexi Zabala"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<input type="text" placeholder="Ej: Alexi Zabala" value={name} onChange={(e) => setName(e.target.value)} />
</div>
<div className="field">
<label>Puesto</label>
<input
type="text"
id="inputRole"
placeholder="Ej: Mercaderista"
value={role}
onChange={(e) => setRole(e.target.value)}
/>
<input type="text" placeholder="Ej: Mercaderista" value={role} onChange={(e) => setRole(e.target.value)} />
</div>
<div className="upload-btn" onClick={() => fileInputRef.current.click()}>
<svg width="14" height="14" viewBox="0 0 14 14" fill="none">
<circle cx="7" cy="5" r="3" stroke="currentColor" strokeWidth="1.2" />
<path d="M1 12c0-3.5 12-3.5 12 0" stroke="currentColor" strokeWidth="1.2" />
</svg>
Subir foto del colaborador
<div className="upload-btn" onClick={() => !photoProcessing && fileInputRef.current.click()} style={{ opacity: photoProcessing ? 0.6 : 1, cursor: photoProcessing ? 'wait' : 'pointer' }}>
{photoProcessing ? '⏳ Procesando foto con IA...' : 'Subir foto del colaborador'}
</div>
<input
type="file"
id="photoInput"
accept="image/*"
style={{ display: 'none' }}
ref={fileInputRef}
onChange={handlePhotoUpload}
/>
<input type="file" accept="image/*" style={{ display: 'none' }} ref={fileInputRef} onChange={handlePhotoUpload} />
</div>
<div className="divider"></div>
{/* Sección Cliente / Proyecto */}
<div className="panel-section">
<div className="panel-section-title">Cliente / Proyecto</div>
<div className="lang-container">
<button
type="button"
className={`lang-btn ${language === 'Esp' ? 'active' : ''}`}
onClick={() => handleLanguageChange('Esp')}
>
Español
</button>
<button
type="button"
className={`lang-btn ${language === 'Ing' ? 'active' : ''}`}
onClick={() => handleLanguageChange('Ing')}
>
Inglés
</button>
<button type="button" className={`lang-btn ${language === 'Esp' ? 'active' : ''}`} onClick={() => setLanguage('Esp')}>Español</button>
<button type="button" className={`lang-btn ${language === 'Ing' ? 'active' : ''}`} onClick={() => setLanguage('Ing')}>Inglés</button>
</div>
<div className="field">
<label>Seleccionar Cliente</label>
<select id="selectClient" value={selectedClient} onChange={handleClientChange}>
<select value={selectedClient} onChange={(e) => setSelectedClient(e.target.value)}>
<option value="Generico">Genérico (Por defecto)</option>
<option value="Claro">Claro</option>
<option value="Colgate">Colgate</option>
@@ -240,103 +482,77 @@ export default function IdCardGenerator() {
<div className="divider"></div>
{/* Sección Código QR */}
<div className="panel-section">
<div className="panel-section-title">Código QR</div>
<div className="field">
<label>ID del empleado</label>
<label>ID del empleado / Cédula</label>
<input
type="text"
id="inputQR"
placeholder="Ej: 12345"
placeholder="Ej: 123456789 (Sin guiones ni espacios)"
value={employeeId}
onChange={(e) => setEmployeeId(e.target.value)}
onChange={handleEmployeeIdChange}
/>
</div>
<button
className="export-btn"
style={{ background: '#6CC24A', marginTop: '2px' }}
onClick={triggerGenerateQR}
>
<button className="export-btn" style={{ background: '#6CC24A', marginTop: '2px' }} onClick={() => renderQRCode(employeeId, qrCanvasRef.current)}>
Generar QR
</button>
</div>
<div className="divider"></div>
{/* Sección Exportar */}
<div className="panel-section">
<div className="panel-section-title">Exportar</div>
<button
className="export-btn blue"
id="btnDownload"
disabled={downloadStatus.processing}
onClick={triggerDownload}
>
<button className="export-btn blue" disabled={downloadStatus.processing || !isFormComplete} onClick={triggerDownload} style={{ opacity: (!isFormComplete || downloadStatus.processing) ? 0.6 : 1 }}>
{downloadStatus.text}
</button>
</div>
</div>
{/* --- STAGE: Vista previa de las tarjetas ─── */}
{/* VISTA PREVIA */}
<div className="stage">
{/* Frente */}
<div className="card-wrap">
<div className="card-label">Frente</div>
<div
className="card"
id="cardFront"
style={{ backgroundImage: `url('${baseUrl}images/AF GLM Frente.png')` }}
>
<div className="front-photo-frame" id="photoFrame" style={{ position: 'relative', overflow: 'hidden' }}>
<div className="card" id="cardFront" style={{ backgroundImage: `url('${baseUrl}images/AF GLM Frente.png')` }}>
<div className="front-photo-frame" style={{ position: 'relative', overflow: 'hidden' }}>
{photoSrc ? (
<img
id="photoImg"
src={photoSrc}
alt="Foto Colaborador"
style={{
width: '100%',
height: '100%',
objectFit: 'cover',
display: 'block'
}}
/>
) : (
<svg className="placeholder-svg" id="photoPlaceholder" viewBox="0 0 28 28" fill="none" style={{ width: '60%', height: '60%', opacity: 0.4 }}>
<img src={photoSrc} alt="Foto Colaborador" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
) : (null)}
{photoProcessing && (
<div style={{
position: 'absolute', inset: 0, display: 'flex',
alignItems: 'center', justifyContent: 'center',
background: 'rgba(0,0,0,0.45)', color: '#fff',
fontSize: '13px', fontWeight: '600', textAlign: 'center', padding: '8px'
}}>
Editando foto con IA...
</div>
)}
{!photoSrc && (
<svg className="placeholder-svg" viewBox="0 0 28 28" fill="none" style={{ width: '60%', height: '60%', opacity: 0.4 }}>
<circle cx="14" cy="10" r="5.5" stroke="currentColor" strokeWidth="1.5" />
<path d="M3 24c0-6 22-6 22 0" stroke="currentColor" strokeWidth="1.5" />
</svg>
)}
</div>
<div className="front-dynamic-name" id="displayName">
{name ? name.toUpperCase() : 'NOMBRE APELLIDO'}
</div>
<div className="front-dynamic-role" id="displayRole">
{role ? role.toUpperCase() : 'PUESTO'}
</div>
<div className="front-dynamic-name">{name ? name.toUpperCase() : 'NOMBRE APELLIDO'}</div>
<div className="front-dynamic-role">{role ? role.toUpperCase() : 'PUESTO'}</div>
</div>
</div>
{/* Reverso */}
<div className="card-wrap">
<div className="card-label">Reverso</div>
<div
className="card"
id="cardBack"
style={{
backgroundImage: `url('${baseUrl}${selectedClient === 'Colgate' ? 'images/GLM Colgate' : 'images/AF ' + selectedClient} ${language}.png')`
backgroundImage: `url('${baseUrl}${(clientTemplates[language] || clientTemplates['Esp'])[selectedClient] || (clientTemplates[language] || clientTemplates['Esp'])['Generico']}')`
}}
>
<div className="back-qr-zone">
{/* Asignamos la referencia de React para un control de pixeles seguro */}
<canvas ref={qrCanvasRef} width="55" height="55"></canvas>
<canvas ref={qrCanvasRef} width={55} height={55}></canvas>
</div>
</div>
</div>
</div>
</div>
</>
+272 -56
View File
@@ -3,7 +3,7 @@ export const clientTemplates = {
'Esp': {
'Generico': 'images/AF Generico Esp.png',
'Claro': 'images/AF Claro Esp.png',
'Colgate': 'images/GLM Colgate Esp.png',
'Colgate': 'images/AF Colgate Esp.png',
'KitchenAid': 'images/AF KitchenAid Esp.png',
'Kraft': 'images/AF Kraft Esp.png',
'Motorola': 'images/AF Motorola Esp.png',
@@ -15,7 +15,7 @@ export const clientTemplates = {
'Ing': {
'Generico': 'images/AF Generico Ing.png',
'Claro': 'images/AF Claro Ing.png',
'Colgate': 'images/GLM Colgate Ing.png',
'Colgate': 'images/AF Colgate Ing.png',
'KitchenAid': 'images/AF KitchenAid Ing.png',
'Kraft': 'images/AF Kraft Ing.png',
'Motorola': 'images/AF Motorola Ing.png',
@@ -37,17 +37,94 @@ function loadScript(src, globalKey) {
});
}
const getQRLib = () => loadScript('https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js', 'QRCode');
export const getQRLib = () => loadScript('https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js', 'QRCode');
const getHtml2Canvas = () => loadScript('https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js', 'html2canvas');
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');
// ── GENERADOR DE QR NATIVO (REACT RENDERING) ──
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]) {
// 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;
}
export async function fetchImageAsBlob(url) {
if (!url) return null;
if (url.startsWith('blob:') || url.startsWith('data:')) {
try {
const response = await fetch(url);
if (response.ok) return await response.blob();
} catch (e) {
console.error("Error al obtener Blob local de URL blob/data:", e);
}
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 {
console.warn("No se pudo obtener el Blob directo de Drive debido a restricciones CORS.");
}
return null;
}
try {
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 externa:", e);
try {
const response = await fetch(url, { mode: 'cors' });
return await response.blob();
} catch {
return null;
}
}
}
function preloadImage(src) {
return new Promise((resolve) => {
if (!src) return resolve(null);
const img = new Image();
img.crossOrigin = 'anonymous';
img.onload = () => resolve(src);
img.onerror = () => {
const retryImg = new Image();
retryImg.onload = () => resolve(src);
retryImg.onerror = () => resolve(null);
retryImg.src = src;
};
img.src = src;
});
}
// ── 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');
@@ -55,7 +132,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',
@@ -63,32 +140,42 @@ export async function renderQRCode(employeeId, canvasElement) {
correctLevel: QRCodeLib.CorrectLevel.M
});
setTimeout(() => {
const img = tmp.querySelector('img') || tmp.querySelector('canvas');
await new Promise((resolve) => setTimeout(resolve, 60));
const drawIt = (src) => {
const img = tmp.querySelector('img') || tmp.querySelector('canvas');
const drawIt = (src) => {
return new Promise((res) => {
const i = new Image();
i.onload = () => {
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, 55, 55);
ctx.drawImage(i, 0, 0, 55, 55);
if (tmp.parentNode) document.body.removeChild(tmp);
res();
};
i.src = src;
};
});
};
if (img && img.tagName === 'CANVAS') {
drawIt(img.toDataURL());
} else if (img) {
if (img.complete) drawIt(img.src);
else img.onload = () => drawIt(img.src);
} else {
if (tmp.parentNode) document.body.removeChild(tmp);
if (img && img.tagName === 'CANVAS') {
await drawIt(img.toDataURL());
} else if (img) {
if (img.complete) await drawIt(img.src);
else {
await new Promise((res) => {
img.onload = async () => {
await drawIt(img.src);
res();
};
});
}
}, 50);
} else {
if (tmp.parentNode) document.body.removeChild(tmp);
}
}
// ── ENGINE DE PROCESAMIENTO ULTRA MAX QUALITY (650x1004) ──
// ── ENGINE DE PROCESAMIENTO INDIVIDUAL ──
export async function downloadIDCards(config) {
const { name, role, selectedClient, language, photoSrc, baseUrl, qrCanvas, onStateChange } = config;
@@ -97,13 +184,11 @@ export async function downloadIDCards(config) {
const html2canvasLib = await getHtml2Canvas();
const cleanName = name.trim().replace(/\s+/g, '') || 'Empleado';
// Resolver rutas absolutas
const frontBgUrl = `${baseUrl}images/AF GLM Frente.png`;
const currentGroup = clientTemplates[language] || clientTemplates['Esp'];
const backBgFile = currentGroup[selectedClient] || 'images/AF Generico Esp.png';
const backBgUrl = `${baseUrl}${backBgFile}`;
// Sandbox virtual aislado
const sandbox = document.createElement('div');
sandbox.style.position = 'fixed';
sandbox.style.top = '-9999px';
@@ -125,27 +210,23 @@ export async function downloadIDCards(config) {
font-family: Arial, Helvetica, sans-serif;
`;
// 1. Frente Virtual en tamaño real
const vFront = document.createElement('div');
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 = `<div style="width:100%; height:100%; background-image:url('${photoSrc}'); background-size:cover; background-position:center; background-repeat:no-repeat;"></div>`;
}
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'}
@@ -155,24 +236,12 @@ export async function downloadIDCards(config) {
</div>
`;
// 2. Reverso Virtual en tamaño real
const vBack = document.createElement('div');
vBack.style.cssText = cardStyleBase;
vBack.style.backgroundImage = `url('${backBgUrl}')`;
const vQRZone = document.createElement('div');
vQRZone.style.cssText = `
position: absolute;
bottom: 27px;
right: 27px;
background: #ffffff;
padding: 11px;
border-radius: 16px;
display: flex;
align-items: center;
justify-content: center;
z-index: 5;
`;
vQRZone.style.cssText = `position: absolute; bottom: 27px; right: 27px; background: #ffffff; padding: 11px; border-radius: 16px; display: flex; align-items: center; justify-content: center; z-index: 5;`;
const vQRCanvas = document.createElement('canvas');
vQRCanvas.width = 149;
@@ -191,15 +260,7 @@ export async function downloadIDCards(config) {
sandbox.appendChild(vFront);
sandbox.appendChild(vBack);
const renderOpts = {
scale: 1,
useCORS: true,
allowTaint: false,
backgroundColor: null,
logging: false,
width: 650,
height: 1004
};
const renderOpts = { scale: 1, useCORS: true, allowTaint: false, backgroundColor: null, logging: false, width: 650, height: 1004 };
try {
const frontCanvas = await html2canvasLib(vFront, renderOpts);
@@ -215,6 +276,161 @@ export async function downloadIDCards(config) {
}
}
// ── 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...' });
const html2canvasLib = await getHtml2Canvas();
const JSZipLib = await getJSZip();
const zip = new JSZipLib();
const hiddenQRCanvas = document.createElement('canvas');
hiddenQRCanvas.width = 55;
hiddenQRCanvas.height = 55;
const sandbox = document.createElement('div');
sandbox.style.position = 'fixed';
sandbox.style.top = '-9999px';
sandbox.style.left = '-9999px';
sandbox.style.width = '1400px';
document.body.appendChild(sandbox);
const cardStyleBase = `
position: relative;
width: 650px;
height: 1004px;
border-radius: 16px;
background-size: cover;
background-position: center;
background-repeat: no-repeat;
display: inline-block;
overflow: hidden;
font-family: Arial, Helvetica, sans-serif;
`;
const renderOpts = { scale: 1, useCORS: true, allowTaint: false, backgroundColor: null, logging: false, width: 650, height: 1004 };
for (let i = 0; i < employees.length; i++) {
const emp = employees[i];
const currentClient = emp.selectedClient || 'Generico';
const sanitizedEmpName = (emp.name || '').trim().replace(/[\\/:*?"<>|]/g, '-') || `Empleado_${i + 1}`;
const sanitizedClientName = String(currentClient).trim().replace(/[\\/:*?"<>|]/g, '-');
const folderName = `${sanitizedEmpName} - ${sanitizedClientName}`;
const strictCleanId = String(emp.employeeId || '').replace(/[-\s]/g, '');
await renderQRCode(strictCleanId, hiddenQRCanvas);
const directDriveUrl = convertDriveUrlToDirect(emp.fotoUrl);
let validatedPhotoUrl = null;
if (directDriveUrl && strictCleanId) {
try {
const blobData = await fetchImageAsBlob(directDriveUrl);
if (blobData) {
validatedPhotoUrl = URL.createObjectURL(blobData);
if (onProcessEmployeePhoto) {
await onProcessEmployeePhoto(strictCleanId, blobData, emp.selectedClient || '');
}
}
} catch (err) {
console.error(`Error guardando foto en Supabase para Cédula: ${strictCleanId}`, err);
}
}
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')`;
// 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) {
photoTagHtml = `<div style="width:100%; height:100%; background-image:url('${validatedPhotoUrl}'); background-size:cover; background-position:center; background-repeat:no-repeat;"></div>`;
}
vFront.innerHTML = `
<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()}
</div>
<div style="position:absolute; bottom:32px; right:15px; font-size:26px; font-weight:700; color:#6B8499; text-align:right; text-transform:uppercase; letter-spacing:1px; max-width:550px; white-space:nowrap; z-index:5;">
${emp.role.toUpperCase()}
</div>
`;
sandbox.appendChild(vFront);
// --- Renderizar Reverso Virtual ---
const currentGroup = clientTemplates[emp.language] || clientTemplates['Esp'];
const backBgFile = currentGroup[currentClient] || currentGroup['Generico'];
const backBgUrl = `${baseUrl}${backBgFile}`;
const vBack = document.createElement('div');
vBack.style.cssText = cardStyleBase;
vBack.style.backgroundImage = `url('${backBgUrl}')`;
const vQRZone = document.createElement('div');
vQRZone.style.cssText = `position: absolute; bottom: 27px; right: 27px; background: #ffffff; padding: 11px; border-radius: 16px; display: flex; align-items: center; justify-content: center; z-index: 5;`;
const vQRCanvas = document.createElement('canvas');
vQRCanvas.width = 149;
vQRCanvas.height = 149;
vQRCanvas.style.width = '100px';
vQRCanvas.style.height = '100px';
const vQRContext = vQRCanvas.getContext('2d');
if (vQRContext) {
vQRContext.imageSmoothingEnabled = false;
vQRContext.drawImage(hiddenQRCanvas, 0, 0, 149, 149);
}
vQRZone.appendChild(vQRCanvas);
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];
zip.file(`${folderName}/Frente.png`, frontData, { base64: true });
const backCanvas = await html2canvasLib(vBack, renderOpts);
const backData = backCanvas.toDataURL('image/png').split(',')[1];
zip.file(`${folderName}/Reverso.png`, backData, { base64: true });
if (validatedPhotoUrl && validatedPhotoUrl.startsWith('blob:')) {
URL.revokeObjectURL(validatedPhotoUrl);
}
sandbox.removeChild(vFront);
sandbox.removeChild(vBack);
}
if (sandbox.parentNode) document.body.removeChild(sandbox);
const content = await zip.generateAsync({ type: 'blob' });
const link = document.createElement('a');
link.href = URL.createObjectURL(content);
link.download = `Lote_Carnets_GLM.zip`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
if (onStateChange) onStateChange({ processing: false, text: '⬇ Descargar' });
}
function executeFileDownload(dataUrl, fileName) {
const link = document.createElement('a');
link.href = dataUrl;
+84 -8
View File
@@ -1,21 +1,97 @@
import { supabase } from "./supabase";
export async function uploadEmployeePhoto(employeeNumber, file) {
/**
* Registra el cliente/proyecto de un carnet descargado en la tabla
* "carnet_empleados_creados_glm".
*
* @param {string} employeeNumber - Número de cédula limpio (sin guiones/espacios)
* @param {string} clienteProyecto - Nombre del cliente/proyecto seleccionado
* @returns {Promise<void>}
*/
export async function saveClienteProyecto(employeeNumber, clienteProyecto) {
const cleanCedula = String(employeeNumber || '').replace(/[-\s]/g, '');
const valorCliente = clienteProyecto || 'Generico';
const extension = file.name.split(".").pop();
console.log(`[Supabase] → saveClienteProyecto llamada con: cedula="${cleanCedula}", cliente_proyecto="${valorCliente}"`);
const fileName = `${employeeNumber}.${extension}`;
if (!cleanCedula) {
console.warn('[Supabase] saveClienteProyecto abortada: cédula vacía.');
return;
}
// CORRECCIÓN: El objeto debe llevar la cédula para que upsert funcione por conflicto
const { data, error } = await supabase
.from('carnet_empleados_creados_glm')
.upsert(
{
cedula: cleanCedula,
cliente_proyecto: valorCliente
},
{ onConflict: 'cedula' }
)
.select();
if (error) {
console.error(`[Supabase] ❌ Error guardando cliente_proyecto para cédula ${cleanCedula}:`, error);
} else {
console.log(`[Supabase] ✅ Guardado exitoso carnet_empleados_creados_glm:`, data);
}
}
/**
* Sube la foto de un empleado al bucket "foto_empleados".
*
* El nombre del archivo sigue el patrón:
* <cedula>_<cliente>.jpg — primera foto
* <cedula>_<cliente>1.jpg — segunda foto del mismo empleado+cliente
* <cedula>_<cliente>2.jpg — tercera, etc.
*
* @param {string} employeeNumber - Número de cédula limpio (sin guiones/espacios)
* @param {File} file - Archivo de imagen a subir
* @param {string} [clientKey=''] - Nombre del cliente/proyecto (p.ej. "claro", "nestle")
* @returns {Promise<string>} - URL pública del archivo subido
*/
export async function uploadEmployeePhoto(employeeNumber, file, clientKey = '') {
const extension = file.name.split('.').pop() || 'jpg';
// Normalizar el nombre del cliente: minúsculas, sin espacios ni caracteres especiales
const safeClient = clientKey
? '_' + clientKey.toLowerCase().replace(/[^a-z0-9]/g, '')
: '';
const baseName = `${employeeNumber}${safeClient}`;
// Buscar archivos existentes con el mismo prefijo para elegir el sufijo correcto
const { data: existingFiles } = await supabase.storage
.from('foto_empleados')
.list('', { search: baseName });
// Filtrar exactamente los archivos que tengan el mismo baseName base
const pattern = new RegExp(`^${baseName}(\\d*)\\.${extension}$`);
const matches = (existingFiles || []).filter(f => pattern.test(f.name));
let fileName;
if (matches.length === 0) {
// No existe ninguno: usar el nombre base sin sufijo numérico
fileName = `${baseName}.${extension}`;
} else {
// Extraer los sufijos numéricos usados y elegir el siguiente
const usedSuffixes = matches.map(f => {
const m = f.name.match(pattern);
return m ? parseInt(m[1] || '0', 10) : 0;
});
const nextSuffix = Math.max(...usedSuffixes) + 1;
fileName = `${baseName}${nextSuffix}.${extension}`;
}
const { error } = await supabase.storage
.from("foto_empleados")
.upload(fileName, file, {
upsert: false
});
.from('foto_empleados')
.upload(fileName, file, { upsert: false });
if (error) throw error;
const { data } = supabase.storage
.from("foto_empleados")
.from('foto_empleados')
.getPublicUrl(fileName);
return data.publicUrl;