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(`
El agente %s preparo el borrador %s.
Tambien puedes revisarla en el panel: %s
" + html.EscapeString(body) + "
"}) } func (s *Service) EnviarCotizacionPorCorreo(to, clienteNombre, numero, proyecto string, pdfBytes []byte) bool { subj := fmt.Sprintf("Cotizacion %s — Uriel Jareth Consulting", numero) htmlBody := fmt.Sprintf(`Hola %s,
Adjuntamos la propuesta economica correspondiente al proyecto %s.
Quedamos atentos a cualquier duda o comentario.
Uriel Jareth Consulting
Hola %s,
Se genero el cobro de %s por %s correspondiente al %s.
Hola %s,
Confirmamos que tu pago de %s por %s (%s) ha sido verificado. Gracias.
`, 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(`Hola %s,
Tu comprobante para %s (%s) fue rechazado.
Motivo: %s
`, 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, `Hola %s,
Tienes los siguientes pagos pendientes por un total de %s:
| Fecha | Concepto | Monto |
|---|