siip-whatsapp-notifications.../public.php
DANYDHSV 761cd667b5 feat: soporte multi-servicio, optimización de recursos y refinamiento de contraseñas
- Implementado soporte multi-servicio para antenas con formato "Servicio X: <pass>".
- Añadido sistema de "Lazy Check" para evitar llamadas redundantes a la API de UISP si ya existe una contraseña válida.
- Refinado algoritmo de generación de contraseñas: ahora son "Printer-Friendly" (alfanumérico + @, #) y sin caracteres ambiguos.
- Mejorada la lógica de detección de antenas: validación por etapas (Servicio -> Sitio -> Dispositivo) para evitar errores en sitios inactivas.
- Agregados mensajes informativos de estado en el CRM (⚠️ Sin sitio, ⚠️ Sin antena).
- Corregido bucle infinito de webhooks en entornos de prueba mediante validación de idempotencia.
- Actualizada documentación (README.md y CHANGELOG.md) a la versión 3.0.0.
2026-01-02 22:41:54 -06:00

600 lines
21 KiB
PHP
Executable File

<?php
require_once __DIR__ . '/vendor/autoload.php';
use Ubnt\UcrmPluginSdk\Service\PluginLogManager;
use Ubnt\UcrmPluginSdk\Service\PluginConfigManager;
use Ubnt\UcrmPluginSdk\Service\UcrmApi;
// Solo permitir acceso si estamos en un entorno UCRM válido
if (!file_exists(__DIR__ . '/data/config.json')) {
die('Acceso denegado o configuración no encontrada.');
}
$configManager = PluginConfigManager::create();
$config = $configManager->loadConfig();
$logger = new \SmsNotifier\Service\Logger();
// LOG DE EMERGENCIA
$debugLogPath = __DIR__ . '/data/debug_public.log';
file_put_contents($debugLogPath, "[" . date('Y-m-d H:i:s') . "] Hit public.php - Method: " . $_SERVER['REQUEST_METHOD'] . PHP_EOL, FILE_APPEND);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$input = file_get_contents('php://input');
$jsonData = json_decode((string)$input, true);
// Si detectamos que es un webhook de UCRM (contiene uuid o eventName típico)
if ($jsonData && (isset($jsonData['uuid']) || isset($jsonData['eventName']))) {
file_put_contents($debugLogPath, "[" . date('Y-m-d H:i:s') . "] Webhook detectado en public.php. Delegando a Plugin->run()" . PHP_EOL, FILE_APPEND);
$builder = new \DI\ContainerBuilder();
$container = $builder->build();
$plugin = $container->get(\SmsNotifier\Plugin::class);
$plugin->run();
exit;
}
$logger->debug('public.php POST input: ' . substr((string)$input, 0, 100) . '...');
}
$ucrmApi = UcrmApi::create();
// Obtener administradores de UCRM para el selector
$admins = [];
try {
$adminsRaw = $ucrmApi->get('users/admins');
foreach ($adminsRaw as $admin) {
$admins[] = [
'id' => $admin['id'],
'nombre' => trim(($admin['firstName'] ?? '') . ' ' . ($admin['lastName'] ?? ''))
];
}
} catch (\Exception $e) {
$logger->error('Error al obtener administradores de UCRM: ' . $e->getMessage());
}
// Manejar actualizaciones del JSON de instaladores
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_installers') {
$installersJson = $_POST['installers_data'] ?? '';
// Validar que sea un JSON válido
if (json_decode($installersJson) !== null) {
$configPath = __DIR__ . '/data/config.json';
$currentConfig = json_decode(file_get_contents($configPath), true);
$currentConfig['installersDataWhatsApp'] = $installersJson;
if (file_put_contents($configPath, json_encode($currentConfig, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE))) {
header('Content-Type: application/json');
echo json_encode(['success' => true]);
exit;
}
}
header('Content-Type: application/json');
echo json_encode(['success' => false, 'message' => 'Error al guardar los datos.']);
exit;
}
// Cargar instaladores actuales
$installersData = json_decode($config['installersDataWhatsApp'] ?? '{"instaladores":[]}', true);
?>
<!DOCTYPE html>
<html lang="es" data-theme="light">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SIIP - Dashboard Admin</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600;700&display=swap" rel="stylesheet">
<style>
:root {
--primary: #2563eb;
--primary-hover: #1d4ed8;
--bg-body: #f8fafc;
--bg-card: #ffffff;
--text-main: #1e293b;
--text-muted: #64748b;
--border: #e2e8f0;
--sidebar-width: 260px;
--danger: #ef4444;
--success: #22c55e;
--transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
[data-theme="dark"] {
--bg-body: #0f172a;
--bg-card: #1e293b;
--text-main: #f1f5f9;
--text-muted: #94a3b8;
--border: #334155;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Outfit', sans-serif;
}
body {
background-color: var(--bg-body);
color: var(--text-main);
transition: var(--transition);
min-height: 100vh;
display: flex;
}
/* Sidebar */
.sidebar {
width: var(--sidebar-width);
background: var(--bg-card);
border-right: 1px solid var(--border);
padding: 2rem 1.5rem;
display: flex;
flex-direction: column;
position: fixed;
height: 100vh;
z-index: 100;
}
.logo {
font-size: 1.5rem;
font-weight: 700;
color: var(--primary);
margin-bottom: 3rem;
display: flex;
align-items: center;
gap: 10px;
}
.nav-link {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 16px;
border-radius: 12px;
color: var(--text-muted);
text-decoration: none;
margin-bottom: 8px;
transition: var(--transition);
font-weight: 500;
}
.nav-link.active, .nav-link:hover {
background: rgba(37, 99, 235, 0.1);
color: var(--primary);
}
/* Main Content */
.main-content {
margin-left: var(--sidebar-width);
flex: 1;
padding: 2rem 3rem;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 2.5rem;
}
.title-section h1 {
font-size: 1.875rem;
font-weight: 700;
}
.title-section p {
color: var(--text-muted);
}
/* Actions */
.actions {
display: flex;
gap: 1rem;
align-items: center;
}
.btn {
padding: 10px 20px;
border-radius: 10px;
border: none;
font-weight: 600;
cursor: pointer;
transition: var(--transition);
display: flex;
align-items: center;
gap: 8px;
}
.btn-primary {
background: var(--primary);
color: white;
}
.btn-primary:hover {
background: var(--primary-hover);
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(37, 99, 235, 0.2);
}
.theme-toggle {
background: var(--bg-card);
border: 1px solid var(--border);
color: var(--text-main);
width: 44px;
height: 44px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 12px;
overflow: hidden;
position: relative;
}
.theme-toggle svg {
position: absolute;
transition: transform 0.4s ease;
}
[data-theme="light"] .theme-toggle .moon-icon { transform: translateY(40px); }
[data-theme="dark"] .theme-toggle .sun-icon { transform: translateY(-40px); }
/* Card / Table */
.card {
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: 20px;
padding: 1.5rem;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}
.table-container {
overflow-x: auto;
}
table {
width: 100%;
border-collapse: collapse;
}
th {
text-align: left;
padding: 1rem;
color: var(--text-muted);
font-weight: 600;
border-bottom: 2px solid var(--border);
}
td {
padding: 1.25rem 1rem;
border-bottom: 1px solid var(--border);
}
.badge {
padding: 4px 12px;
border-radius: 100px;
font-size: 0.875rem;
font-weight: 600;
background: rgba(37, 99, 235, 0.1);
color: var(--primary);
}
.action-btns {
display: flex;
gap: 8px;
}
.action-btn {
width: 36px;
height: 36px;
border-radius: 8px;
border: none;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: var(--transition);
}
.edit-btn { background: rgba(34, 197, 94, 0.1); color: var(--success); }
.delete-btn { background: rgba(239, 68, 68, 0.1); color: var(--danger); }
.edit-btn:hover { background: var(--success); color: white; }
.delete-btn:hover { background: var(--danger); color: white; }
/* Modal */
.modal-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.5);
backdrop-filter: blur(4px);
display: none;
align-items: center;
justify-content: center;
z-index: 1000;
}
.modal {
background: var(--bg-card);
width: 90%;
max-width: 480px;
padding: 2rem;
border-radius: 24px;
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
}
.form-group {
margin-bottom: 1.25rem;
}
.form-group label {
display: block;
margin-bottom: 6px;
font-weight: 600;
font-size: 0.875rem;
}
.form-control {
width: 100%;
padding: 12px 16px;
border-radius: 10px;
border: 1px solid var(--border);
background: var(--bg-body);
color: var(--text-main);
transition: var(--transition);
}
.form-control:focus {
outline: none;
border-color: var(--primary);
}
.modal-footer {
display: flex;
justify-content: flex-end;
gap: 12px;
margin-top: 2rem;
}
/* Toast */
#toast {
position: fixed;
bottom: 2rem;
left: 50%;
transform: translate(-50%, 150%);
padding: 1rem 2rem;
border-radius: 12px;
background: var(--text-main);
color: var(--bg-body);
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.2);
transition: var(--transition);
z-index: 2000;
}
#toast.show { transform: translate(-50%, 0); }
</style>
</head>
<body>
<aside class="sidebar">
<div class="logo">
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="m3 21 1.9-1.9a8.5 8.5 0 1 0-3.4-3.4z"/><path d="M9 13h1"/></svg>
<span>SIIP CRM</span>
</div>
<nav>
<a href="#" class="nav-link active">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="7" height="9" x="3" y="3" rx="1"/><rect width="7" height="5" x="14" y="3" rx="1"/><rect width="7" height="9" x="14" y="12" rx="1"/><rect width="7" height="5" x="3" y="16" rx="1"/></svg>
<span>Instaladores</span>
</a>
</nav>
</aside>
<main class="main-content">
<header class="header">
<div class="title-section">
<h1>Gestión de Equipo</h1>
<p>Administra los técnicos registrados en el sistema</p>
</div>
<div class="actions">
<button class="btn theme-toggle" id="themeBtn" title="Cambiar tema">
<svg class="sun-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="m17.66 17.66 1.41 1.41"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="m6.34 17.66-1.41 1.41"/><path d="m19.07 4.93-1.41 1.41"/></svg>
<svg class="moon-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"/></svg>
</button>
<button class="btn btn-primary" id="addBtn">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="M12 5v14"/></svg>
Nuevo Instalador
</button>
</div>
</header>
<section class="card">
<div class="table-container">
<table id="installersTable">
<thead>
<tr>
<th>ID UCRM</th>
<th>Nombre Completo</th>
<th>WhatsApp</th>
<th>Acciones</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</section>
</main>
<!-- Modal Form -->
<div class="modal-overlay" id="modalOverlay">
<div class="modal">
<div class="modal-header">
<h2 id="modalTitle">Registro de Instalador</h2>
</div>
<form id="installerForm">
<input type="hidden" id="editIndex">
<div class="form-group" id="adminSelectGroup">
<label>Seleccionar Administrador UCRM</label>
<select id="adminSelect" class="form-control">
<option value="">-- Seleccionar de UCRM --</option>
<?php foreach ($admins as $admin): ?>
<option value="<?= $admin['id'] ?>" data-name="<?= $admin['nombre'] ?>"><?= $admin['nombre'] ?> (ID: <?= $admin['id'] ?>)</option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label>ID de Usuario (Automático)</label>
<input type="number" id="installerId" class="form-control" required readonly>
</div>
<div class="form-group">
<label>Nombre Completo</label>
<input type="text" id="installerName" class="form-control" required readonly>
</div>
<div class="form-group">
<label>WhatsApp (Sin +)</label>
<input type="text" id="installerWhatsApp" class="form-control" required placeholder="Ej. 524181234567">
</div>
<div class="modal-footer">
<button type="button" class="btn" onclick="closeModal()">Cancelar</button>
<button type="submit" class="btn btn-primary">Confirmar</button>
</div>
</form>
</div>
</div>
<div id="toast"></div>
<script>
const store = {
installers: <?php echo json_encode($installersData['instaladores']); ?>,
theme: localStorage.getItem('theme') || 'light'
};
document.documentElement.setAttribute('data-theme', store.theme);
function renderTable() {
const tbody = document.querySelector('#installersTable tbody');
tbody.innerHTML = store.installers.map((inst, index) => `
<tr>
<td><span class="badge">#${inst.id}</span></td>
<td><strong>${inst.nombre}</strong></td>
<td>${inst.whatsapp}</td>
<td>
<div class="action-btns">
<button class="action-btn edit-btn" onclick="editInstaller(${index})" title="Editar">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/><path d="m15 5 4 4"/></svg>
</button>
<button class="action-btn delete-btn" onclick="deleteInstaller(${index})" title="Eliminar">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/><line x1="10" x2="10" y1="11" y2="17"/><line x1="14" x2="14" y1="11" y2="17"/></svg>
</button>
</div>
</td>
</tr>
`).join('');
}
async function saveToServer() {
const formData = new FormData();
formData.append('action', 'save_installers');
formData.append('installers_data', JSON.stringify({ instaladores: store.installers }));
try {
const res = await fetch(window.location.href, { method: 'POST', body: formData });
const data = await res.json();
if (data.success) showToast('Éxito: Cambios guardados en config.json');
else showToast('Error al guardar datos', true);
} catch (e) { showToast('Fallo de conexión', true); }
}
function openModal(index = null) {
const form = document.getElementById('installerForm');
form.reset();
const idxField = document.getElementById('editIndex');
idxField.value = index !== null ? index : '';
document.getElementById('modalTitle').textContent = index !== null ? 'Editar Datos' : 'Registrar desde UCRM';
// Si es edición, ocultamos el selector de admins para evitar cambiar el ID accidentalmente
document.getElementById('adminSelectGroup').style.display = index !== null ? 'none' : 'block';
if (index !== null) {
const inst = store.installers[index];
document.getElementById('installerId').value = inst.id;
document.getElementById('installerName').value = inst.nombre;
document.getElementById('installerWhatsApp').value = inst.whatsapp;
}
document.getElementById('modalOverlay').style.display = 'flex';
}
function closeModal() { document.getElementById('modalOverlay').style.display = 'none'; }
// Manejar selección de admin
document.getElementById('adminSelect').onchange = (e) => {
const opt = e.target.options[e.target.selectedIndex];
if (opt.value) {
document.getElementById('installerId').value = opt.value;
document.getElementById('installerName').value = opt.dataset.name;
} else {
document.getElementById('installerId').value = '';
document.getElementById('installerName').value = '';
}
};
document.getElementById('installerForm').onsubmit = (e) => {
e.preventDefault();
const index = document.getElementById('editIndex').value;
const id = parseInt(document.getElementById('installerId').value);
// Validar existencia si es nuevo
if (index === '' && store.installers.some(inst => inst.id === id)) {
showToast('Este instalador ya está registrado', true);
return;
}
const data = {
id: id,
nombre: document.getElementById('installerName').value,
whatsapp: document.getElementById('installerWhatsApp').value
};
if (index === '') store.installers.push(data);
else store.installers[index] = data;
closeModal();
renderTable();
saveToServer();
};
function editInstaller(index) { openModal(index); }
function deleteInstaller(index) {
if (confirm('¿Eliminar a este instalador?')) {
store.installers.splice(index, 1);
renderTable();
saveToServer();
}
}
document.getElementById('themeBtn').onclick = () => {
store.theme = store.theme === 'light' ? 'dark' : 'light';
document.documentElement.setAttribute('data-theme', store.theme);
localStorage.setItem('theme', store.theme);
};
document.getElementById('addBtn').onclick = () => openModal();
function showToast(msg, isError = false) {
const toast = document.getElementById('toast');
toast.textContent = msg;
toast.style.background = isError ? 'var(--danger)' : '#1e293b';
toast.classList.add('show');
setTimeout(() => toast.classList.remove('show'), 3000);
}
renderTable();
</script>
</body>
</html>