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