mejoras en el código y cambios adicionales boton eliminar y demás

This commit is contained in:
remaster 2026-06-15 10:52:39 -06:00
parent b4f97df3a8
commit c94c8f8b69
21 changed files with 3631 additions and 2844 deletions

BIN
.DS_Store vendored

Binary file not shown.

5
.gitignore vendored
View file

@ -1,2 +1,7 @@
# Códigos QR generados (regenerables con generate_qrs.py) # Códigos QR generados (regenerables con generate_qrs.py)
output/ output/
# Sistema / temporales
.DS_Store
*.xlsx
qr_data.csv

109
Faltantes.csv Normal file
View file

@ -0,0 +1,109 @@
modulo,ubicacion
PLP,T-72-11
PLP,T-72-12
PLP,T-73-11
PLP,T-73-12
PLP,T-74-11
PLP,T-74-12
PLP,T-75-11
PLP,T-75-12
PLP,T-76-11
PLP,T-76-12
PLP,T-77-11
PLP,T-77-12
PLP,T-78-11
PLP,T-78-12
PLP,T-79-11
PLP,T-79-12
PLP,T-80-11
PLP,T-80-12
PLP,T-81-11
PLP,T-81-12
PLP,T-82-11
PLP,T-82-12
PLP,T-83-11
PLP,T-83-12
PLP,T-84-11
PLP,T-84-12
PLP,T-85-11
PLP,T-85-12
PLP,T-86-11
PLP,T-86-12
PLP,T-87-11
PLP,T-87-12
PLP,T-88-11
PLP,T-88-12
PLP,T-89-11
PLP,T-89-12
PLP,T-90-11
PLP,T-90-12
PLP,T-91-11
PLP,T-91-12
PLP,T-92-11
PLP,T-92-12
PLP,T-93-11
PLP,T-93-12
PLP,T-94-11
PLP,T-94-12
PLP,T-95-11
PLP,T-95-12
PLP,T-96-11
PLP,T-96-12
PLP,T-97-11
PLP,T-97-12
PLP,T-98-11
PLP,T-98-12
PLP,T-99-11
PLP,T-99-12
PLP,T-100-11
PLP,T-100-12
PLP,T-101-11
PLP,T-101-12
PLP,T-102-11
PLP,T-102-12
PLP,T-103-11
PLP,T-103-12
PLP,T-104-11
PLP,T-104-12
PALAPA,CAMINO ROJO
PALAPA,SALTILLITO
PALAPA,SANTA FE
PALAPA,CHILE COLORADO
PALAPA,NOCHE BUENA
PALAPA,PEÑASQUITO
PALAPA,SALA DIVERSIDAD
CANCHA,CAMPO FUT BOOL
BAÑO PÚBLICO,BAÑO PÚBLICO #1
BAÑO PÚBLICO,BAÑO PÚBLICO #2
BAÑO PÚBLICO,BAÑO PÚBLICO #3
BAÑO PÚBLICO,BAÑO PÚBLICO #4
BAÑO PÚBLICO,BAÑO PÚBLICO #5
CAMPAMENTO,SALA DE LACTANCIA
EDIF.6A,GYM #1
EDIF.6A,BAÑOS GYM #1
EDIF.6A,GYM #2
EDIF.6A,BAÑOS GYM #2
EDIF.6A,AREA TECHADA
EDIF.6A,LAVANDERIA
EDIF.6A,MANTENIMIENTO CAMPAMENTO
EDIF.6A,OFC. TRANSPORTES
EDIF.6A,MONITOREO TRANSPORTES
EDIF.6A,RECURSOS HUMANOS
EDIF.6A,RH RECEPCIÓN Y PASILLOS
EDIF.6A,RH BAÑOS
EDIF.6A,OXO Y TIENDA
EDIF.6A,OXO CAMARA DE REFRIGERACIÓN
EDIF.6A,BODEGA RH
CAMPAMENTO,CINE
CAMPAMENTO,SUM# 1 SALA USOS MULTUPLES
CAMPAMENTO,SUM# 2 SALA USOS MULTUPLES
CAMPAMENTO,SERVICIO MÉDICO
CAMPAMENTO,SALAS TV MOD. E´S
CAMPAMENTO,CAPILLA
CAMPAMENTO,PLANTA EMBOTELLADORA
CAMPAMENTO,SPORT LOUNCH
CAMPAMENTO,TRAINING CENTER
CAMPAMENTO,COMEDOR
CAMPAMENTO,ALMACÉN ALIMENTOS
CAMPAMENTO,CAJERO # 1
CAMPAMENTO,CAJERO # 2
1 modulo ubicacion
2 PLP T-72-11
3 PLP T-72-12
4 PLP T-73-11
5 PLP T-73-12
6 PLP T-74-11
7 PLP T-74-12
8 PLP T-75-11
9 PLP T-75-12
10 PLP T-76-11
11 PLP T-76-12
12 PLP T-77-11
13 PLP T-77-12
14 PLP T-78-11
15 PLP T-78-12
16 PLP T-79-11
17 PLP T-79-12
18 PLP T-80-11
19 PLP T-80-12
20 PLP T-81-11
21 PLP T-81-12
22 PLP T-82-11
23 PLP T-82-12
24 PLP T-83-11
25 PLP T-83-12
26 PLP T-84-11
27 PLP T-84-12
28 PLP T-85-11
29 PLP T-85-12
30 PLP T-86-11
31 PLP T-86-12
32 PLP T-87-11
33 PLP T-87-12
34 PLP T-88-11
35 PLP T-88-12
36 PLP T-89-11
37 PLP T-89-12
38 PLP T-90-11
39 PLP T-90-12
40 PLP T-91-11
41 PLP T-91-12
42 PLP T-92-11
43 PLP T-92-12
44 PLP T-93-11
45 PLP T-93-12
46 PLP T-94-11
47 PLP T-94-12
48 PLP T-95-11
49 PLP T-95-12
50 PLP T-96-11
51 PLP T-96-12
52 PLP T-97-11
53 PLP T-97-12
54 PLP T-98-11
55 PLP T-98-12
56 PLP T-99-11
57 PLP T-99-12
58 PLP T-100-11
59 PLP T-100-12
60 PLP T-101-11
61 PLP T-101-12
62 PLP T-102-11
63 PLP T-102-12
64 PLP T-103-11
65 PLP T-103-12
66 PLP T-104-11
67 PLP T-104-12
68 PALAPA CAMINO ROJO
69 PALAPA SALTILLITO
70 PALAPA SANTA FE
71 PALAPA CHILE COLORADO
72 PALAPA NOCHE BUENA
73 PALAPA PEÑASQUITO
74 PALAPA SALA DIVERSIDAD
75 CANCHA CAMPO FUT BOOL
76 BAÑO PÚBLICO BAÑO PÚBLICO #1
77 BAÑO PÚBLICO BAÑO PÚBLICO #2
78 BAÑO PÚBLICO BAÑO PÚBLICO #3
79 BAÑO PÚBLICO BAÑO PÚBLICO #4
80 BAÑO PÚBLICO BAÑO PÚBLICO #5
81 CAMPAMENTO SALA DE LACTANCIA
82 EDIF.6A GYM #1
83 EDIF.6A BAÑOS GYM #1
84 EDIF.6A GYM #2
85 EDIF.6A BAÑOS GYM #2
86 EDIF.6A AREA TECHADA
87 EDIF.6A LAVANDERIA
88 EDIF.6A MANTENIMIENTO CAMPAMENTO
89 EDIF.6A OFC. TRANSPORTES
90 EDIF.6A MONITOREO TRANSPORTES
91 EDIF.6A RECURSOS HUMANOS
92 EDIF.6A RH RECEPCIÓN Y PASILLOS
93 EDIF.6A RH BAÑOS
94 EDIF.6A OXO Y TIENDA
95 EDIF.6A OXO CAMARA DE REFRIGERACIÓN
96 EDIF.6A BODEGA RH
97 CAMPAMENTO CINE
98 CAMPAMENTO SUM# 1 SALA USOS MULTUPLES
99 CAMPAMENTO SUM# 2 SALA USOS MULTUPLES
100 CAMPAMENTO SERVICIO MÉDICO
101 CAMPAMENTO SALAS TV MOD. E´S
102 CAMPAMENTO CAPILLA
103 CAMPAMENTO PLANTA EMBOTELLADORA
104 CAMPAMENTO SPORT LOUNCH
105 CAMPAMENTO TRAINING CENTER
106 CAMPAMENTO COMEDOR
107 CAMPAMENTO ALMACÉN ALIMENTOS
108 CAMPAMENTO CAJERO # 1
109 CAMPAMENTO CAJERO # 2

