up
This commit is contained in:
@@ -0,0 +1,98 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/robfig/cron/v3"
|
||||
"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
|
||||
)
|
||||
|
||||
var cronScheduler *cron.Cron
|
||||
|
||||
// IniciarCron arranca el scheduler de tareas. Llamar desde app.go o main.go.
|
||||
func IniciarCron() {
|
||||
cronScheduler = cron.New()
|
||||
|
||||
// Ejecutar todos los días a las 8:00 AM
|
||||
_, err := cronScheduler.AddFunc("0 8 * * *", ProcesarVencimientos)
|
||||
if err != nil {
|
||||
log.Printf("[CRON] Error registrando tarea: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
cronScheduler.Start()
|
||||
log.Println("[CRON] Scheduler iniciado — verificando vencimientos diariamente a las 8:00 AM")
|
||||
}
|
||||
|
||||
// DetenerCron para graceful shutdown
|
||||
func DetenerCron() {
|
||||
if cronScheduler != nil {
|
||||
cronScheduler.Stop()
|
||||
}
|
||||
}
|
||||
|
||||
// ProcesarVencimientos es la función principal del cron
|
||||
func ProcesarVencimientos() {
|
||||
log.Println("[CRON] Iniciando procesamiento de vencimientos...")
|
||||
|
||||
reglas, err := models.GetReglasActivas()
|
||||
if err != nil {
|
||||
log.Printf("[CRON] Error obteniendo reglas: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
for _, regla := range reglas {
|
||||
contratos, err := models.GetContratosProximosVencer(regla.DiasAntes)
|
||||
if err != nil {
|
||||
log.Printf("[CRON] Error obteniendo contratos para regla %d: %v", regla.ID, err)
|
||||
continue
|
||||
}
|
||||
if len(contratos) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
// Filtrar por AplicaA
|
||||
var filtrados []models.Contrato
|
||||
for _, c := range contratos {
|
||||
switch regla.AplicaA {
|
||||
case "renovable":
|
||||
if c.Servicio.Tipo == "renovable" {
|
||||
filtrados = append(filtrados, c)
|
||||
}
|
||||
case "unico":
|
||||
if c.Servicio.Tipo == "unico" {
|
||||
filtrados = append(filtrados, c)
|
||||
}
|
||||
default:
|
||||
filtrados = append(filtrados, c)
|
||||
}
|
||||
}
|
||||
if len(filtrados) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
// Agrupar contratos por cliente
|
||||
porCliente := make(map[uint][]models.Contrato)
|
||||
for _, c := range filtrados {
|
||||
porCliente[c.ClienteID] = append(porCliente[c.ClienteID], c)
|
||||
}
|
||||
|
||||
for clienteID, grupoContratos := range porCliente {
|
||||
// Evitar duplicados: ya enviado hoy para esta regla + cliente
|
||||
if models.YaEnviadoHoy(clienteID, regla.ID) {
|
||||
log.Printf("[CRON] Ya enviado hoy a cliente %d para regla %d — saltando", clienteID, regla.ID)
|
||||
continue
|
||||
}
|
||||
|
||||
cliente := &grupoContratos[0].Cliente
|
||||
if err := EnviarNotificacionGrupo(®la, cliente, grupoContratos); err != nil {
|
||||
log.Printf("[CRON] Error enviando a cliente %d: %v", clienteID, err)
|
||||
} else {
|
||||
log.Printf("[CRON] Enviado a cliente %d (%s) — %d contrato(s)",
|
||||
clienteID, cliente.Email, len(grupoContratos))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log.Println("[CRON] Procesamiento de vencimientos finalizado")
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/sujit-baniya/fiber-boilerplate/app"
|
||||
"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
|
||||
)
|
||||
|
||||
// DatosPlantilla es el contexto inyectado al renderizar una plantilla de correo
|
||||
type DatosPlantilla struct {
|
||||
ClienteNombre string
|
||||
ClienteEmpresa string
|
||||
ClienteEmail string
|
||||
Servicios []ItemServicio
|
||||
Total float64
|
||||
FechaVencimiento string
|
||||
DiasRestantes int
|
||||
Asunto string
|
||||
}
|
||||
|
||||
type ItemServicio struct {
|
||||
Nombre string
|
||||
Precio float64
|
||||
Moneda string
|
||||
FechaVenc string
|
||||
}
|
||||
|
||||
// DatosEjemplo devuelve datos de prueba para la previsualización de plantillas
|
||||
func DatosEjemplo() DatosPlantilla {
|
||||
return DatosPlantilla{
|
||||
ClienteNombre: "Juan Pérez",
|
||||
ClienteEmpresa: "Empresa Demo S.A.",
|
||||
ClienteEmail: "cliente@ejemplo.com",
|
||||
Servicios: []ItemServicio{
|
||||
{Nombre: "Hosting Basic", Precio: 29.99, Moneda: "USD", FechaVenc: "2025-12-31"},
|
||||
{Nombre: "Dominio .com", Precio: 14.99, Moneda: "USD", FechaVenc: "2025-12-31"},
|
||||
},
|
||||
Total: 44.98,
|
||||
FechaVencimiento: "31/12/2025",
|
||||
DiasRestantes: 15,
|
||||
Asunto: "Recordatorio de vencimiento",
|
||||
}
|
||||
}
|
||||
|
||||
// RenderPlantilla renderiza el CuerpoHTML de una PlantillaCorreo con los datos dados
|
||||
func RenderPlantilla(p *models.PlantillaCorreo, datos DatosPlantilla) (string, error) {
|
||||
tmpl, err := template.New("correo").Parse(p.CuerpoHTML)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("plantilla HTML inválida: %w", err)
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := tmpl.Execute(&buf, datos); err != nil {
|
||||
return "", fmt.Errorf("error al renderizar plantilla: %w", err)
|
||||
}
|
||||
return buf.String(), nil
|
||||
}
|
||||
|
||||
// EnviarCorreoPrueba envía la plantilla con datos de ejemplo al email dado
|
||||
func EnviarCorreoPrueba(email string, p *models.PlantillaCorreo) error {
|
||||
html, err := RenderPlantilla(p, DatosEjemplo())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return app.Http.Mail.Send(email, "[PRUEBA] "+p.Asunto, html)
|
||||
}
|
||||
|
||||
// EnviarCorreoManual envía correo de aviso para un contrato específico
|
||||
func EnviarCorreoManual(contrato *models.Contrato) error {
|
||||
// Usar la primera plantilla activa de tipo renovacion/vencimiento como fallback
|
||||
plantillas, err := models.GetAllPlantillasSelect()
|
||||
if err != nil || len(plantillas) == 0 {
|
||||
return fmt.Errorf("no hay plantillas de correo disponibles")
|
||||
}
|
||||
p, err := models.GetPlantillaByID(plantillas[0].ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dias := int(contrato.FechaVencimiento.Sub(time.Now()).Hours() / 24)
|
||||
datos := DatosPlantilla{
|
||||
ClienteNombre: contrato.Cliente.Nombre,
|
||||
ClienteEmpresa: contrato.Cliente.Empresa,
|
||||
ClienteEmail: contrato.Cliente.Email,
|
||||
FechaVencimiento: contrato.FechaVencimiento.Format("02/01/2006"),
|
||||
DiasRestantes: dias,
|
||||
Total: contrato.PrecioAcordado,
|
||||
Servicios: []ItemServicio{{
|
||||
Nombre: contrato.Servicio.Nombre,
|
||||
Precio: contrato.PrecioAcordado,
|
||||
Moneda: contrato.Servicio.Moneda,
|
||||
FechaVenc: contrato.FechaVencimiento.Format("02/01/2006"),
|
||||
}},
|
||||
}
|
||||
html, err := RenderPlantilla(p, datos)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return app.Http.Mail.Send(contrato.Cliente.Email, p.Asunto, html)
|
||||
}
|
||||
|
||||
// EnviarNotificacionGrupo envía un correo agrupado para un cliente con múltiples contratos
|
||||
func EnviarNotificacionGrupo(regla *models.NotificacionRegla, cliente *models.Cliente, contratos []models.Contrato) error {
|
||||
p, err := models.GetPlantillaByID(regla.PlantillaID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("plantilla no encontrada: %w", err)
|
||||
}
|
||||
|
||||
var items []ItemServicio
|
||||
var total float64
|
||||
var fechaVenc time.Time
|
||||
|
||||
for _, c := range contratos {
|
||||
items = append(items, ItemServicio{
|
||||
Nombre: c.Servicio.Nombre,
|
||||
Precio: c.PrecioAcordado,
|
||||
Moneda: c.Servicio.Moneda,
|
||||
FechaVenc: c.FechaVencimiento.Format("02/01/2006"),
|
||||
})
|
||||
total += c.PrecioAcordado
|
||||
if fechaVenc.IsZero() || c.FechaVencimiento.Before(fechaVenc) {
|
||||
fechaVenc = c.FechaVencimiento
|
||||
}
|
||||
}
|
||||
|
||||
dias := int(fechaVenc.Sub(time.Now()).Hours() / 24)
|
||||
datos := DatosPlantilla{
|
||||
ClienteNombre: cliente.Nombre,
|
||||
ClienteEmpresa: cliente.Empresa,
|
||||
ClienteEmail: cliente.Email,
|
||||
Servicios: items,
|
||||
Total: total,
|
||||
FechaVencimiento: fechaVenc.Format("02/01/2006"),
|
||||
DiasRestantes: dias,
|
||||
Asunto: p.Asunto,
|
||||
}
|
||||
|
||||
html, err := RenderPlantilla(p, datos)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Construir JSON de IDs de contratos para el log
|
||||
var ids []uint
|
||||
for _, c := range contratos {
|
||||
ids = append(ids, c.ID)
|
||||
}
|
||||
idsJSON, _ := json.Marshal(ids)
|
||||
|
||||
// Crear log previo (pendiente)
|
||||
logEntry := models.NotificacionLog{
|
||||
ClienteID: cliente.ID,
|
||||
ReglaID: regla.ID,
|
||||
ContratosIDs: string(idsJSON),
|
||||
FechaEnvio: time.Now(),
|
||||
Estado: "pendiente",
|
||||
Asunto: p.Asunto,
|
||||
PreviewHTML: html,
|
||||
}
|
||||
savedLog, err := models.CreateNotificacionLog(logEntry)
|
||||
if err != nil {
|
||||
log.Printf("Error guardando log de notificación: %v", err)
|
||||
}
|
||||
|
||||
// Enviar correo (también CC si está definido)
|
||||
sendErr := app.Http.Mail.Send(cliente.Email, p.Asunto, html)
|
||||
if cliente.EmailCC != "" {
|
||||
_ = app.Http.Mail.Send(cliente.EmailCC, "[CC] "+p.Asunto, html)
|
||||
}
|
||||
|
||||
// Actualizar estado del log
|
||||
if savedLog != nil {
|
||||
if sendErr != nil {
|
||||
savedLog.Estado = "fallido"
|
||||
savedLog.ErrorMsg = sendErr.Error()
|
||||
} else {
|
||||
savedLog.Estado = "enviado"
|
||||
}
|
||||
models.UpdateNotificacionLog(*savedLog)
|
||||
}
|
||||
|
||||
return sendErr
|
||||
}
|
||||
|
||||
// ReenviarLog reenvía un correo ya registrado en el historial
|
||||
func ReenviarLog(logEntry *models.NotificacionLog) error {
|
||||
if logEntry.PreviewHTML == "" {
|
||||
return fmt.Errorf("no hay HTML guardado para este envío")
|
||||
}
|
||||
sendErr := app.Http.Mail.Send(logEntry.Cliente.Email, logEntry.Asunto, logEntry.PreviewHTML)
|
||||
if sendErr != nil {
|
||||
logEntry.Estado = "fallido"
|
||||
logEntry.ErrorMsg = sendErr.Error()
|
||||
} else {
|
||||
logEntry.Estado = "enviado"
|
||||
logEntry.ErrorMsg = ""
|
||||
}
|
||||
models.UpdateNotificacionLog(*logEntry)
|
||||
return sendErr
|
||||
}
|
||||
Reference in New Issue
Block a user