186 lines
6.2 KiB
PHP
186 lines
6.2 KiB
PHP
<?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>
|