up
This commit is contained in:
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user