View file

@ -74,7 +74,8 @@ http://localhost:8080/install.php
El instalador: El instalador:
- Crea la base de datos y tablas. - Crea la base de datos y tablas.
- Importa **2 518 ubicaciones** desde `data.csv` (archivo original del proyecto). - **2 518 ubicaciones** desde `data.csv` (archivo original del proyecto).
- Ubicaciones adicionales con `php import_faltantes.php` desde `Faltantes.csv`.
- Asigna códigos únicos a cada módulo (`MOD-001`…) y ubicación (`UB-00001`…). - Asigna códigos únicos a cada módulo (`MOD-001`…) y ubicación (`UB-00001`…).
- Carga catálogos de **empresas** y **servicios**. - Carga catálogos de **empresas** y **servicios**.
- Crea el usuario administrador inicial. - Crea el usuario administrador inicial.
@ -223,9 +224,11 @@ autofillqr/
├── sql/ # Esquema e migraciones ├── sql/ # Esquema e migraciones
├── formulario.php # Formulario público (entrada QR) ├── formulario.php # Formulario público (entrada QR)
├── install.php # Instalador ├── install.php # Instalador
├── import_faltantes.php # Importar ubicaciones desde Faltantes.csv
├── generate_qrs.py # Generador de etiquetas PNG ├── generate_qrs.py # Generador de etiquetas PNG
├── data.csv # Datos originales (importación inicial) ├── data.csv # Datos originales (importación inicial)
├── qr_data.csv # URLs actuales para QR ├── Faltantes.csv # Ubicaciones adicionales (módulo, habitación)
├── qr_data.csv # URLs actuales para QR (generado)
├── NEM.png # Logo del campamento ├── NEM.png # Logo del campamento
└── output/ # QR generados (PNG) └── output/ # QR generados (PNG)
``` ```
@ -258,21 +261,21 @@ Todos editables desde el panel admin.
Desde `data.csv` (formato original de Microsoft Forms): Desde `data.csv` (formato original de Microsoft Forms):
- **19 módulos / áreas** - **19 módulos / áreas** iniciales + adicionales vía `Faltantes.csv`
- **2 518 ubicaciones** - **2 628 ubicaciones** (2 518 base + 108 faltantes)
- **2 518 códigos QR** (1 duplicado de nombre en origen: Trailas T9-1)
--- ---
## Migraciones SQL adicionales ## Importar ubicaciones faltantes
Si actualiza desde una versión anterior: Archivo `Faltantes.csv` con columnas `modulo,ubicacion` (UTF-8):
```bash ```bash
mysql -u root -p mantenimiento_campamento < sql/migrate_empresas.sql php import_faltantes.php
mysql -u root -p mantenimiento_campamento < sql/migrate_usuarios.sql
``` ```
O desde el navegador (requiere login admin): `/import_faltantes.php`
--- ---
## Notas técnicas ## Notas técnicas
@ -291,6 +294,9 @@ mysql -u root -p mantenimiento_campamento < sql/migrate_usuarios.sql
# Instalar (navegador) # Instalar (navegador)
open http://localhost:8080/install.php open http://localhost:8080/install.php
# Importar ubicaciones faltantes
php import_faltantes.php
# Servidor desarrollo # Servidor desarrollo
php -S localhost:8080 -t . php -S localhost:8080 -t .

109
admin/download_qr.php Normal file
View file

@ -0,0 +1,109 @@
<?php
require_once __DIR__ . '/../includes/admin_bootstrap.php';
require_once __DIR__ . '/../config/database.php';
$db = getDB();
$outputDir = qrOutputDir();
$rows = $db->query('
SELECT u.codigo, m.nombre AS modulo, u.nombre AS ubicacion, u.modulo_id
FROM ubicaciones u
JOIN modulos m ON m.id = u.modulo_id
WHERE u.activo = 1
ORDER BY u.codigo
')->fetchAll();
$filenameMap = buildQrFilenameMap($rows);
$codigo = trim($_GET['codigo'] ?? '');
$bulk = isset($_GET['bulk']);
$moduloFiltro = (int) ($_GET['modulo_id'] ?? 0);
$selected = array_filter(array_map('trim', (array) ($_GET['codes'] ?? [])));
if ($codigo !== '') {
$match = null;
foreach ($rows as $r) {
if ($r['codigo'] === $codigo) {
$match = $r;
break;
}
}
if (!$match) {
flash('danger', 'Ubicación no encontrada.');
redirect(BASE_URL . '/admin/qrs.php');
}
$path = qrFilePathForUbicacion($match['modulo'], $match['ubicacion'], $match['codigo'], $filenameMap);
if (!$path) {
flash('warning', 'El QR aún no está generado. Use «Generar QR» primero.');
redirect(BASE_URL . '/admin/qrs.php');
}
$downloadName = $filenameMap[$codigo] ?? basename($path);
header('Content-Type: image/png');
header('Content-Disposition: attachment; filename="' . $downloadName . '"');
header('Content-Length: ' . filesize($path));
readfile($path);
exit;
}
if (!$bulk && empty($selected)) {
redirect(BASE_URL . '/admin/qrs.php');
}
if (!class_exists('ZipArchive')) {
flash('danger', 'ZipArchive no está disponible en el servidor.');
redirect(BASE_URL . '/admin/qrs.php');
}
$toZip = [];
foreach ($rows as $r) {
if ($moduloFiltro > 0 && (int) $r['modulo_id'] !== $moduloFiltro) {
continue;
}
if (!empty($selected) && !in_array($r['codigo'], $selected, true)) {
continue;
}
$path = qrFilePathForUbicacion($r['modulo'], $r['ubicacion'], $r['codigo'], $filenameMap);
if ($path) {
$toZip[] = ['path' => $path, 'name' => $filenameMap[$r['codigo']] ?? basename($path)];
}
}
if (empty($toZip)) {
flash('warning', 'No hay QR generados para descargar con los filtros seleccionados.');
redirect(BASE_URL . '/admin/qrs.php' . ($moduloFiltro ? '?modulo_id=' . $moduloFiltro : ''));
}
$zip = new ZipArchive();
$tmpFile = tempnam(sys_get_temp_dir(), 'qrs_');
if ($zip->open($tmpFile, ZipArchive::OVERWRITE) !== true) {
flash('danger', 'No se pudo crear el archivo ZIP.');
redirect(BASE_URL . '/admin/qrs.php');
}
foreach ($toZip as $item) {
$zip->addFile($item['path'], $item['name']);
}
$zip->close();
$zipName = 'qrs_campamento';
if ($moduloFiltro > 0) {
$stmt = $db->prepare('SELECT nombre FROM modulos WHERE id = ?');
$stmt->execute([$moduloFiltro]);
$modName = $stmt->fetchColumn();
if ($modName) {
$zipName .= '_' . safeQrFilename($modName);
}
}
if (!empty($selected)) {
$zipName .= '_seleccion';
}
$zipName .= '_' . date('Y-m-d') . '.zip';
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . $zipName . '"');
header('Content-Length: ' . filesize($tmpFile));
readfile($tmpFile);
@unlink($tmpFile);
exit;

View file

