fix(soporte): aviso repetido en Telegram y el acuse al cliente que no salía

Telegram: los avisos se mandaban a todas las configuraciones activas sin mirar
a dónde apuntan. Con el mismo chat cargado en dos filas, cada aviso llegaba dos
veces. Ahora se manda una vez por destino (bot + chat); los chats distintos
siguen recibiendo todos.

Correo al remitente: el camino STARTTLS abría una conexión, hacía StartTLS,
autenticaba… y la descartaba para llamar a smtp.SendMail, que abre otra. La
primera quedaba colgada y el envío real salía por una conexión distinta, que
podía no estar autenticada. Reescrito: una sola conexión, asegurada según la
configuración, y cierre con QUIT.

Y como el acuse se manda en segundo plano, su error moría en el log. Ahora hay
un botón "Enviar correo de prueba" que usa exactamente el mismo camino y
devuelve el error del servidor en pantalla, y el último fallo del acuse real
aparece en el resultado de "Revisar buzón ahora".

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Lizandro Guarnizo
2026-08-17 20:13:11 -05:00
co-authored by Claude Opus 5
parent 17ed57cb56
commit 5afbd9e375
5 changed files with 168 additions and 53 deletions
+12
View File
@@ -412,10 +412,22 @@ func sendTelegramAdmin(mensaje string) {
log.Printf("[Notif] Error obteniendo configs telegram: %v", err)
return
}
// Un mismo chat puede estar cargado en más de una configuración (dos bots
// apuntando al mismo grupo, o la misma config duplicada). Sin esto, cada
// aviso llega repetido tantas veces como filas haya.
yaEnviado := map[string]bool{}
for _, cfg := range configs {
if !cfg.Activo {
continue
}
destino := cfg.BotToken + "→" + cfg.ChatID
if yaEnviado[destino] {
log.Printf("[Notif] Chat %s repetido en la config %d (%s), no se manda de nuevo", cfg.ChatID, cfg.ID, cfg.Nombre)
continue
}
yaEnviado[destino] = true
ts := &TelegramService{BotToken: cfg.BotToken}
sendErr := ts.SendMessage(cfg.ChatID, mensaje)
logEntry := &models.TelegramLog{
+104 -53
View File
@@ -6,6 +6,7 @@ import (
"log"
"net/smtp"
"strings"
"sync"
"github.com/sujit-baniya/fiber-boilerplate/app"
"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
@@ -33,61 +34,87 @@ func soporteSendMail(to, subject, htmlBody string) error {
if port == 0 {
port = 587
}
auth := smtp.PlainAuth("", cfg.SmtpUsername, cfg.SmtpPassword, cfg.SmtpHost)
msg := []byte(fmt.Sprintf("From: %s <%s>\r\nTo: %s\r\nSubject: %s\r\nMIME-Version: 1.0\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n%s", fromName, from, to, subject, htmlBody))
addr := fmt.Sprintf("%s:%d", cfg.SmtpHost, port)
enc := strings.ToLower(cfg.SmtpEncryption)
if enc == "tls" {
tlsCfg := &tls.Config{ServerName: cfg.SmtpHost}
conn, err := tls.Dial("tcp", addr, tlsCfg)
if err != nil {
return fmt.Errorf("soporte SMTP TLS: %w", err)
}
client, err := smtp.NewClient(conn, cfg.SmtpHost)
if err != nil {
conn.Close()
return fmt.Errorf("soporte SMTP client: %w", err)
}
defer client.Close()
if err = client.Auth(auth); err != nil {
return fmt.Errorf("soporte SMTP auth: %w", err)
}
if err = client.Mail(from); err != nil {
return err
}
if err = client.Rcpt(to); err != nil {
return err
}
w, err := client.Data()
if err != nil {
return err
}
_, err = w.Write(msg)
if err != nil {
return err
}
return w.Close()
}
if enc == "starttls" {
tlsCfg := &tls.Config{ServerName: cfg.SmtpHost}
conn, err := smtp.Dial(addr)
if err != nil {
goto fallback
}
if err = conn.StartTLS(tlsCfg); err != nil {
conn.Close()
goto fallback
}
if err = conn.Auth(auth); err != nil {
conn.Close()
return fmt.Errorf("soporte SMTP STARTTLS auth: %w", err)
}
return smtp.SendMail(addr, auth, from, []string{to}, msg)
}
return smtp.SendMail(addr, auth, from, []string{to}, msg)
msg := []byte(fmt.Sprintf(
"From: %s <%s>\r\nTo: %s\r\nSubject: %s\r\nMIME-Version: 1.0\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n%s",
fromName, from, to, subject, htmlBody))
fallback:
return app.Http.Mail.Send(to, subject, htmlBody)
if err := enviarPorSMTP(cfg, addr, from, to, msg); err != nil {
return fmt.Errorf("SMTP de soporte (%s): %w", addr, err)
}
return nil
}
// enviarPorSMTP abre una sola conexión, la asegura según la configuración,
// manda el mensaje y cierra con QUIT.
//
// Antes el camino STARTTLS abría una conexión, hacía StartTLS, autenticaba… y
// la descartaba para llamar a smtp.SendMail, que abre otra distinta: la primera
// quedaba colgada y el envío real salía por una conexión que podía no estar
// autenticada igual.
func enviarPorSMTP(cfg *models.SoporteWebhookConfig, addr, from, to string, msg []byte) error {
enc := strings.ToLower(strings.TrimSpace(cfg.SmtpEncryption))
var cliente *smtp.Client
var err error
if enc == "tls" || enc == "ssl" {
conn, errDial := tls.Dial("tcp", addr, &tls.Config{ServerName: cfg.SmtpHost})
if errDial != nil {
return fmt.Errorf("no se pudo conectar por TLS: %w", errDial)
}
cliente, err = smtp.NewClient(conn, cfg.SmtpHost)
if err != nil {
conn.Close()
return fmt.Errorf("saludo SMTP rechazado: %w", err)
}
} else {
cliente, err = smtp.Dial(addr)
if err != nil {
return fmt.Errorf("no se pudo conectar: %w", err)
}
if enc != "none" {
if err := cliente.StartTLS(&tls.Config{ServerName: cfg.SmtpHost}); err != nil {
cliente.Close()
return fmt.Errorf("STARTTLS rechazado: %w", err)
}
}
}
defer cliente.Close()
if cfg.SmtpUsername != "" {
if err := cliente.Auth(smtp.PlainAuth("", cfg.SmtpUsername, cfg.SmtpPassword, cfg.SmtpHost)); err != nil {
return fmt.Errorf("autenticación rechazada para %s: %w", cfg.SmtpUsername, err)
}
}
if err := cliente.Mail(from); err != nil {
return fmt.Errorf("el servidor rechazó el remitente %s: %w", from, err)
}
if err := cliente.Rcpt(to); err != nil {
return fmt.Errorf("el servidor rechazó el destinatario %s: %w", to, err)
}
w, err := cliente.Data()
if err != nil {
return err
}
if _, err := w.Write(msg); err != nil {
return err
}
if err := w.Close(); err != nil {
return fmt.Errorf("el servidor rechazó el mensaje: %w", err)
}
return cliente.Quit()
}
// ProbarEnvioSoporte manda un correo de prueba por el mismo camino que usa el
// acuse automático, y devuelve el error tal cual. Es la única forma de saber
// por qué no llega: el acuse real se manda en segundo plano.
func ProbarEnvioSoporte(destino string) error {
if strings.TrimSpace(destino) == "" {
return fmt.Errorf("indicá a qué dirección mandar la prueba")
}
cuerpo := `<p>Esto es una prueba del envío de soporte.</p>
<p>Si te llegó, el acuse automático de los tickets también va a salir por acá.</p>`
return soporteSendMail(destino, "Prueba de envío de soporte", cuerpo)
}
// SendSoporteAutoRespuesta envía acuse de recibo automático al crear un ticket por email
@@ -123,8 +150,10 @@ func SendSoporteAutoRespuesta(ticket *models.ProyectoTicket) {
go func() {
if err := soporteSendMail(ticket.EmailFrom, subject, htmlBody); err != nil {
log.Printf("[Soporte] Error enviando auto-respuesta a %s: %v", ticket.EmailFrom, err)
guardarErrorAcuse(fmt.Sprintf("el acuse al cliente %s no salió: %v", ticket.EmailFrom, err))
} else {
log.Printf("[Soporte] Auto-respuesta enviada a %s (ticket #%d)", ticket.EmailFrom, ticket.ID)
guardarErrorAcuse("")
}
}()
}
@@ -165,3 +194,25 @@ func SendSoporteNotifAdmin(ticket *models.ProyectoTicket) {
}
}()
}
// El acuse se manda en segundo plano, así que su error no puede devolverse al
// que creó el ticket. Se guarda acá para poder mostrarlo en la pantalla de
// configuración, que es donde alguien lo va a ver.
var (
muErrorAcuse sync.Mutex
ultimoErrAcuse string
)
func guardarErrorAcuse(msg string) {
muErrorAcuse.Lock()
defer muErrorAcuse.Unlock()
ultimoErrAcuse = msg
}
// UltimoErrorAcuse devuelve el último fallo al mandarle el acuse a un cliente
// ("" si el último salió bien).
func UltimoErrorAcuse() string {
muErrorAcuse.Lock()
defer muErrorAcuse.Unlock()
return ultimoErrAcuse
}