Initial commit
This commit is contained in:
commit
b4f97df3a8
42 changed files with 7875 additions and 0 deletions
BIN
.DS_Store
vendored
Normal file
BIN
.DS_Store
vendored
Normal file
Binary file not shown.
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
# Códigos QR generados (regenerables con generate_qrs.py)
|
||||
output/
|
||||
BIN
NEM.png
Normal file
BIN
NEM.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 48 KiB |
305
README.md
Normal file
305
README.md
Normal file
|
|
@ -0,0 +1,305 @@
|
|||
# Sistema de Mantenimiento por QR — Campamento
|
||||
|
||||
Sistema web para registrar actividades de mantenimiento en un campamento minero. Reemplaza el flujo anterior basado en **Microsoft Forms** por una aplicación propia en **PHP + MySQL/MariaDB**, con códigos QR físicos en cada ubicación.
|
||||
|
||||
Al escanear un QR, el técnico abre un formulario con **módulo** y **habitación ya prellenados**. Solo debe indicar la **empresa** que realizó el servicio y el **tipo de servicio** correspondiente.
|
||||
|
||||
---
|
||||
|
||||
## ¿Qué problema resuelve?
|
||||
|
||||
- Evita que el personal escriba manualmente el lugar (errores de captura).
|
||||
- Centraliza todos los registros en una base de datos consultable.
|
||||
- Permite **renombrar módulos y habitaciones** sin reimprimir QR, gracias a identificadores únicos estables.
|
||||
- Genera etiquetas QR con el **mismo estilo visual** de la versión anterior (color azul `#132A7C`, logo `NEM.png`, pie con nombre del lugar).
|
||||
|
||||
---
|
||||
|
||||
## Arquitectura general
|
||||
|
||||
```
|
||||
┌─────────────┐ escaneo ┌──────────────────┐
|
||||
│ QR físico │ ───────────────► │ formulario.php │
|
||||
│ en campo │ ?u=UB-00001 │ (formulario) │
|
||||
└─────────────┘ └────────┬─────────┘
|
||||
│ POST
|
||||
▼
|
||||
┌──────────────────┐
|
||||
│ MariaDB │
|
||||
│ registros, etc. │
|
||||
└────────┬─────────┘
|
||||
│
|
||||
▼
|
||||
┌──────────────────┐
|
||||
│ Panel admin │
|
||||
│ /admin/ │
|
||||
└──────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Requisitos
|
||||
|
||||
| Componente | Versión / detalle |
|
||||
|------------|-------------------|
|
||||
| PHP | 8.0+ (extensiones `pdo_mysql`, `mbstring`) |
|
||||
| MariaDB / MySQL | localhost |
|
||||
| Python 3 | Solo para generar QR (`qrcode`, `Pillow`) |
|
||||
| Servidor web | Apache, Nginx o `php -S` |
|
||||
|
||||
---
|
||||
|
||||
## Instalación
|
||||
|
||||
### 1. Base de datos
|
||||
|
||||
Editar credenciales en `config/config.php` si es necesario:
|
||||
|
||||
```php
|
||||
define('DB_HOST', 'localhost');
|
||||
define('DB_NAME', 'mantenimiento_campamento');
|
||||
define('DB_USER', 'root');
|
||||
define('DB_PASS', 'R3m4st3r');
|
||||
define('BASE_URL', 'http://localhost:8080'); // Ajustar a su URL real
|
||||
```
|
||||
|
||||
### 2. Ejecutar instalador
|
||||
|
||||
Abrir en el navegador o ejecutar por CLI:
|
||||
|
||||
```
|
||||
http://localhost:8080/install.php
|
||||
```
|
||||
|
||||
El instalador:
|
||||
|
||||
- Crea la base de datos y tablas.
|
||||
- Importa **2 518 ubicaciones** desde `data.csv` (archivo original del proyecto).
|
||||
- Asigna códigos únicos a cada módulo (`MOD-001`…) y ubicación (`UB-00001`…).
|
||||
- Carga catálogos de **empresas** y **servicios**.
|
||||
- Crea el usuario administrador inicial.
|
||||
- Genera `qr_data.csv` para el script de QR.
|
||||
|
||||
### 3. Dependencias Python (QR)
|
||||
|
||||
```bash
|
||||
pip3 install 'qrcode[pil]' pillow
|
||||
```
|
||||
|
||||
### 4. Iniciar servidor (desarrollo)
|
||||
|
||||
```bash
|
||||
php -S localhost:8080 -t .
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Acceso al sistema
|
||||
|
||||
| Rol | URL | Credenciales iniciales |
|
||||
|-----|-----|------------------------|
|
||||
| **Administración** | `/admin/login.php` | Usuario: `admin` / Contraseña: `admin123` |
|
||||
| **Formulario (QR)** | `/formulario.php?u=UB-00001` | Sin login (público) |
|
||||
|
||||
> Cambie la contraseña de `admin` en **Admin → Usuarios** después del primer acceso.
|
||||
|
||||
---
|
||||
|
||||
## Flujo del técnico en campo
|
||||
|
||||
1. Escanea el QR pegado en la ubicación.
|
||||
2. Se abre el formulario con datos automáticos:
|
||||
- **Módulo** (ej. PLP)
|
||||
- **Habitación / ubicación** (ej. T-72-1)
|
||||
3. Selecciona **Empresa** (SODEXO, REYSAP, MTTO CAMP, SmartService).
|
||||
4. Aparecen los **servicios** disponibles para esa empresa (lógica condicional).
|
||||
5. Opcional: nombre del técnico y observaciones.
|
||||
6. Envía → el registro queda guardado en la base de datos.
|
||||
|
||||
---
|
||||
|
||||
## Panel de administración
|
||||
|
||||
Ruta base: `/admin/`
|
||||
|
||||
| Sección | Función |
|
||||
|---------|---------|
|
||||
| **Panel** | Estadísticas, registros recientes, accesos rápidos |
|
||||
| **Registros** | Consulta y filtrado por módulo, empresa, fechas y búsqueda libre |
|
||||
| **Módulos** | Ver, editar nombres, activar/desactivar y **crear nuevos módulos** |
|
||||
| **Ubicaciones** | Ver, editar, filtrar y **crear nuevas habitaciones** (una o varias por lote) |
|
||||
| **Empresas** | Gestionar empresas contratistas |
|
||||
| **Servicios** | Gestionar servicios por empresa (aparecen condicionalmente en el formulario) |
|
||||
| **Códigos QR** | Vista previa, exportar CSV, generar etiquetas PNG |
|
||||
| **Usuarios** | Crear, editar, desactivar y eliminar accesos al panel |
|
||||
|
||||
Todas las páginas admin requieren **inicio de sesión**.
|
||||
|
||||
---
|
||||
|
||||
## Identificadores únicos (clave del diseño)
|
||||
|
||||
Cada módulo y ubicación tiene un **código permanente** independiente del nombre visible:
|
||||
|
||||
| Entidad | Código ejemplo | Nombre editable | En el QR |
|
||||
|---------|----------------|-----------------|----------|
|
||||
| Módulo | `MOD-001` | PLP | No (solo en BD) |
|
||||
| Ubicación | `UB-00001` | T-72-1 | Sí (`?u=UB-00001`) |
|
||||
|
||||
**Ventaja:** si mañana "PLP" pasa a llamarse "Campamento Norte", solo se edita el nombre en el panel. El QR impreso sigue apuntando a `UB-00001` sin regenerar nada.
|
||||
|
||||
Al crear nuevos módulos o ubicaciones, el sistema asigna automáticamente el siguiente código disponible (`MOD-020`, `UB-02519`, etc.).
|
||||
|
||||
---
|
||||
|
||||
## Generación de códigos QR
|
||||
|
||||
### Desde el panel
|
||||
|
||||
**Admin → Códigos QR → Generar QR**
|
||||
|
||||
### Desde terminal
|
||||
|
||||
```bash
|
||||
python3 generate_qrs.py
|
||||
```
|
||||
|
||||
### Formato de cada etiqueta
|
||||
|
||||
- Color QR: `#132A7C`
|
||||
- Logo `NEM.png` centrado (corrección de errores alta)
|
||||
- Pie de imagen: `Módulo | Habitación` (ej. `PLP | T-72-1`)
|
||||
- Archivo PNG en `output/`, nombre: `Módulo_Habitación.png`
|
||||
- Si hay colisión de nombre (mismo módulo + misma habitación), se añade el código: `…_UB-01121.png`
|
||||
|
||||
### Archivo de datos
|
||||
|
||||
`qr_data.csv` contiene columnas: `codigo`, `modulo`, `ubicacion`, `url`
|
||||
|
||||
Se regenera al instalar, exportar desde el panel o al crear ubicaciones nuevas.
|
||||
|
||||
---
|
||||
|
||||
## Base de datos
|
||||
|
||||
Base: `mantenimiento_campamento`
|
||||
|
||||
| Tabla | Descripción |
|
||||
|-------|-------------|
|
||||
| `modulos` | Áreas del campamento (PLP, COCINA, 100´s, etc.) |
|
||||
| `ubicaciones` | Habitaciones, trailas, equipos, etc. (vinculadas a un módulo) |
|
||||
| `empresas` | Contratistas (SODEXO, REYSAP, …) |
|
||||
| `servicios` | Tipos de servicio por empresa |
|
||||
| `registros` | Cada actividad de mantenimiento registrada |
|
||||
| `usuarios` | Accesos al panel de administración |
|
||||
|
||||
---
|
||||
|
||||
## Estructura de archivos
|
||||
|
||||
```
|
||||
autofillqr/
|
||||
├── admin/ # Panel de administración
|
||||
│ ├── index.php # Dashboard
|
||||
│ ├── login.php / logout.php
|
||||
│ ├── registros.php
|
||||
│ ├── modulos.php
|
||||
│ ├── ubicaciones.php
|
||||
│ ├── empresas.php
|
||||
│ ├── servicios.php
|
||||
│ ├── usuarios.php
|
||||
│ ├── qrs.php
|
||||
│ ├── generate_qrs.php
|
||||
│ └── export_qr.php
|
||||
├── api/
|
||||
│ ├── guardar.php # Guarda registro del formulario
|
||||
│ └── servicios.php # API JSON: servicios por empresa
|
||||
├── assets/css/ # Estilos
|
||||
├── assets/js/ # JS formulario y admin
|
||||
├── config/
|
||||
│ ├── config.php # Configuración general
|
||||
│ └── database.php # Conexión PDO
|
||||
├── includes/ # Header, auth, funciones
|
||||
├── sql/ # Esquema e migraciones
|
||||
├── formulario.php # Formulario público (entrada QR)
|
||||
├── install.php # Instalador
|
||||
├── generate_qrs.py # Generador de etiquetas PNG
|
||||
├── data.csv # Datos originales (importación inicial)
|
||||
├── qr_data.csv # URLs actuales para QR
|
||||
├── NEM.png # Logo del campamento
|
||||
└── output/ # QR generados (PNG)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Catálogos precargados
|
||||
|
||||
### Empresas
|
||||
|
||||
- SODEXO
|
||||
- REYSAP
|
||||
- MTTO CAMP
|
||||
- SmartService
|
||||
|
||||
### Servicios por empresa
|
||||
|
||||
| Empresa | Servicios |
|
||||
|---------|-----------|
|
||||
| SODEXO | Limpieza / Supervisión, Fumigación |
|
||||
| REYSAP | Servicio de Mantenimiento |
|
||||
| MTTO CAMP | Mtto Preventivo, Mtto Correctivo |
|
||||
| SmartService | Mtto Cocina |
|
||||
|
||||
Todos editables desde el panel admin.
|
||||
|
||||
---
|
||||
|
||||
## Datos importados
|
||||
|
||||
Desde `data.csv` (formato original de Microsoft Forms):
|
||||
|
||||
- **19 módulos / áreas**
|
||||
- **2 518 ubicaciones**
|
||||
- **2 518 códigos QR** (1 duplicado de nombre en origen: Trailas T9-1)
|
||||
|
||||
---
|
||||
|
||||
## Migraciones SQL adicionales
|
||||
|
||||
Si actualiza desde una versión anterior:
|
||||
|
||||
```bash
|
||||
mysql -u root -p mantenimiento_campamento < sql/migrate_empresas.sql
|
||||
mysql -u root -p mantenimiento_campamento < sql/migrate_usuarios.sql
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Notas técnicas
|
||||
|
||||
- Zona horaria: `America/Hermosillo`
|
||||
- Contraseñas de usuarios: hash con `password_hash()` (bcrypt)
|
||||
- El formulario público no requiere autenticación; el panel admin sí
|
||||
- Los POST del admin procesan datos **antes** de enviar HTML (evita errores de headers)
|
||||
- Codificación CSV original: ISO-8859-1; la BD usa UTF-8
|
||||
|
||||
---
|
||||
|
||||
## Resumen rápido de comandos
|
||||
|
||||
```bash
|
||||
# Instalar (navegador)
|
||||
open http://localhost:8080/install.php
|
||||
|
||||
# Servidor desarrollo
|
||||
php -S localhost:8080 -t .
|
||||
|
||||
# Generar todos los QR
|
||||
python3 generate_qrs.py
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## English summary
|
||||
|
||||
Web-based maintenance logging system for a mining camp. QR codes at each physical location open a pre-filled form (module + room). Staff selects contractor company and service type. Data is stored in MariaDB and managed through a password-protected admin panel. Unique stable IDs (`UB-XXXXX`) allow renaming locations without reprinting QR codes. PNG labels use brand color `#132A7C` and embedded `NEM.png` logo.
|
||||
80
admin/empresas.php
Normal file
80
admin/empresas.php
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
<?php
|
||||
$adminSection = 'empresas';
|
||||
$pageTitle = 'Empresas';
|
||||
$pageHeading = 'Empresas';
|
||||
require_once __DIR__ . '/../includes/admin_bootstrap.php';
|
||||
require_once __DIR__ . '/../config/database.php';
|
||||
|
||||
$db = getDB();
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
$action = $_POST['action'] ?? '';
|
||||
if ($action === 'create') {
|
||||
$nombre = trim($_POST['nombre'] ?? '');
|
||||
if ($nombre !== '') {
|
||||
try {
|
||||
$db->prepare('INSERT INTO empresas (nombre) VALUES (?)')->execute([$nombre]);
|
||||
flash('success', 'Empresa agregada.');
|
||||
} catch (PDOException $e) {
|
||||
flash('danger', 'Ya existe esa empresa.');
|
||||
}
|
||||
}
|
||||
} elseif ($action === 'update') {
|
||||
$id = (int) ($_POST['id'] ?? 0);
|
||||
$nombre = trim($_POST['nombre'] ?? '');
|
||||
$activo = isset($_POST['activo']) ? 1 : 0;
|
||||
if ($id > 0 && $nombre !== '') {
|
||||
$db->prepare('UPDATE empresas SET nombre = ?, activo = ? WHERE id = ?')->execute([$nombre, $activo, $id]);
|
||||
flash('success', 'Empresa actualizada.');
|
||||
}
|
||||
}
|
||||
redirect(BASE_URL . '/admin/empresas.php');
|
||||
}
|
||||
|
||||
$empresas = $db->query('
|
||||
SELECT e.*, COUNT(s.id) AS total_servicios
|
||||
FROM empresas e LEFT JOIN servicios s ON s.empresa_id = e.id
|
||||
GROUP BY e.id ORDER BY e.nombre
|
||||
')->fetchAll();
|
||||
$flash = getFlash();
|
||||
require_once __DIR__ . '/../includes/admin_header.php';
|
||||
?>
|
||||
|
||||
<?php if ($flash): ?><div class="alert alert-<?= h($flash['type']) ?>"><?= h($flash['message']) ?></div><?php endif; ?>
|
||||
|
||||
<div class="card mb-4">
|
||||
<div class="card-body">
|
||||
<form method="post" class="row g-2 align-items-end">
|
||||
<input type="hidden" name="action" value="create">
|
||||
<div class="col-md-8">
|
||||
<label class="form-label">Nueva empresa</label>
|
||||
<input type="text" name="nombre" class="form-control" required maxlength="150">
|
||||
</div>
|
||||
<div class="col-md-4"><button type="submit" class="btn btn-primary w-100">Agregar</button></div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="table-responsive">
|
||||
<table class="table table-hover mb-0">
|
||||
<thead class="table-light"><tr><th>Nombre</th><th>Servicios</th><th>Activo</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
<?php foreach ($empresas as $e): ?>
|
||||
<tr>
|
||||
<form method="post">
|
||||
<input type="hidden" name="action" value="update">
|
||||
<input type="hidden" name="id" value="<?= (int) $e['id'] ?>">
|
||||
<td><input type="text" name="nombre" class="form-control form-control-sm" value="<?= h($e['nombre']) ?>" required></td>
|
||||
<td><?= (int) $e['total_servicios'] ?></td>
|
||||
<td><div class="form-check form-switch"><input class="form-check-input" type="checkbox" name="activo" <?= $e['activo'] ? 'checked' : '' ?>></div></td>
|
||||
<td><button type="submit" class="btn btn-sm btn-primary">Guardar</button></td>
|
||||
</form>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php require_once __DIR__ . '/../includes/admin_footer.php'; ?>
|
||||
42
admin/export_qr.php
Normal file
42
admin/export_qr.php
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
<?php
|
||||
require_once __DIR__ . '/../includes/admin_bootstrap.php';
|
||||
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();
|
||||
|
||||
header('Content-Type: text/csv; charset=utf-8');
|
||||
header('Content-Disposition: attachment; filename="qr_data.csv"');
|
||||
|
||||
$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);
|
||||
38
admin/generate_qrs.php
Normal file
38
admin/generate_qrs.php
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
<?php
|
||||
require_once __DIR__ . '/../includes/admin_bootstrap.php';
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
redirect(BASE_URL . '/admin/qrs.php');
|
||||
}
|
||||
|
||||
set_time_limit(600);
|
||||
|
||||
$root = dirname(__DIR__);
|
||||
$python = trim(shell_exec('which python3') ?: 'python3');
|
||||
$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';
|
||||
$output = shell_exec($cmd);
|
||||
|
||||
if ($output !== null && str_contains($output, 'Listo!')) {
|
||||
flash('success', trim(preg_replace('/\s+/', ' ', $output)));
|
||||
} else {
|
||||
flash('danger', 'Error al generar QR: ' . ($output ?: 'sin salida del script'));
|
||||
}
|
||||
|
||||
redirect(BASE_URL . '/admin/qrs.php');
|
||||
177
admin/index.php
Normal file
177
admin/index.php
Normal file
|
|
@ -0,0 +1,177 @@
|
|||
<?php
|
||||
require_once __DIR__ . '/../includes/admin_bootstrap.php';
|
||||
$adminSection = 'index';
|
||||
$pageTitle = 'Panel - ' . APP_NAME;
|
||||
$pageHeading = 'Panel de administración';
|
||||
require_once __DIR__ . '/../includes/admin_header.php';
|
||||
require_once __DIR__ . '/../config/database.php';
|
||||
|
||||
$db = getDB();
|
||||
|
||||
$stats = [
|
||||
'registros' => (int) $db->query('SELECT COUNT(*) FROM registros')->fetchColumn(),
|
||||
'ubicaciones' => (int) $db->query('SELECT COUNT(*) FROM ubicaciones WHERE activo = 1')->fetchColumn(),
|
||||
'modulos' => (int) $db->query('SELECT COUNT(*) FROM modulos WHERE activo = 1')->fetchColumn(),
|
||||
'hoy' => (int) $db->query("SELECT COUNT(*) FROM registros WHERE DATE(created_at) = CURDATE()")->fetchColumn(),
|
||||
'empresas' => (int) $db->query('SELECT COUNT(*) FROM empresas WHERE activo = 1')->fetchColumn(),
|
||||
];
|
||||
|
||||
$qrCount = 0;
|
||||
$outputDir = dirname(__DIR__) . '/output';
|
||||
if (is_dir($outputDir)) {
|
||||
$qrCount = count(array_filter(scandir($outputDir), fn($f) => str_ends_with($f, '.png')));
|
||||
}
|
||||
|
||||
$recientes = $db->query('
|
||||
SELECT r.id, r.created_at, r.registrado_por,
|
||||
m.nombre AS modulo, u.nombre AS ubicacion,
|
||||
e.nombre AS empresa, s.nombre AS servicio
|
||||
FROM registros r
|
||||
JOIN ubicaciones u ON u.id = r.ubicacion_id
|
||||
JOIN modulos m ON m.id = u.modulo_id
|
||||
JOIN empresas e ON e.id = r.empresa_id
|
||||
JOIN servicios s ON s.id = r.servicio_id
|
||||
ORDER BY r.created_at DESC
|
||||
LIMIT 10
|
||||
')->fetchAll();
|
||||
|
||||
$porEmpresa = $db->query('
|
||||
SELECT e.nombre, COUNT(r.id) AS total
|
||||
FROM empresas e
|
||||
LEFT JOIN registros r ON r.empresa_id = e.id
|
||||
GROUP BY e.id
|
||||
ORDER BY total DESC
|
||||
')->fetchAll();
|
||||
|
||||
$flash = getFlash();
|
||||
?>
|
||||
|
||||
<?php if ($flash): ?>
|
||||
<div class="alert alert-<?= h($flash['type']) ?> alert-dismissible fade show">
|
||||
<?= h($flash['message']) ?>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<div class="row g-3 mb-4">
|
||||
<div class="col-6 col-xl">
|
||||
<div class="card stat-card h-100">
|
||||
<div class="card-body d-flex align-items-center gap-3">
|
||||
<div class="stat-icon"><span class="material-symbols-outlined">list_alt</span></div>
|
||||
<div>
|
||||
<div class="text-muted small">Registros totales</div>
|
||||
<div class="h4 mb-0"><?= number_format($stats['registros']) ?></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-6 col-xl">
|
||||
<div class="card stat-card h-100">
|
||||
<div class="card-body d-flex align-items-center gap-3">
|
||||
<div class="stat-icon"><span class="material-symbols-outlined">today</span></div>
|
||||
<div>
|
||||
<div class="text-muted small">Registros hoy</div>
|
||||
<div class="h4 mb-0"><?= number_format($stats['hoy']) ?></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-6 col-xl">
|
||||
<div class="card stat-card h-100">
|
||||
<div class="card-body d-flex align-items-center gap-3">
|
||||
<div class="stat-icon"><span class="material-symbols-outlined">location_on</span></div>
|
||||
<div>
|
||||
<div class="text-muted small">Ubicaciones</div>
|
||||
<div class="h4 mb-0"><?= number_format($stats['ubicaciones']) ?></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-6 col-xl">
|
||||
<div class="card stat-card h-100">
|
||||
<div class="card-body d-flex align-items-center gap-3">
|
||||
<div class="stat-icon"><span class="material-symbols-outlined">qr_code_2</span></div>
|
||||
<div>
|
||||
<div class="text-muted small">QR generados</div>
|
||||
<div class="h4 mb-0"><?= number_format($qrCount) ?></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row g-4">
|
||||
<div class="col-lg-8">
|
||||
<div class="card">
|
||||
<div class="card-header d-flex justify-content-between align-items-center">
|
||||
<span>Registros recientes</span>
|
||||
<a href="registros.php" class="btn btn-sm btn-primary">Ver todos</a>
|
||||
</div>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-hover mb-0">
|
||||
<thead class="table-light">
|
||||
<tr>
|
||||
<th>Fecha</th>
|
||||
<th>Módulo</th>
|
||||
<th>Habitación</th>
|
||||
<th>Empresa</th>
|
||||
<th>Servicio</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php if (empty($recientes)): ?>
|
||||
<tr><td colspan="5" class="text-center text-muted py-4">Sin registros aún.</td></tr>
|
||||
<?php else: ?>
|
||||
<?php foreach ($recientes as $r): ?>
|
||||
<tr>
|
||||
<td class="text-nowrap small"><?= h(formatFecha($r['created_at'])) ?></td>
|
||||
<td><?= h($r['modulo']) ?></td>
|
||||
<td><?= h($r['ubicacion']) ?></td>
|
||||
<td><?= h($r['empresa']) ?></td>
|
||||
<td><span class="badge bg-secondary"><?= h($r['servicio']) ?></span></td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
<?php endif; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-lg-4">
|
||||
<div class="card mb-4">
|
||||
<div class="card-header">Accesos rápidos</div>
|
||||
<div class="card-body d-grid gap-2">
|
||||
<a href="registros.php" class="quick-link-card card p-3">
|
||||
<span class="material-symbols-outlined text-primary">list_alt</span>
|
||||
<strong>Registros</strong>
|
||||
<small class="text-muted">Consultar y filtrar actividades</small>
|
||||
</a>
|
||||
<a href="ubicaciones.php" class="quick-link-card card p-3">
|
||||
<span class="material-symbols-outlined text-primary">edit_location</span>
|
||||
<strong>Ubicaciones</strong>
|
||||
<small class="text-muted">Editar nombres sin cambiar QR</small>
|
||||
</a>
|
||||
<a href="qrs.php" class="quick-link-card card p-3">
|
||||
<span class="material-symbols-outlined text-primary">qr_code_2</span>
|
||||
<strong>Códigos QR</strong>
|
||||
<small class="text-muted">Generar e imprimir etiquetas</small>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-header">Registros por empresa</div>
|
||||
<ul class="list-group list-group-flush">
|
||||
<?php foreach ($porEmpresa as $pe): ?>
|
||||
<li class="list-group-item d-flex justify-content-between">
|
||||
<span><?= h($pe['nombre']) ?></span>
|
||||
<span class="badge bg-primary rounded-pill"><?= (int) $pe['total'] ?></span>
|
||||
</li>
|
||||
<?php endforeach; ?>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php require_once __DIR__ . '/../includes/admin_footer.php'; ?>
|
||||
82
admin/login.php
Normal file
82
admin/login.php
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
<?php
|
||||
$skipAdminAuth = true;
|
||||
require_once __DIR__ . '/../includes/admin_bootstrap.php';
|
||||
require_once __DIR__ . '/../config/database.php';
|
||||
|
||||
if (isLoggedIn()) {
|
||||
redirect(BASE_URL . '/admin/index.php');
|
||||
}
|
||||
|
||||
$error = null;
|
||||
$return = $_GET['return'] ?? BASE_URL . '/admin/index.php';
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
$usuario = trim($_POST['usuario'] ?? '');
|
||||
$password = $_POST['password'] ?? '';
|
||||
$return = $_POST['return'] ?? $return;
|
||||
|
||||
if ($usuario === '' || $password === '') {
|
||||
$error = 'Ingrese usuario y contraseña.';
|
||||
} else {
|
||||
$db = getDB();
|
||||
if (loginUser($db, $usuario, $password)) {
|
||||
redirect($return);
|
||||
}
|
||||
$error = 'Usuario o contraseña incorrectos.';
|
||||
}
|
||||
}
|
||||
|
||||
$pageTitle = 'Iniciar sesión';
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title><?= h($pageTitle) ?> - <?= h(APP_NAME) ?></title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined" rel="stylesheet">
|
||||
<link href="<?= BASE_URL ?>/assets/css/style.css" rel="stylesheet">
|
||||
</head>
|
||||
<body class="bg-light">
|
||||
<div class="container">
|
||||
<div class="row justify-content-center align-items-center min-vh-100">
|
||||
<div class="col-md-5 col-lg-4">
|
||||
<div class="card shadow-sm">
|
||||
<div class="card-body p-4">
|
||||
<div class="text-center mb-4">
|
||||
<?php if (file_exists(dirname(__DIR__) . '/NEM.png')): ?>
|
||||
<img src="<?= BASE_URL ?>/NEM.png" alt="Logo" style="height:56px" class="mb-2">
|
||||
<?php endif; ?>
|
||||
<h4 class="mb-0"><?= h(APP_NAME) ?></h4>
|
||||
<small class="text-muted">Panel de administración</small>
|
||||
</div>
|
||||
|
||||
<?php if ($error): ?>
|
||||
<div class="alert alert-danger py-2"><?= h($error) ?></div>
|
||||
<?php endif; ?>
|
||||
|
||||
<form method="post">
|
||||
<input type="hidden" name="return" value="<?= h($return) ?>">
|
||||
<div class="mb-3">
|
||||
<label for="usuario" class="form-label">Usuario</label>
|
||||
<input type="text" class="form-control" id="usuario" name="usuario"
|
||||
autocomplete="username" required autofocus>
|
||||
</div>
|
||||
<div class="mb-4">
|
||||
<label for="password" class="form-label">Contraseña</label>
|
||||
<input type="password" class="form-control" id="password" name="password"
|
||||
autocomplete="current-password" required>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary w-100 py-2">
|
||||
<span class="material-symbols-outlined align-middle me-1" style="font-size:20px">login</span>
|
||||
Entrar
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
10
admin/logout.php
Normal file
10
admin/logout.php
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
<?php
|
||||
if (session_status() === PHP_SESSION_NONE) {
|
||||
session_start();
|
||||
}
|
||||
require_once __DIR__ . '/../config/config.php';
|
||||
require_once __DIR__ . '/../includes/functions.php';
|
||||
require_once __DIR__ . '/../includes/auth.php';
|
||||
|
||||
logoutUser();
|
||||
redirect(BASE_URL . '/admin/login.php');
|
||||
100
admin/modulos.php
Normal file
100
admin/modulos.php
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
<?php
|
||||
$adminSection = 'modulos';
|
||||
$pageTitle = 'Módulos';
|
||||
$pageHeading = 'Módulos / Áreas';
|
||||
require_once __DIR__ . '/../includes/admin_bootstrap.php';
|
||||
require_once __DIR__ . '/../config/database.php';
|
||||
|
||||
$db = getDB();
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
$action = $_POST['action'] ?? 'update';
|
||||
|
||||
if ($action === 'create') {
|
||||
$nombre = trim($_POST['nombre'] ?? '');
|
||||
if ($nombre !== '') {
|
||||
$codigo = nextModuloCodigo($db);
|
||||
$db->prepare('INSERT INTO modulos (codigo, nombre) VALUES (?, ?)')->execute([$codigo, $nombre]);
|
||||
flash('success', "Módulo creado con código {$codigo}. Ya puede agregar ubicaciones.");
|
||||
} else {
|
||||
flash('danger', 'El nombre del módulo es obligatorio.');
|
||||
}
|
||||
} else {
|
||||
$id = (int) ($_POST['id'] ?? 0);
|
||||
$nombre = trim($_POST['nombre'] ?? '');
|
||||
$activo = isset($_POST['activo']) ? 1 : 0;
|
||||
if ($id > 0 && $nombre !== '') {
|
||||
$db->prepare('UPDATE modulos SET nombre = ?, activo = ? WHERE id = ?')->execute([$nombre, $activo, $id]);
|
||||
flash('success', 'Módulo actualizado. Los QR no requieren regenerarse.');
|
||||
}
|
||||
}
|
||||
redirect(BASE_URL . '/admin/modulos.php');
|
||||
}
|
||||
|
||||
$modulos = $db->query('
|
||||
SELECT m.*, COUNT(u.id) AS total_ubicaciones
|
||||
FROM modulos m LEFT JOIN ubicaciones u ON u.modulo_id = m.id
|
||||
GROUP BY m.id ORDER BY m.codigo
|
||||
')->fetchAll();
|
||||
$flash = getFlash();
|
||||
require_once __DIR__ . '/../includes/admin_header.php';
|
||||
?>
|
||||
|
||||
<?php if ($flash): ?><div class="alert alert-<?= h($flash['type']) ?>"><?= h($flash['message']) ?></div><?php endif; ?>
|
||||
|
||||
<div class="row g-4">
|
||||
<div class="col-lg-4">
|
||||
<div class="card">
|
||||
<div class="card-header">Nuevo módulo / área</div>
|
||||
<div class="card-body">
|
||||
<form method="post">
|
||||
<input type="hidden" name="action" value="create">
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Nombre <span class="text-danger">*</span></label>
|
||||
<input type="text" name="nombre" class="form-control" required maxlength="150"
|
||||
placeholder="Ej. PLP, COCINA, Trailas nuevas...">
|
||||
</div>
|
||||
<p class="text-muted small">Se asignará un código único automático (MOD-xxx) para uso interno y QR.</p>
|
||||
<button type="submit" class="btn btn-primary w-100">
|
||||
<span class="material-symbols-outlined align-middle" style="font-size:18px">add</span>
|
||||
Agregar módulo
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-lg-8">
|
||||
<p class="text-muted">El <strong>código</strong> es permanente. Puede editar el <strong>nombre</strong> sin regenerar QR.</p>
|
||||
<div class="card">
|
||||
<div class="card-header"><?= count($modulos) ?> módulo(s)</div>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-hover mb-0">
|
||||
<thead class="table-light">
|
||||
<tr><th>Código</th><th>Nombre</th><th>Ubicaciones</th><th>Activo</th><th></th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach ($modulos as $m): ?>
|
||||
<tr>
|
||||
<form method="post">
|
||||
<input type="hidden" name="action" value="update">
|
||||
<input type="hidden" name="id" value="<?= (int) $m['id'] ?>">
|
||||
<td><code class="badge-codigo"><?= h($m['codigo']) ?></code></td>
|
||||
<td><input type="text" name="nombre" class="form-control form-control-sm" value="<?= h($m['nombre']) ?>" required></td>
|
||||
<td>
|
||||
<?= (int) $m['total_ubicaciones'] ?>
|
||||
<a href="ubicaciones.php?modulo_id=<?= (int) $m['id'] ?>" class="small ms-1">Ver</a>
|
||||
</td>
|
||||
<td><div class="form-check form-switch"><input class="form-check-input" type="checkbox" name="activo" <?= $m['activo'] ? 'checked' : '' ?>></div></td>
|
||||
<td><button type="submit" class="btn btn-sm btn-primary">Guardar</button></td>
|
||||
</form>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php require_once __DIR__ . '/../includes/admin_footer.php'; ?>
|
||||
107
admin/qrs.php
Normal file
107
admin/qrs.php
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
<?php
|
||||
$adminSection = 'qrs';
|
||||
$pageTitle = 'Códigos QR';
|
||||
$pageHeading = 'Códigos QR';
|
||||
|
||||
$outputDir = dirname(__DIR__) . '/output';
|
||||
$qrCount = 0;
|
||||
$sampleFile = null;
|
||||
|
||||
if (is_dir($outputDir)) {
|
||||
$files = array_values(array_filter(scandir($outputDir), fn($f) => str_ends_with($f, '.png')));
|
||||
$qrCount = count($files);
|
||||
if ($qrCount > 0) {
|
||||
sort($files);
|
||||
$sampleFile = $files[0];
|
||||
}
|
||||
}
|
||||
|
||||
$topbarActions = '
|
||||
<a href="export_qr.php" class="btn btn-outline-primary btn-sm me-2">
|
||||
<span class="material-symbols-outlined align-middle" style="font-size:18px">download</span> Exportar CSV
|
||||
</a>
|
||||
<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">
|
||||
<span class="material-symbols-outlined align-middle" style="font-size:18px">qr_code_2</span> Generar QR
|
||||
</button>
|
||||
</form>
|
||||
';
|
||||
|
||||
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): ?>
|
||||
<div class="alert alert-<?= h($flash['type']) ?> alert-dismissible fade show">
|
||||
<?= h($flash['message']) ?>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<div class="row g-4">
|
||||
<div class="col-lg-5">
|
||||
<div class="card h-100">
|
||||
<div class="card-header">Vista previa</div>
|
||||
<div class="card-body">
|
||||
<div class="qr-preview-box">
|
||||
<?php if ($sampleFile): ?>
|
||||
<img src="<?= h(BASE_URL) ?>/output/<?= h(rawurlencode($sampleFile)) ?>" alt="QR ejemplo">
|
||||
<p class="text-muted small mt-3 mb-0"><?= h($sampleFile) ?></p>
|
||||
<?php else: ?>
|
||||
<span class="material-symbols-outlined text-muted" style="font-size:64px">qr_code_2</span>
|
||||
<p class="text-muted mt-3">Aún no hay QR generados.<br>Use el botón <strong>Generar QR</strong>.</p>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-lg-7">
|
||||
<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">
|
||||
<p class="mb-2">Los QR mantienen el mismo estilo que los anteriores:</p>
|
||||
<ul class="mb-3">
|
||||
<li>Color azul campamento <code>#132A7C</code></li>
|
||||
<li>Logo <strong>NEM.png</strong> centrado en el código</li>
|
||||
<li>Pie de imagen: <em>Módulo | Habitación</em></li>
|
||||
<li>URL interna: <code>formulario.php?u=UB-XXXXX</code></li>
|
||||
</ul>
|
||||
<p class="text-muted small mb-0">
|
||||
También puede generar desde terminal:
|
||||
<code>python3 generate_qrs.py</code>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php require_once __DIR__ . '/../includes/admin_footer.php'; ?>
|
||||
128
admin/registros.php
Normal file
128
admin/registros.php
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
<?php
|
||||
$adminSection = 'registros';
|
||||
$pageTitle = 'Registros';
|
||||
$pageHeading = 'Registros de mantenimiento';
|
||||
require_once __DIR__ . '/../includes/admin_header.php';
|
||||
require_once __DIR__ . '/../config/database.php';
|
||||
|
||||
$db = getDB();
|
||||
|
||||
$moduloId = (int) ($_GET['modulo_id'] ?? 0);
|
||||
$empresaId = (int) ($_GET['empresa_id'] ?? 0);
|
||||
$fechaDesde = trim($_GET['desde'] ?? '');
|
||||
$fechaHasta = trim($_GET['hasta'] ?? '');
|
||||
$buscar = trim($_GET['q'] ?? '');
|
||||
|
||||
$modulos = $db->query('SELECT id, nombre FROM modulos WHERE activo = 1 ORDER BY nombre')->fetchAll();
|
||||
$empresas = $db->query('SELECT id, nombre FROM empresas WHERE activo = 1 ORDER BY nombre')->fetchAll();
|
||||
|
||||
$sql = '
|
||||
SELECT r.id, r.created_at, r.registrado_por, r.observaciones,
|
||||
m.nombre AS modulo, u.nombre AS ubicacion, u.codigo AS ubicacion_codigo,
|
||||
e.nombre AS empresa, s.nombre AS servicio
|
||||
FROM registros r
|
||||
JOIN ubicaciones u ON u.id = r.ubicacion_id
|
||||
JOIN modulos m ON m.id = u.modulo_id
|
||||
JOIN empresas e ON e.id = r.empresa_id
|
||||
JOIN servicios s ON s.id = r.servicio_id
|
||||
WHERE 1=1
|
||||
';
|
||||
$params = [];
|
||||
|
||||
if ($moduloId > 0) { $sql .= ' AND m.id = ?'; $params[] = $moduloId; }
|
||||
if ($empresaId > 0) { $sql .= ' AND e.id = ?'; $params[] = $empresaId; }
|
||||
if ($fechaDesde !== '') { $sql .= ' AND DATE(r.created_at) >= ?'; $params[] = $fechaDesde; }
|
||||
if ($fechaHasta !== '') { $sql .= ' AND DATE(r.created_at) <= ?'; $params[] = $fechaHasta; }
|
||||
if ($buscar !== '') {
|
||||
$sql .= ' AND (u.nombre LIKE ? OR m.nombre LIKE ? OR e.nombre LIKE ? OR s.nombre LIKE ? OR r.registrado_por LIKE ?)';
|
||||
$like = '%' . $buscar . '%';
|
||||
array_push($params, $like, $like, $like, $like, $like);
|
||||
}
|
||||
|
||||
$sql .= ' ORDER BY r.created_at DESC LIMIT 500';
|
||||
$stmt = $db->prepare($sql);
|
||||
$stmt->execute($params);
|
||||
$registros = $stmt->fetchAll();
|
||||
?>
|
||||
|
||||
<div class="card mb-4">
|
||||
<div class="card-body">
|
||||
<form method="get" class="row g-3 align-items-end">
|
||||
<div class="col-md-3">
|
||||
<label class="form-label">Módulo</label>
|
||||
<select name="modulo_id" class="form-select">
|
||||
<option value="">Todos</option>
|
||||
<?php foreach ($modulos as $m): ?>
|
||||
<option value="<?= (int) $m['id'] ?>" <?= $moduloId === (int) $m['id'] ? 'selected' : '' ?>><?= h($m['nombre']) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<label class="form-label">Empresa</label>
|
||||
<select name="empresa_id" class="form-select">
|
||||
<option value="">Todas</option>
|
||||
<?php foreach ($empresas as $e): ?>
|
||||
<option value="<?= (int) $e['id'] ?>" <?= $empresaId === (int) $e['id'] ? 'selected' : '' ?>><?= h($e['nombre']) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<label class="form-label">Desde</label>
|
||||
<input type="date" name="desde" class="form-control" value="<?= h($fechaDesde) ?>">
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<label class="form-label">Hasta</label>
|
||||
<input type="date" name="hasta" class="form-control" value="<?= h($fechaHasta) ?>">
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<label class="form-label">Buscar</label>
|
||||
<input type="text" name="q" class="form-control" value="<?= h($buscar) ?>">
|
||||
</div>
|
||||
<div class="col-md-1">
|
||||
<button type="submit" class="btn btn-primary w-100">Filtrar</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-header"><?= count($registros) ?> registro(s)</div>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-hover table-sm mb-0">
|
||||
<thead class="table-light">
|
||||
<tr>
|
||||
<th>#</th>
|
||||
<th>Fecha</th>
|
||||
<th>Módulo</th>
|
||||
<th>Habitación</th>
|
||||
<th>ID QR</th>
|
||||
<th>Empresa</th>
|
||||
<th>Servicio</th>
|
||||
<th>Por</th>
|
||||
<th>Obs.</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php if (empty($registros)): ?>
|
||||
<tr><td colspan="9" class="text-center text-muted py-4">No hay registros.</td></tr>
|
||||
<?php else: ?>
|
||||
<?php foreach ($registros as $r): ?>
|
||||
<tr>
|
||||
<td><?= (int) $r['id'] ?></td>
|
||||
<td class="text-nowrap small"><?= h(formatFecha($r['created_at'])) ?></td>
|
||||
<td><?= h($r['modulo']) ?></td>
|
||||
<td><?= h($r['ubicacion']) ?></td>
|
||||
<td><code class="table-codigo"><?= h($r['ubicacion_codigo']) ?></code></td>
|
||||
<td><?= h($r['empresa']) ?></td>
|
||||
<td><span class="badge bg-secondary"><?= h($r['servicio']) ?></span></td>
|
||||
<td><?= h($r['registrado_por'] ?? '—') ?></td>
|
||||
<td class="small"><?= h($r['observaciones'] ?? '') ?></td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
<?php endif; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php require_once __DIR__ . '/../includes/admin_footer.php'; ?>
|
||||
110
admin/servicios.php
Normal file
110
admin/servicios.php
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
<?php
|
||||
$adminSection = 'servicios';
|
||||
$pageTitle = 'Servicios';
|
||||
$pageHeading = 'Servicios por empresa';
|
||||
require_once __DIR__ . '/../includes/admin_bootstrap.php';
|
||||
require_once __DIR__ . '/../config/database.php';
|
||||
|
||||
$db = getDB();
|
||||
$empresaFiltro = (int) ($_GET['empresa_id'] ?? 0);
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
$action = $_POST['action'] ?? '';
|
||||
if ($action === 'create') {
|
||||
$empresaId = (int) ($_POST['empresa_id'] ?? 0);
|
||||
$nombre = trim($_POST['nombre'] ?? '');
|
||||
if ($empresaId > 0 && $nombre !== '') {
|
||||
try {
|
||||
$db->prepare('INSERT INTO servicios (empresa_id, nombre) VALUES (?, ?)')->execute([$empresaId, $nombre]);
|
||||
flash('success', 'Servicio agregado.');
|
||||
} catch (PDOException $e) {
|
||||
flash('danger', 'Ese servicio ya existe para la empresa.');
|
||||
}
|
||||
}
|
||||
} elseif ($action === 'update') {
|
||||
$id = (int) ($_POST['id'] ?? 0);
|
||||
$nombre = trim($_POST['nombre'] ?? '');
|
||||
$activo = isset($_POST['activo']) ? 1 : 0;
|
||||
if ($id > 0 && $nombre !== '') {
|
||||
$db->prepare('UPDATE servicios SET nombre = ?, activo = ? WHERE id = ?')->execute([$nombre, $activo, $id]);
|
||||
flash('success', 'Servicio actualizado.');
|
||||
}
|
||||
}
|
||||
redirect(BASE_URL . '/admin/servicios.php' . ($empresaFiltro ? '?empresa_id='.$empresaFiltro : ''));
|
||||
}
|
||||
|
||||
$empresas = $db->query('SELECT id, nombre FROM empresas ORDER BY nombre')->fetchAll();
|
||||
$sql = 'SELECT s.*, e.nombre AS empresa FROM servicios s JOIN empresas e ON e.id = s.empresa_id WHERE 1=1';
|
||||
$params = [];
|
||||
if ($empresaFiltro > 0) { $sql .= ' AND s.empresa_id = ?'; $params[] = $empresaFiltro; }
|
||||
$sql .= ' ORDER BY e.nombre, s.nombre';
|
||||
$stmt = $db->prepare($sql);
|
||||
$stmt->execute($params);
|
||||
$servicios = $stmt->fetchAll();
|
||||
$flash = getFlash();
|
||||
require_once __DIR__ . '/../includes/admin_header.php';
|
||||
?>
|
||||
|
||||
<?php if ($flash): ?><div class="alert alert-<?= h($flash['type']) ?>"><?= h($flash['message']) ?></div><?php endif; ?>
|
||||
|
||||
<div class="card mb-4">
|
||||
<div class="card-body">
|
||||
<form method="post" class="row g-2 align-items-end">
|
||||
<input type="hidden" name="action" value="create">
|
||||
<div class="col-md-4">
|
||||
<label class="form-label">Empresa</label>
|
||||
<select name="empresa_id" class="form-select" required>
|
||||
<option value="">— Seleccione —</option>
|
||||
<?php foreach ($empresas as $e): ?>
|
||||
<option value="<?= (int) $e['id'] ?>"><?= h($e['nombre']) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-5">
|
||||
<label class="form-label">Nuevo servicio</label>
|
||||
<input type="text" name="nombre" class="form-control" required maxlength="150">
|
||||
</div>
|
||||
<div class="col-md-3"><button type="submit" class="btn btn-primary w-100">Agregar</button></div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mb-3">
|
||||
<div class="card-body py-2">
|
||||
<form method="get" class="row g-2 align-items-end">
|
||||
<div class="col-md-4">
|
||||
<select name="empresa_id" class="form-select">
|
||||
<option value="">Todas las empresas</option>
|
||||
<?php foreach ($empresas as $e): ?>
|
||||
<option value="<?= (int) $e['id'] ?>" <?= $empresaFiltro === (int) $e['id'] ? 'selected' : '' ?>><?= h($e['nombre']) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-2"><button type="submit" class="btn btn-outline-primary">Filtrar</button></div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="table-responsive">
|
||||
<table class="table table-hover mb-0">
|
||||
<thead class="table-light"><tr><th>Empresa</th><th>Servicio</th><th>Activo</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
<?php foreach ($servicios as $s): ?>
|
||||
<tr>
|
||||
<form method="post">
|
||||
<input type="hidden" name="action" value="update">
|
||||
<input type="hidden" name="id" value="<?= (int) $s['id'] ?>">
|
||||
<td><?= h($s['empresa']) ?></td>
|
||||
<td><input type="text" name="nombre" class="form-control form-control-sm" value="<?= h($s['nombre']) ?>" required></td>
|
||||
<td><div class="form-check form-switch"><input class="form-check-input" type="checkbox" name="activo" <?= $s['activo'] ? 'checked' : '' ?>></div></td>
|
||||
<td><button type="submit" class="btn btn-sm btn-primary">Guardar</button></td>
|
||||
</form>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php require_once __DIR__ . '/../includes/admin_footer.php'; ?>
|
||||
179
admin/ubicaciones.php
Normal file
179
admin/ubicaciones.php
Normal file
|
|
@ -0,0 +1,179 @@
|
|||
<?php
|
||||
$adminSection = 'ubicaciones';
|
||||
$pageTitle = 'Ubicaciones';
|
||||
$pageHeading = 'Ubicaciones / Habitaciones';
|
||||
require_once __DIR__ . '/../includes/admin_bootstrap.php';
|
||||
require_once __DIR__ . '/../config/database.php';
|
||||
|
||||
$db = getDB();
|
||||
$moduloFiltro = (int) ($_GET['modulo_id'] ?? 0);
|
||||
$buscar = trim($_GET['q'] ?? '');
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
$action = $_POST['action'] ?? 'update';
|
||||
$redirectParams = array_filter(['modulo_id' => $moduloFiltro ?: null, 'q' => $buscar ?: null]);
|
||||
|
||||
if ($action === 'create') {
|
||||
$moduloId = (int) ($_POST['modulo_id'] ?? 0);
|
||||
$nombre = trim($_POST['nombre'] ?? '');
|
||||
$nombres = array_filter(array_map('trim', preg_split('/\r\n|\r|\n/', $_POST['nombres'] ?? '')));
|
||||
|
||||
if ($moduloId <= 0) {
|
||||
flash('danger', 'Seleccione un módulo.');
|
||||
} elseif ($nombre === '' && empty($nombres)) {
|
||||
flash('danger', 'Indique al menos una habitación o ubicación.');
|
||||
} else {
|
||||
$lista = $nombre !== '' ? [$nombre] : $nombres;
|
||||
$stmtMod = $db->prepare('SELECT id, nombre FROM modulos WHERE id = ? AND activo = 1');
|
||||
$stmtMod->execute([$moduloId]);
|
||||
$modulo = $stmtMod->fetch();
|
||||
|
||||
if (!$modulo) {
|
||||
flash('danger', 'Módulo no válido o inactivo.');
|
||||
} else {
|
||||
$stmtIns = $db->prepare('INSERT INTO ubicaciones (codigo, modulo_id, nombre) VALUES (?, ?, ?)');
|
||||
$creadas = [];
|
||||
foreach ($lista as $nom) {
|
||||
if ($nom === '') continue;
|
||||
$codigo = nextUbicacionCodigo($db);
|
||||
$stmtIns->execute([$codigo, $moduloId, $nom]);
|
||||
appendUbicacionToQrCsv($codigo, $modulo['nombre'], $nom);
|
||||
$creadas[] = $codigo;
|
||||
}
|
||||
$total = count($creadas);
|
||||
$msg = $total === 1
|
||||
? "Ubicación {$creadas[0]} creada. Genere su QR en Códigos QR."
|
||||
: "{$total} ubicaciones creadas (" . implode(', ', array_slice($creadas, 0, 3)) . ($total > 3 ? '...' : '') . "). Genere los QR en Códigos QR.";
|
||||
flash('success', $msg);
|
||||
$redirectParams['modulo_id'] = $moduloId;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$id = (int) ($_POST['id'] ?? 0);
|
||||
$nombre = trim($_POST['nombre'] ?? '');
|
||||
$activo = isset($_POST['activo']) ? 1 : 0;
|
||||
if ($id > 0 && $nombre !== '') {
|
||||
$db->prepare('UPDATE ubicaciones SET nombre = ?, activo = ? WHERE id = ?')->execute([$nombre, $activo, $id]);
|
||||
flash('success', 'Ubicación actualizada.');
|
||||
}
|
||||
}
|
||||
redirect(BASE_URL . '/admin/ubicaciones.php?' . http_build_query($redirectParams));
|
||||
}
|
||||
|
||||
$modulos = $db->query('SELECT id, nombre, codigo FROM modulos WHERE activo = 1 ORDER BY nombre')->fetchAll();
|
||||
$modulosTodos = $db->query('SELECT id, nombre FROM modulos ORDER BY nombre')->fetchAll();
|
||||
|
||||
$sql = 'SELECT u.*, m.nombre AS modulo_nombre FROM ubicaciones u JOIN modulos m ON m.id = u.modulo_id WHERE 1=1';
|
||||
$params = [];
|
||||
if ($moduloFiltro > 0) { $sql .= ' AND u.modulo_id = ?'; $params[] = $moduloFiltro; }
|
||||
if ($buscar !== '') { $sql .= ' AND (u.nombre LIKE ? OR u.codigo LIKE ?)'; $params[] = '%'.$buscar.'%'; $params[] = '%'.$buscar.'%'; }
|
||||
$sql .= ' ORDER BY u.codigo LIMIT 200';
|
||||
$stmt = $db->prepare($sql);
|
||||
$stmt->execute($params);
|
||||
$ubicaciones = $stmt->fetchAll();
|
||||
|
||||
$totalFiltrado = count($ubicaciones);
|
||||
$flash = getFlash();
|
||||
$moduloNuevoDefault = $moduloFiltro;
|
||||
require_once __DIR__ . '/../includes/admin_header.php';
|
||||
?>
|
||||
|
||||
<?php if ($flash): ?><div class="alert alert-<?= h($flash['type']) ?>"><?= h($flash['message']) ?></div><?php endif; ?>
|
||||
|
||||
<div class="row g-4 mb-4">
|
||||
<div class="col-lg-5">
|
||||
<div class="card">
|
||||
<div class="card-header">Nueva ubicación</div>
|
||||
<div class="card-body">
|
||||
<?php if (empty($modulos)): ?>
|
||||
<p class="text-muted mb-0">Primero cree un módulo en <a href="modulos.php">Módulos</a>.</p>
|
||||
<?php else: ?>
|
||||
<form method="post">
|
||||
<input type="hidden" name="action" value="create">
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Módulo <span class="text-danger">*</span></label>
|
||||
<select name="modulo_id" class="form-select" required>
|
||||
<option value="">— Seleccione —</option>
|
||||
<?php foreach ($modulos as $m): ?>
|
||||
<option value="<?= (int) $m['id'] ?>" <?= $moduloNuevoDefault === (int) $m['id'] ? 'selected' : '' ?>>
|
||||
<?= h($m['nombre']) ?> (<?= h($m['codigo']) ?>)
|
||||
</option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Habitación / ubicación (una)</label>
|
||||
<input type="text" name="nombre" class="form-control" maxlength="150" placeholder="Ej. T-99-1">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">O varias (una por línea)</label>
|
||||
<textarea name="nombres" class="form-control" rows="4" placeholder="T-99-1 T-99-2 T-99-3"></textarea>
|
||||
</div>
|
||||
<p class="text-muted small">Código QR único automático (UB-xxxxx). Después genere la etiqueta en <a href="qrs.php">Códigos QR</a>.</p>
|
||||
<button type="submit" class="btn btn-primary w-100">
|
||||
<span class="material-symbols-outlined align-middle" style="font-size:18px">add_location</span>
|
||||
Agregar ubicación(es)
|
||||
</button>
|
||||
</form>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-lg-7">
|
||||
<div class="card">
|
||||
<div class="card-header">Filtrar listado</div>
|
||||
<div class="card-body">
|
||||
<form method="get" class="row g-3 align-items-end">
|
||||
<div class="col-md-5">
|
||||
<label class="form-label">Módulo</label>
|
||||
<select name="modulo_id" class="form-select">
|
||||
<option value="">Todos</option>
|
||||
<?php foreach ($modulosTodos as $m): ?>
|
||||
<option value="<?= (int) $m['id'] ?>" <?= $moduloFiltro === (int) $m['id'] ? 'selected' : '' ?>><?= h($m['nombre']) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-5">
|
||||
<label class="form-label">Buscar</label>
|
||||
<input type="text" name="q" class="form-control" value="<?= h($buscar) ?>" placeholder="Nombre o UB-...">
|
||||
</div>
|
||||
<div class="col-md-2"><button type="submit" class="btn btn-primary w-100">Filtrar</button></div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-header"><?= $totalFiltrado ?> ubicación(es)<?= $totalFiltrado >= 200 ? ' (máx. 200 en listado)' : '' ?></div>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-hover table-sm mb-0">
|
||||
<thead class="table-light">
|
||||
<tr><th>Código QR</th><th>Módulo</th><th>Habitación</th><th>Enlace</th><th>Activo</th><th></th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php if (empty($ubicaciones)): ?>
|
||||
<tr><td colspan="6" class="text-center text-muted py-4">No hay ubicaciones con estos filtros.</td></tr>
|
||||
<?php else: ?>
|
||||
<?php foreach ($ubicaciones as $u): ?>
|
||||
<tr>
|
||||
<form method="post">
|
||||
<input type="hidden" name="action" value="update">
|
||||
<input type="hidden" name="id" value="<?= (int) $u['id'] ?>">
|
||||
<td><code class="badge-codigo"><?= h($u['codigo']) ?></code></td>
|
||||
<td class="small"><?= h($u['modulo_nombre']) ?></td>
|
||||
<td><input type="text" name="nombre" class="form-control form-control-sm" value="<?= h($u['nombre']) ?>" required></td>
|
||||
<td class="small"><a href="<?= h(BASE_URL) ?>/formulario.php?u=<?= h($u['codigo']) ?>" target="_blank">Abrir</a></td>
|
||||
<td><div class="form-check form-switch"><input class="form-check-input" type="checkbox" name="activo" <?= $u['activo'] ? 'checked' : '' ?>></div></td>
|
||||
<td><button type="submit" class="btn btn-sm btn-primary">Guardar</button></td>
|
||||
</form>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
<?php endif; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php require_once __DIR__ . '/../includes/admin_footer.php'; ?>
|
||||
182
admin/usuarios.php
Normal file
182
admin/usuarios.php
Normal file
|
|
@ -0,0 +1,182 @@
|
|||
<?php
|
||||
$adminSection = 'usuarios';
|
||||
$pageTitle = 'Usuarios';
|
||||
$pageHeading = 'Usuarios de acceso';
|
||||
require_once __DIR__ . '/../includes/admin_bootstrap.php';
|
||||
require_once __DIR__ . '/../config/database.php';
|
||||
|
||||
$db = getDB();
|
||||
$current = getCurrentUser();
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
$action = $_POST['action'] ?? '';
|
||||
|
||||
if ($action === 'create') {
|
||||
$usuario = trim($_POST['usuario'] ?? '');
|
||||
$password = $_POST['password'] ?? '';
|
||||
$nombre = trim($_POST['nombre'] ?? '');
|
||||
|
||||
if ($usuario === '' || strlen($password) < 6) {
|
||||
flash('danger', 'Usuario requerido y contraseña mínimo 6 caracteres.');
|
||||
} else {
|
||||
try {
|
||||
$hash = password_hash($password, PASSWORD_DEFAULT);
|
||||
$db->prepare('INSERT INTO usuarios (usuario, password_hash, nombre) VALUES (?, ?, ?)')
|
||||
->execute([$usuario, $hash, $nombre !== '' ? $nombre : null]);
|
||||
flash('success', 'Usuario agregado correctamente.');
|
||||
} catch (PDOException $e) {
|
||||
flash('danger', 'Ese nombre de usuario ya existe.');
|
||||
}
|
||||
}
|
||||
} elseif ($action === 'update') {
|
||||
$id = (int) ($_POST['id'] ?? 0);
|
||||
$nombre = trim($_POST['nombre'] ?? '');
|
||||
$activo = isset($_POST['activo']) ? 1 : 0;
|
||||
$password = $_POST['password'] ?? '';
|
||||
|
||||
if ($id <= 0) {
|
||||
flash('danger', 'Usuario no válido.');
|
||||
} elseif ($id === $current['id'] && !$activo) {
|
||||
flash('danger', 'No puede desactivar su propio usuario.');
|
||||
} elseif ($activo === 0 && countActiveUsers($db) <= 1) {
|
||||
flash('danger', 'Debe existir al menos un usuario activo.');
|
||||
} else {
|
||||
if ($password !== '') {
|
||||
if (strlen($password) < 6) {
|
||||
flash('danger', 'La contraseña debe tener al menos 6 caracteres.');
|
||||
redirect(BASE_URL . '/admin/usuarios.php');
|
||||
}
|
||||
$hash = password_hash($password, PASSWORD_DEFAULT);
|
||||
$db->prepare('UPDATE usuarios SET nombre = ?, activo = ?, password_hash = ? WHERE id = ?')
|
||||
->execute([$nombre !== '' ? $nombre : null, $activo, $hash, $id]);
|
||||
} else {
|
||||
$db->prepare('UPDATE usuarios SET nombre = ?, activo = ? WHERE id = ?')
|
||||
->execute([$nombre !== '' ? $nombre : null, $activo, $id]);
|
||||
}
|
||||
flash('success', 'Usuario actualizado.');
|
||||
}
|
||||
} elseif ($action === 'delete') {
|
||||
$id = (int) ($_POST['id'] ?? 0);
|
||||
if ($id === $current['id']) {
|
||||
flash('danger', 'No puede eliminar su propio usuario.');
|
||||
} elseif (countActiveUsers($db) <= 1) {
|
||||
$stmt = $db->prepare('SELECT activo FROM usuarios WHERE id = ?');
|
||||
$stmt->execute([$id]);
|
||||
$target = $stmt->fetch();
|
||||
if ($target && $target['activo']) {
|
||||
flash('danger', 'No puede eliminar el último usuario activo.');
|
||||
redirect(BASE_URL . '/admin/usuarios.php');
|
||||
}
|
||||
}
|
||||
if ($id > 0) {
|
||||
$db->prepare('DELETE FROM usuarios WHERE id = ?')->execute([$id]);
|
||||
flash('success', 'Usuario eliminado.');
|
||||
}
|
||||
}
|
||||
|
||||
redirect(BASE_URL . '/admin/usuarios.php');
|
||||
}
|
||||
|
||||
$usuarios = $db->query('SELECT * FROM usuarios ORDER BY usuario')->fetchAll();
|
||||
$flash = getFlash();
|
||||
require_once __DIR__ . '/../includes/admin_header.php';
|
||||
?>
|
||||
|
||||
<?php if ($flash): ?>
|
||||
<div class="alert alert-<?= h($flash['type']) ?> alert-dismissible fade show">
|
||||
<?= h($flash['message']) ?>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<div class="row g-4">
|
||||
<div class="col-lg-4">
|
||||
<div class="card">
|
||||
<div class="card-header">Nuevo usuario</div>
|
||||
<div class="card-body">
|
||||
<form method="post">
|
||||
<input type="hidden" name="action" value="create">
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Usuario <span class="text-danger">*</span></label>
|
||||
<input type="text" name="usuario" class="form-control" required maxlength="50"
|
||||
pattern="[a-zA-Z0-9._-]+" title="Solo letras, números, punto, guion y guion bajo">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Contraseña <span class="text-danger">*</span></label>
|
||||
<input type="password" name="password" class="form-control" required minlength="6">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Nombre completo</label>
|
||||
<input type="text" name="nombre" class="form-control" maxlength="100">
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary w-100">Agregar usuario</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-lg-8">
|
||||
<div class="card">
|
||||
<div class="card-header">Usuarios registrados (<?= count($usuarios) ?>)</div>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-hover mb-0">
|
||||
<thead class="table-light">
|
||||
<tr>
|
||||
<th>Usuario</th>
|
||||
<th>Nombre</th>
|
||||
<th>Activo</th>
|
||||
<th>Nueva contraseña</th>
|
||||
<th></th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach ($usuarios as $u): ?>
|
||||
<tr>
|
||||
<form method="post">
|
||||
<input type="hidden" name="action" value="update">
|
||||
<input type="hidden" name="id" value="<?= (int) $u['id'] ?>">
|
||||
<td>
|
||||
<strong><?= h($u['usuario']) ?></strong>
|
||||
<?php if ((int) $u['id'] === $current['id']): ?>
|
||||
<span class="badge bg-info ms-1">Tú</span>
|
||||
<?php endif; ?>
|
||||
</td>
|
||||
<td>
|
||||
<input type="text" name="nombre" class="form-control form-control-sm"
|
||||
value="<?= h($u['nombre'] ?? '') ?>" maxlength="100">
|
||||
</td>
|
||||
<td>
|
||||
<div class="form-check form-switch">
|
||||
<input class="form-check-input" type="checkbox" name="activo"
|
||||
<?= $u['activo'] ? 'checked' : '' ?>
|
||||
<?= (int) $u['id'] === $current['id'] ? 'disabled' : '' ?>>
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<input type="password" name="password" class="form-control form-control-sm"
|
||||
placeholder="Dejar vacío = sin cambio" minlength="6">
|
||||
</td>
|
||||
<td>
|
||||
<button type="submit" class="btn btn-sm btn-primary">Guardar</button>
|
||||
</td>
|
||||
</form>
|
||||
<td>
|
||||
<?php if ((int) $u['id'] !== $current['id']): ?>
|
||||
<form method="post" onsubmit="return confirm('¿Eliminar usuario <?= h($u['usuario']) ?>?');">
|
||||
<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">Eliminar</button>
|
||||
</form>
|
||||
<?php endif; ?>
|
||||
</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php require_once __DIR__ . '/../includes/admin_footer.php'; ?>
|
||||
53
api/guardar.php
Normal file
53
api/guardar.php
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
<?php
|
||||
require_once __DIR__ . '/../config/config.php';
|
||||
require_once __DIR__ . '/../config/database.php';
|
||||
require_once __DIR__ . '/../includes/functions.php';
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
redirect(BASE_URL . '/formulario.php');
|
||||
}
|
||||
|
||||
$ubicacionCodigo = trim($_POST['ubicacion_codigo'] ?? '');
|
||||
$empresaId = (int) ($_POST['empresa_id'] ?? 0);
|
||||
$servicioId = (int) ($_POST['servicio_id'] ?? 0);
|
||||
$observaciones = trim($_POST['observaciones'] ?? '');
|
||||
$registradoPor = trim($_POST['registrado_por'] ?? '');
|
||||
|
||||
$redirectError = BASE_URL . '/formulario.php?u=' . urlencode($ubicacionCodigo);
|
||||
|
||||
if ($ubicacionCodigo === '' || $empresaId <= 0 || $servicioId <= 0) {
|
||||
redirect($redirectError);
|
||||
}
|
||||
|
||||
try {
|
||||
$db = getDB();
|
||||
$ubicacion = getUbicacionByCodigo($db, $ubicacionCodigo);
|
||||
if (!$ubicacion) {
|
||||
redirect($redirectError);
|
||||
}
|
||||
|
||||
$stmtCheck = $db->prepare('
|
||||
SELECT id FROM servicios
|
||||
WHERE id = ? AND empresa_id = ? AND activo = 1
|
||||
');
|
||||
$stmtCheck->execute([$servicioId, $empresaId]);
|
||||
if (!$stmtCheck->fetch()) {
|
||||
redirect($redirectError);
|
||||
}
|
||||
|
||||
$stmt = $db->prepare('
|
||||
INSERT INTO registros (ubicacion_id, empresa_id, servicio_id, observaciones, registrado_por)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
');
|
||||
$stmt->execute([
|
||||
$ubicacion['id'],
|
||||
$empresaId,
|
||||
$servicioId,
|
||||
$observaciones !== '' ? $observaciones : null,
|
||||
$registradoPor !== '' ? $registradoPor : null,
|
||||
]);
|
||||
|
||||
redirect(BASE_URL . '/formulario.php?u=' . urlencode($ubicacionCodigo) . '&ok=1');
|
||||
} catch (Throwable $e) {
|
||||
redirect($redirectError);
|
||||
}
|
||||
20
api/servicios.php
Normal file
20
api/servicios.php
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
<?php
|
||||
require_once __DIR__ . '/../config/config.php';
|
||||
require_once __DIR__ . '/../config/database.php';
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
|
||||
$empresaId = (int) ($_GET['empresa_id'] ?? 0);
|
||||
if ($empresaId <= 0) {
|
||||
echo json_encode([]);
|
||||
exit;
|
||||
}
|
||||
|
||||
$db = getDB();
|
||||
$stmt = $db->prepare('
|
||||
SELECT id, nombre FROM servicios
|
||||
WHERE empresa_id = ? AND activo = 1
|
||||
ORDER BY nombre
|
||||
');
|
||||
$stmt->execute([$empresaId]);
|
||||
echo json_encode($stmt->fetchAll(), JSON_UNESCAPED_UNICODE);
|
||||
193
assets/css/admin.css
Normal file
193
assets/css/admin.css
Normal file
|
|
@ -0,0 +1,193 @@
|
|||
.admin-body {
|
||||
background: #eef1f8;
|
||||
}
|
||||
|
||||
.admin-wrapper {
|
||||
display: flex;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.admin-sidebar {
|
||||
width: 260px;
|
||||
background: var(--camp-blue);
|
||||
color: #fff;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
bottom: 0;
|
||||
z-index: 1040;
|
||||
transition: transform 0.25s ease;
|
||||
}
|
||||
|
||||
.sidebar-brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 20px 18px;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.12);
|
||||
}
|
||||
|
||||
.sidebar-logo {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
object-fit: contain;
|
||||
background: #fff;
|
||||
border-radius: 8px;
|
||||
padding: 4px;
|
||||
}
|
||||
|
||||
.sidebar-logo-icon {
|
||||
font-size: 40px;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.sidebar-title {
|
||||
font-weight: 700;
|
||||
font-size: 0.95rem;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.sidebar-subtitle {
|
||||
font-size: 0.75rem;
|
||||
opacity: 0.75;
|
||||
}
|
||||
|
||||
.sidebar-nav {
|
||||
flex: 1;
|
||||
padding: 12px 10px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.sidebar-link {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 10px 14px;
|
||||
color: rgba(255, 255, 255, 0.85);
|
||||
text-decoration: none;
|
||||
border-radius: 8px;
|
||||
margin-bottom: 4px;
|
||||
font-size: 0.925rem;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
|
||||
.sidebar-link .material-symbols-outlined {
|
||||
font-size: 22px;
|
||||
}
|
||||
|
||||
.sidebar-link:hover {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.sidebar-link.active {
|
||||
background: rgba(255, 255, 255, 0.18);
|
||||
color: #fff;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.sidebar-footer {
|
||||
padding: 12px 10px 16px;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.12);
|
||||
}
|
||||
|
||||
.admin-main {
|
||||
flex: 1;
|
||||
margin-left: 260px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.admin-topbar {
|
||||
background: #fff;
|
||||
border-bottom: 1px solid #e3e8f0;
|
||||
padding: 14px 24px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 1020;
|
||||
}
|
||||
|
||||
.topbar-title {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 600;
|
||||
margin: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.sidebar-toggle {
|
||||
color: var(--camp-blue);
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.admin-content {
|
||||
padding: 24px;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.admin-footer {
|
||||
padding: 12px 24px;
|
||||
font-size: 0.8rem;
|
||||
border-top: 1px solid #e3e8f0;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.stat-icon {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
border-radius: 12px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: rgba(19, 42, 124, 0.1);
|
||||
color: var(--camp-blue);
|
||||
}
|
||||
|
||||
.stat-icon .material-symbols-outlined {
|
||||
font-size: 26px;
|
||||
}
|
||||
|
||||
.qr-preview-box {
|
||||
background: #fff;
|
||||
border-radius: 12px;
|
||||
padding: 20px;
|
||||
text-align: center;
|
||||
border: 1px solid #e3e8f0;
|
||||
}
|
||||
|
||||
.qr-preview-box img {
|
||||
max-width: 280px;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
.quick-link-card {
|
||||
transition: transform 0.15s, box-shadow 0.15s;
|
||||
cursor: pointer;
|
||||
text-decoration: none;
|
||||
color: inherit;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.quick-link-card:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 6px 20px rgba(19, 42, 124, 0.12);
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
@media (max-width: 991.98px) {
|
||||
.admin-sidebar {
|
||||
transform: translateX(-100%);
|
||||
}
|
||||
.admin-sidebar.show {
|
||||
transform: translateX(0);
|
||||
}
|
||||
.admin-main {
|
||||
margin-left: 0;
|
||||
}
|
||||
}
|
||||
80
assets/css/style.css
Normal file
80
assets/css/style.css
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
:root {
|
||||
--camp-blue: #132A7C;
|
||||
}
|
||||
|
||||
body {
|
||||
background-color: #f4f6fb;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.navbar.bg-primary {
|
||||
background-color: var(--camp-blue) !important;
|
||||
}
|
||||
|
||||
.material-symbols-outlined {
|
||||
vertical-align: middle;
|
||||
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 24;
|
||||
}
|
||||
|
||||
.card {
|
||||
border: none;
|
||||
box-shadow: 0 2px 12px rgba(19, 42, 124, 0.08);
|
||||
}
|
||||
|
||||
.card-header {
|
||||
background: #fff;
|
||||
border-bottom: 1px solid #e9ecef;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.form-control:read-only,
|
||||
.form-control[readonly] {
|
||||
background-color: #e9ecef;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.badge-codigo {
|
||||
font-family: monospace;
|
||||
font-size: 0.85em;
|
||||
}
|
||||
|
||||
.qr-form-card {
|
||||
max-width: 520px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.stat-card {
|
||||
border-left: 4px solid var(--camp-blue);
|
||||
}
|
||||
|
||||
.table-codigo {
|
||||
font-family: monospace;
|
||||
font-size: 0.9em;
|
||||
color: #6c757d;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background-color: var(--camp-blue);
|
||||
border-color: var(--camp-blue);
|
||||
}
|
||||
|
||||
.btn-primary:hover,
|
||||
.btn-primary:focus {
|
||||
background-color: #0f2060;
|
||||
border-color: #0f2060;
|
||||
}
|
||||
|
||||
.alert-success-form {
|
||||
animation: fadeIn 0.4s ease;
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from { opacity: 0; transform: translateY(-8px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
@media (max-width: 576px) {
|
||||
.table-responsive {
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
}
|
||||
9
assets/js/admin.js
Normal file
9
assets/js/admin.js
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
document.addEventListener('DOMContentLoaded', function () {
|
||||
var toggle = document.getElementById('sidebarToggle');
|
||||
var sidebar = document.getElementById('adminSidebar');
|
||||
if (toggle && sidebar) {
|
||||
toggle.addEventListener('click', function () {
|
||||
sidebar.classList.toggle('show');
|
||||
});
|
||||
}
|
||||
});
|
||||
33
assets/js/formulario.js
Normal file
33
assets/js/formulario.js
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
document.addEventListener('DOMContentLoaded', function () {
|
||||
var empresaSelect = document.getElementById('empresa_id');
|
||||
var servicioSelect = document.getElementById('servicio_id');
|
||||
var servicioBlock = document.getElementById('servicioBlock');
|
||||
var servicioLabel = document.getElementById('servicioLabel');
|
||||
|
||||
if (!empresaSelect || !servicioSelect) return;
|
||||
|
||||
empresaSelect.addEventListener('change', function () {
|
||||
var empresaId = this.value;
|
||||
servicioSelect.innerHTML = '<option value="">— Seleccione servicio —</option>';
|
||||
servicioSelect.required = false;
|
||||
servicioBlock.classList.add('d-none');
|
||||
|
||||
if (!empresaId) return;
|
||||
|
||||
var empresaNombre = empresaSelect.options[empresaSelect.selectedIndex].text;
|
||||
servicioLabel.textContent = empresaNombre;
|
||||
|
||||
fetch('api/servicios.php?empresa_id=' + encodeURIComponent(empresaId))
|
||||
.then(function (r) { return r.json(); })
|
||||
.then(function (items) {
|
||||
items.forEach(function (item) {
|
||||
var opt = document.createElement('option');
|
||||
opt.value = item.id;
|
||||
opt.textContent = item.nombre;
|
||||
servicioSelect.appendChild(opt);
|
||||
});
|
||||
servicioBlock.classList.remove('d-none');
|
||||
servicioSelect.required = true;
|
||||
});
|
||||
});
|
||||
});
|
||||
17
config/config.php
Normal file
17
config/config.php
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
<?php
|
||||
/**
|
||||
* Configuración general del sistema de mantenimiento
|
||||
*/
|
||||
define('DB_HOST', 'localhost');
|
||||
define('DB_NAME', 'mantenimiento_campamento');
|
||||
define('DB_USER', 'root');
|
||||
define('DB_PASS', 'R3m4st3r');
|
||||
define('DB_CHARSET', 'utf8mb4');
|
||||
|
||||
// Cambiar según la URL donde esté alojada la aplicación
|
||||
define('BASE_URL', 'http://localhost:8080');
|
||||
|
||||
define('APP_NAME', 'Mantenimiento Campamento');
|
||||
define('APP_VERSION', '1.0.0');
|
||||
|
||||
date_default_timezone_set('America/Hermosillo');
|
||||
25
config/database.php
Normal file
25
config/database.php
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
<?php
|
||||
require_once __DIR__ . '/config.php';
|
||||
|
||||
function getDB(): PDO
|
||||
{
|
||||
static $pdo = null;
|
||||
if ($pdo === null) {
|
||||
$dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET;
|
||||
$pdo = new PDO($dsn, DB_USER, DB_PASS, [
|
||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
||||
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
|
||||
PDO::ATTR_EMULATE_PREPARES => false,
|
||||
]);
|
||||
}
|
||||
return $pdo;
|
||||
}
|
||||
|
||||
function getDBWithoutName(): PDO
|
||||
{
|
||||
$dsn = 'mysql:host=' . DB_HOST . ';charset=' . DB_CHARSET;
|
||||
return new PDO($dsn, DB_USER, DB_PASS, [
|
||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
||||
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
|
||||
]);
|
||||
}
|
||||
115
formulario.php
Normal file
115
formulario.php
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
<?php
|
||||
require_once __DIR__ . '/includes/header.php';
|
||||
require_once __DIR__ . '/config/database.php';
|
||||
|
||||
$codigo = trim($_GET['u'] ?? '');
|
||||
$error = null;
|
||||
$ubicacion = null;
|
||||
$empresas = [];
|
||||
$guardado = isset($_GET['ok']);
|
||||
$extraJs = 'formulario.js';
|
||||
|
||||
if ($codigo === '') {
|
||||
$error = 'Código de ubicación no proporcionado. Escanee el código QR correcto.';
|
||||
} else {
|
||||
try {
|
||||
$db = getDB();
|
||||
$ubicacion = getUbicacionByCodigo($db, $codigo);
|
||||
if (!$ubicacion) {
|
||||
$error = 'Ubicación no encontrada o inactiva. Verifique el código QR.';
|
||||
} else {
|
||||
$empresas = $db->query('SELECT id, nombre FROM empresas WHERE activo = 1 ORDER BY nombre')->fetchAll();
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
$error = 'Error de conexión. Contacte al administrador.';
|
||||
}
|
||||
}
|
||||
|
||||
$pageTitle = 'Registro de mantenimiento';
|
||||
?>
|
||||
|
||||
<div class="container py-4">
|
||||
<?php if ($guardado): ?>
|
||||
<div class="alert alert-success alert-success-form text-center qr-form-card">
|
||||
<span class="material-symbols-outlined d-block mb-2" style="font-size:48px">check_circle</span>
|
||||
<h5>¡Registro guardado!</h5>
|
||||
<p class="mb-3 text-muted">El mantenimiento quedó registrado correctamente.</p>
|
||||
<a href="formulario.php?u=<?= h($codigo) ?>" class="btn btn-primary">Registrar otro en esta ubicación</a>
|
||||
</div>
|
||||
<?php elseif ($error): ?>
|
||||
<div class="alert alert-danger qr-form-card text-center">
|
||||
<span class="material-symbols-outlined d-block mb-2" style="font-size:48px">error</span>
|
||||
<h5>No se puede abrir el formulario</h5>
|
||||
<p class="mb-0"><?= h($error) ?></p>
|
||||
</div>
|
||||
<?php else: ?>
|
||||
<div class="card qr-form-card">
|
||||
<div class="card-header text-center py-3">
|
||||
<?php if (file_exists(__DIR__ . '/NEM.png')): ?>
|
||||
<img src="<?= BASE_URL ?>/NEM.png" alt="Logo" style="height:48px" class="mb-2">
|
||||
<?php endif; ?>
|
||||
<h4 class="mb-0">Registro de mantenimiento</h4>
|
||||
<small class="text-muted">Datos automáticos + servicio realizado</small>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<form id="formMantenimiento" method="post" action="api/guardar.php" novalidate>
|
||||
<input type="hidden" name="ubicacion_codigo" value="<?= h($ubicacion['ubicacion_codigo']) ?>">
|
||||
|
||||
<p class="text-muted small fw-semibold mb-3">Datos automáticos</p>
|
||||
|
||||
<div class="mb-3">
|
||||
<label class="form-label fw-semibold">1. Módulo</label>
|
||||
<input type="text" class="form-control" readonly value="<?= h($ubicacion['modulo_nombre']) ?>">
|
||||
<div class="form-text table-codigo"><?= h($ubicacion['modulo_codigo']) ?></div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label class="form-label fw-semibold">2. Habitación</label>
|
||||
<input type="text" class="form-control" readonly value="<?= h($ubicacion['ubicacion_nombre']) ?>">
|
||||
<div class="form-text table-codigo"><?= h($ubicacion['ubicacion_codigo']) ?></div>
|
||||
</div>
|
||||
|
||||
<hr>
|
||||
|
||||
<div class="mb-3">
|
||||
<label for="empresa_id" class="form-label fw-semibold">3. Empresa <span class="text-danger">*</span></label>
|
||||
<select class="form-select" id="empresa_id" name="empresa_id" required>
|
||||
<option value="">— Seleccione empresa —</option>
|
||||
<?php foreach ($empresas as $e): ?>
|
||||
<option value="<?= (int) $e['id'] ?>"><?= h($e['nombre']) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="mb-4 d-none" id="servicioBlock">
|
||||
<label for="servicio_id" class="form-label fw-semibold">
|
||||
<span id="servicioLabel">Servicio</span> <span class="text-danger">*</span>
|
||||
</label>
|
||||
<select class="form-select" id="servicio_id" name="servicio_id">
|
||||
<option value="">— Seleccione servicio —</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label for="registrado_por" class="form-label fw-semibold">Registrado por</label>
|
||||
<input type="text" class="form-control" id="registrado_por" name="registrado_por"
|
||||
maxlength="100" placeholder="Nombre del técnico (opcional)">
|
||||
</div>
|
||||
|
||||
<div class="mb-4">
|
||||
<label for="observaciones" class="form-label fw-semibold">Observaciones</label>
|
||||
<textarea class="form-control" id="observaciones" name="observaciones" rows="2"
|
||||
maxlength="2000" placeholder="Opcional"></textarea>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-primary w-100 py-2">
|
||||
<span class="material-symbols-outlined align-middle me-1" style="font-size:20px">save</span>
|
||||
Enviar
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
|
||||
<?php require_once __DIR__ . '/includes/footer.php'; ?>
|
||||
114
generate_qrs.py
Normal file
114
generate_qrs.py
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
# Genera códigos QR para el sistema de mantenimiento del campamento.
|
||||
# Mismo formato visual que la versión anterior: color #132A7C, logo NEM.png,
|
||||
# pie de foto "Módulo | Habitación".
|
||||
import csv
|
||||
import qrcode
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
import os
|
||||
import re
|
||||
|
||||
CSV_FILE = "qr_data.csv"
|
||||
LOGO_FILE = "NEM.png"
|
||||
OUTPUT_DIR = "output"
|
||||
QR_COLOR = "#132A7C"
|
||||
BG_COLOR = "#FFFFFF"
|
||||
QR_SIZE = 400
|
||||
LOGO_SIZE = 80
|
||||
FOOTER_HEIGHT = 60
|
||||
PADDING = 20
|
||||
|
||||
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
||||
|
||||
if not os.path.exists(CSV_FILE):
|
||||
print(f"Error: no se encontró '{CSV_FILE}'.")
|
||||
print("Ejecute install.php o exporte desde el panel admin.")
|
||||
raise SystemExit(1)
|
||||
|
||||
logo = None
|
||||
if os.path.exists(LOGO_FILE):
|
||||
logo = Image.open(LOGO_FILE).convert("RGBA")
|
||||
logo.thumbnail((LOGO_SIZE, LOGO_SIZE), Image.LANCZOS)
|
||||
logo_bg = Image.new("RGBA", (logo.width + 12, logo.height + 12), "white")
|
||||
logo_bg.paste(logo, (6, 6), logo)
|
||||
logo = logo_bg
|
||||
else:
|
||||
print("Advertencia: NEM.png no encontrado. QR sin logo.")
|
||||
|
||||
try:
|
||||
font = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 22)
|
||||
except Exception:
|
||||
try:
|
||||
font = ImageFont.truetype("/Library/Fonts/Arial.ttf", 22)
|
||||
except Exception:
|
||||
font = ImageFont.load_default()
|
||||
|
||||
|
||||
def safe_filename(text):
|
||||
return re.sub(r'[\\/:*?"<>|]', "-", text)
|
||||
|
||||
|
||||
def generate_qr(url, filename, caption_modulo, caption_ubicacion):
|
||||
qr = qrcode.QRCode(
|
||||
version=None,
|
||||
error_correction=qrcode.constants.ERROR_CORRECT_H,
|
||||
box_size=10,
|
||||
border=4,
|
||||
)
|
||||
qr.add_data(url)
|
||||
qr.make(fit=True)
|
||||
|
||||
qr_img = qr.make_image(fill_color=QR_COLOR, back_color=BG_COLOR).convert("RGB")
|
||||
qr_img = qr_img.resize((QR_SIZE, QR_SIZE), Image.LANCZOS)
|
||||
|
||||
if logo:
|
||||
qr_img_rgba = qr_img.convert("RGBA")
|
||||
logo_x = (QR_SIZE - logo.width) // 2
|
||||
logo_y = (QR_SIZE - logo.height) // 2
|
||||
qr_img_rgba.paste(logo, (logo_x, logo_y), logo)
|
||||
qr_img = qr_img_rgba
|
||||
|
||||
total_width = QR_SIZE + PADDING * 2
|
||||
total_height = QR_SIZE + FOOTER_HEIGHT + PADDING * 2
|
||||
|
||||
final = Image.new("RGB", (total_width, total_height), BG_COLOR)
|
||||
final.paste(qr_img.convert("RGB"), (PADDING, PADDING))
|
||||
|
||||
draw = ImageDraw.Draw(final)
|
||||
caption = f"{caption_modulo} | {caption_ubicacion}"
|
||||
bbox = draw.textbbox((0, 0), caption, font=font)
|
||||
text_w = bbox[2] - bbox[0]
|
||||
text_h = bbox[3] - bbox[1]
|
||||
text_x = (total_width - text_w) // 2
|
||||
text_y = QR_SIZE + PADDING + (FOOTER_HEIGHT - text_h) // 2
|
||||
draw.text((text_x, text_y), caption, fill=QR_COLOR, font=font)
|
||||
|
||||
filepath = os.path.join(OUTPUT_DIR, filename)
|
||||
final.save(filepath, "PNG")
|
||||
return filepath
|
||||
|
||||
|
||||
count = 0
|
||||
used_filenames = set()
|
||||
with open(CSV_FILE, newline="", encoding="utf-8") as f:
|
||||
reader = csv.DictReader(f)
|
||||
for row in reader:
|
||||
codigo = row["codigo"].strip()
|
||||
modulo = row["modulo"].strip()
|
||||
ubicacion = row["ubicacion"].strip()
|
||||
url = row["url"].strip()
|
||||
|
||||
if not url or not codigo:
|
||||
continue
|
||||
|
||||
base_name = f"{safe_filename(modulo)}_{safe_filename(ubicacion)}"
|
||||
filename = f"{base_name}.png"
|
||||
if filename in used_filenames:
|
||||
filename = f"{base_name}_{safe_filename(codigo)}.png"
|
||||
used_filenames.add(filename)
|
||||
|
||||
generate_qr(url, filename, modulo, ubicacion)
|
||||
count += 1
|
||||
if count % 100 == 0:
|
||||
print(f"Progreso: {count} QR generados...")
|
||||
|
||||
print(f"\nListo! {count} códigos QR guardados en '{OUTPUT_DIR}/'")
|
||||
12
includes/admin_bootstrap.php
Normal file
12
includes/admin_bootstrap.php
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
<?php
|
||||
if (session_status() === PHP_SESSION_NONE) {
|
||||
session_start();
|
||||
}
|
||||
require_once __DIR__ . '/../config/config.php';
|
||||
require_once __DIR__ . '/functions.php';
|
||||
require_once __DIR__ . '/auth.php';
|
||||
|
||||
if (empty($skipAdminAuth)) {
|
||||
require_once __DIR__ . '/../config/database.php';
|
||||
requireAdmin();
|
||||
}
|
||||
13
includes/admin_footer.php
Normal file
13
includes/admin_footer.php
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
</div>
|
||||
<footer class="admin-footer text-muted">
|
||||
<?= h(APP_NAME) ?> v<?= h(APP_VERSION) ?>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<script src="<?= BASE_URL ?>/assets/js/admin.js"></script>
|
||||
<?php if (!empty($extraJs)): ?>
|
||||
<script src="<?= BASE_URL ?>/assets/js/<?= h($extraJs) ?>"></script>
|
||||
<?php endif; ?>
|
||||
</body>
|
||||
</html>
|
||||
81
includes/admin_header.php
Normal file
81
includes/admin_header.php
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
<?php
|
||||
require_once __DIR__ . '/admin_bootstrap.php';
|
||||
|
||||
$adminPage = basename($_SERVER['PHP_SELF'], '.php');
|
||||
$adminSection = $adminSection ?? $adminPage;
|
||||
|
||||
$navItems = [
|
||||
['id' => 'index', 'href' => 'index.php', 'icon' => 'dashboard', 'label' => 'Panel'],
|
||||
['id' => 'registros', 'href' => 'registros.php', 'icon' => 'list_alt', 'label' => 'Registros'],
|
||||
['id' => 'modulos', 'href' => 'modulos.php', 'icon' => 'domain', 'label' => 'Módulos'],
|
||||
['id' => 'ubicaciones', 'href' => 'ubicaciones.php', 'icon' => 'location_on', 'label' => 'Ubicaciones'],
|
||||
['id' => 'empresas', 'href' => 'empresas.php', 'icon' => 'business', 'label' => 'Empresas'],
|
||||
['id' => 'servicios', 'href' => 'servicios.php', 'icon' => 'handyman', 'label' => 'Servicios'],
|
||||
['id' => 'qrs', 'href' => 'qrs.php', 'icon' => 'qr_code_2', 'label' => 'Códigos QR'],
|
||||
['id' => 'usuarios', 'href' => 'usuarios.php', 'icon' => 'group', 'label' => 'Usuarios'],
|
||||
];
|
||||
$currentUser = getCurrentUser();
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title><?= h($pageTitle ?? 'Admin - ' . APP_NAME) ?></title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined" rel="stylesheet">
|
||||
<link href="<?= BASE_URL ?>/assets/css/style.css" rel="stylesheet">
|
||||
<link href="<?= BASE_URL ?>/assets/css/admin.css" rel="stylesheet">
|
||||
</head>
|
||||
<body class="admin-body">
|
||||
<div class="admin-wrapper">
|
||||
<aside class="admin-sidebar" id="adminSidebar">
|
||||
<div class="sidebar-brand">
|
||||
<?php if (file_exists(dirname(__DIR__) . '/NEM.png')): ?>
|
||||
<img src="<?= BASE_URL ?>/NEM.png" alt="Logo" class="sidebar-logo">
|
||||
<?php else: ?>
|
||||
<span class="material-symbols-outlined sidebar-logo-icon">construction</span>
|
||||
<?php endif; ?>
|
||||
<div>
|
||||
<div class="sidebar-title"><?= h(APP_NAME) ?></div>
|
||||
<div class="sidebar-subtitle">Administración</div>
|
||||
</div>
|
||||
</div>
|
||||
<nav class="sidebar-nav">
|
||||
<?php foreach ($navItems as $item): ?>
|
||||
<a href="<?= BASE_URL ?>/admin/<?= h($item['href']) ?>"
|
||||
class="sidebar-link <?= $adminSection === $item['id'] ? 'active' : '' ?>">
|
||||
<span class="material-symbols-outlined"><?= h($item['icon']) ?></span>
|
||||
<?= h($item['label']) ?>
|
||||
</a>
|
||||
<?php endforeach; ?>
|
||||
</nav>
|
||||
<div class="sidebar-footer">
|
||||
<a href="<?= BASE_URL ?>/formulario.php?u=UB-00001" target="_blank" class="sidebar-link">
|
||||
<span class="material-symbols-outlined">open_in_new</span>
|
||||
Ver formulario
|
||||
</a>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<div class="admin-main">
|
||||
<header class="admin-topbar">
|
||||
<button class="btn btn-link sidebar-toggle d-lg-none" type="button" id="sidebarToggle">
|
||||
<span class="material-symbols-outlined">menu</span>
|
||||
</button>
|
||||
<h1 class="topbar-title"><?= h($pageHeading ?? 'Panel') ?></h1>
|
||||
<div class="topbar-actions d-flex align-items-center gap-2">
|
||||
<?php if ($currentUser): ?>
|
||||
<span class="text-muted small d-none d-md-inline">
|
||||
<span class="material-symbols-outlined align-middle" style="font-size:18px">person</span>
|
||||
<?= h($currentUser['nombre'] ?: $currentUser['usuario']) ?>
|
||||
</span>
|
||||
<a href="<?= BASE_URL ?>/admin/logout.php" class="btn btn-outline-secondary btn-sm">
|
||||
<span class="material-symbols-outlined align-middle" style="font-size:18px">logout</span>
|
||||
Salir
|
||||
</a>
|
||||
<?php endif; ?>
|
||||
<?php if (!empty($topbarActions)) echo $topbarActions; ?>
|
||||
</div>
|
||||
</header>
|
||||
<div class="admin-content">
|
||||
64
includes/auth.php
Normal file
64
includes/auth.php
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
<?php
|
||||
|
||||
function getCurrentUser(): ?array
|
||||
{
|
||||
if (empty($_SESSION['usuario_id'])) {
|
||||
return null;
|
||||
}
|
||||
return [
|
||||
'id' => (int) $_SESSION['usuario_id'],
|
||||
'usuario' => $_SESSION['usuario'] ?? '',
|
||||
'nombre' => $_SESSION['usuario_nombre'] ?? '',
|
||||
];
|
||||
}
|
||||
|
||||
function isLoggedIn(): bool
|
||||
{
|
||||
return getCurrentUser() !== null;
|
||||
}
|
||||
|
||||
function requireAdmin(): void
|
||||
{
|
||||
if (isLoggedIn()) {
|
||||
return;
|
||||
}
|
||||
$return = urlencode($_SERVER['REQUEST_URI'] ?? BASE_URL . '/admin/index.php');
|
||||
header('Location: ' . BASE_URL . '/admin/login.php?return=' . $return);
|
||||
exit;
|
||||
}
|
||||
|
||||
function loginUser(PDO $db, string $usuario, string $password): bool
|
||||
{
|
||||
$stmt = $db->prepare('SELECT id, usuario, nombre, password_hash FROM usuarios WHERE usuario = ? AND activo = 1');
|
||||
$stmt->execute([$usuario]);
|
||||
$row = $stmt->fetch();
|
||||
if (!$row || !password_verify($password, $row['password_hash'])) {
|
||||
return false;
|
||||
}
|
||||
$_SESSION['usuario_id'] = (int) $row['id'];
|
||||
$_SESSION['usuario'] = $row['usuario'];
|
||||
$_SESSION['usuario_nombre'] = $row['nombre'] ?? $row['usuario'];
|
||||
return true;
|
||||
}
|
||||
|
||||
function logoutUser(): void
|
||||
{
|
||||
unset($_SESSION['usuario_id'], $_SESSION['usuario'], $_SESSION['usuario_nombre']);
|
||||
}
|
||||
|
||||
function countActiveUsers(PDO $db): int
|
||||
{
|
||||
return (int) $db->query('SELECT COUNT(*) FROM usuarios WHERE activo = 1')->fetchColumn();
|
||||
}
|
||||
|
||||
function seedDefaultAdmin(PDO $db): bool
|
||||
{
|
||||
$count = (int) $db->query('SELECT COUNT(*) FROM usuarios')->fetchColumn();
|
||||
if ($count > 0) {
|
||||
return false;
|
||||
}
|
||||
$hash = password_hash('admin123', PASSWORD_DEFAULT);
|
||||
$stmt = $db->prepare('INSERT INTO usuarios (usuario, password_hash, nombre) VALUES (?, ?, ?)');
|
||||
$stmt->execute(['admin', $hash, 'Administrador']);
|
||||
return true;
|
||||
}
|
||||
7
includes/footer.php
Normal file
7
includes/footer.php
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
</main>
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<?php if (!empty($extraJs)): ?>
|
||||
<script src="<?= BASE_URL ?>/assets/js/<?= h($extraJs) ?>"></script>
|
||||
<?php endif; ?>
|
||||
</body>
|
||||
</html>
|
||||
76
includes/functions.php
Normal file
76
includes/functions.php
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
<?php
|
||||
|
||||
function h(?string $s): string
|
||||
{
|
||||
return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8');
|
||||
}
|
||||
|
||||
function redirect(string $url): never
|
||||
{
|
||||
header('Location: ' . $url);
|
||||
exit;
|
||||
}
|
||||
|
||||
function flash(string $type, string $message): void
|
||||
{
|
||||
$_SESSION['flash'] = ['type' => $type, 'message' => $message];
|
||||
}
|
||||
|
||||
function getFlash(): ?array
|
||||
{
|
||||
if (!isset($_SESSION['flash'])) {
|
||||
return null;
|
||||
}
|
||||
$flash = $_SESSION['flash'];
|
||||
unset($_SESSION['flash']);
|
||||
return $flash;
|
||||
}
|
||||
|
||||
function getUbicacionByCodigo(PDO $db, string $codigo): ?array
|
||||
{
|
||||
$stmt = $db->prepare('
|
||||
SELECT u.id, u.codigo AS ubicacion_codigo, u.nombre AS ubicacion_nombre,
|
||||
m.id AS modulo_id, m.codigo AS modulo_codigo, m.nombre AS modulo_nombre
|
||||
FROM ubicaciones u
|
||||
JOIN modulos m ON m.id = u.modulo_id
|
||||
WHERE u.codigo = ? AND u.activo = 1 AND m.activo = 1
|
||||
');
|
||||
$stmt->execute([$codigo]);
|
||||
$row = $stmt->fetch();
|
||||
return $row ?: null;
|
||||
}
|
||||
|
||||
function formatFecha(?string $datetime): string
|
||||
{
|
||||
if (!$datetime) {
|
||||
return '';
|
||||
}
|
||||
$dt = new DateTime($datetime);
|
||||
return $dt->format('d/m/Y H:i');
|
||||
}
|
||||
|
||||
function nextModuloCodigo(PDO $db): string
|
||||
{
|
||||
$row = $db->query("SELECT codigo FROM modulos WHERE codigo REGEXP '^MOD-[0-9]+$' ORDER BY CAST(SUBSTRING(codigo, 5) AS UNSIGNED) DESC LIMIT 1")->fetch();
|
||||
$num = $row ? (int) substr($row['codigo'], 4) : 0;
|
||||
return sprintf('MOD-%03d', $num + 1);
|
||||
}
|
||||
|
||||
function nextUbicacionCodigo(PDO $db): string
|
||||
{
|
||||
$row = $db->query("SELECT codigo FROM ubicaciones WHERE codigo REGEXP '^UB-[0-9]+$' ORDER BY CAST(SUBSTRING(codigo, 4) AS UNSIGNED) DESC LIMIT 1")->fetch();
|
||||
$num = $row ? (int) substr($row['codigo'], 4) : 0;
|
||||
return sprintf('UB-%05d', $num + 1);
|
||||
}
|
||||
|
||||
function appendUbicacionToQrCsv(string $codigo, string $modulo, string $ubicacion): void
|
||||
{
|
||||
$path = dirname(__DIR__) . '/qr_data.csv';
|
||||
$exists = file_exists($path);
|
||||
$fh = fopen($path, 'a');
|
||||
if (!$exists) {
|
||||
fputcsv($fh, ['codigo', 'modulo', 'ubicacion', 'url']);
|
||||
}
|
||||
fputcsv($fh, [$codigo, $modulo, $ubicacion, BASE_URL . '/formulario.php?u=' . $codigo]);
|
||||
fclose($fh);
|
||||
}
|
||||
63
includes/header.php
Normal file
63
includes/header.php
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
<?php
|
||||
if (session_status() === PHP_SESSION_NONE) {
|
||||
session_start();
|
||||
}
|
||||
require_once __DIR__ . '/../config/config.php';
|
||||
require_once __DIR__ . '/functions.php';
|
||||
|
||||
$currentPage = basename($_SERVER['PHP_SELF'], '.php');
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title><?= h($pageTitle ?? APP_NAME) ?></title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined" rel="stylesheet">
|
||||
<link href="<?= BASE_URL ?>/assets/css/style.css" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<?php if (!empty($showNav)): ?>
|
||||
<nav class="navbar navbar-expand-lg navbar-dark bg-primary shadow-sm">
|
||||
<div class="container">
|
||||
<a class="navbar-brand d-flex align-items-center gap-2" href="<?= BASE_URL ?>/index.php">
|
||||
<span class="material-symbols-outlined">construction</span>
|
||||
<?= h(APP_NAME) ?>
|
||||
</a>
|
||||
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navMain">
|
||||
<span class="navbar-toggler-icon"></span>
|
||||
</button>
|
||||
<div class="collapse navbar-collapse" id="navMain">
|
||||
<ul class="navbar-nav ms-auto">
|
||||
<li class="nav-item">
|
||||
<a class="nav-link <?= $currentPage === 'index' ? 'active' : '' ?>" href="<?= BASE_URL ?>/index.php">
|
||||
<span class="material-symbols-outlined align-middle me-1" style="font-size:18px">dashboard</span>
|
||||
Inicio
|
||||
</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link <?= $currentPage === 'registros' ? 'active' : '' ?>" href="<?= BASE_URL ?>/admin/registros.php">
|
||||
<span class="material-symbols-outlined align-middle me-1" style="font-size:18px">list_alt</span>
|
||||
Registros
|
||||
</a>
|
||||
</li>
|
||||
<li class="nav-item dropdown">
|
||||
<a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown">
|
||||
<span class="material-symbols-outlined align-middle me-1" style="font-size:18px">settings</span>
|
||||
Catálogos
|
||||
</a>
|
||||
<ul class="dropdown-menu dropdown-menu-end">
|
||||
<li><a class="dropdown-item" href="<?= BASE_URL ?>/admin/modulos.php">Módulos / Áreas</a></li>
|
||||
<li><a class="dropdown-item" href="<?= BASE_URL ?>/admin/ubicaciones.php">Ubicaciones</a></li>
|
||||
<li><hr class="dropdown-divider"></li>
|
||||
<li><a class="dropdown-item" href="<?= BASE_URL ?>/admin/proveedores.php">Proveedores</a></li>
|
||||
<li><a class="dropdown-item" href="<?= BASE_URL ?>/admin/tipos.php">Tipos de mantenimiento</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
<?php endif; ?>
|
||||
<main class="<?= !empty($showNav) ? 'py-4' : '' ?>">
|
||||
3
index.php
Normal file
3
index.php
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
<?php
|
||||
header('Location: admin/index.php');
|
||||
exit;
|
||||
186
install.php
Normal file
186
install.php
Normal file
|
|
@ -0,0 +1,186 @@
|
|||
<?php
|
||||
/**
|
||||
* Instalación: crea la BD, importa data.csv y genera códigos únicos estables.
|
||||
* Ejecutar una sola vez: http://localhost/autofillqr/install.php
|
||||
*/
|
||||
set_time_limit(300);
|
||||
require_once __DIR__ . '/config/config.php';
|
||||
require_once __DIR__ . '/config/database.php';
|
||||
|
||||
$messages = [];
|
||||
$errors = [];
|
||||
|
||||
try {
|
||||
$pdo = getDBWithoutName();
|
||||
$schema = file_get_contents(__DIR__ . '/sql/schema.sql');
|
||||
foreach (array_filter(array_map('trim', explode(';', $schema))) as $stmt) {
|
||||
if ($stmt !== '') {
|
||||
$pdo->exec($stmt);
|
||||
}
|
||||
}
|
||||
$messages[] = 'Base de datos y tablas creadas.';
|
||||
|
||||
$db = getDB();
|
||||
|
||||
$countModulos = (int) $db->query('SELECT COUNT(*) FROM modulos')->fetchColumn();
|
||||
if ($countModulos > 0) {
|
||||
$messages[] = 'Los datos ya estaban importados. No se repite la importación.';
|
||||
} else {
|
||||
$csvFile = __DIR__ . '/data.csv';
|
||||
if (!file_exists($csvFile)) {
|
||||
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);
|
||||
|
||||
require_once __DIR__ . '/includes/auth.php';
|
||||
if (seedDefaultAdmin($db)) {
|
||||
$messages[] = 'Usuario admin creado (usuario: admin, contraseña: admin123).';
|
||||
}
|
||||
|
||||
$exportFile = __DIR__ . '/qr_data.csv';
|
||||
exportQrCsv($db, $exportFile);
|
||||
$messages[] = "Archivo qr_data.csv generado para el script de QR's.";
|
||||
|
||||
} catch (Throwable $e) {
|
||||
if (isset($db) && $db->inTransaction()) {
|
||||
$db->rollBack();
|
||||
}
|
||||
$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';
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Instalación - <?= htmlspecialchars(APP_NAME) ?></title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
</head>
|
||||
<body class="bg-light">
|
||||
<div class="container py-5">
|
||||
<div class="row justify-content-center">
|
||||
<div class="col-md-8">
|
||||
<div class="card">
|
||||
<div class="card-header">Instalación del sistema</div>
|
||||
<div class="card-body">
|
||||
<?php foreach ($messages as $m): ?>
|
||||
<div class="alert alert-success"><?= htmlspecialchars($m) ?></div>
|
||||
<?php endforeach; ?>
|
||||
<?php foreach ($errors as $e): ?>
|
||||
<div class="alert alert-danger"><?= htmlspecialchars($e) ?></div>
|
||||
<?php endforeach; ?>
|
||||
<?php if (empty($errors)): ?>
|
||||
<p class="mb-3">El sistema está listo. Los QR deben apuntar a:</p>
|
||||
<code><?= htmlspecialchars(BASE_URL) ?>/formulario.php?u=UB-00001</code>
|
||||
<div class="mt-4 d-flex gap-2">
|
||||
<a href="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>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
2521
qr_data.csv
Normal file
2521
qr_data.csv
Normal file
File diff suppressed because it is too large
Load diff
BIN
screen1.png
Normal file
BIN
screen1.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
BIN
screen2.png
Normal file
BIN
screen2.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 36 KiB |
53
sql/migrate_empresas.sql
Normal file
53
sql/migrate_empresas.sql
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
-- 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');
|
||||
10
sql/migrate_usuarios.sql
Normal file
10
sql/migrate_usuarios.sql
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
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;
|
||||
66
sql/schema.sql
Normal file
66
sql/schema.sql
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
CREATE DATABASE IF NOT EXISTS mantenimiento_campamento
|
||||
CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
USE mantenimiento_campamento;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS modulos (
|
||||
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
|
||||
codigo VARCHAR(20) NOT NULL UNIQUE COMMENT 'Identificador estable para QR/API',
|
||||
nombre VARCHAR(150) NOT NULL,
|
||||
activo TINYINT(1) NOT NULL DEFAULT 1,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
||||
) ENGINE=InnoDB;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS ubicaciones (
|
||||
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
|
||||
codigo VARCHAR(20) NOT NULL UNIQUE COMMENT 'Identificador estable en QR (?u=UB-00001)',
|
||||
modulo_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,
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (modulo_id) REFERENCES modulos(id) ON DELETE RESTRICT,
|
||||
INDEX idx_modulo (modulo_id)
|
||||
) ENGINE=InnoDB;
|
||||
|
||||
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;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS 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;
|
||||
|
||||
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;
|
||||
Loading…
Add table
Reference in a new issue