@ -27,6 +27,17 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$db->prepare('UPDATE empresas SET nombre = ?, activo = ? WHERE id = ?')->execute([$nombre, $activo, $id]); $db->prepare('UPDATE empresas SET nombre = ?, activo = ? WHERE id = ?')->execute([$nombre, $activo, $id]);
flash('success', 'Empresa actualizada.'); flash('success', 'Empresa actualizada.');
} }
} elseif ($action === 'delete') {
$id = (int) ($_POST['id'] ?? 0);
if ($id > 0) {
$registros = countRegistrosForEmpresa($db, $id);
if ($registros > 0) {
flash('danger', "No se puede eliminar: tiene {$registros} registro(s) asociado(s). Desactívela en su lugar.");
} else {
$db->prepare('DELETE FROM empresas WHERE id = ?')->execute([$id]);
flash('success', 'Empresa eliminada (sus servicios también se eliminaron).');
}
}
} }
redirect(BASE_URL . '/admin/empresas.php'); redirect(BASE_URL . '/admin/empresas.php');
} }
@ -62,14 +73,29 @@ require_once __DIR__ . '/../includes/admin_header.php';
<tbody> <tbody>
<?php foreach ($empresas as $e): ?> <?php foreach ($empresas as $e): ?>
<tr> <tr>
<form method="post"> <td>
<input type="hidden" name="action" value="update"> <form method="post" class="d-flex gap-2 align-items-center">
<input type="hidden" name="id" value="<?= (int) $e['id'] ?>"> <input type="hidden" name="action" value="update">
<td><input type="text" name="nombre" class="form-control form-control-sm" value="<?= h($e['nombre']) ?>" required></td> <input type="hidden" name="id" value="<?= (int) $e['id'] ?>">
<td><?= (int) $e['total_servicios'] ?></td> <input type="text" name="nombre" class="form-control form-control-sm" value="<?= h($e['nombre']) ?>" required>
<td><div class="form-check form-switch"><input class="form-check-input" type="checkbox" name="activo" <?= $e['activo'] ? 'checked' : '' ?>></div></td> </td>
<td><button type="submit" class="btn btn-sm btn-primary">Guardar</button></td> <td><?= (int) $e['total_servicios'] ?></td>
</form> <td>
<div class="form-check form-switch mb-0">
<input class="form-check-input" type="checkbox" name="activo" <?= $e['activo'] ? 'checked' : '' ?>>
</div>
</td>
<td class="text-nowrap">
<button type="submit" class="btn btn-sm btn-primary">Guardar</button>
</form>
<form method="post" class="d-inline" onsubmit="return confirm('¿Eliminar la empresa «<?= h($e['nombre']) ?>» y todos sus servicios?');">
<input type="hidden" name="action" value="delete">
<input type="hidden" name="id" value="<?= (int) $e['id'] ?>">
<button type="submit" class="btn btn-sm btn-outline-danger" title="Eliminar">
<span class="material-symbols-outlined align-middle" style="font-size:18px">delete</span>
</button>
</form>
</td>
</tr> </tr>
<?php endforeach; ?> <?php endforeach; ?>
</tbody> </tbody>

View file

