feat: migrar backend unificado a Go 1.27 + SPA Vite embebido
This commit is contained in:
@@ -0,0 +1,694 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html"
|
||||
"log"
|
||||
"mime/quotedprintable"
|
||||
"net"
|
||||
"net/smtp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/config"
|
||||
"cotizador/internal/domain"
|
||||
"cotizador/internal/webhooks"
|
||||
|
||||
webpush "github.com/SherClockHolmes/webpush-go"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type Attachment struct {
|
||||
Filename string
|
||||
ContentType string
|
||||
Content []byte
|
||||
}
|
||||
|
||||
type MailMessage struct {
|
||||
To string
|
||||
Subject string
|
||||
Text string
|
||||
HTML string
|
||||
Attachments []Attachment
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
cfg *config.Config
|
||||
pool *pgxpool.Pool
|
||||
webhooks *webhooks.Dispatcher
|
||||
}
|
||||
|
||||
func NewService(cfg *config.Config, pool *pgxpool.Pool, wh *webhooks.Dispatcher) *Service {
|
||||
return &Service{cfg: cfg, pool: pool, webhooks: wh}
|
||||
}
|
||||
|
||||
func (s *Service) SMTPConfigured() bool {
|
||||
return s != nil && s.cfg != nil && s.cfg.SMTPHost != "" && s.cfg.SMTPFrom != ""
|
||||
}
|
||||
|
||||
func (s *Service) VAPIDConfigured() bool {
|
||||
return s != nil && s.cfg != nil && s.cfg.VAPIDPublicKey != "" && s.cfg.VAPIDPrivateKey != ""
|
||||
}
|
||||
|
||||
func (s *Service) EnviarCorreo(msg MailMessage) bool {
|
||||
if !s.SMTPConfigured() {
|
||||
log.Printf("[email] SMTP no configurado; omitiendo correo a %s (%s)", msg.To, msg.Subject)
|
||||
return false
|
||||
}
|
||||
to := strings.TrimSpace(msg.To)
|
||||
if to == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
raw := buildMIMEMessage(s.cfg.SMTPFromName, s.cfg.SMTPFrom, to, msg)
|
||||
addr := fmt.Sprintf("%s:%d", s.cfg.SMTPHost, s.cfg.SMTPPort)
|
||||
|
||||
var err error
|
||||
if s.cfg.SMTPPort == 465 {
|
||||
err = sendSMTPImplicitTLS(addr, s.cfg.SMTPHost, s.cfg.SMTPUser, s.cfg.SMTPPass, s.cfg.SMTPFrom, to, raw)
|
||||
} else {
|
||||
err = sendSMTPStartTLS(addr, s.cfg.SMTPHost, s.cfg.SMTPUser, s.cfg.SMTPPass, s.cfg.SMTPFrom, to, raw)
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("[email] error enviando correo a %s: %v", to, err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func sendSMTPImplicitTLS(addr, host, user, pass, from, to string, raw []byte) error {
|
||||
dialer := &net.Dialer{Timeout: 10 * time.Second}
|
||||
conn, err := tls.DialWithDialer(dialer, "tcp", addr, &tls.Config{ServerName: host, MinVersion: tls.VersionTLS12})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
client, err := smtp.NewClient(conn, host)
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
return err
|
||||
}
|
||||
defer client.Close()
|
||||
if user != "" {
|
||||
if err := client.Auth(smtp.PlainAuth("", user, pass, host)); err != nil {
|
||||
return 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
|
||||
}
|
||||
if _, err := w.Write(raw); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return client.Quit()
|
||||
}
|
||||
|
||||
func sendSMTPStartTLS(addr, host, user, pass, from, to string, raw []byte) error {
|
||||
conn, err := net.DialTimeout("tcp", addr, 10*time.Second)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
client, err := smtp.NewClient(conn, host)
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
return err
|
||||
}
|
||||
defer client.Close()
|
||||
if ok, _ := client.Extension("STARTTLS"); ok {
|
||||
if err := client.StartTLS(&tls.Config{ServerName: host, MinVersion: tls.VersionTLS12}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if user != "" {
|
||||
if err := client.Auth(smtp.PlainAuth("", user, pass, host)); err != nil {
|
||||
return 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
|
||||
}
|
||||
if _, err := w.Write(raw); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return client.Quit()
|
||||
}
|
||||
|
||||
func buildMIMEMessage(fromName, fromAddr, to string, msg MailMessage) []byte {
|
||||
var buf bytes.Buffer
|
||||
fromHeader := fromAddr
|
||||
if fromName != "" {
|
||||
fromHeader = fmt.Sprintf("=?UTF-8?B?%s?= <%s>", base64.StdEncoding.EncodeToString([]byte(fromName)), fromAddr)
|
||||
}
|
||||
subjHeader := fmt.Sprintf("=?UTF-8?B?%s?=", base64.StdEncoding.EncodeToString([]byte(msg.Subject)))
|
||||
|
||||
fmt.Fprintf(&buf, "From: %s\r\n", fromHeader)
|
||||
fmt.Fprintf(&buf, "To: %s\r\n", to)
|
||||
fmt.Fprintf(&buf, "Subject: %s\r\n", subjHeader)
|
||||
fmt.Fprintf(&buf, "Date: %s\r\n", time.Now().Format(time.RFC1123Z))
|
||||
fmt.Fprintf(&buf, "MIME-Version: 1.0\r\n")
|
||||
|
||||
mixedBoundary := fmt.Sprintf("ujc-mixed-%d", time.Now().UnixNano())
|
||||
altBoundary := fmt.Sprintf("ujc-alt-%d", time.Now().UnixNano())
|
||||
|
||||
if len(msg.Attachments) > 0 {
|
||||
fmt.Fprintf(&buf, "Content-Type: multipart/mixed; boundary=%q\r\n\r\n", mixedBoundary)
|
||||
fmt.Fprintf(&buf, "--%s\r\n", mixedBoundary)
|
||||
}
|
||||
|
||||
fmt.Fprintf(&buf, "Content-Type: multipart/alternative; boundary=%q\r\n\r\n", altBoundary)
|
||||
|
||||
textBody := msg.Text
|
||||
if textBody == "" {
|
||||
textBody = "Consulta este mensaje en un cliente de correo compatible con HTML."
|
||||
}
|
||||
fmt.Fprintf(&buf, "--%s\r\n", altBoundary)
|
||||
fmt.Fprintf(&buf, "Content-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n")
|
||||
writeQP(&buf, textBody)
|
||||
fmt.Fprintf(&buf, "\r\n")
|
||||
|
||||
if msg.HTML != "" {
|
||||
fmt.Fprintf(&buf, "--%s\r\n", altBoundary)
|
||||
fmt.Fprintf(&buf, "Content-Type: text/html; charset=UTF-8\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n")
|
||||
writeQP(&buf, msg.HTML)
|
||||
fmt.Fprintf(&buf, "\r\n")
|
||||
}
|
||||
fmt.Fprintf(&buf, "--%s--\r\n", altBoundary)
|
||||
|
||||
for _, att := range msg.Attachments {
|
||||
fmt.Fprintf(&buf, "\r\n--%s\r\n", mixedBoundary)
|
||||
ct := att.ContentType
|
||||
if ct == "" {
|
||||
ct = "application/octet-stream"
|
||||
}
|
||||
fmt.Fprintf(&buf, "Content-Type: %s; name=%q\r\n", ct, att.Filename)
|
||||
fmt.Fprintf(&buf, "Content-Disposition: attachment; filename=%q\r\n", att.Filename)
|
||||
fmt.Fprintf(&buf, "Content-Transfer-Encoding: base64\r\n\r\n")
|
||||
enc := base64.StdEncoding.EncodeToString(att.Content)
|
||||
for i := 0; i < len(enc); i += 76 {
|
||||
end := i + 76
|
||||
if end > len(enc) {
|
||||
end = len(enc)
|
||||
}
|
||||
buf.WriteString(enc[i:end])
|
||||
buf.WriteString("\r\n")
|
||||
}
|
||||
}
|
||||
if len(msg.Attachments) > 0 {
|
||||
fmt.Fprintf(&buf, "--%s--\r\n", mixedBoundary)
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func writeQP(buf *bytes.Buffer, s string) {
|
||||
qw := quotedprintable.NewWriter(buf)
|
||||
_, _ = qw.Write([]byte(s))
|
||||
_ = qw.Close()
|
||||
}
|
||||
|
||||
// EnviarPush sends a Web Push notification to all subscriptions of userID. Returns number delivered.
|
||||
func (s *Service) EnviarPush(ctx context.Context, userID, titulo, cuerpo, urlPath string) int {
|
||||
if !s.VAPIDConfigured() || s.pool == nil || userID == "" {
|
||||
return 0
|
||||
}
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT "id", "endpoint", "p256dh", "auth"
|
||||
FROM "SuscripcionPush"
|
||||
WHERE "userId" = $1
|
||||
`, userID)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
payload, _ := json.Marshal(map[string]string{
|
||||
"titulo": titulo,
|
||||
"cuerpo": cuerpo,
|
||||
"url": urlPath,
|
||||
})
|
||||
|
||||
sent := 0
|
||||
var expiredIDs []string
|
||||
for rows.Next() {
|
||||
var id, endpoint, p256dh, authKey string
|
||||
if err := rows.Scan(&id, &endpoint, &p256dh, &authKey); err != nil {
|
||||
continue
|
||||
}
|
||||
sub := &webpush.Subscription{
|
||||
Endpoint: endpoint,
|
||||
Keys: webpush.Keys{
|
||||
P256dh: p256dh,
|
||||
Auth: authKey,
|
||||
},
|
||||
}
|
||||
resp, err := webpush.SendNotification(payload, sub, &webpush.Options{
|
||||
Subscriber: strings.TrimPrefix(s.cfg.VAPIDSubject, "mailto:"),
|
||||
VAPIDPublicKey: s.cfg.VAPIDPublicKey,
|
||||
VAPIDPrivateKey: s.cfg.VAPIDPrivateKey,
|
||||
TTL: 86400,
|
||||
})
|
||||
if err != nil {
|
||||
log.Printf("[push] error enviando a %s: %v", id, err)
|
||||
continue
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
if resp.StatusCode == 404 || resp.StatusCode == 410 {
|
||||
expiredIDs = append(expiredIDs, id)
|
||||
} else if resp.StatusCode >= 200 && resp.StatusCode < 300 {
|
||||
sent++
|
||||
}
|
||||
}
|
||||
|
||||
for _, id := range expiredIDs {
|
||||
_, _ = s.pool.Exec(ctx, `DELETE FROM "SuscripcionPush" WHERE "id" = $1`, id)
|
||||
}
|
||||
return sent
|
||||
}
|
||||
|
||||
func (s *Service) GetAdminEmail(ctx context.Context) string {
|
||||
if s.cfg != nil && s.cfg.AdminNotifyEmail != "" {
|
||||
return s.cfg.AdminNotifyEmail
|
||||
}
|
||||
if s.pool == nil {
|
||||
return ""
|
||||
}
|
||||
var email string
|
||||
_ = s.pool.QueryRow(ctx, `SELECT "email" FROM "User" WHERE "role" = 'admin' ORDER BY "createdAt" ASC LIMIT 1`).Scan(&email)
|
||||
return email
|
||||
}
|
||||
|
||||
func (s *Service) NotificarJarethBorrador(ctx context.Context, cotID, numero, clienteNombre, clienteEmpresa, proyecto, agenteNombre, approvalURL string, totalUnico, totalMensual float64) {
|
||||
adminEmail := s.GetAdminEmail(ctx)
|
||||
if adminEmail == "" {
|
||||
log.Printf("[notify] sin correo de administrador para notificar borrador %s", numero)
|
||||
return
|
||||
}
|
||||
portalURL := fmt.Sprintf("%s/cotizaciones/%s", s.cfg.AppURL, cotID)
|
||||
empresaTxt := ""
|
||||
if clienteEmpresa != "" {
|
||||
empresaTxt = fmt.Sprintf(" (%s)", clienteEmpresa)
|
||||
}
|
||||
subj := fmt.Sprintf("Aprobacion requerida: Cotizacion %s — %s", numero, clienteNombre)
|
||||
htmlBody := fmt.Sprintf(`
|
||||
<div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto;color:#0f172a">
|
||||
<h2 style="color:#0400C4">Nueva cotizacion pendiente de aprobacion</h2>
|
||||
<p>El agente <strong>%s</strong> preparo el borrador <strong>%s</strong>.</p>
|
||||
<ul>
|
||||
<li><strong>Cliente:</strong> %s%s</li>
|
||||
<li><strong>Proyecto:</strong> %s</li>
|
||||
<li><strong>Pago unico:</strong> %s</li>
|
||||
<li><strong>Pago mensual:</strong> %s</li>
|
||||
</ul>
|
||||
<p style="margin:24px 0">
|
||||
<a href="%s" style="background:#0400C4;color:#ffffff;padding:12px 20px;border-radius:8px;text-decoration:none;font-weight:bold">Revisar y aprobar cotizacion</a>
|
||||
</p>
|
||||
<p style="font-size:12px;color:#64748b">Tambien puedes revisarla en el panel: <a href="%s">%s</a></p>
|
||||
</div>
|
||||
`, html.EscapeString(agenteNombre), html.EscapeString(numero), html.EscapeString(clienteNombre), html.EscapeString(empresaTxt), html.EscapeString(proyecto), domain.FormatCurrency(totalUnico), domain.FormatCurrency(totalMensual), approvalURL, portalURL, portalURL)
|
||||
|
||||
textBody := fmt.Sprintf("Nueva cotizacion %s creada por %s para %s%s.\nAprobar: %s\nPanel: %s", numero, agenteNombre, clienteNombre, empresaTxt, approvalURL, portalURL)
|
||||
s.EnviarCorreo(MailMessage{To: adminEmail, Subject: subj, HTML: htmlBody, Text: textBody})
|
||||
}
|
||||
|
||||
func (s *Service) NotificarJarethWhatsAppFueraVentana(ctx context.Context, numero, clienteNombre, telefono string) {
|
||||
adminEmail := s.GetAdminEmail(ctx)
|
||||
if adminEmail == "" {
|
||||
return
|
||||
}
|
||||
subj := fmt.Sprintf("WhatsApp fuera de ventana 24h — Cotizacion %s", numero)
|
||||
body := fmt.Sprintf("No se pudo enviar la cotizacion %s a %s (%s) por WhatsApp porque excedio la ventana de 24 horas y no hubo fallback de correo.", numero, clienteNombre, telefono)
|
||||
s.EnviarCorreo(MailMessage{To: adminEmail, Subject: subj, Text: body, HTML: "<p>" + html.EscapeString(body) + "</p>"})
|
||||
}
|
||||
|
||||
func (s *Service) EnviarCotizacionPorCorreo(to, clienteNombre, numero, proyecto string, pdfBytes []byte) bool {
|
||||
subj := fmt.Sprintf("Cotizacion %s — Uriel Jareth Consulting", numero)
|
||||
htmlBody := fmt.Sprintf(`
|
||||
<div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto;color:#0f172a">
|
||||
<h2 style="color:#0400C4">Cotizacion %s</h2>
|
||||
<p>Hola %s,</p>
|
||||
<p>Adjuntamos la propuesta economica correspondiente al proyecto <strong>%s</strong>.</p>
|
||||
<p>Quedamos atentos a cualquier duda o comentario.</p>
|
||||
<p style="margin-top:24px;color:#64748b;font-size:13px">Uriel Jareth Consulting</p>
|
||||
</div>
|
||||
`, html.EscapeString(numero), html.EscapeString(clienteNombre), html.EscapeString(proyecto))
|
||||
textBody := fmt.Sprintf("Hola %s,\n\nAdjuntamos la cotizacion %s para el proyecto %s.\n\nSaludos,\nUriel Jareth Consulting", clienteNombre, numero, proyecto)
|
||||
return s.EnviarCorreo(MailMessage{
|
||||
To: to,
|
||||
Subject: subj,
|
||||
HTML: htmlBody,
|
||||
Text: textBody,
|
||||
Attachments: []Attachment{
|
||||
{
|
||||
Filename: fmt.Sprintf("Cotizacion_%s.pdf", domain.SanitizeFilename(numero)),
|
||||
ContentType: "application/pdf",
|
||||
Content: pdfBytes,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) NotificarCobrosNuevos(ctx context.Context, pagoIDs []string) {
|
||||
if s.pool == nil || len(pagoIDs) == 0 {
|
||||
return
|
||||
}
|
||||
for _, pid := range pagoIDs {
|
||||
var concepto, moneda, clienteNombre string
|
||||
var email, userID *string
|
||||
var monto float64
|
||||
var fecha time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT pr."concepto", pr."moneda", p."monto", p."fecha",
|
||||
c."nombre", c."email", u."id"
|
||||
FROM "PagoRecurrente" p
|
||||
JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
JOIN "Cliente" c ON c."id" = pr."clienteId"
|
||||
LEFT JOIN "User" u ON u."clienteId" = c."id"
|
||||
WHERE p."id" = $1
|
||||
`, pid).Scan(&concepto, &moneda, &monto, &fecha, &clienteNombre, &email, &userID)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
montoStr := domain.FormatMonto(monto, moneda)
|
||||
fechaStr := domain.FormatFechaCobro(fecha)
|
||||
urlPagos := fmt.Sprintf("%s/cliente/pagos", s.cfg.AppURL)
|
||||
|
||||
if email != nil && strings.TrimSpace(*email) != "" {
|
||||
s.EnviarCorreo(MailMessage{
|
||||
To: *email,
|
||||
Subject: fmt.Sprintf("Nuevo cobro programado: %s (%s)", concepto, montoStr),
|
||||
Text: fmt.Sprintf("Hola %s, tienes un cobro programado por %s (%s) con fecha %s. Sube tu comprobante en %s", clienteNombre, montoStr, concepto, fechaStr, urlPagos),
|
||||
HTML: fmt.Sprintf(`<div style="font-family:Arial,sans-serif;max-width:600px;color:#0f172a">
|
||||
<h2 style="color:#0400C4">Nuevo cobro programado</h2>
|
||||
<p>Hola %s,</p>
|
||||
<p>Se genero el cobro de <strong>%s</strong> por <strong>%s</strong> correspondiente al <strong>%s</strong>.</p>
|
||||
<p><a href="%s" style="background:#0400C4;color:#fff;padding:10px 16px;border-radius:6px;text-decoration:none">Ver y subir comprobante</a></p>
|
||||
</div>`, html.EscapeString(clienteNombre), html.EscapeString(concepto), montoStr, fechaStr, urlPagos),
|
||||
})
|
||||
}
|
||||
if userID != nil && *userID != "" {
|
||||
s.EnviarPush(ctx, *userID, "Nuevo cobro programado", fmt.Sprintf("%s — %s (%s)", concepto, montoStr, domain.FormatFechaCorta(fecha)), "/cliente/pagos")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) NotificarVerificacion(ctx context.Context, pagoID string) {
|
||||
if s.pool == nil {
|
||||
return
|
||||
}
|
||||
var concepto, moneda, clienteNombre string
|
||||
var email, userID *string
|
||||
var monto float64
|
||||
var fecha time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT pr."concepto", pr."moneda", p."monto", p."fecha",
|
||||
c."nombre", c."email", u."id"
|
||||
FROM "PagoRecurrente" p
|
||||
JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
JOIN "Cliente" c ON c."id" = pr."clienteId"
|
||||
LEFT JOIN "User" u ON u."clienteId" = c."id"
|
||||
WHERE p."id" = $1
|
||||
`, pagoID).Scan(&concepto, &moneda, &monto, &fecha, &clienteNombre, &email, &userID)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
montoStr := domain.FormatMonto(monto, moneda)
|
||||
fechaStr := domain.FormatFechaCobro(fecha)
|
||||
if email != nil && strings.TrimSpace(*email) != "" {
|
||||
s.EnviarCorreo(MailMessage{
|
||||
To: *email,
|
||||
Subject: fmt.Sprintf("Pago verificado: %s (%s)", concepto, montoStr),
|
||||
Text: fmt.Sprintf("Hola %s, confirmamos tu pago de %s por %s (%s). Gracias.", clienteNombre, montoStr, concepto, fechaStr),
|
||||
HTML: fmt.Sprintf(`<p>Hola %s,</p><p>Confirmamos que tu pago de <strong>%s</strong> por <strong>%s</strong> (%s) ha sido verificado. Gracias.</p>`, html.EscapeString(clienteNombre), montoStr, html.EscapeString(concepto), fechaStr),
|
||||
})
|
||||
}
|
||||
if userID != nil && *userID != "" {
|
||||
s.EnviarPush(ctx, *userID, "Pago verificado", fmt.Sprintf("%s — %s confirmado", concepto, montoStr), "/cliente/pagos")
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) NotificarRechazo(ctx context.Context, pagoID, motivo string) {
|
||||
if s.pool == nil {
|
||||
return
|
||||
}
|
||||
var concepto, moneda, clienteNombre string
|
||||
var email, userID *string
|
||||
var monto float64
|
||||
var fecha time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT pr."concepto", pr."moneda", p."monto", p."fecha",
|
||||
c."nombre", c."email", u."id"
|
||||
FROM "PagoRecurrente" p
|
||||
JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
JOIN "Cliente" c ON c."id" = pr."clienteId"
|
||||
LEFT JOIN "User" u ON u."clienteId" = c."id"
|
||||
WHERE p."id" = $1
|
||||
`, pagoID).Scan(&concepto, &moneda, &monto, &fecha, &clienteNombre, &email, &userID)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
montoStr := domain.FormatMonto(monto, moneda)
|
||||
urlPagos := fmt.Sprintf("%s/cliente/pagos", s.cfg.AppURL)
|
||||
if email != nil && strings.TrimSpace(*email) != "" {
|
||||
s.EnviarCorreo(MailMessage{
|
||||
To: *email,
|
||||
Subject: fmt.Sprintf("Comprobante rechazado: %s (%s)", concepto, montoStr),
|
||||
Text: fmt.Sprintf("Hola %s, tu comprobante para %s (%s) fue rechazado. Motivo: %s. Puedes subir uno nuevo en %s", clienteNombre, concepto, montoStr, motivo, urlPagos),
|
||||
HTML: fmt.Sprintf(`<p>Hola %s,</p><p>Tu comprobante para <strong>%s</strong> (%s) fue rechazado.</p><p><strong>Motivo:</strong> %s</p><p><a href="%s">Subir nuevo comprobante</a></p>`, html.EscapeString(clienteNombre), html.EscapeString(concepto), montoStr, html.EscapeString(motivo), urlPagos),
|
||||
})
|
||||
}
|
||||
if userID != nil && *userID != "" {
|
||||
s.EnviarPush(ctx, *userID, "Comprobante rechazado", fmt.Sprintf("%s: %s", concepto, motivo), "/cliente/pagos")
|
||||
}
|
||||
}
|
||||
|
||||
type RecordatoriosResult struct {
|
||||
ClientesNotificados int `json:"clientesNotificados"`
|
||||
PagosRecordados int `json:"pagosRecordados"`
|
||||
PagosVencidosEmit int `json:"pagosVencidosEmitidos"`
|
||||
PagoIDsCubiertos []string `json:"-"`
|
||||
}
|
||||
|
||||
// EnviarRecordatoriosPendientes sends one account-statement reminder per client for overdue/due charges
|
||||
// (estado in pendiente|rechazado, fecha <= hoy) and emits pago.vencido idempotently.
|
||||
func (s *Service) EnviarRecordatoriosPendientes(ctx context.Context, clienteIDFilter string, forzar bool) (*RecordatoriosResult, error) {
|
||||
if s.pool == nil {
|
||||
return &RecordatoriosResult{}, nil
|
||||
}
|
||||
hoy := domain.HoyCalendario()
|
||||
diasEspera := s.cfg.CobrosRecordatorioDias
|
||||
if !forzar && diasEspera <= 0 {
|
||||
return &RecordatoriosResult{}, nil
|
||||
}
|
||||
|
||||
args := []any{hoy}
|
||||
whereCliente := ""
|
||||
if clienteIDFilter != "" {
|
||||
whereCliente = ` AND c."id" = $2`
|
||||
args = append(args, clienteIDFilter)
|
||||
}
|
||||
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT p."id", p."programaId", p."fecha", p."monto", p."estado", p."ultimoRecordatorioAt",
|
||||
pr."concepto", pr."moneda",
|
||||
c."id", c."nombre", COALESCE(c."empresa", ''), COALESCE(c."email", ''), COALESCE(c."telefono", ''),
|
||||
COALESCE(u."id", '')
|
||||
FROM "PagoRecurrente" p
|
||||
JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
JOIN "Cliente" c ON c."id" = pr."clienteId"
|
||||
LEFT JOIN "User" u ON u."clienteId" = c."id"
|
||||
WHERE p."estado" IN ('pendiente', 'rechazado')
|
||||
AND p."fecha" <= $1`+whereCliente+`
|
||||
ORDER BY c."nombre" ASC, p."fecha" ASC
|
||||
`, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
type pagoRow struct {
|
||||
ID string
|
||||
ProgramaID string
|
||||
Fecha time.Time
|
||||
Monto float64
|
||||
Estado string
|
||||
UltimoRecordatorioAt *time.Time
|
||||
Concepto string
|
||||
Moneda string
|
||||
ClienteID string
|
||||
ClienteNombre string
|
||||
ClienteEmpresa string
|
||||
ClienteEmail string
|
||||
ClienteTelefono string
|
||||
UserID string
|
||||
}
|
||||
|
||||
byClient := map[string][]pagoRow{}
|
||||
var clientOrder []string
|
||||
var vencidosItems []webhooks.PagoVencidoItem
|
||||
|
||||
for rows.Next() {
|
||||
var r pagoRow
|
||||
if err := rows.Scan(
|
||||
&r.ID, &r.ProgramaID, &r.Fecha, &r.Monto, &r.Estado, &r.UltimoRecordatorioAt,
|
||||
&r.Concepto, &r.Moneda,
|
||||
&r.ClienteID, &r.ClienteNombre, &r.ClienteEmpresa, &r.ClienteEmail, &r.ClienteTelefono,
|
||||
&r.UserID,
|
||||
); err != nil {
|
||||
continue
|
||||
}
|
||||
if _, ok := byClient[r.ClienteID]; !ok {
|
||||
clientOrder = append(clientOrder, r.ClienteID)
|
||||
}
|
||||
byClient[r.ClienteID] = append(byClient[r.ClienteID], r)
|
||||
|
||||
atraso := domain.DiasDeAtraso(r.Fecha, hoy)
|
||||
if atraso > 0 {
|
||||
vencidosItems = append(vencidosItems, webhooks.PagoVencidoItem{
|
||||
PagoID: r.ID,
|
||||
ProgramaID: r.ProgramaID,
|
||||
ClienteID: r.ClienteID,
|
||||
ClienteNombre: r.ClienteNombre,
|
||||
ClienteEmpresa: r.ClienteEmpresa,
|
||||
ClienteEmail: r.ClienteEmail,
|
||||
ClienteTelefono: r.ClienteTelefono,
|
||||
Concepto: r.Concepto,
|
||||
Monto: r.Monto,
|
||||
Moneda: r.Moneda,
|
||||
Fecha: r.Fecha.UTC().Format("2006-01-02"),
|
||||
DiasAtraso: atraso,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Best-effort idempotent webhook emission for overdue payments
|
||||
res := &RecordatoriosResult{}
|
||||
if s.webhooks != nil && len(vencidosItems) > 0 {
|
||||
res.PagosVencidosEmit = s.webhooks.EmitirPagosVencidos(ctx, vencidosItems)
|
||||
}
|
||||
|
||||
// Load bank config for statement email
|
||||
bancaria := map[string]string{}
|
||||
cfgRows, err := s.pool.Query(ctx, `SELECT "clave", "valor" FROM "Configuracion"`)
|
||||
if err == nil {
|
||||
defer cfgRows.Close()
|
||||
for cfgRows.Next() {
|
||||
var k, v string
|
||||
if cfgRows.Scan(&k, &v) == nil {
|
||||
bancaria[k] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cutoff := time.Now().Add(-time.Duration(diasEspera) * 24 * time.Hour)
|
||||
for _, cid := range clientOrder {
|
||||
pagos := byClient[cid]
|
||||
if len(pagos) == 0 {
|
||||
continue
|
||||
}
|
||||
if !forzar {
|
||||
needsSend := false
|
||||
for _, p := range pagos {
|
||||
if p.UltimoRecordatorioAt == nil || p.UltimoRecordatorioAt.Before(cutoff) {
|
||||
needsSend = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !needsSend {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
first := pagos[0]
|
||||
totales := map[string]float64{}
|
||||
var rowsHTML strings.Builder
|
||||
var rowsText strings.Builder
|
||||
for _, p := range pagos {
|
||||
totales[p.Moneda] = domain.Round2(totales[p.Moneda] + p.Monto)
|
||||
fStr := domain.FormatFechaCorta(p.Fecha)
|
||||
mStr := domain.FormatMonto(p.Monto, p.Moneda)
|
||||
fmt.Fprintf(&rowsHTML, `<tr><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0">%s</td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0">%s</td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;text-align:right">%s</td></tr>`,
|
||||
html.EscapeString(fStr), html.EscapeString(p.Concepto), mStr)
|
||||
fmt.Fprintf(&rowsText, "- %s | %s | %s\n", fStr, p.Concepto, mStr)
|
||||
}
|
||||
|
||||
totalStr := domain.FormatTotales(totales)
|
||||
urlPagos := fmt.Sprintf("%s/cliente/pagos", s.cfg.AppURL)
|
||||
|
||||
bancoHTML := ""
|
||||
if bancaria["banco_nacional"] != "" || bancaria["clabe_nacional"] != "" {
|
||||
bancoHTML = fmt.Sprintf(`<div style="margin-top:16px;padding:12px;background:#f8fafc;border-radius:8px;font-size:13px">
|
||||
<strong>Datos bancarios</strong><br/>
|
||||
Banco: %s<br/>CLABE: %s<br/>Cuenta: %s<br/>Beneficiario: %s
|
||||
</div>`, html.EscapeString(bancaria["banco_nacional"]), html.EscapeString(bancaria["clabe_nacional"]), html.EscapeString(bancaria["cuenta_nacional"]), html.EscapeString(bancaria["razon_social"]))
|
||||
}
|
||||
|
||||
delivered := false
|
||||
if first.ClienteEmail != "" {
|
||||
ok := s.EnviarCorreo(MailMessage{
|
||||
To: first.ClienteEmail,
|
||||
Subject: fmt.Sprintf("Recordatorio de pagos pendientes (%s) — Uriel Jareth Consulting", totalStr),
|
||||
Text: fmt.Sprintf("Hola %s,\n\nTienes pagos pendientes por %s:\n%s\nPuedes subir tus comprobantes en: %s", first.ClienteNombre, totalStr, rowsText.String(), urlPagos),
|
||||
HTML: fmt.Sprintf(`<div style="font-family:Arial,sans-serif;max-width:600px;color:#0f172a">
|
||||
<h2 style="color:#0400C4">Estado de pagos pendientes</h2>
|
||||
<p>Hola %s,</p>
|
||||
<p>Tienes los siguientes pagos pendientes por un total de <strong>%s</strong>:</p>
|
||||
<table style="width:100%%;border-collapse:collapse;font-size:14px">
|
||||
<thead><tr style="background:#f1f5f9"><th style="padding:6px 8px;text-align:left">Fecha</th><th style="padding:6px 8px;text-align:left">Concepto</th><th style="padding:6px 8px;text-align:right">Monto</th></tr></thead>
|
||||
<tbody>%s</tbody>
|
||||
</table>
|
||||
%s
|
||||
<p style="margin-top:20px"><a href="%s" style="background:#0400C4;color:#fff;padding:10px 16px;border-radius:6px;text-decoration:none">Subir comprobante</a></p>
|
||||
</div>`, html.EscapeString(first.ClienteNombre), totalStr, rowsHTML.String(), bancoHTML, urlPagos),
|
||||
})
|
||||
if ok {
|
||||
delivered = true
|
||||
}
|
||||
}
|
||||
|
||||
if first.UserID != "" {
|
||||
if n := s.EnviarPush(ctx, first.UserID, "Pagos pendientes", fmt.Sprintf("Saldo pendiente: %s (%d cobro(s))", totalStr, len(pagos)), "/cliente/pagos"); n > 0 {
|
||||
delivered = true
|
||||
}
|
||||
}
|
||||
|
||||
if delivered {
|
||||
res.ClientesNotificados++
|
||||
for _, p := range pagos {
|
||||
_, _ = s.pool.Exec(ctx, `
|
||||
UPDATE "PagoRecurrente"
|
||||
SET "ultimoRecordatorioAt" = NOW(),
|
||||
"recordatoriosEnviados" = "recordatoriosEnviados" + 1,
|
||||
"updatedAt" = NOW()
|
||||
WHERE "id" = $1
|
||||
`, p.ID)
|
||||
res.PagosRecordados++
|
||||
res.PagoIDsCubiertos = append(res.PagoIDsCubiertos, p.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
Reference in New Issue
Block a user