ip
This commit is contained in:
@@ -87,6 +87,7 @@ func Migrate() {
|
|||||||
// Sistema de notificaciones por evento
|
// Sistema de notificaciones por evento
|
||||||
&models.NotifEventoConfig{},
|
&models.NotifEventoConfig{},
|
||||||
&models.SistemaNotificacion{},
|
&models.SistemaNotificacion{},
|
||||||
|
&models.ServidorAlertaUmbral{},
|
||||||
// Submódulo Partner
|
// Submódulo Partner
|
||||||
&models.PartnerRecurso{},
|
&models.PartnerRecurso{},
|
||||||
&models.PartnerComunicado{},
|
&models.PartnerComunicado{},
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
package models
|
package models
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/sujit-baniya/fiber-boilerplate/app"
|
"github.com/sujit-baniya/fiber-boilerplate/app"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
@@ -130,3 +132,57 @@ func MarcarNotifsFacturasLeidas(usuarioID uint) error {
|
|||||||
Where("tipo_usuario = 'portal_user' AND usuario_id = ? AND icono = '🧾'", usuarioID).
|
Where("tipo_usuario = 'portal_user' AND usuario_id = ? AND icono = '🧾'", usuarioID).
|
||||||
Update("leida", true).Error
|
Update("leida", true).Error
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── ServidorAlertaUmbral ─────────────────────────────────────────────────────
|
||||||
|
// Configuración global de umbrales para alertas de servidores.
|
||||||
|
// Solo existe un registro (singleton, ID = 1).
|
||||||
|
|
||||||
|
type ServidorAlertaUmbral struct {
|
||||||
|
gorm.Model
|
||||||
|
Activo bool `json:"activo" gorm:"column:activo;default:true"`
|
||||||
|
MinutosSinPing int `json:"minutos_sin_ping" gorm:"column:minutos_sin_ping;default:10"`
|
||||||
|
UmbralCPU int `json:"umbral_cpu" gorm:"column:umbral_cpu;default:90"`
|
||||||
|
UmbralRAM int `json:"umbral_ram" gorm:"column:umbral_ram;default:90"`
|
||||||
|
UmbralDisco int `json:"umbral_disco" gorm:"column:umbral_disco;default:90"`
|
||||||
|
DiasAnteVencimiento int `json:"dias_ante_vencimiento" gorm:"column:dias_ante_vencimiento;default:7"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ServidorAlertaUmbral) TableName() string { return "servidor_alerta_umbral" }
|
||||||
|
|
||||||
|
// GetServidorAlertaUmbral obtiene el singleton de umbrales; crea uno con defaults si no existe.
|
||||||
|
func GetServidorAlertaUmbral() *ServidorAlertaUmbral {
|
||||||
|
var cfg ServidorAlertaUmbral
|
||||||
|
db := app.Http.Database.DB
|
||||||
|
if err := db.First(&cfg).Error; err != nil {
|
||||||
|
cfg = ServidorAlertaUmbral{Activo: true, MinutosSinPing: 10, UmbralCPU: 90, UmbralRAM: 90, UmbralDisco: 90, DiasAnteVencimiento: 7}
|
||||||
|
db.Create(&cfg)
|
||||||
|
}
|
||||||
|
return &cfg
|
||||||
|
}
|
||||||
|
|
||||||
|
// SaveServidorAlertaUmbral guarda el singleton.
|
||||||
|
func SaveServidorAlertaUmbral(cfg *ServidorAlertaUmbral) error {
|
||||||
|
db := app.Http.Database.DB
|
||||||
|
var existing ServidorAlertaUmbral
|
||||||
|
if err := db.First(&existing).Error; err != nil {
|
||||||
|
return db.Create(cfg).Error
|
||||||
|
}
|
||||||
|
return db.Model(&existing).Updates(map[string]interface{}{
|
||||||
|
"activo": cfg.Activo,
|
||||||
|
"minutos_sin_ping": cfg.MinutosSinPing,
|
||||||
|
"umbral_cpu": cfg.UmbralCPU,
|
||||||
|
"umbral_ram": cfg.UmbralRAM,
|
||||||
|
"umbral_disco": cfg.UmbralDisco,
|
||||||
|
"dias_ante_vencimiento": cfg.DiasAnteVencimiento,
|
||||||
|
}).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
// YaExisteAlertaServidor evita spam: true si ya se creó una notificación con el
|
||||||
|
// mismo título para este servidor en las últimas `horas` horas.
|
||||||
|
func YaExisteAlertaServidor(titulo string, horas int) bool {
|
||||||
|
var count int64
|
||||||
|
app.Http.Database.DB.Model(&SistemaNotificacion{}).
|
||||||
|
Where("titulo = ? AND created_at > ?", titulo, time.Now().Add(-time.Duration(horas)*time.Hour)).
|
||||||
|
Count(&count)
|
||||||
|
return count > 0
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
package services
|
package services
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/robfig/cron/v3"
|
"github.com/robfig/cron/v3"
|
||||||
"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
|
"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
|
||||||
@@ -32,8 +35,14 @@ func IniciarCron() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Salud de servidores — cada 5 minutos
|
||||||
|
if _, err := cronScheduler.AddFunc("*/5 * * * *", VerificarSaludServidores); err != nil {
|
||||||
|
log.Printf("[CRON] Error registrando tarea salud_servidores: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
cronScheduler.Start()
|
cronScheduler.Start()
|
||||||
log.Println("[CRON] Scheduler iniciado — vencimientos próximos 8AM, ya vencidos 9AM, Bold polling cada 15min")
|
log.Println("[CRON] Scheduler iniciado — vencimientos próximos 8AM, ya vencidos 9AM, Bold polling cada 15min, salud servidores cada 5min")
|
||||||
}
|
}
|
||||||
|
|
||||||
// DetenerCron para graceful shutdown
|
// DetenerCron para graceful shutdown
|
||||||
@@ -208,3 +217,100 @@ func VerificarPagosBoldPendientes() {
|
|||||||
|
|
||||||
log.Println("[BOLD-POLL] Verificación completada")
|
log.Println("[BOLD-POLL] Verificación completada")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── Salud de Servidores ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
// VerificarSaludServidores corre cada 5 min y genera notificaciones del sistema
|
||||||
|
// cuando detecta: agente caído, recurso al límite o VPS próximo a vencer.
|
||||||
|
func VerificarSaludServidores() {
|
||||||
|
cfg := models.GetServidorAlertaUmbral()
|
||||||
|
if !cfg.Activo {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
servidores, _, err := models.GetAllServidores(1000, 0, "")
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("[CRON-SRV] Error obteniendo servidores: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, srv := range servidores {
|
||||||
|
// 1. Agente caído (sin ping en X minutos)
|
||||||
|
if srv.AgentToken != "" && srv.AgentLastSeen != nil {
|
||||||
|
minutos := time.Since(*srv.AgentLastSeen).Minutes()
|
||||||
|
if minutos > float64(cfg.MinutosSinPing) {
|
||||||
|
titulo := fmt.Sprintf("🔴 Sin señal: %s", srv.Nombre)
|
||||||
|
if !models.YaExisteAlertaServidor(titulo, 1) {
|
||||||
|
crearNotifServidor(titulo,
|
||||||
|
fmt.Sprintf("El agente no reporta hace %.0f minutos (umbral: %d min)", minutos, cfg.MinutosSinPing),
|
||||||
|
"servidor_caido")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Recursos (CPU / RAM / Disco) al límite
|
||||||
|
if srv.MetricasJson != "" {
|
||||||
|
var m struct {
|
||||||
|
CPU struct{ Porcentaje float64 `json:"porcentaje"` } `json:"cpu"`
|
||||||
|
RAM struct{ Porcentaje float64 `json:"porcentaje"` } `json:"ram"`
|
||||||
|
Disco struct{ Porcentaje float64 `json:"porcentaje"` } `json:"disco"`
|
||||||
|
}
|
||||||
|
if jsonErr := json.Unmarshal([]byte(srv.MetricasJson), &m); jsonErr == nil {
|
||||||
|
checkRecurso(srv.Nombre, "CPU", m.CPU.Porcentaje, cfg.UmbralCPU)
|
||||||
|
checkRecurso(srv.Nombre, "RAM", m.RAM.Porcentaje, cfg.UmbralRAM)
|
||||||
|
checkRecurso(srv.Nombre, "Disco", m.Disco.Porcentaje, cfg.UmbralDisco)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Vencimiento próximo
|
||||||
|
if srv.Vencimiento != "" && cfg.DiasAnteVencimiento > 0 {
|
||||||
|
vence, parseErr := time.Parse("2006-01-02", srv.Vencimiento)
|
||||||
|
if parseErr == nil {
|
||||||
|
dias := int(time.Until(vence).Hours() / 24)
|
||||||
|
if dias >= 0 && dias <= cfg.DiasAnteVencimiento {
|
||||||
|
titulo := fmt.Sprintf("📅 %s vence en %s", srv.Nombre, strconv.Itoa(dias)+" días")
|
||||||
|
if dias == 0 {
|
||||||
|
titulo = fmt.Sprintf("📅 %s vence HOY", srv.Nombre)
|
||||||
|
}
|
||||||
|
if !models.YaExisteAlertaServidor(titulo, 12) {
|
||||||
|
crearNotifServidor(titulo,
|
||||||
|
fmt.Sprintf("Fecha de vencimiento: %s. Renueva a tiempo.", srv.Vencimiento),
|
||||||
|
"servidor_vence_pronto")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkRecurso(nombre, recurso string, valor float64, umbral int) {
|
||||||
|
if valor < float64(umbral) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
titulo := fmt.Sprintf("⚠️ %s alto en %s (%.0f%%)", recurso, nombre, valor)
|
||||||
|
if !models.YaExisteAlertaServidor(titulo, 1) {
|
||||||
|
crearNotifServidor(titulo,
|
||||||
|
fmt.Sprintf("%s al %.0f%% (umbral: %d%%)", recurso, valor, umbral),
|
||||||
|
"servidor_recurso_alto")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func crearNotifServidor(titulo, cuerpo, evento string) {
|
||||||
|
// Verificar si la notificación del sistema está habilitada para este evento
|
||||||
|
evtCfg := models.GetNotifConfig(evento, "admin")
|
||||||
|
// Por defecto, si no hay config, crear notificación de sistema igualmente
|
||||||
|
if evtCfg == nil || evtCfg.CanalSistema {
|
||||||
|
_ = models.CreateSistemaNotif(&models.SistemaNotificacion{
|
||||||
|
TipoUsuario: "admin",
|
||||||
|
Titulo: titulo,
|
||||||
|
Cuerpo: cuerpo,
|
||||||
|
Url: "/app/servidor-dashboard",
|
||||||
|
Icono: "🖥️",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
// Telegram (si está configurado para este evento)
|
||||||
|
if evtCfg != nil && evtCfg.CanalTelegram {
|
||||||
|
msg := fmt.Sprintf("<b>%s</b>\n%s", titulo, cuerpo)
|
||||||
|
sendTelegramAdmin(msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -91,7 +91,81 @@
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Toast -->
|
<!-- ── Umbrales de alerta de servidores ─────────────────────────────── -->
|
||||||
|
<div class="mt-8" x-data="servidorUmbralConfig()">
|
||||||
|
<div class="flex items-center justify-between mb-3">
|
||||||
|
<h2 class="text-base font-bold text-slate-700">🖥️ Umbrales de alerta de servidores</h2>
|
||||||
|
<label class="flex items-center gap-2 cursor-pointer">
|
||||||
|
<span class="text-sm text-slate-600">Activo</span>
|
||||||
|
<input type="checkbox" x-model="form.activo" class="w-4 h-4 rounded accent-[#8eb02f]">
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="bg-white border border-slate-200 rounded-xl overflow-hidden shadow-sm">
|
||||||
|
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-0 divide-y sm:divide-y-0 sm:divide-x divide-slate-100">
|
||||||
|
|
||||||
|
<!-- Minutos sin ping -->
|
||||||
|
<div class="p-4">
|
||||||
|
<label class="block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-1">⏱ Sin señal (minutos)</label>
|
||||||
|
<p class="text-xs text-slate-400 mb-2">Alerta si el agente no reporta en X minutos.</p>
|
||||||
|
<input type="number" min="1" max="120" x-model.number="form.minutos_sin_ping"
|
||||||
|
class="w-full border border-slate-200 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-[#8eb02f]">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Umbral CPU -->
|
||||||
|
<div class="p-4">
|
||||||
|
<label class="block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-1">🔥 Umbral CPU (%)</label>
|
||||||
|
<p class="text-xs text-slate-400 mb-2">Alerta si la CPU supera este porcentaje.</p>
|
||||||
|
<input type="number" min="50" max="100" x-model.number="form.umbral_cpu"
|
||||||
|
class="w-full border border-slate-200 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-[#8eb02f]">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Umbral RAM -->
|
||||||
|
<div class="p-4">
|
||||||
|
<label class="block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-1">🧠 Umbral RAM (%)</label>
|
||||||
|
<p class="text-xs text-slate-400 mb-2">Alerta si la RAM supera este porcentaje.</p>
|
||||||
|
<input type="number" min="50" max="100" x-model.number="form.umbral_ram"
|
||||||
|
class="w-full border border-slate-200 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-[#8eb02f]">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Umbral Disco -->
|
||||||
|
<div class="p-4">
|
||||||
|
<label class="block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-1">💾 Umbral Disco (%)</label>
|
||||||
|
<p class="text-xs text-slate-400 mb-2">Alerta si el disco supera este porcentaje.</p>
|
||||||
|
<input type="number" min="50" max="100" x-model.number="form.umbral_disco"
|
||||||
|
class="w-full border border-slate-200 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-[#8eb02f]">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Días antes de vencimiento -->
|
||||||
|
<div class="p-4">
|
||||||
|
<label class="block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-1">📅 Avisar antes de vencer (días)</label>
|
||||||
|
<p class="text-xs text-slate-400 mb-2">Alerta X días antes de que venza el VPS.</p>
|
||||||
|
<input type="number" min="1" max="60" x-model.number="form.dias_ante_vencimiento"
|
||||||
|
class="w-full border border-slate-200 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-[#8eb02f]">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Guardar -->
|
||||||
|
<div class="p-4 flex items-end">
|
||||||
|
<button @click="guardar()"
|
||||||
|
class="w-full px-4 py-2 rounded-lg text-white text-sm font-medium transition-colors"
|
||||||
|
style="background:#8eb02f"
|
||||||
|
onmouseover="this.style.background='#6d8c24'" onmouseout="this.style.background='#8eb02f'">
|
||||||
|
Guardar umbrales
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Feedback -->
|
||||||
|
<div x-show="umbralToast.visible" x-transition
|
||||||
|
class="fixed bottom-6 left-6 z-50 px-4 py-3 rounded-xl shadow-lg text-white text-sm font-medium"
|
||||||
|
:class="umbralToast.ok ? 'bg-green-600' : 'bg-red-500'"
|
||||||
|
x-text="umbralToast.msg">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Toast (eventos) -->
|
||||||
<div x-show="toast.visible" x-transition
|
<div x-show="toast.visible" x-transition
|
||||||
class="fixed bottom-6 right-6 z-50 px-4 py-3 rounded-xl shadow-lg text-white text-sm font-medium"
|
class="fixed bottom-6 right-6 z-50 px-4 py-3 rounded-xl shadow-lg text-white text-sm font-medium"
|
||||||
:class="toast.ok ? 'bg-green-600' : 'bg-red-500'"
|
:class="toast.ok ? 'bg-green-600' : 'bg-red-500'"
|
||||||
@@ -107,6 +181,10 @@ const EVENTOS = [
|
|||||||
{ evento: 'ticket_respuesta_cliente', destinatario: 'admin', label: 'Respuesta del cliente', icon: '💬' },
|
{ evento: 'ticket_respuesta_cliente', destinatario: 'admin', label: 'Respuesta del cliente', icon: '💬' },
|
||||||
{ evento: 'ticket_respuesta_admin', destinatario: 'portal_user', label: 'Respuesta del admin', icon: '💬' },
|
{ evento: 'ticket_respuesta_admin', destinatario: 'portal_user', label: 'Respuesta del admin', icon: '💬' },
|
||||||
{ evento: 'factura_subida', destinatario: 'portal_user', label: 'Factura subida / disponible', icon: '🧾' },
|
{ evento: 'factura_subida', destinatario: 'portal_user', label: 'Factura subida / disponible', icon: '🧾' },
|
||||||
|
// Servidores
|
||||||
|
{ evento: 'servidor_caido', destinatario: 'admin', label: 'Servidor sin señal (agente caído)', icon: '🔴' },
|
||||||
|
{ evento: 'servidor_vence_pronto', destinatario: 'admin', label: 'VPS próximo a vencer', icon: '📅' },
|
||||||
|
{ evento: 'servidor_recurso_alto', destinatario: 'admin', label: 'Recurso al límite (CPU/RAM/Disco)', icon: '⚠️' },
|
||||||
// Próximos eventos (deshabilitados por ahora):
|
// Próximos eventos (deshabilitados por ahora):
|
||||||
// { evento: 'factura_emitida', destinatario: 'portal_user', label: 'Factura emitida', icon: '🧾' },
|
// { evento: 'factura_emitida', destinatario: 'portal_user', label: 'Factura emitida', icon: '🧾' },
|
||||||
// { evento: 'avance_publicado', destinatario: 'portal_user', label: 'Avance publicado', icon: '📦' },
|
// { evento: 'avance_publicado', destinatario: 'portal_user', label: 'Avance publicado', icon: '📦' },
|
||||||
@@ -169,4 +247,26 @@ function notifConfig() {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function servidorUmbralConfig() {
|
||||||
|
return {
|
||||||
|
form: { activo: true, minutos_sin_ping: 10, umbral_cpu: 90, umbral_ram: 90, umbral_disco: 90, dias_ante_vencimiento: 7 },
|
||||||
|
umbralToast: { visible: false, ok: true, msg: '' },
|
||||||
|
async init() {
|
||||||
|
try {
|
||||||
|
const r = await axios.get('/app/servidor-alerta-config');
|
||||||
|
if (r.data?.data) this.form = r.data.data;
|
||||||
|
} catch {}
|
||||||
|
},
|
||||||
|
async guardar() {
|
||||||
|
try {
|
||||||
|
await axios.post('/app/servidor-alerta-config', this.form);
|
||||||
|
this.umbralToast = { visible: true, ok: true, msg: 'Umbrales guardados' };
|
||||||
|
} catch {
|
||||||
|
this.umbralToast = { visible: true, ok: false, msg: 'Error al guardar' };
|
||||||
|
}
|
||||||
|
setTimeout(() => this.umbralToast.visible = false, 3000);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -46,10 +46,9 @@
|
|||||||
<span x-show="agentOnline(servidor)">● En línea</span>
|
<span x-show="agentOnline(servidor)">● En línea</span>
|
||||||
<span x-show="!agentOnline(servidor) && servidor.agent_token">● Fuera</span>
|
<span x-show="!agentOnline(servidor) && servidor.agent_token">● Fuera</span>
|
||||||
<span x-show="!servidor.agent_token">○ Sin agente</span>
|
<span x-show="!servidor.agent_token">○ Sin agente</span>
|
||||||
</span> <!-- Badge estado Hostinger -->
|
</span> <!-- Badge estado Hostinger: solo mostrar cuando NO es running (estados críticos como stopped/error) -->
|
||||||
<span x-show="servidor.hostinger_vps_id" class="text-xs px-2 py-0.5 rounded-full font-bold"
|
<span x-show="servidor.hostinger_vps_id && servidor.hostinger_state && servidor.hostinger_state !== 'running'" class="text-xs px-2 py-0.5 rounded-full font-bold bg-amber-200 text-amber-900">
|
||||||
:class="servidor.hostinger_state === 'running' ? 'bg-emerald-200 text-emerald-900' : (servidor.hostinger_state ? 'bg-amber-200 text-amber-900' : 'bg-slate-200 text-slate-600')">
|
<span x-text="servidor.hostinger_state" class="capitalize"></span>
|
||||||
<span x-text="servidor.hostinger_state || 'Hostinger'" class="capitalize"></span>
|
|
||||||
</span> </div>
|
</span> </div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -129,13 +128,23 @@
|
|||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<!-- Provider & Conexiones -->
|
<!-- Provider, Vencimiento & Conexiones -->
|
||||||
<div class="flex items-center justify-between text-xs text-slate-500 pt-1">
|
<div class="space-y-1.5 pt-1">
|
||||||
<span x-text="servidor.prov_servidor?.nombre || 'Sin proveedor'"></span>
|
<!-- Vencimiento -->
|
||||||
<span>
|
<template x-if="servidor.vencimiento">
|
||||||
<span class="font-bold text-blue-600" x-text="servidor.conx_count ?? servidor._conexiones?.length ?? 0"></span>
|
<div x-data="{ info: vencimientoInfo(servidor.vencimiento) }">
|
||||||
BD
|
<span class="inline-flex items-center gap-1 text-xs font-semibold px-2 py-0.5 rounded-full"
|
||||||
</span>
|
:class="info.clase"
|
||||||
|
x-text="'📅 ' + info.texto"></span>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<div class="flex items-center justify-between text-xs text-slate-500">
|
||||||
|
<span x-text="servidor.prov_servidor?.nombre || 'Sin proveedor'"></span>
|
||||||
|
<span>
|
||||||
|
<span class="font-bold text-blue-600" x-text="servidor.conx_count ?? servidor._conexiones?.length ?? 0"></span>
|
||||||
|
BD
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Action Buttons -->
|
<!-- Action Buttons -->
|
||||||
@@ -608,6 +617,18 @@
|
|||||||
return diffMs < 3 * 60 * 1000; // online si reportó en últimos 3 minutos
|
return diffMs < 3 * 60 * 1000; // online si reportó en últimos 3 minutos
|
||||||
},
|
},
|
||||||
|
|
||||||
|
vencimientoInfo(fecha) {
|
||||||
|
if (!fecha) return null;
|
||||||
|
const hoy = new Date(); hoy.setHours(0,0,0,0);
|
||||||
|
const vence = new Date(fecha); vence.setHours(0,0,0,0);
|
||||||
|
const dias = Math.round((vence - hoy) / 86400000);
|
||||||
|
if (dias < 0) return { texto: 'Vencido', clase: 'bg-red-100 text-red-700' };
|
||||||
|
if (dias === 0) return { texto: 'Vence hoy', clase: 'bg-red-100 text-red-700' };
|
||||||
|
if (dias <= 7) return { texto: `Vence en ${dias}d`, clase: 'bg-red-100 text-red-700' };
|
||||||
|
if (dias <= 30) return { texto: `Vence en ${dias}d`, clase: 'bg-amber-100 text-amber-700' };
|
||||||
|
return { texto: fecha, clase: 'bg-slate-100 text-slate-500' };
|
||||||
|
},
|
||||||
|
|
||||||
tiempoDesde(isoStr) {
|
tiempoDesde(isoStr) {
|
||||||
if (!isoStr) return '—';
|
if (!isoStr) return '—';
|
||||||
const diff = Math.floor((Date.now() - new Date(isoStr).getTime()) / 1000);
|
const diff = Math.floor((Date.now() - new Date(isoStr).getTime()) / 1000);
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package controllers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GetServidorAlertaConfig devuelve la configuración actual de umbrales de alerta.
|
||||||
|
func GetServidorAlertaConfig(c *fiber.Ctx) error {
|
||||||
|
cfg := models.GetServidorAlertaUmbral()
|
||||||
|
return c.JSON(fiber.Map{"ok": true, "data": cfg})
|
||||||
|
}
|
||||||
|
|
||||||
|
// SaveServidorAlertaConfig guarda la configuración de umbrales de alerta.
|
||||||
|
func SaveServidorAlertaConfig(c *fiber.Ctx) error {
|
||||||
|
var input models.ServidorAlertaUmbral
|
||||||
|
if err := c.BodyParser(&input); err != nil {
|
||||||
|
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"ok": false, "error": "JSON inválido"})
|
||||||
|
}
|
||||||
|
if err := models.SaveServidorAlertaUmbral(&input); err != nil {
|
||||||
|
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"ok": false, "error": err.Error()})
|
||||||
|
}
|
||||||
|
return c.JSON(fiber.Map{"ok": true})
|
||||||
|
}
|
||||||
@@ -346,6 +346,9 @@ func UserRoutes(app fiber.Router) {
|
|||||||
protected.Get("/notif-config", middlewares.MenuMiddleware, controllers.NotifConfigIndex)
|
protected.Get("/notif-config", middlewares.MenuMiddleware, controllers.NotifConfigIndex)
|
||||||
protected.Get("/notif-config/data", controllers.GetNotifConfigs)
|
protected.Get("/notif-config/data", controllers.GetNotifConfigs)
|
||||||
protected.Post("/notif-config", controllers.SaveNotifConfig)
|
protected.Post("/notif-config", controllers.SaveNotifConfig)
|
||||||
|
// Umbrales de alerta de servidores
|
||||||
|
protected.Get("/servidor-alerta-config", controllers.GetServidorAlertaConfig)
|
||||||
|
protected.Post("/servidor-alerta-config", controllers.SaveServidorAlertaConfig)
|
||||||
|
|
||||||
// Partner Recursos (documentación y comunicados para partners)
|
// Partner Recursos (documentación y comunicados para partners)
|
||||||
protected.Get("/partner-recursos", middlewares.MenuMiddleware, controllers.PartnerRecursosIndex)
|
protected.Get("/partner-recursos", middlewares.MenuMiddleware, controllers.PartnerRecursosIndex)
|
||||||
|
|||||||
Reference in New Issue
Block a user