@ -3,40 +3,9 @@ require_once __DIR__ . '/../includes/admin_bootstrap.php';
require_once __DIR__ . '/../config/database.php'; require_once __DIR__ . '/../config/database.php';
$db = getDB(); $db = getDB();
regenerateQrCsv($db);
$rows = $db->query(' $path = dirname(__DIR__) . '/qr_data.csv';
SELECT u.codigo, m.nombre AS modulo, u.nombre AS ubicacion
FROM ubicaciones u
JOIN modulos m ON m.id = u.modulo_id
WHERE u.activo = 1
ORDER BY u.codigo
')->fetchAll();
header('Content-Type: text/csv; charset=utf-8'); header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="qr_data.csv"'); header('Content-Disposition: attachment; filename="qr_data.csv"');
readfile($path);
$out = fopen('php://output', 'w');
fputcsv($out, ['codigo', 'modulo', 'ubicacion', 'url']);
foreach ($rows as $r) {
fputcsv($out, [
$r['codigo'],
$r['modulo'],
$r['ubicacion'],
BASE_URL . '/formulario.php?u=' . $r['codigo'],
]);
}
fclose($out);
// También guardar copia local para generate_qrs.py
$localPath = dirname(__DIR__) . '/qr_data.csv';
$fh = fopen($localPath, 'w');
fputcsv($fh, ['codigo', 'modulo', 'ubicacion', 'url']);
foreach ($rows as $r) {
fputcsv($fh, [
$r['codigo'],
$r['modulo'],
$r['ubicacion'],
BASE_URL . '/formulario.php?u=' . $r['codigo'],
]);
}
fclose($fh);

View file

@ -8,24 +8,12 @@ if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
set_time_limit(600); set_time_limit(600);
$root = dirname(__DIR__); $root = dirname(__DIR__);
require_once __DIR__ . '/../config/database.php';
regenerateQrCsv(getDB());
$python = trim(shell_exec('which python3') ?: 'python3'); $python = trim(shell_exec('which python3') ?: 'python3');
$script = $root . '/generate_qrs.py'; $script = $root . '/generate_qrs.py';
// Actualizar qr_data.csv antes de generar
require_once __DIR__ . '/../config/database.php';
$db = getDB();
$rows = $db->query('
SELECT u.codigo, m.nombre AS modulo, u.nombre AS ubicacion
FROM ubicaciones u JOIN modulos m ON m.id = u.modulo_id
WHERE u.activo = 1 ORDER BY u.codigo
')->fetchAll();
$fh = fopen($root . '/qr_data.csv', 'w');
fputcsv($fh, ['codigo', 'modulo', 'ubicacion', 'url']);
foreach ($rows as $r) {
fputcsv($fh, [$r['codigo'], $r['modulo'], $r['ubicacion'], BASE_URL . '/formulario.php?u=' . $r['codigo']]);
}
fclose($fh);
$cmd = escapeshellarg($python) . ' ' . escapeshellarg($script) . ' 2>&1'; $cmd = escapeshellarg($python) . ' ' . escapeshellarg($script) . ' 2>&1';
$output = shell_exec($cmd); $output = shell_exec($cmd);

View file

@ -3,38 +3,101 @@ $adminSection = 'qrs';
$pageTitle = 'Códigos QR'; $pageTitle = 'Códigos QR';
$pageHeading = 'Códigos QR'; $pageHeading = 'Códigos QR';
$outputDir = dirname(__DIR__) . '/output'; require_once __DIR__ . '/../includes/admin_bootstrap.php';
$qrCount = 0; require_once __DIR__ . '/../config/database.php';
$sampleFile = null;
if (is_dir($outputDir)) { $db = getDB();
$files = array_values(array_filter(scandir($outputDir), fn($f) => str_ends_with($f, '.png'))); $outputDir = qrOutputDir();
$qrCount = count($files); $moduloFiltro = (int) ($_GET['modulo_id'] ?? 0);
if ($qrCount > 0) { $buscar = trim($_GET['q'] ?? '');
sort($files); $soloPendientes = isset($_GET['pendientes']);
$sampleFile = $files[0];
$sql = '
SELECT u.id, u.codigo, u.nombre AS ubicacion, u.modulo_id,
m.nombre AS modulo
FROM ubicaciones u
JOIN modulos m ON m.id = u.modulo_id
WHERE u.activo = 1
';
$params = [];
if ($moduloFiltro > 0) {
$sql .= ' AND u.modulo_id = ?';
$params[] = $moduloFiltro;
}
if ($buscar !== '') {
$sql .= ' AND (u.nombre LIKE ? OR u.codigo LIKE ? OR m.nombre LIKE ?)';
$params[] = '%' . $buscar . '%';
$params[] = '%' . $buscar . '%';
$params[] = '%' . $buscar . '%';
}
$sql .= ' ORDER BY u.codigo';
$stmt = $db->prepare($sql);
$stmt->execute($params);
$ubicaciones = $stmt->fetchAll();
$allForMap = $db->query('
SELECT u.codigo, m.nombre AS modulo, u.nombre AS ubicacion
FROM ubicaciones u JOIN modulos m ON m.id = u.modulo_id
WHERE u.activo = 1 ORDER BY u.codigo
')->fetchAll();
$filenameMap = buildQrFilenameMap($allForMap);
$qrList = [];
$qrGenerados = 0;
foreach ($ubicaciones as $u) {
$filename = $filenameMap[$u['codigo']] ?? null;
$path = $filename ? qrFilePathForUbicacion($u['modulo'], $u['ubicacion'], $u['codigo'], $filenameMap) : null;
$exists = $path !== null;
if ($exists) {
$qrGenerados++;
} }
if ($soloPendientes && $exists) {
continue;
}
$qrList[] = [
'id' => $u['id'],
'codigo' => $u['codigo'],
'modulo' => $u['modulo'],
'ubicacion'=> $u['ubicacion'],
'filename' => $filename,
'url' => $path ? BASE_URL . '/output/' . rawurlencode($filename) : null,
'exists' => $exists,
];
} }
$totalUbicaciones = (int) $db->query('SELECT COUNT(*) FROM ubicaciones WHERE activo = 1')->fetchColumn();
$totalQrFiles = 0;
if (is_dir($outputDir)) {
$totalQrFiles = count(array_filter(scandir($outputDir), fn($f) => str_ends_with($f, '.png')));
}
$modulos = $db->query('SELECT id, nombre FROM modulos WHERE activo = 1 ORDER BY nombre')->fetchAll();
$qrDataExists = file_exists(dirname(__DIR__) . '/qr_data.csv');
$logoExists = file_exists(dirname(__DIR__) . '/NEM.png');
$flash = getFlash();
$bulkUrl = 'download_qr.php?bulk=1' . ($moduloFiltro ? '&modulo_id=' . $moduloFiltro : '');
$filterQuery = http_build_query(array_filter([
'modulo_id' => $moduloFiltro ?: null,
'q' => $buscar ?: null,
'pendientes'=> $soloPendientes ? '1' : null,
]));
$topbarActions = ' $topbarActions = '
<a href="export_qr.php" class="btn btn-outline-primary btn-sm me-2"> <a href="export_qr.php" class="btn btn-outline-secondary btn-sm">
<span class="material-symbols-outlined align-middle" style="font-size:18px">download</span> Exportar CSV <span class="material-symbols-outlined align-middle" style="font-size:18px">table</span> CSV
</a>
<a href="' . h($bulkUrl) . '" class="btn btn-outline-primary btn-sm">
<span class="material-symbols-outlined align-middle" style="font-size:18px">folder_zip</span> ZIP masivo
</a> </a>
<form method="post" action="generate_qrs.php" class="d-inline" onsubmit="return confirm(\'¿Generar todos los QR? Puede tardar varios minutos.\');"> <form method="post" action="generate_qrs.php" class="d-inline" onsubmit="return confirm(\'¿Generar todos los QR? Puede tardar varios minutos.\');">
<button type="submit" class="btn btn-primary btn-sm"> <button type="submit" class="btn btn-primary btn-sm">
<span class="material-symbols-outlined align-middle" style="font-size:18px">qr_code_2</span> Generar QR <span class="material-symbols-outlined align-middle" style="font-size:18px">qr_code_2</span> Generar todos
</button> </button>
</form> </form>
'; ';
$extraJs = 'admin-qrs.js';
require_once __DIR__ . '/../includes/admin_header.php'; require_once __DIR__ . '/../includes/admin_header.php';
require_once __DIR__ . '/../config/database.php';
$db = getDB();
$totalUbicaciones = (int) $db->query('SELECT COUNT(*) FROM ubicaciones WHERE activo = 1')->fetchColumn();
$qrDataExists = file_exists(dirname(__DIR__) . '/qr_data.csv');
$logoExists = file_exists(dirname(__DIR__) . '/NEM.png');
$flash = getFlash();
?> ?>
<?php if ($flash): ?> <?php if ($flash): ?>
@ -44,64 +107,175 @@ $flash = getFlash();
</div> </div>
<?php endif; ?> <?php endif; ?>
<div class="row g-4"> <div class="row g-3 mb-4">
<div class="col-lg-5"> <div class="col-md-3">
<div class="card h-100"> <div class="card stat-card h-100">
<div class="card-header">Vista previa</div>
<div class="card-body"> <div class="card-body">
<div class="qr-preview-box"> <div class="text-muted small">Ubicaciones activas</div>
<?php if ($sampleFile): ?> <div class="h4 mb-0"><?= number_format($totalUbicaciones) ?></div>
<img src="<?= h(BASE_URL) ?>/output/<?= h(rawurlencode($sampleFile)) ?>" alt="QR ejemplo"> </div>
<p class="text-muted small mt-3 mb-0"><?= h($sampleFile) ?></p> </div>
<?php else: ?> </div>
<span class="material-symbols-outlined text-muted" style="font-size:64px">qr_code_2</span> <div class="col-md-3">
<p class="text-muted mt-3">Aún no hay QR generados.<br>Use el botón <strong>Generar QR</strong>.</p> <div class="card stat-card h-100">
<?php endif; ?> <div class="card-body">
<div class="text-muted small">QR generados</div>
<div class="h4 mb-0 <?= $qrGenerados >= count($ubicaciones) && count($ubicaciones) > 0 ? 'text-success' : 'text-warning' ?>">
<?= number_format($qrGenerados) ?> <span class="fs-6 text-muted">/ <?= count($ubicaciones) ?> filtradas</span>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<div class="col-md-3">
<div class="col-lg-7"> <div class="card stat-card h-100">
<div class="card mb-4">
<div class="card-header">Estado</div>
<ul class="list-group list-group-flush">
<li class="list-group-item d-flex justify-content-between">
<span>Ubicaciones activas</span>
<strong><?= number_format($totalUbicaciones) ?></strong>
</li>
<li class="list-group-item d-flex justify-content-between">
<span>QR en carpeta output/</span>
<strong class="<?= $qrCount >= $totalUbicaciones ? 'text-success' : 'text-warning' ?>"><?= number_format($qrCount) ?></strong>
</li>
<li class="list-group-item d-flex justify-content-between">
<span>Archivo qr_data.csv</span>
<?= $qrDataExists ? '<span class="badge bg-success">Listo</span>' : '<span class="badge bg-danger">Falta</span>' ?>
</li>
<li class="list-group-item d-flex justify-content-between">
<span>Logo NEM.png</span>
<?= $logoExists ? '<span class="badge bg-success">Presente</span>' : '<span class="badge bg-warning">No encontrado</span>' ?>
</li>
</ul>
</div>
<div class="card">
<div class="card-header">Formato de impresión</div>
<div class="card-body"> <div class="card-body">
<p class="mb-2">Los QR mantienen el mismo estilo que los anteriores:</p> <div class="text-muted small">Archivos en output/</div>
<ul class="mb-3"> <div class="h4 mb-0"><?= number_format($totalQrFiles) ?></div>
<li>Color azul campamento <code>#132A7C</code></li> </div>
<li>Logo <strong>NEM.png</strong> centrado en el código</li> </div>
<li>Pie de imagen: <em>Módulo | Habitación</em></li> </div>
<li>URL interna: <code>formulario.php?u=UB-XXXXX</code></li> <div class="col-md-3">
</ul> <div class="card stat-card h-100">
<p class="text-muted small mb-0"> <div class="card-body d-flex flex-column justify-content-center gap-1">
También puede generar desde terminal: <span><?= $qrDataExists ? '<span class="badge bg-success">CSV listo</span>' : '<span class="badge bg-danger">CSV falta</span>' ?></span>
<code>python3 generate_qrs.py</code> <span><?= $logoExists ? '<span class="badge bg-success">Logo NEM.png</span>' : '<span class="badge bg-warning">Sin logo</span>' ?></span>
</p>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<div class="card mb-4">
<div class="card-body">
<form method="get" class="row g-3 align-items-end">
<div class="col-md-4">
<label class="form-label">Módulo</label>
<select name="modulo_id" class="form-select">
<option value="">Todos los módulos</option>
<?php foreach ($modulos as $m): ?>
<option value="<?= (int) $m['id'] ?>" <?= $moduloFiltro === (int) $m['id'] ? 'selected' : '' ?>>
<?= h($m['nombre']) ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="col-md-4">
<label class="form-label">Buscar</label>
<input type="text" name="q" class="form-control" value="<?= h($buscar) ?>" placeholder="Código, habitación o módulo">
</div>
<div class="col-md-2">
<div class="form-check mt-4">
<input class="form-check-input" type="checkbox" name="pendientes" id="pendientes" value="1" <?= $soloPendientes ? 'checked' : '' ?>>
<label class="form-check-label" for="pendientes">Solo pendientes</label>
</div>
</div>
<div class="col-md-2 d-flex gap-2">
<button type="submit" class="btn btn-primary flex-grow-1">Filtrar</button>
<?php if ($filterQuery): ?>
<a href="qrs.php" class="btn btn-outline-secondary" title="Limpiar filtros">
<span class="material-symbols-outlined" style="font-size:20px">close</span>
</a>
<?php endif; ?>
</div>
</form>
</div>
</div>
<div class="card">
<div class="card-header d-flex flex-wrap justify-content-between align-items-center gap-2">
<span><?= count($qrList) ?> ubicación(es)</span>
<div class="d-flex flex-wrap gap-2 align-items-center">
<button type="button" class="btn btn-sm btn-outline-secondary" id="btnSelectAll">Seleccionar todos</button>
<button type="button" class="btn btn-sm btn-primary" id="btnDownloadSelected" disabled>
<span class="material-symbols-outlined align-middle" style="font-size:18px">download</span>
Descargar seleccionados (ZIP)
</button>
</div>
</div>
<div class="table-responsive">
<table class="table table-hover align-middle mb-0 qr-table">
<thead class="table-light">
<tr>
<th style="width:40px"><input type="checkbox" class="form-check-input" id="checkAll" title="Seleccionar todos"></th>
<th>Código</th>
<th>Módulo</th>
<th>Habitación</th>
<th>Estado</th>
<th class="text-end">Acciones</th>
</tr>
</thead>
<tbody>
<?php if (empty($qrList)): ?>
<tr><td colspan="6" class="text-center text-muted py-5">No hay ubicaciones con estos filtros.</td></tr>
<?php else: ?>
<?php foreach ($qrList as $qr): ?>
<tr class="<?= $qr['exists'] ? '' : 'qr-row-pending' ?>">
<td>
<?php if ($qr['exists']): ?>
<input type="checkbox" class="form-check-input qr-check" value="<?= h($qr['codigo']) ?>">
<?php endif; ?>
</td>
<td><code class="badge-codigo"><?= h($qr['codigo']) ?></code></td>
<td><?= h($qr['modulo']) ?></td>
<td><?= h($qr['ubicacion']) ?></td>
<td>
<?php if ($qr['exists']): ?>
<span class="badge bg-success-subtle text-success border border-success-subtle">Generado</span>
<?php else: ?>
<span class="badge bg-warning-subtle text-warning-emphasis border border-warning-subtle">Pendiente</span>
<?php endif; ?>
</td>
<td class="text-end text-nowrap">
<?php if ($qr['exists']): ?>
<button type="button" class="btn btn-sm btn-outline-primary btn-qr-preview"
data-codigo="<?= h($qr['codigo']) ?>"
data-modulo="<?= h($qr['modulo']) ?>"
data-ubicacion="<?= h($qr['ubicacion']) ?>"
data-url="<?= h($qr['url']) ?>"
data-filename="<?= h($qr['filename']) ?>">
<span class="material-symbols-outlined align-middle" style="font-size:18px">visibility</span>
</button>
<a href="download_qr.php?codigo=<?= urlencode($qr['codigo']) ?>" class="btn btn-sm btn-primary" title="Descargar PNG">
<span class="material-symbols-outlined align-middle" style="font-size:18px">download</span>
</a>
<?php else: ?>
<span class="text-muted small">Genere QR primero</span>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
<div class="modal fade" id="qrPreviewModal" tabindex="-1" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="qrPreviewTitle">Vista previa QR</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body text-center">
<div class="qr-preview-box mb-3">
<img id="qrPreviewImg" src="" alt="QR" class="img-fluid">
</div>
<p class="mb-1"><code id="qrPreviewCodigo"></code></p>
<p class="text-muted small mb-0" id="qrPreviewCaption"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
<a href="#" id="qrPreviewDownload" class="btn btn-primary">
<span class="material-symbols-outlined align-middle" style="font-size:18px">download</span>
Descargar PNG
</a>
</div>
</div>
</div>
</div>
<form id="formBulkSelected" method="get" action="download_qr.php" class="d-none">
<input type="hidden" name="bulk" value="1">
</form>
<?php require_once __DIR__ . '/../includes/admin_footer.php'; ?> <?php require_once __DIR__ . '/../includes/admin_footer.php'; ?>

View file

@ -29,6 +29,17 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$db->prepare('UPDATE servicios SET nombre = ?, activo = ? WHERE id = ?')->execute([$nombre, $activo, $id]); $db->prepare('UPDATE servicios SET nombre = ?, activo = ? WHERE id = ?')->execute([$nombre, $activo, $id]);
flash('success', 'Servicio actualizado.'); flash('success', 'Servicio actualizado.');
} }
} elseif ($action === 'delete') {
$id = (int) ($_POST['id'] ?? 0);
if ($id > 0) {
$registros = countRegistrosForServicio($db, $id);
if ($registros > 0) {
flash('danger', "No se puede eliminar: tiene {$registros} registro(s) asociado(s). Desactívelo en su lugar.");
} else {
$db->prepare('DELETE FROM servicios WHERE id = ?')->execute([$id]);
flash('success', 'Servicio eliminado.');
}
}
} }
redirect(BASE_URL . '/admin/servicios.php' . ($empresaFiltro ? '?empresa_id='.$empresaFiltro : '')); redirect(BASE_URL . '/admin/servicios.php' . ($empresaFiltro ? '?empresa_id='.$empresaFiltro : ''));
} }
@ -92,14 +103,29 @@ require_once __DIR__ . '/../includes/admin_header.php';
<tbody> <tbody>
<?php foreach ($servicios as $s): ?> <?php foreach ($servicios as $s): ?>
<tr> <tr>
<form method="post"> <td><?= h($s['empresa']) ?></td>
<input type="hidden" name="action" value="update"> <td>
<input type="hidden" name="id" value="<?= (int) $s['id'] ?>"> <form method="post" class="d-flex gap-2 align-items-center">
<td><?= h($s['empresa']) ?></td> <input type="hidden" name="action" value="update">
<td><input type="text" name="nombre" class="form-control form-control-sm" value="<?= h($s['nombre']) ?>" required></td> <input type="hidden" name="id" value="<?= (int) $s['id'] ?>">
<td><div class="form-check form-switch"><input class="form-check-input" type="checkbox" name="activo" <?= $s['activo'] ? 'checked' : '' ?>></div></td> <input type="text" name="nombre" class="form-control form-control-sm" value="<?= h($s['nombre']) ?>" required>
<td><button type="submit" class="btn btn-sm btn-primary">Guardar</button></td> </td>
</form> <td>
<div class="form-check form-switch mb-0">
<input class="form-check-input" type="checkbox" name="activo" <?= $s['activo'] ? 'checked' : '' ?>>
</div>
</td>
<td class="text-nowrap">
<button type="submit" class="btn btn-sm btn-primary">Guardar</button>
</form>
<form method="post" class="d-inline" onsubmit="return confirm('¿Eliminar el servicio «<?= h($s['nombre']) ?>»?');">
<input type="hidden" name="action" value="delete">
<input type="hidden" name="id" value="<?= (int) $s['id'] ?>">
<button type="submit" class="btn btn-sm btn-outline-danger" title="Eliminar">
<span class="material-symbols-outlined align-middle" style="font-size:18px">delete</span>
</button>
</form>
</td>
</tr> </tr>
<?php endforeach; ?> <?php endforeach; ?>
</tbody> </tbody>

