This commit is contained in:
Lizandro Guarnizo
2026-05-15 21:01:30 -05:00
parent 5555514929
commit 5ec5595196
13 changed files with 788 additions and 9 deletions
+1
View File
@@ -74,6 +74,7 @@ func main() {
migrations.SeedPlantillasBase()
migrations.SeedTelegram()
migrations.SeedPortalClientes()
migrations.SeedNotifDefaults()
// Iniciar cron de vencimientos
services.IniciarCron()
defer services.DetenerCron()
+24 -2
View File
@@ -81,8 +81,9 @@ func Migrate() {
&models.ProyectoEntregable{},
&models.ProyectoTicket{},
&models.TicketMensaje{},
&models.Factura{},
); err != nil {
&models.Factura{}, // Sistema de notificaciones
&models.NotifEventoConfig{},
&models.SistemaNotificacion{}, ); err != nil {
log.Fatalf("Error during main migration: %v", err)
}
@@ -850,3 +851,24 @@ func SeedPortalClientes() {
}
log.Println("[SEED] Seed de Portal de Clientes completado.")
}
// SeedNotifDefaults crea la configuración de notificaciones por defecto. Es idempotente.
func SeedNotifDefaults() {
db := app.Http.Database.DB
defaults := []models.NotifEventoConfig{
{Evento: "ticket_nuevo", Destinatario: "admin", CanalEmail: true, CanalTelegram: false, CanalSistema: true, Descripcion: "Admin recibe cuando el cliente abre un ticket"},
{Evento: "ticket_respuesta_cliente", Destinatario: "admin", CanalEmail: true, CanalTelegram: false, CanalSistema: true, Descripcion: "Admin recibe cuando el cliente responde un ticket"},
{Evento: "ticket_respuesta_admin", Destinatario: "portal_user", CanalEmail: true, CanalTelegram: false, CanalSistema: true, Descripcion: "Cliente recibe cuando el admin responde su ticket"},
}
for _, cfg := range defaults {
var existing models.NotifEventoConfig
if err := db.Where("evento = ? AND destinatario = ?", cfg.Evento, cfg.Destinatario).First(&existing).Error; err != nil {
if err := db.Create(&cfg).Error; err != nil {
log.Printf("[SEED] Error creando notif config %s/%s: %v", cfg.Evento, cfg.Destinatario, err)
} else {
log.Printf("[SEED] Notif config creada: %s → %s", cfg.Evento, cfg.Destinatario)
}
}
}
log.Println("[SEED] Seed de notificaciones completado.")
}
+110
View File
@@ -0,0 +1,110 @@
package models
import (
"github.com/sujit-baniya/fiber-boilerplate/app"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// ─── NotifEventoConfig ────────────────────────────────────────────────────────
// Define qué canales activar para cada combinación evento × destinatario.
//
// Eventos disponibles (extensibles):
// ticket_nuevo → admin recibe cuando el cliente abre un ticket
// ticket_respuesta_cliente → admin recibe cuando el cliente responde
// ticket_respuesta_admin → portal_user recibe cuando admin responde
// factura_emitida → portal_user recibe cuando se emite factura
// avance_publicado → portal_user recibe cuando se publica avance
//
// Destinatarios: "admin" | "portal_user"
type NotifEventoConfig struct {
gorm.Model
Evento string `json:"evento" gorm:"column:evento;uniqueIndex:uidx_notif_ev_dest"`
Destinatario string `json:"destinatario" gorm:"column:destinatario;uniqueIndex:uidx_notif_ev_dest"`
CanalEmail bool `json:"canal_email" gorm:"column:canal_email;default:true"`
CanalTelegram bool `json:"canal_telegram" gorm:"column:canal_telegram;default:false"`
CanalSistema bool `json:"canal_sistema" gorm:"column:canal_sistema;default:true"`
Descripcion string `json:"descripcion" gorm:"column:descripcion"`
}
func (NotifEventoConfig) TableName() string { return "notif_evento_configs" }
// ─── SistemaNotificacion ──────────────────────────────────────────────────────
// Notificaciones in-app visibles en el badge del header.
// tipo_usuario = "admin" → visible para todos los admins (usuario_id = 0)
// tipo_usuario = "portal_user" → visible solo para ese portal user
type SistemaNotificacion struct {
gorm.Model
TipoUsuario string `json:"tipo_usuario" gorm:"column:tipo_usuario;index"`
UsuarioID uint `json:"usuario_id" gorm:"column:usuario_id;index"`
Titulo string `json:"titulo" gorm:"column:titulo"`
Cuerpo string `json:"cuerpo" gorm:"column:cuerpo;type:text"`
Leida bool `json:"leida" gorm:"column:leida;default:false"`
Url string `json:"url" gorm:"column:url"`
Icono string `json:"icono" gorm:"column:icono"` // emoji: 🎫 🧾 📦
}
func (SistemaNotificacion) TableName() string { return "sistema_notificaciones" }
// ─── CRUD NotifEventoConfig ───────────────────────────────────────────────────
func GetAllNotifConfigs() ([]NotifEventoConfig, error) {
var items []NotifEventoConfig
err := app.Http.Database.DB.Order("evento, destinatario").Find(&items).Error
return items, err
}
func GetNotifConfig(evento, destinatario string) *NotifEventoConfig {
var item NotifEventoConfig
if err := app.Http.Database.DB.
Where("evento = ? AND destinatario = ?", evento, destinatario).
First(&item).Error; err != nil {
return nil
}
return &item
}
// UpsertNotifConfig inserta o actualiza los canales para un evento × destinatario.
func UpsertNotifConfig(cfg *NotifEventoConfig) error {
return app.Http.Database.DB.
Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "evento"}, {Name: "destinatario"}},
DoUpdates: clause.AssignmentColumns([]string{"canal_email", "canal_telegram", "canal_sistema"}),
}).
Create(cfg).Error
}
// ─── CRUD SistemaNotificacion ─────────────────────────────────────────────────
func CreateSistemaNotif(n *SistemaNotificacion) error {
return app.Http.Database.DB.Create(n).Error
}
func GetSistemaNotifs(tipoUsuario string, usuarioID uint, soloNoLeidas bool) ([]SistemaNotificacion, error) {
var items []SistemaNotificacion
db := app.Http.Database.DB.Where("tipo_usuario = ? AND (usuario_id = ? OR usuario_id = 0)", tipoUsuario, usuarioID)
if soloNoLeidas {
db = db.Where("leida = false")
}
err := db.Order("created_at DESC").Limit(50).Find(&items).Error
return items, err
}
func CountUnreadNotifs(tipoUsuario string, usuarioID uint) int64 {
var count int64
app.Http.Database.DB.Model(&SistemaNotificacion{}).
Where("tipo_usuario = ? AND (usuario_id = ? OR usuario_id = 0) AND leida = false", tipoUsuario, usuarioID).
Count(&count)
return count
}
func MarcarNotifLeida(id uint) error {
return app.Http.Database.DB.Model(&SistemaNotificacion{}).
Where("id = ?", id).Update("leida", true).Error
}
func MarcarTodasLeidas(tipoUsuario string, usuarioID uint) error {
return app.Http.Database.DB.Model(&SistemaNotificacion{}).
Where("tipo_usuario = ? AND (usuario_id = ? OR usuario_id = 0)", tipoUsuario, usuarioID).
Update("leida", true).Error
}
+11 -5
View File
@@ -22,9 +22,12 @@ type PortalUser struct {
Rol string `json:"rol" gorm:"column:rol;default:'cliente'"`
RoleID *uint `json:"role_id" gorm:"column:role_id;index"`
Role *Roles `json:"role" gorm:"foreignKey:RoleID"`
Activo bool `json:"activo" gorm:"column:activo;default:true"`
Notas string `json:"notas" gorm:"column:notas;type:text"`
PortalAccesos []PortalAcceso `json:"portal_accesos" gorm:"foreignKey:PortalUserID"`
Activo bool `json:"activo" gorm:"column:activo;default:true"`
Notas string `json:"notas" gorm:"column:notas;type:text"`
TelegramChatID string `json:"telegram_chat_id" gorm:"column:telegram_chat_id"`
Telefono string `json:"telefono" gorm:"column:telefono"`
Pais string `json:"pais" gorm:"column:pais"`
PortalAccesos []PortalAcceso `json:"portal_accesos" gorm:"foreignKey:PortalUserID"`
}
func (PortalUser) TableName() string { return "portal_users" }
@@ -78,8 +81,11 @@ func UpdatePortalUser(u *PortalUser) error {
"cliente_id": u.ClienteID,
"rol": u.Rol,
"role_id": u.RoleID,
"activo": u.Activo,
"notas": u.Notas,
"activo": u.Activo,
"notas": u.Notas,
"telegram_chat_id": u.TelegramChatID,
"telefono": u.Telefono,
"pais": u.Pais,
}).Error
}
+69
View File
@@ -107,3 +107,72 @@ func SendPortalCredentialsEmail(email, nombre, password string) {
}
}()
}
// ─── Notificaciones de Tickets ────────────────────────────────────────────────
// SendTicketNuevoAdmin notifica al admin que el cliente abrió un ticket.
func SendTicketNuevoAdmin(adminEmail, proyectoNombre, autorNombre, titulo, descripcion, ticketURL string) {
subject := fmt.Sprintf("🎫 Nuevo ticket: %s", titulo)
htmlBody := fmt.Sprintf(`<!DOCTYPE html>
<html><body style="font-family:Inter,sans-serif;background:#f1f5f9;padding:32px">
<div style="max-width:520px;margin:0 auto;background:#fff;border-radius:16px;padding:32px;border:1px solid #e2e8f0">
<div style="display:flex;align-items:center;gap:12px;margin-bottom:20px">
<div style="width:40px;height:40px;border-radius:50%%;background:#8eb02f;display:flex;align-items:center;justify-content:center;color:#fff;font-size:18px">🎫</div>
<div><h2 style="margin:0;color:#1e293b;font-size:17px">Nuevo ticket de soporte</h2>
<p style="margin:0;color:#64748b;font-size:13px">Proyecto: <strong>%s</strong></p></div>
</div>
<div style="background:#f8fafc;border-radius:10px;padding:16px;margin-bottom:20px;border:1px solid #e2e8f0">
<p style="margin:0 0 6px;font-size:14px;color:#334155"><strong>Cliente:</strong> %s</p>
<p style="margin:0 0 6px;font-size:14px;color:#334155"><strong>Título:</strong> %s</p>
<p style="margin:0;font-size:14px;color:#334155"><strong>Descripción:</strong> %s</p>
</div>
<a href="%s" style="display:block;text-align:center;background:#8eb02f;color:#fff;padding:12px 24px;border-radius:10px;font-weight:600;text-decoration:none;font-size:15px">Ver ticket</a>
</div></body></html>`, proyectoNombre, autorNombre, titulo, descripcion, ticketURL)
go func() {
if err := app.Http.Mail.Send(adminEmail, subject, htmlBody, ""); err != nil {
log.Printf("[Notif] Error enviando ticket nuevo a admin: %v", err)
}
}()
}
// SendTicketRespuestaPortalUser notifica al portal user que el admin respondió.
func SendTicketRespuestaPortalUser(userEmail, userName, proyectoNombre, titulo, respuesta, ticketURL string) {
subject := fmt.Sprintf("💬 Respuesta en tu ticket: %s", titulo)
htmlBody := fmt.Sprintf(`<!DOCTYPE html>
<html><body style="font-family:Inter,sans-serif;background:#f1f5f9;padding:32px">
<div style="max-width:520px;margin:0 auto;background:#fff;border-radius:16px;padding:32px;border:1px solid #e2e8f0">
<div style="display:flex;align-items:center;gap:12px;margin-bottom:20px">
<div style="width:40px;height:40px;border-radius:50%%;background:#8eb02f;display:flex;align-items:center;justify-content:center;color:#fff;font-size:18px">💬</div>
<div><h2 style="margin:0;color:#1e293b;font-size:17px">Hay una respuesta en tu ticket</h2>
<p style="margin:0;color:#64748b;font-size:13px">Proyecto: <strong>%s</strong></p></div>
</div>
<p style="color:#334155;font-size:15px">Hola <strong>%s</strong>,</p>
<p style="color:#64748b;font-size:14px">El equipo respondió tu ticket <strong>"%s"</strong>:</p>
<div style="background:#f0fdf4;border-left:4px solid #8eb02f;border-radius:0 10px 10px 0;padding:14px 16px;margin:16px 0;font-size:14px;color:#334155">%s</div>
<a href="%s" style="display:block;text-align:center;background:#8eb02f;color:#fff;padding:12px 24px;border-radius:10px;font-weight:600;text-decoration:none;font-size:15px">Ver mi ticket</a>
</div></body></html>`, proyectoNombre, userName, titulo, respuesta, ticketURL)
go func() {
if err := app.Http.Mail.Send(userEmail, subject, htmlBody, ""); err != nil {
log.Printf("[Notif] Error enviando respuesta ticket a %s: %v", userEmail, err)
}
}()
}
// SendTicketRespuestaAdmin notifica al admin que el portal user respondió.
func SendTicketRespuestaAdmin(adminEmail, proyectoNombre, autorNombre, titulo, respuesta, ticketURL string) {
subject := fmt.Sprintf("💬 Respuesta de cliente en ticket: %s", titulo)
htmlBody := fmt.Sprintf(`<!DOCTYPE html>
<html><body style="font-family:Inter,sans-serif;background:#f1f5f9;padding:32px">
<div style="max-width:520px;margin:0 auto;background:#fff;border-radius:16px;padding:32px;border:1px solid #e2e8f0">
<h2 style="margin:0 0 8px;color:#1e293b;font-size:17px">💬 Respuesta de cliente</h2>
<p style="margin:0 0 16px;color:#64748b;font-size:13px">Proyecto: <strong>%s</strong> | Cliente: <strong>%s</strong></p>
<p style="color:#64748b;font-size:14px">En el ticket <strong>"%s"</strong>:</p>
<div style="background:#f8fafc;border-left:4px solid #64748b;border-radius:0 10px 10px 0;padding:14px 16px;margin:16px 0;font-size:14px;color:#334155">%s</div>
<a href="%s" style="display:block;text-align:center;background:#1e293b;color:#fff;padding:12px 24px;border-radius:10px;font-weight:600;text-decoration:none;font-size:15px">Ver ticket</a>
</div></body></html>`, proyectoNombre, autorNombre, titulo, respuesta, ticketURL)
go func() {
if err := app.Http.Mail.Send(adminEmail, subject, htmlBody, ""); err != nil {
log.Printf("[Notif] Error enviando respuesta cliente a admin: %v", err)
}
}()
}
+162
View File
@@ -0,0 +1,162 @@
package services
import (
"fmt"
"log"
"github.com/sujit-baniya/fiber-boilerplate/app"
"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
)
// ─── DispatchTicketNuevo ──────────────────────────────────────────────────────
// Llamar cuando el portal user crea un nuevo ticket.
// Notifica al ADMIN según su configuración de canales.
func DispatchTicketNuevo(ticket *models.ProyectoTicket, portalUser *models.PortalUser, proyectoNombre string) {
cfg := models.GetNotifConfig("ticket_nuevo", "admin")
if cfg == nil {
return
}
ticketURL := fmt.Sprintf("%s/app/tickets", app.Http.Server.Url)
titulo := fmt.Sprintf("Nuevo ticket: %s", ticket.Titulo)
cuerpo := fmt.Sprintf("Cliente %s abrió: %s", ticket.AutorNombre, ticket.Titulo)
if cfg.CanalSistema {
_ = models.CreateSistemaNotif(&models.SistemaNotificacion{
TipoUsuario: "admin",
UsuarioID: 0,
Titulo: titulo,
Cuerpo: cuerpo,
Url: ticketURL,
Icono: "🎫",
})
}
if cfg.CanalEmail {
if adminEmail := getAdminEmail(); adminEmail != "" {
SendTicketNuevoAdmin(adminEmail, proyectoNombre, ticket.AutorNombre, ticket.Titulo, ticket.Descripcion, ticketURL)
}
}
if cfg.CanalTelegram {
msg := fmt.Sprintf("🎫 <b>Nuevo ticket</b>\nProyecto: <b>%s</b>\nCliente: %s\nTítulo: <b>%s</b>\n\n%s\n\n🔗 %s",
proyectoNombre, ticket.AutorNombre, ticket.Titulo, ticket.Descripcion, ticketURL)
sendTelegramAdmin(msg)
}
}
// ─── DispatchTicketRespuestaCliente ──────────────────────────────────────────
// Llamar cuando el portal user responde un ticket.
// Notifica al ADMIN según su configuración de canales.
func DispatchTicketRespuestaCliente(ticket *models.ProyectoTicket, contenido string, proyectoNombre string) {
cfg := models.GetNotifConfig("ticket_respuesta_cliente", "admin")
if cfg == nil {
return
}
ticketURL := fmt.Sprintf("%s/app/tickets", app.Http.Server.Url)
titulo := fmt.Sprintf("Respuesta de cliente: %s", ticket.Titulo)
cuerpo := fmt.Sprintf("%s respondió: %s", ticket.AutorNombre, contenido)
if cfg.CanalSistema {
_ = models.CreateSistemaNotif(&models.SistemaNotificacion{
TipoUsuario: "admin",
UsuarioID: 0,
Titulo: titulo,
Cuerpo: cuerpo,
Url: ticketURL,
Icono: "💬",
})
}
if cfg.CanalEmail {
if adminEmail := getAdminEmail(); adminEmail != "" {
SendTicketRespuestaAdmin(adminEmail, proyectoNombre, ticket.AutorNombre, ticket.Titulo, contenido, ticketURL)
}
}
if cfg.CanalTelegram {
msg := fmt.Sprintf("💬 <b>Respuesta de cliente</b>\nProyecto: <b>%s</b>\nCliente: %s\n\n%s\n\n🔗 %s",
proyectoNombre, ticket.AutorNombre, contenido, ticketURL)
sendTelegramAdmin(msg)
}
}
// ─── DispatchTicketRespuestaAdmin ─────────────────────────────────────────────
// Llamar cuando el admin responde un ticket.
// Notifica al PORTAL USER según su configuración de canales.
func DispatchTicketRespuestaAdmin(ticket *models.ProyectoTicket, contenido string, proyectoNombre string) {
cfg := models.GetNotifConfig("ticket_respuesta_admin", "portal_user")
if cfg == nil {
return
}
// Obtener portal user para saber email y telegram
portalUser, err := models.GetPortalUserByID(ticket.PortalUserID)
if err != nil || portalUser == nil {
log.Printf("[Notif] PortalUser %d no encontrado: %v", ticket.PortalUserID, err)
return
}
portalURL := fmt.Sprintf("%s/portal/proyecto/%s", app.Http.Server.Url, ticket.Proyecto.Slug)
titulo := fmt.Sprintf("Respuesta en tu ticket: %s", ticket.Titulo)
cuerpo := fmt.Sprintf("El equipo respondió: %s", contenido)
if cfg.CanalSistema {
_ = models.CreateSistemaNotif(&models.SistemaNotificacion{
TipoUsuario: "portal_user",
UsuarioID: portalUser.ID,
Titulo: titulo,
Cuerpo: cuerpo,
Url: portalURL,
Icono: "💬",
})
}
if cfg.CanalEmail && portalUser.Email != "" {
SendTicketRespuestaPortalUser(portalUser.Email, portalUser.Nombre, proyectoNombre, ticket.Titulo, contenido, portalURL)
}
if cfg.CanalTelegram && portalUser.TelegramChatID != "" {
ts := NewTelegramService()
msg := fmt.Sprintf("💬 <b>El equipo respondió tu ticket</b>\nProyecto: <b>%s</b>\nTicket: <b>%s</b>\n\n%s\n\n🔗 %s",
proyectoNombre, ticket.Titulo, contenido, portalURL)
if err := ts.SendMessageWithToken(portalUser.TelegramChatID, msg, getAdminBotToken()); err != nil {
log.Printf("[Notif] Error telegram portal_user %d: %v", portalUser.ID, err)
}
}
}
// ─── helpers internos ─────────────────────────────────────────────────────────
// getAdminEmail devuelve el from_address del SMTP activo como email del admin.
func getAdminEmail() string {
cfg, err := models.GetSmtpConfig()
if err != nil || cfg == nil {
return ""
}
return cfg.FromAddress
}
// getAdminBotToken devuelve el token del primer TelegramConfig activo.
func getAdminBotToken() string {
configs, err := models.GetAllTelegramConfigs()
if err != nil {
return ""
}
for _, c := range configs {
if c.Activo {
return c.BotToken
}
}
return ""
}
// sendTelegramAdmin envía un mensaje usando el primer TelegramConfig activo.
func sendTelegramAdmin(mensaje string) {
configs, err := models.GetAllTelegramConfigs()
if err != nil {
log.Printf("[Notif] Error obteniendo configs telegram: %v", err)
return
}
for _, cfg := range configs {
if !cfg.Activo {
continue
}
ts := &TelegramService{BotToken: cfg.BotToken}
if err := ts.SendMessage(cfg.ChatID, mensaje); err != nil {
log.Printf("[Notif] Error enviando telegram admin (cfg %d): %v", cfg.ID, err)
}
}
}
+6
View File
@@ -56,3 +56,9 @@ func (ts *TelegramService) SendMessage(chatID interface{}, message string) error
return nil
}
// SendMessageWithToken envía un mensaje usando un bot token explícito (útil para notificar a usuarios con su propio chat_id).
func (ts *TelegramService) SendMessageWithToken(chatID interface{}, message, botToken string) error {
svc := &TelegramService{BotToken: botToken}
return svc.SendMessage(chatID, message)
}
+169
View File
@@ -0,0 +1,169 @@
<div x-data="notifConfig()" x-init="init()" class="p-6">
<div class="mb-6">
<h1 class="text-xl font-bold text-slate-800">Configuración de notificaciones</h1>
<p class="text-sm text-slate-500 mt-0.5">
Define por qué canales se envían las alertas a cada destinatario. Más eventos se agregarán conforme el sistema crezca.
</p>
</div>
<!-- Tabla de configuración -->
<div class="bg-white border border-slate-200 rounded-xl shadow-sm overflow-hidden">
<table class="w-full text-sm">
<thead>
<tr class="bg-slate-50 border-b border-slate-200">
<th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider w-48">Evento</th>
<th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider w-40">Destinatario</th>
<th class="px-4 py-3 text-center text-xs font-semibold text-slate-500 uppercase tracking-wider">
📧 Email
</th>
<th class="px-4 py-3 text-center text-xs font-semibold text-slate-500 uppercase tracking-wider">
✈️ Telegram
</th>
<th class="px-4 py-3 text-center text-xs font-semibold text-slate-500 uppercase tracking-wider">
🔔 Sistema
</th>
<th class="px-4 py-3 text-center text-xs font-semibold text-slate-500 uppercase tracking-wider w-24">Guardar</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-100">
<template x-for="row in rows" :key="row.key">
<tr class="hover:bg-slate-50 transition-colors">
<td class="px-4 py-3">
<span class="font-medium text-slate-700" x-text="row.eventoLabel"></span>
</td>
<td class="px-4 py-3">
<span class="inline-flex items-center gap-1.5 px-2 py-1 rounded-full text-xs font-medium"
:class="row.destinatario==='admin' ? 'bg-slate-100 text-slate-700' : 'bg-emerald-50 text-emerald-700'">
<span x-text="row.destinatario==='admin' ? '👤 Admin' : '🧑‍💼 Cliente portal'"></span>
</span>
</td>
<!-- Email -->
<td class="px-4 py-3 text-center">
<label class="inline-flex items-center justify-center cursor-pointer">
<input type="checkbox" x-model="row.canal_email"
class="w-4 h-4 rounded accent-[#8eb02f]">
</label>
</td>
<!-- Telegram -->
<td class="px-4 py-3 text-center">
<div class="flex flex-col items-center gap-1">
<label class="inline-flex items-center justify-center cursor-pointer">
<input type="checkbox" x-model="row.canal_telegram"
:disabled="row.destinatario==='portal_user' ? false : !hasTelegramConfig"
class="w-4 h-4 rounded accent-[#8eb02f] disabled:opacity-40">
</label>
<span x-show="row.destinatario==='admin' && !hasTelegramConfig"
class="text-xs text-amber-500">Sin bot config.</span>
<span x-show="row.destinatario==='portal_user'"
class="text-xs text-slate-400">Requiere Chat ID en usuario</span>
</div>
</td>
<!-- Sistema -->
<td class="px-4 py-3 text-center">
<label class="inline-flex items-center justify-center cursor-pointer">
<input type="checkbox" x-model="row.canal_sistema"
class="w-4 h-4 rounded accent-[#8eb02f]">
</label>
</td>
<!-- Guardar -->
<td class="px-4 py-3 text-center">
<button @click="save(row)"
class="px-3 py-1.5 rounded-lg text-white text-xs font-medium transition-colors"
style="background:#8eb02f"
onmouseover="this.style.background='#6d8c24'" onmouseout="this.style.background='#8eb02f'">
Guardar
</button>
</td>
</tr>
</template>
</tbody>
</table>
</div>
<!-- Ayuda: Telegram para portal users -->
<div class="mt-6 bg-blue-50 border border-blue-200 rounded-xl p-4 text-sm text-blue-800">
<p class="font-semibold mb-1">📱 Telegram para clientes del portal</p>
<p class="text-blue-700 text-xs leading-relaxed">
Para notificar a un cliente por Telegram, el cliente debe abrir una conversación con el bot y compartirte su <strong>Chat ID</strong>.
Luego ve a <a href="/app/portal-usuarios" class="underline font-medium">Portal Usuarios</a> y agrega el Chat ID en su perfil.
El bot a usar es el mismo configurado en <a href="/app/telegram" class="underline font-medium">Configuración Telegram</a>.
</p>
</div>
<!-- Toast -->
<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="toast.ok ? 'bg-green-600' : 'bg-red-500'"
x-text="toast.msg">
</div>
</div>
<script>
// Definición de todos los eventos configurables (extensible)
const EVENTOS = [
{ evento: 'ticket_nuevo', destinatario: 'admin', label: 'Ticket nuevo', icon: '🎫' },
{ evento: 'ticket_respuesta_cliente', destinatario: 'admin', label: 'Respuesta del cliente', icon: '💬' },
{ evento: 'ticket_respuesta_admin', destinatario: 'portal_user', label: 'Respuesta del admin', icon: '💬' },
// Próximos eventos (deshabilitados por ahora):
// { evento: 'factura_emitida', destinatario: 'portal_user', label: 'Factura emitida', icon: '🧾' },
// { evento: 'avance_publicado', destinatario: 'portal_user', label: 'Avance publicado', icon: '📦' },
];
function notifConfig() {
return {
rows: [],
hasTelegramConfig: false,
toast: { visible: false, ok: true, msg: '' },
async init() {
// Verificar si hay telegram configurado
try {
const t = await axios.get('/app/loadtelegram');
this.hasTelegramConfig = (t.data?.items?.length ?? 0) > 0;
} catch {}
// Cargar configuración existente
const r = await axios.get('/app/notif-config/data');
const existing = {};
(r.data || []).forEach(cfg => { existing[`${cfg.evento}__${cfg.destinatario}`] = cfg; });
// Construir filas combinando EVENTOS con config guardada
this.rows = EVENTOS.map(ev => {
const key = `${ev.evento}__${ev.destinatario}`;
const saved = existing[key] || {};
return {
key,
evento: ev.evento,
destinatario: ev.destinatario,
eventoLabel: `${ev.icon} ${ev.label}`,
canal_email: saved.canal_email ?? (ev.destinatario === 'admin'),
canal_telegram: saved.canal_telegram ?? false,
canal_sistema: saved.canal_sistema ?? true,
};
});
},
async save(row) {
try {
await axios.post('/app/notif-config', {
evento: row.evento,
destinatario: row.destinatario,
canal_email: row.canal_email,
canal_telegram: row.canal_telegram,
canal_sistema: row.canal_sistema,
});
this.showToast('Configuración guardada', true);
} catch (e) {
this.showToast('Error al guardar', false);
}
},
showToast(msg, ok) {
this.toast = { visible: true, ok, msg };
setTimeout(() => this.toast.visible = false, 3000);
},
};
}
</script>
+152 -2
View File
@@ -3,8 +3,158 @@
open: false,
initial: '{{ .user.NombreUsuario }}'.charAt(0).toUpperCase() || 'U',
userName: '{{ .user.NombreUsuario }}',
roleName: '{{ .user.Role.Name }}'
}">
roleName: '{{ .user.Role.Name }}',
bellOpen: false,
notifs: [],
unread: 0,
async loadNotifs() {
try {
const r = await axios.get('/app/mis-notifs?no_leidas=0');
this.notifs = r.data.items || [];
this.unread = r.data.unread || 0;
} catch {}
},
async markRead(id) {
await axios.put('/app/mis-notifs/' + id + '/leida');
const n = this.notifs.find(x => x.ID === id);
if (n) { n.leida = true; this.unread = Math.max(0, this.unread - 1); }
},
async markAll() {
await axios.post('/app/mis-notifs/marcar-todas');
this.notifs.forEach(n => n.leida = true);
this.unread = 0;
}
}"
x-init="loadNotifs(); setInterval(() => loadNotifs(), 30000)">
<!-- Left: page context -->
<div class="flex items-center gap-3">
<div class="md:hidden w-8"></div>
<div class="hidden sm:flex items-center gap-2 text-sm text-slate-500">
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M2.25 12l8.954-8.955c.44-.439 1.152-.439 1.591 0L21.75 12M4.5 9.75v10.125c0 .621.504 1.125 1.125 1.125H9.75v-4.875c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125V21h4.125c.621 0 1.125-.504 1.125-1.125V9.75M8.25 21h8.25"/>
</svg>
<span class="text-slate-400">Panel de control</span>
</div>
</div>
<!-- Right: actions + user menu -->
<div class="flex items-center gap-3">
<!-- 🔔 Bell de notificaciones -->
<div class="relative">
<button @click="bellOpen = !bellOpen; if(bellOpen) loadNotifs()"
class="relative p-2 rounded-xl hover:bg-slate-100 transition-colors focus:outline-none">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-slate-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M14.857 17.082a23.848 23.848 0 005.454-1.31A8.967 8.967 0 0118 9.75v-.7V9A6 6 0 006 9v.75a8.967 8.967 0 01-2.312 6.022c1.733.64 3.56 1.085 5.455 1.31m5.714 0a24.255 24.255 0 01-5.714 0m5.714 0a3 3 0 11-5.714 0"/>
</svg>
<!-- Badge -->
<span x-show="unread > 0"
class="absolute -top-0.5 -right-0.5 h-4 w-4 flex items-center justify-center rounded-full text-white text-[10px] font-bold"
style="background:#8eb02f"
x-text="unread > 9 ? '9+' : unread">
</span>
</button>
<!-- Dropdown notificaciones -->
<div x-show="bellOpen"
@click.outside="bellOpen = false"
x-transition:enter="transition ease-out duration-150"
x-transition:enter-start="opacity-0 scale-95 -translate-y-1"
x-transition:enter-end="opacity-100 scale-100 translate-y-0"
x-transition:leave="transition ease-in duration-100"
x-transition:leave-start="opacity-100 scale-100 translate-y-0"
x-transition:leave-end="opacity-0 scale-95 -translate-y-1"
class="absolute right-0 top-12 w-80 bg-white rounded-xl shadow-lg border border-slate-200 overflow-hidden z-50">
<!-- Header -->
<div class="px-4 py-3 border-b border-slate-100 flex items-center justify-between">
<span class="text-sm font-semibold text-slate-800">Notificaciones</span>
<button x-show="unread > 0" @click="markAll()"
class="text-xs text-slate-400 hover:text-slate-600">Marcar todas leídas</button>
</div>
<!-- Lista -->
<div class="max-h-72 overflow-y-auto divide-y divide-slate-100">
<template x-if="notifs.length === 0">
<div class="px-4 py-6 text-center text-slate-400 text-sm">Sin notificaciones</div>
</template>
<template x-for="n in notifs" :key="n.ID">
<a :href="n.url || '#'"
@click="if(!n.leida) markRead(n.ID)"
class="flex items-start gap-3 px-4 py-3 hover:bg-slate-50 transition-colors"
:class="!n.leida ? 'bg-emerald-50/50' : ''">
<span class="text-lg leading-none mt-0.5" x-text="n.icono || '🔔'"></span>
<div class="flex-1 min-w-0">
<p class="text-sm font-medium text-slate-800 truncate" x-text="n.titulo"></p>
<p class="text-xs text-slate-500 truncate mt-0.5" x-text="n.cuerpo"></p>
</div>
<div x-show="!n.leida" class="w-2 h-2 rounded-full flex-shrink-0 mt-1.5" style="background:#8eb02f"></div>
</a>
</template>
</div>
<!-- Footer -->
<div class="border-t border-slate-100 px-4 py-2">
<a href="/app/tickets" class="text-xs text-slate-500 hover:text-slate-700">Ver todos los tickets →</a>
</div>
</div>
</div>
<!-- User info (desktop) -->
<div class="hidden md:flex flex-col items-end mr-1">
<span class="text-xs font-semibold text-slate-700 leading-tight" x-text="userName"></span>
<span class="text-xs text-slate-400 leading-tight" x-text="roleName"></span>
</div>
<!-- Avatar dropdown -->
<div class="relative">
<button @click="open = !open"
class="flex items-center gap-2 p-1 rounded-xl hover:bg-slate-100 transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-1"
style="--tw-ring-color:#8eb02f">
<div class="ui-avatar ui-avatar-lg" x-text="initial"></div>
<svg xmlns="http://www.w3.org/2000/svg"
class="h-3.5 w-3.5 text-slate-400 transition-transform duration-150"
:class="open ? 'rotate-180' : ''"
fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5"/>
</svg>
</button>
<!-- Dropdown -->
<div x-show="open"
@click.outside="open = false"
x-transition:enter="transition ease-out duration-150"
x-transition:enter-start="opacity-0 scale-95 -translate-y-1"
x-transition:enter-end="opacity-100 scale-100 translate-y-0"
x-transition:leave="transition ease-in duration-100"
x-transition:leave-start="opacity-100 scale-100 translate-y-0"
x-transition:leave-end="opacity-0 scale-95 -translate-y-1"
class="absolute right-0 top-12 w-52 bg-white rounded-xl shadow-lg border border-slate-200 overflow-hidden z-50">
<div class="px-4 py-3 border-b border-slate-100">
<p class="text-sm font-semibold text-slate-800 truncate" x-text="userName"></p>
<p class="text-xs text-slate-500 truncate" x-text="roleName"></p>
</div>
<div class="py-1">
<a href="/app/profile"
class="flex items-center gap-3 px-4 py-2.5 text-sm text-slate-700 hover:bg-slate-50 transition-colors">
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M17.982 18.725A7.488 7.488 0 0012 15.75a7.488 7.488 0 00-5.982 2.975m11.963 0a9 9 0 10-11.963 0m11.963 0A8.966 8.966 0 0112 21a8.966 8.966 0 01-5.982-2.275M15 9.75a3 3 0 11-6 0 3 3 0 016 0z"/>
</svg>
Mi cuenta
</a>
<div class="border-t border-slate-100 my-1"></div>
<a href="/do/logout"
class="flex items-center gap-3 px-4 py-2.5 text-sm text-red-600 hover:bg-red-50 transition-colors"
onclick="event.preventDefault(); document.getElementById('header-logout').submit();">
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M15.75 9V5.25A2.25 2.25 0 0013.5 3h-6a2.25 2.25 0 00-2.25 2.25v13.5A2.25 2.25 0 007.5 21h6a2.25 2.25 0 002.25-2.25V15M12 9l-3 3m0 0l3 3m-3-3h12.75"/>
</svg>
Cerrar sesión
</a>
<form id="header-logout" action="/do/logout" method="POST" class="hidden"></form>
</div>
</div>
</div>
</div>
</header>
<!-- Left: page context -->
<div class="flex items-center gap-3">
@@ -0,0 +1,65 @@
package controllers
import (
"github.com/gofiber/fiber/v2"
"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
)
// ─── Configuración de canales de notificación ─────────────────────────────────
func NotifConfigIndex(c *fiber.Ctx) error {
return c.Render("notif_config", fiber.Map{
"user": c.Locals("user"),
"modules": c.Locals("userModules"),
}, "layouts/main")
}
func GetNotifConfigs(c *fiber.Ctx) error {
items, err := models.GetAllNotifConfigs()
if err != nil {
return c.Status(500).JSON(fiber.Map{"error": err.Error()})
}
return c.JSON(items)
}
func SaveNotifConfig(c *fiber.Ctx) error {
var cfg models.NotifEventoConfig
if err := c.BodyParser(&cfg); err != nil {
return c.Status(400).JSON(fiber.Map{"error": err.Error()})
}
if cfg.Evento == "" || cfg.Destinatario == "" {
return c.Status(400).JSON(fiber.Map{"error": "evento y destinatario son requeridos"})
}
if err := models.UpsertNotifConfig(&cfg); err != nil {
return c.Status(500).JSON(fiber.Map{"error": err.Error()})
}
return c.JSON(fiber.Map{"ok": true})
}
// ─── Notificaciones in-app (sistema) ─────────────────────────────────────────
// GetMisNotifs devuelve notificaciones del admin autenticado (tipo_usuario=admin, usuario_id=0).
func GetMisNotifs(c *fiber.Ctx) error {
soloNoLeidas := c.Query("no_leidas") == "1"
items, err := models.GetSistemaNotifs("admin", 0, soloNoLeidas)
if err != nil {
return c.Status(500).JSON(fiber.Map{"error": err.Error()})
}
count := models.CountUnreadNotifs("admin", 0)
return c.JSON(fiber.Map{"items": items, "unread": count})
}
func MarcarNotifLeida(c *fiber.Ctx) error {
id, _ := c.ParamsInt("id")
if err := models.MarcarNotifLeida(uint(id)); err != nil {
return c.Status(500).JSON(fiber.Map{"error": err.Error()})
}
return c.JSON(fiber.Map{"ok": true})
}
func MarcarTodasLeidas(c *fiber.Ctx) error {
if err := models.MarcarTodasLeidas("admin", 0); err != nil {
return c.Status(500).JSON(fiber.Map{"error": err.Error()})
}
return c.JSON(fiber.Map{"ok": true})
}
+3
View File
@@ -9,6 +9,7 @@ import (
"github.com/gofiber/fiber/v2"
"github.com/sujit-baniya/fiber-boilerplate/pkg/auth"
"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
"github.com/sujit-baniya/fiber-boilerplate/pkg/services"
"github.com/sujit-baniya/fiber-boilerplate/rest/middlewares"
)
@@ -228,6 +229,7 @@ func PortalCrearTicket(c *fiber.Ctx) error {
if err := models.CreateProyectoTicket(t); err != nil {
return c.Status(500).JSON(fiber.Map{"error": err.Error()})
}
go services.DispatchTicketNuevo(t, u, proy.Nombre)
return c.Status(201).JSON(t)
}
@@ -262,6 +264,7 @@ func PortalResponderTicket(c *fiber.Ctx) error {
if err := models.CreateTicketMensaje(msg); err != nil {
return c.Status(500).JSON(fiber.Map{"error": err.Error()})
}
go services.DispatchTicketRespuestaCliente(ticket, req.Contenido, ticket.Proyecto.Nombre)
return c.Status(201).JSON(msg)
}
+6
View File
@@ -12,6 +12,7 @@ import (
"github.com/gofiber/fiber/v2"
"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
"github.com/sujit-baniya/fiber-boilerplate/pkg/services"
)
// ─── Admin pages ──────────────────────────────────────────────────────────────
@@ -458,6 +459,11 @@ func AdminResponderTicket(c *fiber.Ctx) error {
}
// Cambiar estado a en_progreso si estaba abierto
_ = models.UpdateTicketEstado(uint(ticketID), "en_progreso")
// Notificar al portal user
ticket, _ := models.GetTicketByID(uint(ticketID))
if ticket != nil {
go services.DispatchTicketRespuestaAdmin(ticket, req.Contenido, ticket.Proyecto.Nombre)
}
return c.Status(201).JSON(msg)
}
+10
View File
@@ -253,6 +253,16 @@ func UserRoutes(app fiber.Router) {
protected.Put("/tickets/:ticketID/estado", controllers.UpdateTicketEstadoAdmin)
protected.Post("/tickets/:ticketID/mensaje", controllers.AdminResponderTicket)
// Configuración de notificaciones
protected.Get("/notif-config", middlewares.MenuMiddleware, controllers.NotifConfigIndex)
protected.Get("/notif-config/data", controllers.GetNotifConfigs)
protected.Post("/notif-config", controllers.SaveNotifConfig)
// Notificaciones in-app del admin (bell)
protected.Get("/mis-notifs", controllers.GetMisNotifs)
protected.Put("/mis-notifs/:id/leida", controllers.MarcarNotifLeida)
protected.Post("/mis-notifs/marcar-todas", controllers.MarcarTodasLeidas)
protected.Get("/portal-usuarios", middlewares.MenuMiddleware, controllers.PortalUsuariosIndex)
protected.Get("/loadportalusuarios", controllers.LoadPortalUsuarios)
protected.Post("/portal-usuarios", controllers.CreatePortalUsuario)