Gestión de Notificaciones
This commit is contained in:
@@ -97,9 +97,4 @@ function guardar()
|
|||||||
function automatizaciones()
|
function automatizaciones()
|
||||||
{
|
{
|
||||||
include __DIR__ . '/../../views/configuracion/automatizaciones.php';
|
include __DIR__ . '/../../views/configuracion/automatizaciones.php';
|
||||||
}
|
|
||||||
|
|
||||||
function preferencias()
|
|
||||||
{
|
|
||||||
include __DIR__ . '/../../views/configuracion/preferencias.php';
|
|
||||||
}
|
}
|
||||||
342
app/controllers/preferencias.php
Normal file
342
app/controllers/preferencias.php
Normal file
@@ -0,0 +1,342 @@
|
|||||||
|
<?php
|
||||||
|
require_once __DIR__ . '/../helpers/session.php';
|
||||||
|
require_once __DIR__ . '/../../config/database.php';
|
||||||
|
require_once __DIR__ . '/../helpers/crypto.php';
|
||||||
|
|
||||||
|
function index()
|
||||||
|
{
|
||||||
|
include __DIR__ . '/../../views/preferencias/dashboard_preferencias.php';
|
||||||
|
}
|
||||||
|
|
||||||
|
function notificaciones()
|
||||||
|
{
|
||||||
|
$conn = getConnection();
|
||||||
|
$idUsuario = $_SESSION['usuario_id'] ?? null;
|
||||||
|
|
||||||
|
if (!$idUsuario) {
|
||||||
|
header("Location: /login");
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Obtener configuración general de notificaciones
|
||||||
|
$query = "SELECT notificaciones, notificaciones_extra FROM usuarios_sistema WHERE id_usuario = ?";
|
||||||
|
$stmt = sqlsrv_prepare($conn, $query, [$idUsuario]);
|
||||||
|
if (!$stmt || !sqlsrv_execute($stmt)) {
|
||||||
|
die("Error al obtener configuración: " . print_r(sqlsrv_errors(), true));
|
||||||
|
}
|
||||||
|
$notificaciones = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC) ?: ['notificaciones' => 0, 'notificaciones_extra' => 0];
|
||||||
|
sqlsrv_free_stmt($stmt);
|
||||||
|
|
||||||
|
// Obtener preferencias específicas de notificaciones
|
||||||
|
$query = "SELECT * FROM preferencias_notificaciones_usuario WHERE id_usuario = ?";
|
||||||
|
$stmt = sqlsrv_prepare($conn, $query, [$idUsuario]);
|
||||||
|
if ($stmt && sqlsrv_execute($stmt)) {
|
||||||
|
$preferenciasRow = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
|
||||||
|
sqlsrv_free_stmt($stmt);
|
||||||
|
} else {
|
||||||
|
$preferenciasRow = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Si no existe registro, crear valores por defecto
|
||||||
|
if (!$preferenciasRow) {
|
||||||
|
$preferencias = [
|
||||||
|
'nuevas_solicitudes' => 0,
|
||||||
|
'registro_solicitud' => 0,
|
||||||
|
'cambio_estado' => 0,
|
||||||
|
'resumen_diario' => 0,
|
||||||
|
'alertas_tiempo' => 0,
|
||||||
|
'documentos_expediente' => 0,
|
||||||
|
'nuevos_archivos' => 0,
|
||||||
|
'intentos_fallidos' => 0,
|
||||||
|
'bloqueo_cuenta' => 0
|
||||||
|
];
|
||||||
|
} else {
|
||||||
|
$preferencias = $preferenciasRow;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Obtener tipos de notificaciones disponibles
|
||||||
|
$query = "SELECT nombre, descripcion FROM tipos_notificaciones ORDER BY nombre";
|
||||||
|
$stmt = sqlsrv_query($conn, $query);
|
||||||
|
if (!$stmt) {
|
||||||
|
die("Error al obtener tipos: " . print_r(sqlsrv_errors(), true));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Crear array asociativo para la vista
|
||||||
|
$tipos = [];
|
||||||
|
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
|
||||||
|
$tipos[$row['nombre']] = $row['descripcion'];
|
||||||
|
}
|
||||||
|
sqlsrv_free_stmt($stmt);
|
||||||
|
|
||||||
|
// Obtener correo extra si existe
|
||||||
|
$query = "SELECT correo FROM correo_extra WHERE id_usuario = ?";
|
||||||
|
$stmt = sqlsrv_prepare($conn, $query, [$idUsuario]);
|
||||||
|
$correoExtra = '';
|
||||||
|
if ($stmt && sqlsrv_execute($stmt)) {
|
||||||
|
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
|
||||||
|
$correoExtra = $row ? $row['correo'] : '';
|
||||||
|
sqlsrv_free_stmt($stmt);
|
||||||
|
}
|
||||||
|
|
||||||
|
sqlsrv_close($conn);
|
||||||
|
include __DIR__ . '/../../views/preferencias/notificaciones.php';
|
||||||
|
}
|
||||||
|
|
||||||
|
function guardarPreferenciasAjax()
|
||||||
|
{
|
||||||
|
// Verificar que sea una petición AJAX
|
||||||
|
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') {
|
||||||
|
http_response_code(400);
|
||||||
|
echo json_encode(['success' => false, 'message' => 'Petición inválida']);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verificar método POST
|
||||||
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||||
|
http_response_code(405);
|
||||||
|
echo json_encode(['success' => false, 'message' => 'Método no permitido']);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
$conn = getConnection();
|
||||||
|
|
||||||
|
// Verificar autenticación
|
||||||
|
if (!isset($_SESSION['usuario_id']) || ($_SESSION['pendiente_confirmacion'] ?? false)) {
|
||||||
|
http_response_code(401);
|
||||||
|
echo json_encode(['success' => false, 'message' => 'Usuario no autenticado']);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
$id_usuario = $_SESSION['usuario_id'];
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Leer datos JSON del cuerpo de la petición
|
||||||
|
$input = json_decode(file_get_contents('php://input'), true);
|
||||||
|
|
||||||
|
if (!$input) {
|
||||||
|
throw new Exception("Datos inválidos");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Iniciar transacción
|
||||||
|
sqlsrv_begin_transaction($conn);
|
||||||
|
|
||||||
|
// Determinar qué tipo de cambio se está realizando
|
||||||
|
$tipo_cambio = $input['tipo'] ?? 'general';
|
||||||
|
|
||||||
|
switch ($tipo_cambio) {
|
||||||
|
case 'notificaciones_general':
|
||||||
|
$notificaciones = $input['valor'] ? 1 : 0;
|
||||||
|
|
||||||
|
// Si se desactivan las notificaciones, también desactivar notificaciones extra
|
||||||
|
$notificaciones_extra = $notificaciones ? ($input['notificaciones_extra'] ?? 0) : 0;
|
||||||
|
|
||||||
|
$query = "UPDATE usuarios_sistema SET notificaciones = ?, notificaciones_extra = ? WHERE id_usuario = ?";
|
||||||
|
$stmt = sqlsrv_prepare($conn, $query, [$notificaciones, $notificaciones_extra, $id_usuario]);
|
||||||
|
|
||||||
|
if (!$stmt || !sqlsrv_execute($stmt)) {
|
||||||
|
throw new Exception("Error al actualizar configuración general");
|
||||||
|
}
|
||||||
|
sqlsrv_free_stmt($stmt);
|
||||||
|
|
||||||
|
// Si se desactivan las notificaciones, limpiar preferencias específicas
|
||||||
|
if (!$notificaciones) {
|
||||||
|
$query_delete = "DELETE FROM preferencias_notificaciones_usuario WHERE id_usuario = ?";
|
||||||
|
$stmt_delete = sqlsrv_prepare($conn, $query_delete, [$id_usuario]);
|
||||||
|
if ($stmt_delete) {
|
||||||
|
sqlsrv_execute($stmt_delete);
|
||||||
|
sqlsrv_free_stmt($stmt_delete);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'notificaciones_extra':
|
||||||
|
$notificaciones_extra = $input['valor'] ? 1 : 0;
|
||||||
|
|
||||||
|
// Validar que existe correo extra si se quiere activar
|
||||||
|
if ($notificaciones_extra) {
|
||||||
|
$query_check = "SELECT correo FROM correo_extra WHERE id_usuario = ?";
|
||||||
|
$stmt_check = sqlsrv_prepare($conn, $query_check, [$id_usuario]);
|
||||||
|
if ($stmt_check && sqlsrv_execute($stmt_check)) {
|
||||||
|
$row = sqlsrv_fetch_array($stmt_check, SQLSRV_FETCH_ASSOC);
|
||||||
|
sqlsrv_free_stmt($stmt_check);
|
||||||
|
|
||||||
|
if (!$row || empty($row['correo'])) {
|
||||||
|
throw new Exception("No tienes un correo adicional registrado. Ve a Seguridad para registrar uno primero.");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw new Exception("No tienes un correo adicional registrado. Ve a Seguridad para registrar uno primero.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$query = "UPDATE usuarios_sistema SET notificaciones_extra = ? WHERE id_usuario = ?";
|
||||||
|
$stmt = sqlsrv_prepare($conn, $query, [$notificaciones_extra, $id_usuario]);
|
||||||
|
|
||||||
|
if (!$stmt || !sqlsrv_execute($stmt)) {
|
||||||
|
throw new Exception("Error al actualizar configuración de correo extra");
|
||||||
|
}
|
||||||
|
sqlsrv_free_stmt($stmt);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'tipo_notificacion':
|
||||||
|
$tipo_nombre = $input['nombre'] ?? '';
|
||||||
|
$valor = $input['valor'] ? 1 : 0;
|
||||||
|
|
||||||
|
if (empty($tipo_nombre)) {
|
||||||
|
throw new Exception("Tipo de notificación no especificado");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verificar que las notificaciones generales estén activadas
|
||||||
|
$query_check = "SELECT notificaciones FROM usuarios_sistema WHERE id_usuario = ?";
|
||||||
|
$stmt_check = sqlsrv_prepare($conn, $query_check, [$id_usuario]);
|
||||||
|
if ($stmt_check && sqlsrv_execute($stmt_check)) {
|
||||||
|
$row = sqlsrv_fetch_array($stmt_check, SQLSRV_FETCH_ASSOC);
|
||||||
|
sqlsrv_free_stmt($stmt_check);
|
||||||
|
|
||||||
|
if (!$row || !$row['notificaciones']) {
|
||||||
|
throw new Exception("Las notificaciones generales deben estar activadas primero");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw new Exception("Error al verificar configuración");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verificar si existe el registro
|
||||||
|
$query_exists = "SELECT COUNT(*) as count FROM preferencias_notificaciones_usuario WHERE id_usuario = ?";
|
||||||
|
$stmt_exists = sqlsrv_prepare($conn, $query_exists, [$id_usuario]);
|
||||||
|
$exists = false;
|
||||||
|
if ($stmt_exists && sqlsrv_execute($stmt_exists)) {
|
||||||
|
$row = sqlsrv_fetch_array($stmt_exists, SQLSRV_FETCH_ASSOC);
|
||||||
|
$exists = $row['count'] > 0;
|
||||||
|
sqlsrv_free_stmt($stmt_exists);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($exists) {
|
||||||
|
// Actualizar el campo específico
|
||||||
|
$query = "UPDATE preferencias_notificaciones_usuario SET $tipo_nombre = ? WHERE id_usuario = ?";
|
||||||
|
$stmt = sqlsrv_prepare($conn, $query, [$valor, $id_usuario]);
|
||||||
|
} else {
|
||||||
|
// Crear registro con valores por defecto y el campo específico
|
||||||
|
$tipos_default = [
|
||||||
|
'nuevas_solicitudes' => 0,
|
||||||
|
'registro_solicitud' => 0,
|
||||||
|
'cambio_estado' => 0,
|
||||||
|
'resumen_diario' => 0,
|
||||||
|
'alertas_tiempo' => 0,
|
||||||
|
'documentos_expediente' => 0,
|
||||||
|
'nuevos_archivos' => 0,
|
||||||
|
'intentos_fallidos' => 0,
|
||||||
|
'bloqueo_cuenta' => 0
|
||||||
|
];
|
||||||
|
|
||||||
|
// Establecer el valor específico
|
||||||
|
$tipos_default[$tipo_nombre] = $valor;
|
||||||
|
|
||||||
|
$campos = implode(', ', array_keys($tipos_default));
|
||||||
|
$placeholders = rtrim(str_repeat('?, ', count($tipos_default)), ', ');
|
||||||
|
$query = "INSERT INTO preferencias_notificaciones_usuario (id_usuario, $campos) VALUES (?, $placeholders)";
|
||||||
|
|
||||||
|
$params = array_merge([$id_usuario], array_values($tipos_default));
|
||||||
|
$stmt = sqlsrv_prepare($conn, $query, $params);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!$stmt || !sqlsrv_execute($stmt)) {
|
||||||
|
throw new Exception("Error al actualizar preferencia específica");
|
||||||
|
}
|
||||||
|
sqlsrv_free_stmt($stmt);
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
throw new Exception("Tipo de cambio no válido");
|
||||||
|
}
|
||||||
|
|
||||||
|
sqlsrv_commit($conn);
|
||||||
|
sqlsrv_close($conn);
|
||||||
|
|
||||||
|
echo json_encode([
|
||||||
|
'success' => true,
|
||||||
|
'message' => 'Preferencias guardadas automáticamente',
|
||||||
|
'tipo' => $tipo_cambio
|
||||||
|
]);
|
||||||
|
|
||||||
|
} catch (Exception $e) {
|
||||||
|
sqlsrv_rollback($conn);
|
||||||
|
sqlsrv_close($conn);
|
||||||
|
|
||||||
|
http_response_code(400);
|
||||||
|
echo json_encode([
|
||||||
|
'success' => false,
|
||||||
|
'message' => $e->getMessage(),
|
||||||
|
'tipo' => $tipo_cambio ?? 'unknown'
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Función auxiliar para obtener el correo extra de un usuario (útil para el sistema de notificaciones)
|
||||||
|
function obtenerCorreoExtra($id_usuario)
|
||||||
|
{
|
||||||
|
$conn = getConnection();
|
||||||
|
$query = "
|
||||||
|
SELECT ce.correo
|
||||||
|
FROM correo_extra ce
|
||||||
|
INNER JOIN usuarios_sistema us ON ce.id_usuario = us.id_usuario
|
||||||
|
WHERE ce.id_usuario = ? AND us.notificaciones_extra = 1
|
||||||
|
";
|
||||||
|
$stmt = sqlsrv_prepare($conn, $query, [$id_usuario]);
|
||||||
|
$correo = null;
|
||||||
|
if ($stmt && sqlsrv_execute($stmt)) {
|
||||||
|
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
|
||||||
|
$correo = $row ? $row['correo'] : null;
|
||||||
|
sqlsrv_free_stmt($stmt);
|
||||||
|
}
|
||||||
|
sqlsrv_close($conn);
|
||||||
|
return $correo;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Función auxiliar para obtener todas las preferencias de notificación de un usuario
|
||||||
|
function obtenerPreferenciasNotificacion($id_usuario)
|
||||||
|
{
|
||||||
|
$conn = getConnection();
|
||||||
|
|
||||||
|
// Obtener configuración general
|
||||||
|
$query = "SELECT notificaciones, notificaciones_extra FROM usuarios_sistema WHERE id_usuario = ?";
|
||||||
|
$stmt = sqlsrv_prepare($conn, $query, [$id_usuario]);
|
||||||
|
if (!$stmt || !sqlsrv_execute($stmt)) {
|
||||||
|
sqlsrv_close($conn);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
$config = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
|
||||||
|
sqlsrv_free_stmt($stmt);
|
||||||
|
|
||||||
|
if (!$config || !$config['notificaciones']) {
|
||||||
|
sqlsrv_close($conn);
|
||||||
|
return null; // Usuario no tiene notificaciones activadas
|
||||||
|
}
|
||||||
|
|
||||||
|
// Obtener preferencias específicas
|
||||||
|
$query = "SELECT * FROM preferencias_notificaciones_usuario WHERE id_usuario = ?";
|
||||||
|
$stmt = sqlsrv_prepare($conn, $query, [$id_usuario]);
|
||||||
|
$preferencias = null;
|
||||||
|
if ($stmt && sqlsrv_execute($stmt)) {
|
||||||
|
$preferencias = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
|
||||||
|
sqlsrv_free_stmt($stmt);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Obtener correo extra si está activado
|
||||||
|
$correo_extra = null;
|
||||||
|
if ($config['notificaciones_extra']) {
|
||||||
|
$query = "SELECT correo FROM correo_extra WHERE id_usuario = ?";
|
||||||
|
$stmt = sqlsrv_prepare($conn, $query, [$id_usuario]);
|
||||||
|
if ($stmt && sqlsrv_execute($stmt)) {
|
||||||
|
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
|
||||||
|
$correo_extra = $row ? $row['correo'] : null;
|
||||||
|
sqlsrv_free_stmt($stmt);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sqlsrv_close($conn);
|
||||||
|
return [
|
||||||
|
'config_general' => $config,
|
||||||
|
'preferencias' => $preferencias,
|
||||||
|
'correo_extra' => $correo_extra
|
||||||
|
];
|
||||||
|
}
|
||||||
34
notificaciones_table.txt
Normal file
34
notificaciones_table.txt
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
ALTER TABLE usuarios_sistema
|
||||||
|
ADD notificaciones BIT DEFAULT 0,
|
||||||
|
notificaciones_extra BIT DEFAULT 0;
|
||||||
|
|
||||||
|
CREATE TABLE tipos_notificaciones (
|
||||||
|
id INT PRIMARY KEY IDENTITY,
|
||||||
|
nombre NVARCHAR(255) NOT NULL,
|
||||||
|
descripcion NVARCHAR(500) NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO tipos_notificaciones (nombre, descripcion) VALUES
|
||||||
|
('nuevas_solicitudes', 'Creación de nuevas solicitudes de importación'),
|
||||||
|
('registro_solicitud', 'Notificación inmediata al registrar una solicitud'),
|
||||||
|
('cambio_estado', 'Cambio de estado de solicitudes de importación'),
|
||||||
|
('resumen_diario', 'Resumen diario de solicitudes de importación'),
|
||||||
|
('alertas_tiempo', 'Alertas por tiempo excedido en estados críticos'),
|
||||||
|
('documentos_expediente', 'Incorporación de documentos al expediente electrónico'),
|
||||||
|
('nuevos_archivos', 'Aviso al agregarse nuevos archivos o documentos'),
|
||||||
|
('intentos_fallidos', 'Intentos fallidos de acceso'),
|
||||||
|
('bloqueo_cuenta', 'Bloqueo de cuenta');
|
||||||
|
|
||||||
|
CREATE TABLE preferencias_notificaciones_usuario (
|
||||||
|
id_usuario INT PRIMARY KEY,
|
||||||
|
nuevas_solicitudes BIT DEFAULT 0,
|
||||||
|
registro_solicitud BIT DEFAULT 0,
|
||||||
|
cambio_estado BIT DEFAULT 0,
|
||||||
|
resumen_diario BIT DEFAULT 0,
|
||||||
|
alertas_tiempo BIT DEFAULT 0,
|
||||||
|
documentos_expediente BIT DEFAULT 0,
|
||||||
|
nuevos_archivos BIT DEFAULT 0,
|
||||||
|
intentos_fallidos BIT DEFAULT 0,
|
||||||
|
bloqueo_cuenta BIT DEFAULT 0,
|
||||||
|
FOREIGN KEY (id_usuario) REFERENCES usuarios_sistema(id_usuario)
|
||||||
|
);
|
||||||
@@ -63,6 +63,8 @@ if (!isset($_SESSION['usuario_id']) || $_SESSION['tipo_usuario'] !== 'importador
|
|||||||
$esVistaBitacoras = str_contains($_SERVER['REQUEST_URI'], '/bitacoras');
|
$esVistaBitacoras = str_contains($_SERVER['REQUEST_URI'], '/bitacoras');
|
||||||
// Detecta si estamos en alguna parta de seguridad
|
// Detecta si estamos en alguna parta de seguridad
|
||||||
$esVistaSeguridad = str_contains($_SERVER['REQUEST_URI'], '/seguridad');
|
$esVistaSeguridad = str_contains($_SERVER['REQUEST_URI'], '/seguridad');
|
||||||
|
// Detecta si estamos en alguna parte de preferencias
|
||||||
|
$esVistaPreferencias = str_contains($_SERVER['REQUEST_URI'], '/preferencias')
|
||||||
?>
|
?>
|
||||||
|
|
||||||
<!-- INFORMACIÓN GENERAL -->
|
<!-- INFORMACIÓN GENERAL -->
|
||||||
@@ -78,10 +80,31 @@ if (!isset($_SESSION['usuario_id']) || $_SESSION['tipo_usuario'] !== 'importador
|
|||||||
</a>
|
</a>
|
||||||
|
|
||||||
<!-- PREFERENCIAS -->
|
<!-- PREFERENCIAS -->
|
||||||
<a href="/IMPORTADORES/configuracion/preferencias"
|
<?php if ($esVistaPreferencias): ?>
|
||||||
class="nav-link px-3 py-2 <?= str_contains($_SERVER['REQUEST_URI'], '/configuracion/preferencias') ? 'active' : '' ?>">
|
<?php $enDashboardPreferencias = $_SERVER['REQUEST_URI'] === '/IMPORTADORES/preferencias/index'; ?>
|
||||||
✅ Preferencias
|
<a class="nav-link px-3 py-2 d-flex justify-content-between align-items-center <?= $esVistaPreferencias ? 'active' : '' ?>"
|
||||||
</a>
|
href="<?= $enDashboardPreferencias ? '#submenuPreferencias' : '/IMPORTADORES/preferencias/index' ?>"
|
||||||
|
<?= $enDashboardPreferencias ? 'data-bd-toggle="collapse"' : '' ?>
|
||||||
|
role="button" aria-expanded="true" aria-controls="submenuPreferencias"
|
||||||
|
onclick="<? $enDashboardPreferenecias ? '' : 'event.preventDefault(); window.location.href = \'/IMPORTADORES/preferencias/index\';' ?>">
|
||||||
|
✅ Preferencias
|
||||||
|
<span class="badge bg-secondary">1</span>
|
||||||
|
</a>
|
||||||
|
<div class="collapse show" id="submenuPreferencias">
|
||||||
|
<nav class="nav flex-column ms-3">
|
||||||
|
<a href="/IMPORTADORES/preferencias/notificaciones"
|
||||||
|
class="nav-link px-3 py-1 <?= $_SERVER['REQUEST_URI'] === '/IMPORTADORES/preferencias/notificaciones' ? 'active' : '' ?>">
|
||||||
|
• Gestión de Notificaciones
|
||||||
|
</a>
|
||||||
|
</nav>
|
||||||
|
</div>
|
||||||
|
<?php elseif ($esConfiguracion || $esVistaBitacoras || $esVistaSeguridad): ?>
|
||||||
|
<a href="/IMPORTADORES/preferencias/index"
|
||||||
|
class="nav-link px-3 py-2 d-flex justify-content-between align-items-center">
|
||||||
|
✅ Preferencias
|
||||||
|
<span class="badge bg-secondary">1</span>
|
||||||
|
</a>
|
||||||
|
<?php endif; ?>
|
||||||
|
|
||||||
<!-- SEGURIDAD -->
|
<!-- SEGURIDAD -->
|
||||||
<?php if ($esVistaSeguridad): ?>
|
<?php if ($esVistaSeguridad): ?>
|
||||||
@@ -102,7 +125,7 @@ if (!isset($_SESSION['usuario_id']) || $_SESSION['tipo_usuario'] !== 'importador
|
|||||||
</a>
|
</a>
|
||||||
</nav>
|
</nav>
|
||||||
</div>
|
</div>
|
||||||
<?php elseif ($esConfiguracion || $esVistaBitacoras): ?>
|
<?php elseif ($esConfiguracion || $esVistaBitacoras || $esVistaPreferencias): ?>
|
||||||
<a href="/IMPORTADORES/seguridad/index"
|
<a href="/IMPORTADORES/seguridad/index"
|
||||||
class="nav-link px-3 py-2 d-flex justify-content-between align-items-center">
|
class="nav-link px-3 py-2 d-flex justify-content-between align-items-center">
|
||||||
👮 Seguridad
|
👮 Seguridad
|
||||||
@@ -130,7 +153,7 @@ if (!isset($_SESSION['usuario_id']) || $_SESSION['tipo_usuario'] !== 'importador
|
|||||||
</a>
|
</a>
|
||||||
</nav>
|
</nav>
|
||||||
</div>
|
</div>
|
||||||
<?php elseif ($esConfiguracion || $esVistaSeguridad): ?>
|
<?php elseif ($esConfiguracion || $esVistaSeguridad || $esVistaPreferencias): ?>
|
||||||
<!-- Si estamos en configuración, pero no en bitácoras -->
|
<!-- Si estamos en configuración, pero no en bitácoras -->
|
||||||
<a href="/IMPORTADORES/bitacoras/index"
|
<a href="/IMPORTADORES/bitacoras/index"
|
||||||
class="nav-link px-3 py-2 d-flex justify-content-between align-items-center">
|
class="nav-link px-3 py-2 d-flex justify-content-between align-items-center">
|
||||||
@@ -159,10 +182,31 @@ if (!isset($_SESSION['usuario_id']) || $_SESSION['tipo_usuario'] !== 'importador
|
|||||||
</a>
|
</a>
|
||||||
|
|
||||||
<!-- PREFERENCIAS -->
|
<!-- PREFERENCIAS -->
|
||||||
<a href="/IMPORTADORES/configuracion/preferencias"
|
<?php if ($esVistaPreferencias): ?>
|
||||||
class="nav-link px-3 py-2 <?= str_contains($_SERVER['REQUEST_URI'], '/configuracion/preferencias') ? 'active' : '' ?>">
|
<?php $enDashboardPreferencias = $_SERVER['REQUEST_URI'] === '/IMPORTADORES/preferencias/index'; ?>
|
||||||
✅ Preferencias
|
<a class="nav-link px-3 py-2 d-flex justify-content-between align-items-center <?= $esVistaPreferencias ? 'active' : '' ?>"
|
||||||
</a>
|
href="<?= $enDashboardPreferencias ? '#submenuPreferencias' : '/IMPORTADORES/preferencias/index' ?>"
|
||||||
|
<?= $enDashboardPreferencias ? 'data-bd-toggle="collapse"' : '' ?>
|
||||||
|
role="button" aria-expanded="true" aria-controls="submenuPreferencias"
|
||||||
|
onclick="<? $enDashboardPreferenecias ? '' : 'event.preventDefault(); window.location.href = \'/IMPORTADORES/preferencias/index\';' ?>">
|
||||||
|
✅ Preferencias
|
||||||
|
<span class="badge bg-secondary">1</span>
|
||||||
|
</a>
|
||||||
|
<div class="collapse show" id="submenuPreferencias">
|
||||||
|
<nav class="nav flex-column ms-3">
|
||||||
|
<a href="/IMPORTADORES/preferencias/notificaciones"
|
||||||
|
class="nav-link px-3 py-1 <?= $_SERVER['REQUEST_URI'] === '/IMPORTADORES/preferencias/notificaciones' ? 'active' : '' ?>">
|
||||||
|
• Gestión de Notificaciones
|
||||||
|
</a>
|
||||||
|
</nav>
|
||||||
|
</div>
|
||||||
|
<?php elseif ($esConfiguracion || $esVistaBitacoras || $esVistaSeguridad): ?>
|
||||||
|
<a href="/IMPORTADORES/preferencias/index"
|
||||||
|
class="nav-link px-3 py-2 d-flex justify-content-between align-items-center">
|
||||||
|
✅ Preferencias
|
||||||
|
<span class="badge bg-secondary">1</span>
|
||||||
|
</a>
|
||||||
|
<?php endif; ?>
|
||||||
|
|
||||||
<!-- SEGURIDAD -->
|
<!-- SEGURIDAD -->
|
||||||
<?php if ($esVistaSeguridad): ?>
|
<?php if ($esVistaSeguridad): ?>
|
||||||
@@ -183,7 +227,7 @@ if (!isset($_SESSION['usuario_id']) || $_SESSION['tipo_usuario'] !== 'importador
|
|||||||
</a>
|
</a>
|
||||||
</nav>
|
</nav>
|
||||||
</div>
|
</div>
|
||||||
<?php elseif ($esConfiguracion || $esVistaBitacoras): ?>
|
<?php elseif ($esConfiguracion || $esVistaBitacoras || $esVistaPreferencias): ?>
|
||||||
<a href="/IMPORTADORES/seguridad/index"
|
<a href="/IMPORTADORES/seguridad/index"
|
||||||
class="nav-link px-3 py-2 d-flex justify-content-between align-items-center">
|
class="nav-link px-3 py-2 d-flex justify-content-between align-items-center">
|
||||||
👮 Seguridad
|
👮 Seguridad
|
||||||
@@ -211,7 +255,7 @@ if (!isset($_SESSION['usuario_id']) || $_SESSION['tipo_usuario'] !== 'importador
|
|||||||
</a>
|
</a>
|
||||||
</nav>
|
</nav>
|
||||||
</div>
|
</div>
|
||||||
<?php elseif ($esConfiguracion || $esVistaSeguridad): ?>
|
<?php elseif ($esConfiguracion || $esVistaSeguridad || $esVistaPreferencias): ?>
|
||||||
<!-- Si estamos en configuración, pero no en bitácoras -->
|
<!-- Si estamos en configuración, pero no en bitácoras -->
|
||||||
<a href="/IMPORTADORES/bitacoras/index"
|
<a href="/IMPORTADORES/bitacoras/index"
|
||||||
class="nav-link px-3 py-2 d-flex justify-content-between align-items-center">
|
class="nav-link px-3 py-2 d-flex justify-content-between align-items-center">
|
||||||
|
|||||||
@@ -78,9 +78,23 @@ include __DIR__ . '/../partials/sidebar_configuracion.php';
|
|||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
|
||||||
<div class="content">
|
<div class="content">
|
||||||
<h4 class="mb-4">✅ Preferencias</h4>
|
<h4 class="mb-4">✅ Preferencias</h4>
|
||||||
|
|
||||||
|
<div class="row g-4">
|
||||||
|
<div class="col-md-4">
|
||||||
|
<div class="card shadow-sm p-3">
|
||||||
|
<h5 class="text-primary">Notificaciones</h5>
|
||||||
|
<p>Gestiona y configura las notificaciones.</p>
|
||||||
|
<a href="/IMPORTADORES/preferencias/notificaciones"
|
||||||
|
class="btn btn-primary btn-sm mt-2 <?= $_SERVER['REQUEST_URI'] === '/IMPORTADORES/preferencias/notificaciones' ? 'active' : '' ?>">
|
||||||
|
Configurar Notificaciones
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
471
views/preferencias/notificaciones.php
Normal file
471
views/preferencias/notificaciones.php
Normal file
@@ -0,0 +1,471 @@
|
|||||||
|
<?php
|
||||||
|
include __DIR__ . '/../partials/sidebar_configuracion.php';
|
||||||
|
?>
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="es">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>Dashboard | Configuración</title>
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
||||||
|
<style>
|
||||||
|
body {
|
||||||
|
font-family: 'Segoe UI', sans-serif;
|
||||||
|
background-color: #f4f6f9;
|
||||||
|
}
|
||||||
|
.sidebar {
|
||||||
|
width: 220px;
|
||||||
|
height: 100vh;
|
||||||
|
background-color: #343a40;
|
||||||
|
position: fixed;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
padding-top: 56px; /* Alineado con la altura de la navbar */
|
||||||
|
z-index: 1040; /* Asegura que esté por encima del contenido */
|
||||||
|
}
|
||||||
|
.sidebar .nav-link {
|
||||||
|
font-weight: bold;
|
||||||
|
color: white;
|
||||||
|
transition: all 0.3s ease;
|
||||||
|
}
|
||||||
|
.sidebar .nav-link:hover,
|
||||||
|
.sidebar .nav-link.active {
|
||||||
|
background-color: #495057;
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
.content {
|
||||||
|
margin-top: 56px; /* Ajusta debajo de navbar */
|
||||||
|
padding: 40px 20px;
|
||||||
|
position: relative;
|
||||||
|
z-index: 1;
|
||||||
|
background-color: #f4f6f9; /* Asegura fondo uniforme */
|
||||||
|
transition: margin-left 0.3s ease;
|
||||||
|
}
|
||||||
|
.navbar {
|
||||||
|
position: fixed;
|
||||||
|
top: 0;
|
||||||
|
width: 100%;
|
||||||
|
z-index: 1050;
|
||||||
|
}
|
||||||
|
/* A partir de dispositivos medianos (>=768px), deja espacio lateral */
|
||||||
|
@media (min-width: 768px) {
|
||||||
|
.content {
|
||||||
|
margin-left: 250px; /* Ancho del sidebar */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* En móviles, sin margen lateral */
|
||||||
|
@media (max-width: 767.98px) {
|
||||||
|
.content {
|
||||||
|
margin-left: 0;
|
||||||
|
}
|
||||||
|
.sidebar .nav-link {
|
||||||
|
font-weight: normal;
|
||||||
|
color: #343a40;
|
||||||
|
background-color: transparent;
|
||||||
|
}
|
||||||
|
.sidebar .nav-link:hover,
|
||||||
|
.sidebar .nav-link.active {
|
||||||
|
background-color: #e9ecef;
|
||||||
|
color: #212529;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.card {
|
||||||
|
border-radius: 12px;
|
||||||
|
}
|
||||||
|
.section-divider {
|
||||||
|
border-left: 4px solid #007bff;
|
||||||
|
padding-left: 15px;
|
||||||
|
margin: 20px 0;
|
||||||
|
}
|
||||||
|
.fade-transition {
|
||||||
|
transition: opacity 0.3s ease-in-out;
|
||||||
|
}
|
||||||
|
.correo-extra-section {
|
||||||
|
background-color: #f8f9fa;
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 15px;
|
||||||
|
margin-top: 15px;
|
||||||
|
}
|
||||||
|
.success-message {
|
||||||
|
background-color: #d4edda;
|
||||||
|
color: #155724;
|
||||||
|
padding: 10px;
|
||||||
|
border-radius: 5px;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
border: 1px solid #c3e6cb;
|
||||||
|
}
|
||||||
|
.error-message {
|
||||||
|
background-color: #f8d7da;
|
||||||
|
color: #721c24;
|
||||||
|
padding: 10px;
|
||||||
|
border-radius: 5px;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
border: 1px solid #f5c6cb;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Estilos para indicadores de guardado */
|
||||||
|
.save-indicator {
|
||||||
|
position: fixed;
|
||||||
|
top: 20px;
|
||||||
|
right: 20px;
|
||||||
|
padding: 10px 15px;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-weight: 500;
|
||||||
|
z-index: 9999;
|
||||||
|
transition: all 0.3s ease;
|
||||||
|
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
|
||||||
|
}
|
||||||
|
|
||||||
|
.save-indicator.saving {
|
||||||
|
background-color: #fff3cd;
|
||||||
|
color: #856404;
|
||||||
|
border: 1px solid #ffeaa7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.save-indicator.saved {
|
||||||
|
background-color: #d1ecf1;
|
||||||
|
color: #0c5460;
|
||||||
|
border: 1px solid #bee5eb;
|
||||||
|
}
|
||||||
|
|
||||||
|
.save-indicator.error {
|
||||||
|
background-color: #f8d7da;
|
||||||
|
color: #721c24;
|
||||||
|
border: 1px solid #f5c6cb;
|
||||||
|
}
|
||||||
|
|
||||||
|
.spinner-border-sm {
|
||||||
|
width: 1rem;
|
||||||
|
height: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Estilo para switches deshabilitados temporalmente */
|
||||||
|
.form-check-input:disabled {
|
||||||
|
opacity: 0.6;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Animación sutil para switches */
|
||||||
|
.form-check-input {
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<div class="content">
|
||||||
|
<div class="d-flex justify-content-between align-items-center mb-4">
|
||||||
|
<h4 class="mb-0">🔔 Gestión de Notificaciones</h4>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Mensajes de éxito o error iniciales -->
|
||||||
|
<?php if (isset($_GET['success'])): ?>
|
||||||
|
<div class="success-message">
|
||||||
|
✅ Las preferencias de notificación se han guardado correctamente.
|
||||||
|
</div>
|
||||||
|
<?php endif; ?>
|
||||||
|
|
||||||
|
<?php if (isset($_GET['error'])): ?>
|
||||||
|
<div class="error-message">
|
||||||
|
❌ Error: <?= htmlspecialchars($_GET['error']) ?>
|
||||||
|
</div>
|
||||||
|
<?php endif; ?>
|
||||||
|
|
||||||
|
<div class="card shadow-sm p-4 mb-4 bg-white">
|
||||||
|
<!-- Switch general de notificaciones -->
|
||||||
|
<div class="section-divider">
|
||||||
|
<div class="form-check form-switch">
|
||||||
|
<input class="form-check-input" type="checkbox" id="notificaciones"
|
||||||
|
data-tipo="notificaciones_general"
|
||||||
|
<?= $notificaciones['notificaciones'] ? 'checked' : '' ?>>
|
||||||
|
<label class="form-check-label fw-bold" for="notificaciones">
|
||||||
|
Recibir notificaciones del sistema
|
||||||
|
</label>
|
||||||
|
<div class="form-text">Activa o desactiva todas las notificaciones del sistema</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Tipos de notificaciones -->
|
||||||
|
<div id="tipos-notificaciones" class="fade-transition"
|
||||||
|
<?= !$notificaciones['notificaciones'] ? 'style="display:none; opacity:0;"' : 'style="opacity:1;"' ?>>
|
||||||
|
|
||||||
|
<div class="section-divider">
|
||||||
|
<h6 class="mb-3">📋 Tipos de Notificaciones</h6>
|
||||||
|
<div class="row">
|
||||||
|
<?php foreach ($tipos as $clave => $descripcion): ?>
|
||||||
|
<div class="col-md-6 mb-3">
|
||||||
|
<div class="form-check form-switch">
|
||||||
|
<input class="form-check-input tipo-notificacion" type="checkbox"
|
||||||
|
name="<?= $clave ?>" id="<?= $clave ?>"
|
||||||
|
data-tipo="tipo_notificacion" data-nombre="<?= $clave ?>"
|
||||||
|
<?= ($preferencias[$clave] ?? 0) ? 'checked' : '' ?>>
|
||||||
|
<label class="form-check-label" for="<?= $clave ?>">
|
||||||
|
<strong><?= ucwords(str_replace('_', ' ', $clave)) ?></strong>
|
||||||
|
<div class="form-text"><?= htmlspecialchars($descripcion) ?></div>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<?php endforeach; ?>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Configuración de correo adicional -->
|
||||||
|
<div class="section-divider">
|
||||||
|
<div class="form-check form-switch">
|
||||||
|
<input class="form-check-input" type="checkbox" id="notificaciones_extra"
|
||||||
|
data-tipo="notificaciones_extra"
|
||||||
|
<?= $notificaciones['notificaciones_extra'] ? 'checked' : '' ?>>
|
||||||
|
<label class="form-check-label fw-bold" for="notificaciones_extra">
|
||||||
|
Enviar notificaciones a correo adicional
|
||||||
|
</label>
|
||||||
|
<div class="form-text">Recibe una copia de las notificaciones en un correo adicional</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Campo informativo del correo adicional -->
|
||||||
|
<div id="correo-extra-section" class="correo-extra-section fade-transition"
|
||||||
|
<?= !$notificaciones['notificaciones_extra'] ? 'style="display:none; opacity:0;"' : 'style="opacity:1;"' ?>>
|
||||||
|
|
||||||
|
<?php if (!empty($correoExtra)): ?>
|
||||||
|
<div class="alert alert-info d-flex align-items-center">
|
||||||
|
<div class="me-3">
|
||||||
|
<i class="fas fa-envelope" style="font-size: 1.2em;"></i>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<strong>📧 Correo adicional configurado:</strong><br>
|
||||||
|
<code><?= htmlspecialchars($correoExtra) ?></code>
|
||||||
|
<div class="form-text mt-1">
|
||||||
|
Las notificaciones se enviarán también a este correo.
|
||||||
|
<a href="/IMPORTADORES/seguridad/index" class="text-decoration-none">
|
||||||
|
Gestionar en Seguridad →
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<?php else: ?>
|
||||||
|
<div class="alert alert-warning d-flex align-items-center">
|
||||||
|
<div class="me-3">
|
||||||
|
<i class="fas fa-exclamation-triangle" style="font-size: 1.2em;"></i>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<strong>⚠️ No hay correo adicional registrado</strong><br>
|
||||||
|
<div class="form-text">
|
||||||
|
Para usar esta función, primero debes registrar un correo adicional en la sección de Seguridad.
|
||||||
|
<a href="/IMPORTADORES/seguridad/index" class="text-decoration-none">
|
||||||
|
Ir a Seguridad →
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<?php endif; ?>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Indicador de guardado -->
|
||||||
|
<div id="save-indicator" class="save-indicator" style="display: none;">
|
||||||
|
<span class="indicator-text">Guardando...</span>
|
||||||
|
<div class="spinner-border spinner-border-sm ms-2" style="display: none;"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
// Estado global para controlar las peticiones
|
||||||
|
let isAutoSaving = false;
|
||||||
|
let saveTimeout = null;
|
||||||
|
|
||||||
|
// Referencias a elementos
|
||||||
|
const saveIndicator = document.getElementById('save-indicator');
|
||||||
|
const indicatorText = saveIndicator.querySelector('.indicator-text');
|
||||||
|
const spinner = saveIndicator.querySelector('.spinner-border');
|
||||||
|
|
||||||
|
// Función para mostrar indicador de guardado
|
||||||
|
function showSaveIndicator(type, message) {
|
||||||
|
// Limpiar clases anteriores
|
||||||
|
saveIndicator.className = 'save-indicator';
|
||||||
|
|
||||||
|
// Agregar clase según el tipo
|
||||||
|
saveIndicator.classList.add(type);
|
||||||
|
indicatorText.textContent = message;
|
||||||
|
|
||||||
|
// Mostrar/ocultar spinner
|
||||||
|
if (type === 'saving') {
|
||||||
|
spinner.style.display = 'inline-block';
|
||||||
|
} else {
|
||||||
|
spinner.style.display = 'none';
|
||||||
|
}
|
||||||
|
|
||||||
|
saveIndicator.style.display = 'block';
|
||||||
|
|
||||||
|
// Auto-ocultar después de unos segundos (excepto cuando está guardando)
|
||||||
|
if (type !== 'saving') {
|
||||||
|
setTimeout(() => {
|
||||||
|
saveIndicator.style.display = 'none';
|
||||||
|
}, type === 'error' ? 5000 : 3000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Función para realizar guardado automático
|
||||||
|
async function autoSave(tipo, data) {
|
||||||
|
if (isAutoSaving) return;
|
||||||
|
|
||||||
|
isAutoSaving = true;
|
||||||
|
showSaveIndicator('saving', 'Guardando cambios...');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch('/IMPORTADORES/preferencias/guardarPreferenciasAjax', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'X-Requested-With': 'XMLHttpRequest'
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
tipo: tipo,
|
||||||
|
...data
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await response.json();
|
||||||
|
|
||||||
|
if (result.success) {
|
||||||
|
showSaveIndicator('saved', '✓ Cambios guardados');
|
||||||
|
} else {
|
||||||
|
throw new Error(result.message || 'Error desconocido');
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error al guardar:', error);
|
||||||
|
showSaveIndicator('error', '✗ Error: ' + error.message);
|
||||||
|
|
||||||
|
// En caso de error, podríamos revertir el estado del switch
|
||||||
|
// pero por ahora solo mostramos el error
|
||||||
|
} finally {
|
||||||
|
isAutoSaving = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Función para mostrar/ocultar secciones con animación
|
||||||
|
function toggleSection(checkbox, targetId) {
|
||||||
|
const target = document.getElementById(targetId);
|
||||||
|
const isChecked = checkbox.checked;
|
||||||
|
|
||||||
|
if (isChecked) {
|
||||||
|
target.style.display = 'block';
|
||||||
|
setTimeout(() => {
|
||||||
|
target.style.opacity = '1';
|
||||||
|
}, 10);
|
||||||
|
} else {
|
||||||
|
target.style.opacity = '0';
|
||||||
|
setTimeout(() => {
|
||||||
|
target.style.display = 'none';
|
||||||
|
}, 300);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Event listener para switch general de notificaciones
|
||||||
|
document.getElementById('notificaciones').addEventListener('change', function() {
|
||||||
|
const isChecked = this.checked;
|
||||||
|
|
||||||
|
// Deshabilitar temporalmente otros switches para evitar conflictos
|
||||||
|
const allSwitches = document.querySelectorAll('.form-check-input');
|
||||||
|
allSwitches.forEach(sw => sw.disabled = true);
|
||||||
|
|
||||||
|
// Guardar cambio
|
||||||
|
autoSave('notificaciones_general', {
|
||||||
|
valor: isChecked
|
||||||
|
}).finally(() => {
|
||||||
|
// Rehabilitar switches
|
||||||
|
allSwitches.forEach(sw => sw.disabled = false);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Mostrar/ocultar sección de tipos
|
||||||
|
toggleSection(this, 'tipos-notificaciones');
|
||||||
|
|
||||||
|
// Si se desactivan las notificaciones, también desactivar correo extra
|
||||||
|
if (!isChecked) {
|
||||||
|
const correoExtraCheckbox = document.getElementById('notificaciones_extra');
|
||||||
|
correoExtraCheckbox.checked = false;
|
||||||
|
toggleSection(correoExtraCheckbox, 'correo-extra-section');
|
||||||
|
|
||||||
|
// Desmarcar todos los tipos de notificación
|
||||||
|
document.querySelectorAll('.tipo-notificacion').forEach(checkbox => {
|
||||||
|
checkbox.checked = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Event listener para switch de correo extra
|
||||||
|
document.getElementById('notificaciones_extra').addEventListener('change', function() {
|
||||||
|
const isChecked = this.checked;
|
||||||
|
const correoExtraSection = document.getElementById('correo-extra-section');
|
||||||
|
const correoExtraInfo = correoExtraSection.querySelector('.alert');
|
||||||
|
|
||||||
|
// Verificar si hay correo registrado antes de activar
|
||||||
|
if (isChecked && correoExtraInfo && correoExtraInfo.classList.contains('alert-warning')) {
|
||||||
|
showSaveIndicator('error', 'Primero debes registrar un correo adicional en Seguridad');
|
||||||
|
this.checked = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deshabilitar switch temporalmente
|
||||||
|
this.disabled = true;
|
||||||
|
|
||||||
|
// Guardar cambio
|
||||||
|
autoSave('notificaciones_extra', {
|
||||||
|
valor: isChecked
|
||||||
|
}).finally(() => {
|
||||||
|
this.disabled = false;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Mostrar/ocultar sección
|
||||||
|
toggleSection(this, 'correo-extra-section');
|
||||||
|
});
|
||||||
|
|
||||||
|
// Event listeners para tipos específicos de notificación
|
||||||
|
document.querySelectorAll('.tipo-notificacion').forEach(checkbox => {
|
||||||
|
checkbox.addEventListener('change', function() {
|
||||||
|
const isChecked = this.checked;
|
||||||
|
const tipoNombre = this.dataset.nombre;
|
||||||
|
|
||||||
|
// Verificar que las notificaciones generales estén activadas
|
||||||
|
const notificacionesGenerales = document.getElementById('notificaciones').checked;
|
||||||
|
if (!notificacionesGenerales) {
|
||||||
|
showSaveIndicator('error', 'Primero debes activar las notificaciones generales');
|
||||||
|
this.checked = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deshabilitar switch temporalmente
|
||||||
|
this.disabled = true;
|
||||||
|
|
||||||
|
// Guardar cambio
|
||||||
|
autoSave('tipo_notificacion', {
|
||||||
|
nombre: tipoNombre,
|
||||||
|
valor: isChecked
|
||||||
|
}).finally(() => {
|
||||||
|
this.disabled = false;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Prevenir envío accidental del formulario (aunque ya no lo necesitamos)
|
||||||
|
document.addEventListener('keydown', function(e) {
|
||||||
|
if (e.key === 'Enter' && e.target.type !== 'submit') {
|
||||||
|
e.preventDefault();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Mensaje de confirmación antes de salir si hay guardado en progreso
|
||||||
|
window.addEventListener('beforeunload', function(e) {
|
||||||
|
if (isAutoSaving) {
|
||||||
|
e.preventDefault();
|
||||||
|
e.returnValue = 'Hay cambios pendientes de guardar. ¿Estás seguro de que quieres salir?';
|
||||||
|
return e.returnValue;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -84,20 +84,20 @@ include __DIR__ . '/../partials/sidebar_configuracion.php';
|
|||||||
<div class="row g-3">
|
<div class="row g-3">
|
||||||
|
|
||||||
<div class="col-md-7">
|
<div class="col-md-7">
|
||||||
<div class="card shadow-sm p-3">
|
<div class="card shadow-sm p-3">
|
||||||
<h4 class="mb-4 text-dark">Autenticación de dos factores</h4>
|
<h4 class="mb-4 text-dark">Autenticación de dos factores</h4>
|
||||||
<form>
|
<form>
|
||||||
<div class="form-check form-switch">
|
<div class="form-check form-switch">
|
||||||
<input type="checkbox" class="form-check-input" role="switch"
|
<input type="checkbox" class="form-check-input" role="switch"
|
||||||
id="dos_factores" name="dos_factores" disabled
|
id="dos_factores" name="dos_factores" disabled
|
||||||
<?php if(!empty($correos['dos_factores'])) echo "checked"; ?>>
|
<?php if(!empty($correos['dos_factores'])) echo "checked"; ?>>
|
||||||
<label class="form-check-label" for="dos_factores">
|
<label class="form-check-label" for="dos_factores">
|
||||||
<?php echo !empty($correos['dos_factores']) ? "Activo" : "Inactivo"; ?>
|
<?php echo !empty($correos['dos_factores']) ? "Activo" : "Inactivo"; ?>
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="col-md-7">
|
<div class="col-md-7">
|
||||||
<div class="card shadow-sm p-3">
|
<div class="card shadow-sm p-3">
|
||||||
|
|||||||
Reference in New Issue
Block a user