View file

@ -37,9 +37,11 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if ($nom === '') continue; if ($nom === '') continue;
$codigo = nextUbicacionCodigo($db); $codigo = nextUbicacionCodigo($db);
$stmtIns->execute([$codigo, $moduloId, $nom]); $stmtIns->execute([$codigo, $moduloId, $nom]);
appendUbicacionToQrCsv($codigo, $modulo['nombre'], $nom);
$creadas[] = $codigo; $creadas[] = $codigo;
} }
if ($creadas) {
regenerateQrCsv($db);
}
$total = count($creadas); $total = count($creadas);
$msg = $total === 1 $msg = $total === 1
? "Ubicación {$creadas[0]} creada. Genere su QR en Códigos QR." ? "Ubicación {$creadas[0]} creada. Genere su QR en Códigos QR."
@ -48,6 +50,33 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$redirectParams['modulo_id'] = $moduloId; $redirectParams['modulo_id'] = $moduloId;
} }
} }
} elseif ($action === 'delete') {
$id = (int) ($_POST['id'] ?? 0);
if ($id > 0) {
$registros = countRegistrosForUbicacion($db, $id);
if ($registros > 0) {
flash('danger', "No se puede eliminar: tiene {$registros} registro(s) asociado(s). Desactívela en su lugar.");
} else {
$stmt = $db->prepare('
SELECT u.codigo, u.nombre AS ubicacion, m.nombre AS modulo
FROM ubicaciones u JOIN modulos m ON m.id = u.modulo_id
WHERE u.id = ?
');
$stmt->execute([$id]);
$ub = $stmt->fetch();
if ($ub) {
$allRows = $db->query('
SELECT u.codigo, m.nombre AS modulo, u.nombre AS ubicacion
FROM ubicaciones u JOIN modulos m ON m.id = u.modulo_id
')->fetchAll();
$map = buildQrFilenameMap($allRows);
deleteQrFileForUbicacion($ub['modulo'], $ub['ubicacion'], $ub['codigo'], $map);
$db->prepare('DELETE FROM ubicaciones WHERE id = ?')->execute([$id]);
regenerateQrCsv($db);
flash('success', 'Ubicación eliminada.');
}
}
}
} else { } else {
$id = (int) ($_POST['id'] ?? 0); $id = (int) ($_POST['id'] ?? 0);
$nombre = trim($_POST['nombre'] ?? ''); $nombre = trim($_POST['nombre'] ?? '');
@ -158,16 +187,31 @@ require_once __DIR__ . '/../includes/admin_header.php';
<?php else: ?> <?php else: ?>
<?php foreach ($ubicaciones as $u): ?> <?php foreach ($ubicaciones as $u): ?>
<tr> <tr>
<form method="post"> <td><code class="badge-codigo"><?= h($u['codigo']) ?></code></td>
<input type="hidden" name="action" value="update"> <td class="small"><?= h($u['modulo_nombre']) ?></td>
<input type="hidden" name="id" value="<?= (int) $u['id'] ?>"> <td>
<td><code class="badge-codigo"><?= h($u['codigo']) ?></code></td> <form method="post" class="d-flex gap-2 align-items-center">
<td class="small"><?= h($u['modulo_nombre']) ?></td> <input type="hidden" name="action" value="update">
<td><input type="text" name="nombre" class="form-control form-control-sm" value="<?= h($u['nombre']) ?>" required></td> <input type="hidden" name="id" value="<?= (int) $u['id'] ?>">
<td class="small"><a href="<?= h(BASE_URL) ?>/formulario.php?u=<?= h($u['codigo']) ?>" target="_blank">Abrir</a></td> <input type="text" name="nombre" class="form-control form-control-sm" value="<?= h($u['nombre']) ?>" required>
<td><div class="form-check form-switch"><input class="form-check-input" type="checkbox" name="activo" <?= $u['activo'] ? 'checked' : '' ?>></div></td> </td>
<td><button type="submit" class="btn btn-sm btn-primary">Guardar</button></td> <td class="small"><a href="<?= h(BASE_URL) ?>/formulario.php?u=<?= h($u['codigo']) ?>" target="_blank">Abrir</a></td>
</form> <td>
<div class="form-check form-switch mb-0">
<input class="form-check-input" type="checkbox" name="activo" <?= $u['activo'] ? 'checked' : '' ?>>
</div>
</td>
<td class="text-nowrap">
<button type="submit" class="btn btn-sm btn-primary">Guardar</button>
</form>
<form method="post" class="d-inline" onsubmit="return confirm('¿Eliminar la ubicación <?= h($u['codigo']) ?>? Esta acción no se puede deshacer.');">
<input type="hidden" name="action" value="delete">
<input type="hidden" name="id" value="<?= (int) $u['id'] ?>">
<button type="submit" class="btn btn-sm btn-outline-danger" title="Eliminar">
<span class="material-symbols-outlined align-middle" style="font-size:18px">delete</span>
</button>
</form>
</td>
</tr> </tr>
<?php endforeach; ?> <?php endforeach; ?>
<?php endif; ?> <?php endif; ?>

View file

@ -166,6 +166,26 @@
height: auto; height: auto;
} }
.qr-table .badge-codigo {
font-size: 0.8rem;
}
.qr-row-pending {
background: rgba(255, 193, 7, 0.06);
}
.bg-success-subtle {
background-color: rgba(25, 135, 84, 0.12) !important;
}
.bg-warning-subtle {
background-color: rgba(255, 193, 7, 0.15) !important;
}
#qrPreviewModal .qr-preview-box img {
max-width: 100%;
}
.quick-link-card { .quick-link-card {
transition: transform 0.15s, box-shadow 0.15s; transition: transform 0.15s, box-shadow 0.15s;
cursor: pointer; cursor: pointer;

74
assets/js/admin-qrs.js Normal file
View file

@ -0,0 +1,74 @@
document.addEventListener('DOMContentLoaded', function () {
var checks = document.querySelectorAll('.qr-check');
var checkAll = document.getElementById('checkAll');
var btnSelectAll = document.getElementById('btnSelectAll');
var btnDownloadSelected = document.getElementById('btnDownloadSelected');
var formBulk = document.getElementById('formBulkSelected');
var previewModal = document.getElementById('qrPreviewModal');
function updateBulkButton() {
if (!btnDownloadSelected) return;
var selected = document.querySelectorAll('.qr-check:checked');
btnDownloadSelected.disabled = selected.length === 0;
btnDownloadSelected.innerHTML =
'<span class="material-symbols-outlined align-middle" style="font-size:18px">download</span> ' +
'Descargar seleccionados (' + selected.length + ')';
}
checks.forEach(function (cb) {
cb.addEventListener('change', updateBulkButton);
});
if (checkAll) {
checkAll.addEventListener('change', function () {
checks.forEach(function (cb) {
cb.checked = checkAll.checked;
});
updateBulkButton();
});
}
if (btnSelectAll) {
btnSelectAll.addEventListener('click', function () {
var allChecked = Array.from(checks).every(function (cb) { return cb.checked; });
checks.forEach(function (cb) {
cb.checked = !allChecked;
});
if (checkAll) checkAll.checked = !allChecked;
updateBulkButton();
});
}
if (btnDownloadSelected && formBulk) {
btnDownloadSelected.addEventListener('click', function () {
formBulk.querySelectorAll('input[name="codes[]"]').forEach(function (el) { el.remove(); });
document.querySelectorAll('.qr-check:checked').forEach(function (cb) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = 'codes[]';
input.value = cb.value;
formBulk.appendChild(input);
});
formBulk.submit();
});
}
document.querySelectorAll('.btn-qr-preview').forEach(function (btn) {
btn.addEventListener('click', function () {
var codigo = btn.dataset.codigo;
var modulo = btn.dataset.modulo;
var ubicacion = btn.dataset.ubicacion;
var url = btn.dataset.url;
document.getElementById('qrPreviewTitle').textContent = ubicacion + ' — ' + codigo;
document.getElementById('qrPreviewImg').src = url + '?t=' + Date.now();
document.getElementById('qrPreviewCodigo').textContent = codigo;
document.getElementById('qrPreviewCaption').textContent = modulo + ' | ' + ubicacion;
document.getElementById('qrPreviewDownload').href = 'download_qr.php?codigo=' + encodeURIComponent(codigo);
if (previewModal && window.bootstrap) {
bootstrap.Modal.getOrCreateInstance(previewModal).show();
}
});
});
updateBulkButton();
});

45
import_faltantes.php Normal file
View file

@ -0,0 +1,45 @@
<?php
/**
* Importa ubicaciones desde Faltantes.csv (columnas: módulo, habitación).
* CLI: php import_faltantes.php
* Web: requiere sesión admin.
*/
set_time_limit(120);
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/includes/functions.php';
$isCli = PHP_SAPI === 'cli';
if (!$isCli) {
require_once __DIR__ . '/includes/auth.php';
requireAdmin();
}
$csvPath = __DIR__ . '/Faltantes.csv';
try {
$db = getDB();
$result = importModuloUbicacionCsv($db, $csvPath);
$msg = sprintf(
'Importación completada: %d módulo(s) nuevo(s), %d ubicación(es) creada(s), %d omitida(s) (ya existían).',
$result['modulos_nuevos'],
$result['creadas'],
$result['omitidas']
);
if ($isCli) {
echo $msg . PHP_EOL;
exit(0);
}
flash('success', $msg);
} catch (Throwable $e) {
if ($isCli) {
fwrite(STDERR, 'Error: ' . $e->getMessage() . PHP_EOL);
exit(1);
}
flash('danger', 'Error al importar: ' . $e->getMessage());
}
redirect(BASE_URL . '/admin/ubicaciones.php');

View file

@ -63,14 +63,259 @@ function nextUbicacionCodigo(PDO $db): string
return sprintf('UB-%05d', $num + 1); return sprintf('UB-%05d', $num + 1);
} }
function appendUbicacionToQrCsv(string $codigo, string $modulo, string $ubicacion): void function seedEmpresasServicios(PDO $db, bool $onlyIfEmpty = false): void
{
$count = (int) $db->query('SELECT COUNT(*) FROM empresas')->fetchColumn();
if ($count > 0 && $onlyIfEmpty) {
return;
}
if ($count > 0 && !$onlyIfEmpty) {
return;
}
$db->exec('DELETE FROM servicios');
$db->exec('DELETE FROM empresas');
$empresas = ['SODEXO', 'REYSAP', 'MTTO CAMP', 'SmartService'];
$stmt = $db->prepare('INSERT INTO empresas (nombre) VALUES (?)');
foreach ($empresas as $e) {
$stmt->execute([$e]);
}
$servicios = [
'SODEXO' => ['Limpieza / Supervisión', 'Fumigación'],
'REYSAP' => ['Servicio de Mantenimiento'],
'MTTO CAMP' => ['Mtto Preventivo', 'Mtto Correctivo'],
'SmartService' => ['Mtto Cocina'],
];
$stmtSrv = $db->prepare('
INSERT INTO servicios (empresa_id, nombre)
SELECT id, ? FROM empresas WHERE nombre = ?
');
foreach ($servicios as $empresa => $lista) {
foreach ($lista as $srv) {
$stmtSrv->execute([$srv, $empresa]);
}
}
}
function importDataCsv(PDO $db, string $path): array
{
if (!file_exists($path)) {
throw new RuntimeException('No se encontró ' . basename($path));
}
$moduloMap = [];
$modCounter = 0;
$ubCounter = 0;
$stmtMod = $db->prepare('INSERT INTO modulos (codigo, nombre) VALUES (?, ?)');
$stmtUb = $db->prepare('INSERT INTO ubicaciones (codigo, modulo_id, nombre) VALUES (?, ?, ?)');
$fh = fopen($path, 'r');
fgetcsv($fh, 0, ',', '"', '\\');
$db->beginTransaction();
try {
while (($row = fgetcsv($fh, 0, ',', '"', '\\')) !== false) {
if (empty($row[0])) {
continue;
}
$modNombre = trim(mb_convert_encoding($row[2], 'UTF-8', 'ISO-8859-1'));
$ubNombre = trim(mb_convert_encoding($row[4], 'UTF-8', 'ISO-8859-1'));
if (!isset($moduloMap[$modNombre])) {
$modCounter++;
$modCodigo = sprintf('MOD-%03d', $modCounter);
$stmtMod->execute([$modCodigo, $modNombre]);
$moduloMap[$modNombre] = (int) $db->lastInsertId();
}
$ubCounter++;
$ubCodigo = sprintf('UB-%05d', $ubCounter);
$stmtUb->execute([$ubCodigo, $moduloMap[$modNombre], $ubNombre]);
}
$db->commit();
} catch (Throwable $e) {
$db->rollBack();
throw $e;
} finally {
fclose($fh);
}
return ['modulos' => $modCounter, 'ubicaciones' => $ubCounter];
}
/**
* Importa CSV módulo,ubicación (p. ej. Faltantes.csv: R1,R2).
* @return array{modulos_nuevos: int, creadas: int, omitidas: int}
*/
function importModuloUbicacionCsv(PDO $db, string $path): array
{
if (!file_exists($path)) {
throw new RuntimeException('No se encontró ' . basename($path));
}
$stmtModByName = $db->prepare('SELECT id FROM modulos WHERE nombre = ?');
$stmtInsMod = $db->prepare('INSERT INTO modulos (codigo, nombre) VALUES (?, ?)');
$stmtExists = $db->prepare('
SELECT u.id FROM ubicaciones u
JOIN modulos m ON m.id = u.modulo_id
WHERE m.nombre = ? AND u.nombre = ?
');
$stmtInsUb = $db->prepare('INSERT INTO ubicaciones (codigo, modulo_id, nombre) VALUES (?, ?, ?)');
$modulosNuevos = 0;
$creadas = 0;
$omitidas = 0;
$fh = fopen($path, 'r');
$first = fgetcsv($fh, 0, ',', '"', '\\');
$hasHeader = $first && in_array(strtoupper(trim($first[0] ?? '')), ['R1', 'MODULO', 'MÓDULO', 'MODULE'], true);
$db->beginTransaction();
try {
if (!$hasHeader && $first) {
$rows = [$first];
} else {
$rows = [];
}
while (($row = fgetcsv($fh, 0, ',', '"', '\\')) !== false) {
$rows[] = $row;
}
foreach ($rows as $row) {
if (count($row) < 2) {
continue;
}
$modNombre = trim($row[0]);
$ubNombre = trim($row[1]);
if ($modNombre === '' || $ubNombre === '') {
continue;
}
$stmtModByName->execute([$modNombre]);
$moduloId = $stmtModByName->fetchColumn();
if (!$moduloId) {
$codigo = nextModuloCodigo($db);
$stmtInsMod->execute([$codigo, $modNombre]);
$moduloId = (int) $db->lastInsertId();
$modulosNuevos++;
} else {
$moduloId = (int) $moduloId;
}
$stmtExists->execute([$modNombre, $ubNombre]);
if ($stmtExists->fetchColumn()) {
$omitidas++;
continue;
}
$ubCodigo = nextUbicacionCodigo($db);
$stmtInsUb->execute([$ubCodigo, $moduloId, $ubNombre]);
$creadas++;
}
$db->commit();
} catch (Throwable $e) {
$db->rollBack();
throw $e;
} finally {
fclose($fh);
}
if ($creadas > 0) {
regenerateQrCsv($db);
}
return ['modulos_nuevos' => $modulosNuevos, 'creadas' => $creadas, 'omitidas' => $omitidas];
}
function safeQrFilename(string $text): string
{
return preg_replace('/[\\\\\/:*?"<>|]/', '-', $text);
}
/** @return array<string, string> codigo => filename.png */
function buildQrFilenameMap(array $ubicaciones): array
{
$used = [];
$map = [];
foreach ($ubicaciones as $u) {
$base = safeQrFilename($u['modulo']) . '_' . safeQrFilename($u['ubicacion']);
$filename = $base . '.png';
if (isset($used[$filename])) {
$filename = $base . '_' . safeQrFilename($u['codigo']) . '.png';
}
$used[$filename] = true;
$map[$u['codigo']] = $filename;
}
return $map;
}
function regenerateQrCsv(PDO $db): void
{ {
$path = dirname(__DIR__) . '/qr_data.csv'; $path = dirname(__DIR__) . '/qr_data.csv';
$exists = file_exists($path); $rows = $db->query('
$fh = fopen($path, 'a'); SELECT u.codigo, m.nombre AS modulo, u.nombre AS ubicacion
if (!$exists) { FROM ubicaciones u
fputcsv($fh, ['codigo', 'modulo', 'ubicacion', 'url']); JOIN modulos m ON m.id = u.modulo_id
WHERE u.activo = 1
ORDER BY u.codigo
')->fetchAll();
$fh = fopen($path, 'w');
fputcsv($fh, ['codigo', 'modulo', 'ubicacion', 'url'], ',', '"', '\\');
foreach ($rows as $r) {
fputcsv($fh, [
$r['codigo'],
$r['modulo'],
$r['ubicacion'],
BASE_URL . '/formulario.php?u=' . $r['codigo'],
], ',', '"', '\\');
} }
fputcsv($fh, [$codigo, $modulo, $ubicacion, BASE_URL . '/formulario.php?u=' . $codigo]);
fclose($fh); fclose($fh);
} }
function qrOutputDir(): string
{
return dirname(__DIR__) . '/output';
}
function qrFilePathForUbicacion(string $modulo, string $ubicacion, string $codigo, array $filenameMap): ?string
{
$filename = $filenameMap[$codigo] ?? null;
if (!$filename) {
return null;
}
$path = qrOutputDir() . '/' . $filename;
return is_file($path) ? $path : null;
}
function deleteQrFileForUbicacion(string $modulo, string $ubicacion, string $codigo, array $filenameMap): void
{
$path = qrFilePathForUbicacion($modulo, $ubicacion, $codigo, $filenameMap);
if ($path) {
@unlink($path);
}
}
function countRegistrosForUbicacion(PDO $db, int $id): int
{
$stmt = $db->prepare('SELECT COUNT(*) FROM registros WHERE ubicacion_id = ?');
$stmt->execute([$id]);
return (int) $stmt->fetchColumn();
}
function countRegistrosForEmpresa(PDO $db, int $id): int
{
$stmt = $db->prepare('SELECT COUNT(*) FROM registros WHERE empresa_id = ?');
$stmt->execute([$id]);
return (int) $stmt->fetchColumn();
}
function countRegistrosForServicio(PDO $db, int $id): int
{
$stmt = $db->prepare('SELECT COUNT(*) FROM registros WHERE servicio_id = ?');
$stmt->execute([$id]);
return (int) $stmt->fetchColumn();
}

View file

@ -6,6 +6,7 @@
set_time_limit(300); set_time_limit(300);
require_once __DIR__ . '/config/config.php'; require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/config/database.php'; require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/includes/functions.php';
$messages = []; $messages = [];
$errors = []; $errors = [];
@ -26,47 +27,8 @@ try {
if ($countModulos > 0) { if ($countModulos > 0) {
$messages[] = 'Los datos ya estaban importados. No se repite la importación.'; $messages[] = 'Los datos ya estaban importados. No se repite la importación.';
} else { } else {
$csvFile = __DIR__ . '/data.csv'; $stats = importDataCsv($db, __DIR__ . '/data.csv');
if (!file_exists($csvFile)) { $messages[] = "Importados {$stats['modulos']} módulos y {$stats['ubicaciones']} ubicaciones desde data.csv.";
throw new RuntimeException('No se encontró data.csv');
}
$moduloMap = [];
$modCounter = 0;
$ubCounter = 0;
$stmtMod = $db->prepare('INSERT INTO modulos (codigo, nombre) VALUES (?, ?)');
$stmtUb = $db->prepare('INSERT INTO ubicaciones (codigo, modulo_id, nombre) VALUES (?, ?, ?)');
$fh = fopen($csvFile, 'r');
fgetcsv($fh, 0, ',', '"', '\\');
$db->beginTransaction();
while (($row = fgetcsv($fh, 0, ',', '"', '\\')) !== false) {
if (empty($row[0])) {
continue;
}
$modNombre = trim(mb_convert_encoding($row[2], 'UTF-8', 'ISO-8859-1'));
$ubNombre = trim(mb_convert_encoding($row[4], 'UTF-8', 'ISO-8859-1'));
if (!isset($moduloMap[$modNombre])) {
$modCounter++;
$modCodigo = sprintf('MOD-%03d', $modCounter);
$stmtMod->execute([$modCodigo, $modNombre]);
$moduloMap[$modNombre] = [
'id' => (int) $db->lastInsertId(),
'codigo' => $modCodigo,
];
}
$ubCounter++;
$ubCodigo = sprintf('UB-%05d', $ubCounter);
$stmtUb->execute([$ubCodigo, $moduloMap[$modNombre]['id'], $ubNombre]);
}
fclose($fh);
$db->commit();
$messages[] = "Importados {$modCounter} módulos y {$ubCounter} ubicaciones desde data.csv.";
} }
seedEmpresasServicios($db, true); seedEmpresasServicios($db, true);
@ -76,8 +38,7 @@ try {
$messages[] = 'Usuario admin creado (usuario: admin, contraseña: admin123).'; $messages[] = 'Usuario admin creado (usuario: admin, contraseña: admin123).';
} }
$exportFile = __DIR__ . '/qr_data.csv'; regenerateQrCsv($db);
exportQrCsv($db, $exportFile);
$messages[] = "Archivo qr_data.csv generado para el script de QR's."; $messages[] = "Archivo qr_data.csv generado para el script de QR's.";
} catch (Throwable $e) { } catch (Throwable $e) {
@ -87,65 +48,6 @@ try {
$errors[] = $e->getMessage(); $errors[] = $e->getMessage();
} }
function seedEmpresasServicios(PDO $db, bool $onlyIfEmpty = false): void
{
$count = (int) $db->query('SELECT COUNT(*) FROM empresas')->fetchColumn();
if ($onlyIfEmpty && $count > 0) {
return;
}
if (!$onlyIfEmpty && $count > 0) {
return;
}
$db->exec('DELETE FROM servicios');
$db->exec('DELETE FROM empresas');
$empresas = ['SODEXO', 'REYSAP', 'MTTO CAMP', 'SmartService'];
$stmt = $db->prepare('INSERT INTO empresas (nombre) VALUES (?)');
foreach ($empresas as $e) {
$stmt->execute([$e]);
}
$servicios = [
'SODEXO' => ['Limpieza / Supervisión', 'Fumigación'],
'REYSAP' => ['Servicio de Mantenimiento'],
'MTTO CAMP' => ['Mtto Preventivo', 'Mtto Correctivo'],
'SmartService' => ['Mtto Cocina'],
];
$stmtSrv = $db->prepare('
INSERT INTO servicios (empresa_id, nombre)
SELECT id, ? FROM empresas WHERE nombre = ?
');
foreach ($servicios as $empresa => $lista) {
foreach ($lista as $srv) {
$stmtSrv->execute([$srv, $empresa]);
}
}
}
function exportQrCsv(PDO $db, string $path): void
{
$rows = $db->query('
SELECT u.codigo, m.nombre AS modulo, u.nombre AS ubicacion
FROM ubicaciones u
JOIN modulos m ON m.id = u.modulo_id
WHERE u.activo = 1
ORDER BY u.codigo
')->fetchAll();
$fh = fopen($path, 'w');
fputcsv($fh, ['codigo', 'modulo', 'ubicacion', 'url']);
foreach ($rows as $r) {
fputcsv($fh, [
$r['codigo'],
$r['modulo'],
$r['ubicacion'],
BASE_URL . '/formulario.php?u=' . $r['codigo'],
]);
}
fclose($fh);
}
$pageTitle = 'Instalación'; $pageTitle = 'Instalación';
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
@ -173,7 +75,7 @@ $pageTitle = 'Instalación';
<p class="mb-3">El sistema está listo. Los QR deben apuntar a:</p> <p class="mb-3">El sistema está listo. Los QR deben apuntar a:</p>
<code><?= htmlspecialchars(BASE_URL) ?>/formulario.php?u=UB-00001</code> <code><?= htmlspecialchars(BASE_URL) ?>/formulario.php?u=UB-00001</code>
<div class="mt-4 d-flex gap-2"> <div class="mt-4 d-flex gap-2">
<a href="index.php" class="btn btn-primary">Ir al panel</a> <a href="admin/index.php" class="btn btn-primary">Ir al panel</a>
<a href="formulario.php?u=UB-00001" class="btn btn-outline-secondary">Probar formulario</a> <a href="formulario.php?u=UB-00001" class="btn btn-outline-secondary">Probar formulario</a>
</div> </div>
<?php endif; ?> <?php endif; ?>

File diff suppressed because it is too large Load diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

View file

@ -1,53 +0,0 @@
-- Migración: empresas y servicios (reemplaza proveedores/tipos genéricos)
USE mantenimiento_campamento;
CREATE TABLE IF NOT EXISTS empresas (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
nombre VARCHAR(150) NOT NULL UNIQUE,
activo TINYINT(1) NOT NULL DEFAULT 1,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS servicios (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
empresa_id INT UNSIGNED NOT NULL,
nombre VARCHAR(150) NOT NULL,
activo TINYINT(1) NOT NULL DEFAULT 1,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (empresa_id) REFERENCES empresas(id) ON DELETE CASCADE,
UNIQUE KEY uk_empresa_servicio (empresa_id, nombre)
) ENGINE=InnoDB;
-- Recrear tabla registros con nueva estructura
DROP TABLE IF EXISTS registros;
CREATE TABLE registros (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
ubicacion_id INT UNSIGNED NOT NULL,
empresa_id INT UNSIGNED NOT NULL,
servicio_id INT UNSIGNED NOT NULL,
observaciones TEXT,
registrado_por VARCHAR(100),
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (ubicacion_id) REFERENCES ubicaciones(id) ON DELETE RESTRICT,
FOREIGN KEY (empresa_id) REFERENCES empresas(id) ON DELETE RESTRICT,
FOREIGN KEY (servicio_id) REFERENCES servicios(id) ON DELETE RESTRICT,
INDEX idx_fecha (created_at),
INDEX idx_ubicacion (ubicacion_id)
) ENGINE=InnoDB;
-- Catálogos según formulario original
DELETE FROM servicios;
DELETE FROM empresas;
INSERT INTO empresas (nombre) VALUES
('SODEXO'), ('REYSAP'), ('MTTO CAMP'), ('SmartService');
INSERT INTO servicios (empresa_id, nombre) VALUES
((SELECT id FROM empresas WHERE nombre='SODEXO'), 'Limpieza / Supervisión'),
((SELECT id FROM empresas WHERE nombre='SODEXO'), 'Fumigación'),
((SELECT id FROM empresas WHERE nombre='REYSAP'), 'Servicio de Mantenimiento'),
((SELECT id FROM empresas WHERE nombre='MTTO CAMP'), 'Mtto Preventivo'),
((SELECT id FROM empresas WHERE nombre='MTTO CAMP'), 'Mtto Correctivo'),
((SELECT id FROM empresas WHERE nombre='SmartService'), 'Mtto Cocina');

View file

@ -1,10 +0,0 @@
USE mantenimiento_campamento;
CREATE TABLE IF NOT EXISTS usuarios (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
usuario VARCHAR(50) NOT NULL UNIQUE,
password_hash VARCHAR(255) NOT NULL,
nombre VARCHAR(100),
activo TINYINT(1) NOT NULL DEFAULT 1,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;