up
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/sujit-baniya/fiber-boilerplate/app"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Cliente struct {
|
||||
gorm.Model
|
||||
Nombre string `json:"nombre" gorm:"column:nombre"`
|
||||
Empresa string `json:"empresa" gorm:"column:empresa"`
|
||||
Email string `json:"email" gorm:"column:email"`
|
||||
EmailCC string `json:"email_cc" gorm:"column:email_cc"`
|
||||
Telefono string `json:"telefono" gorm:"column:telefono"`
|
||||
Documento string `json:"documento" gorm:"column:documento"`
|
||||
Notas string `json:"notas" gorm:"column:notas"`
|
||||
Activo bool `json:"activo" gorm:"column:activo;default:true"`
|
||||
}
|
||||
|
||||
func (Cliente) TableName() string { return "clientes" }
|
||||
|
||||
func GetAllClientes(limit, offset int, search string) ([]Cliente, int64, error) {
|
||||
var items []Cliente
|
||||
var total int64
|
||||
db := app.Http.Database.DB.Model(&Cliente{})
|
||||
if search != "" {
|
||||
db = db.Where("nombre ILIKE ? OR email ILIKE ? OR empresa ILIKE ?",
|
||||
"%"+search+"%", "%"+search+"%", "%"+search+"%")
|
||||
}
|
||||
if err := db.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if err := db.Order("created_at DESC").Limit(limit).Offset(offset).Find(&items).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return items, total, nil
|
||||
}
|
||||
|
||||
func GetAllClientesSelect() ([]Cliente, error) {
|
||||
var items []Cliente
|
||||
if err := app.Http.Database.DB.Where("activo = ?", true).Order("nombre ASC").Find(&items).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func GetClienteByID(id uint) (*Cliente, error) {
|
||||
var item Cliente
|
||||
if err := app.Http.Database.DB.First(&item, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &item, nil
|
||||
}
|
||||
|
||||
func CreateCliente(c Cliente) error {
|
||||
return app.Http.Database.DB.Create(&c).Error
|
||||
}
|
||||
|
||||
func UpdateCliente(c Cliente) error {
|
||||
return app.Http.Database.DB.Model(&c).Updates(c).Error
|
||||
}
|
||||
|
||||
func DeleteCliente(id uint) error {
|
||||
var c Cliente
|
||||
if err := app.Http.Database.DB.First(&c, id).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := app.Http.Database.DB.Delete(&c).Error; err != nil {
|
||||
log.Printf("Error deleting cliente: %v", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/sujit-baniya/fiber-boilerplate/app"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Contrato struct {
|
||||
gorm.Model
|
||||
ClienteID uint `json:"cliente_id" gorm:"column:cliente_id"`
|
||||
Cliente Cliente `json:"cliente" gorm:"foreignKey:ClienteID"`
|
||||
ServicioID uint `json:"servicio_id" gorm:"column:servicio_id"`
|
||||
Servicio Servicio `json:"servicio" gorm:"foreignKey:ServicioID"`
|
||||
FechaInicio time.Time `json:"fecha_inicio" gorm:"column:fecha_inicio"`
|
||||
FechaVencimiento time.Time `json:"fecha_vencimiento" gorm:"column:fecha_vencimiento"`
|
||||
PrecioAcordado float64 `json:"precio_acordado" gorm:"column:precio_acordado"`
|
||||
Estado string `json:"estado" gorm:"column:estado;default:'activo'"` // activo | vencido | cancelado | renovado
|
||||
AutoRenovar bool `json:"auto_renovar" gorm:"column:auto_renovar;default:false"`
|
||||
Notas string `json:"notas" gorm:"column:notas"`
|
||||
}
|
||||
|
||||
func (Contrato) TableName() string { return "contratos" }
|
||||
|
||||
func GetAllContratos(limit, offset int, search, estado string) ([]Contrato, int64, error) {
|
||||
var items []Contrato
|
||||
var total int64
|
||||
db := app.Http.Database.DB.Model(&Contrato{}).
|
||||
Preload("Cliente").Preload("Servicio")
|
||||
if search != "" {
|
||||
db = db.Joins("JOIN clientes ON clientes.id = contratos.cliente_id").
|
||||
Where("clientes.nombre ILIKE ? OR clientes.empresa ILIKE ?",
|
||||
"%"+search+"%", "%"+search+"%")
|
||||
}
|
||||
if estado != "" {
|
||||
db = db.Where("contratos.estado = ?", estado)
|
||||
}
|
||||
if err := db.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if err := db.Order("contratos.fecha_vencimiento ASC").Limit(limit).Offset(offset).Find(&items).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return items, total, nil
|
||||
}
|
||||
|
||||
func GetContratoByID(id uint) (*Contrato, error) {
|
||||
var item Contrato
|
||||
if err := app.Http.Database.DB.Preload("Cliente").Preload("Servicio").First(&item, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &item, nil
|
||||
}
|
||||
|
||||
// GetContratosByCliente devuelve contratos de un cliente específico
|
||||
func GetContratosByCliente(clienteID uint) ([]Contrato, error) {
|
||||
var items []Contrato
|
||||
if err := app.Http.Database.DB.Preload("Servicio").
|
||||
Where("cliente_id = ?", clienteID).
|
||||
Order("fecha_vencimiento ASC").Find(&items).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
// GetContratosProximosVencer retorna contratos activos que vencen exactamente en N días
|
||||
func GetContratosProximosVencer(diasAntes int) ([]Contrato, error) {
|
||||
var items []Contrato
|
||||
target := time.Now().AddDate(0, 0, diasAntes).UTC()
|
||||
startOfDay := time.Date(target.Year(), target.Month(), target.Day(), 0, 0, 0, 0, time.UTC)
|
||||
endOfDay := startOfDay.Add(24 * time.Hour)
|
||||
|
||||
if err := app.Http.Database.DB.Preload("Cliente").Preload("Servicio").
|
||||
Where("estado = 'activo' AND fecha_vencimiento >= ? AND fecha_vencimiento < ?", startOfDay, endOfDay).
|
||||
Find(&items).Error; err != nil {
|
||||
log.Printf("Error getting contratos proximos: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func CreateContrato(c Contrato) error {
|
||||
return app.Http.Database.DB.Create(&c).Error
|
||||
}
|
||||
|
||||
func UpdateContrato(c Contrato) error {
|
||||
return app.Http.Database.DB.Model(&c).Updates(c).Error
|
||||
}
|
||||
|
||||
func DeleteContrato(id uint) error {
|
||||
var c Contrato
|
||||
if err := app.Http.Database.DB.First(&c, id).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return app.Http.Database.DB.Delete(&c).Error
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/sujit-baniya/fiber-boilerplate/app"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type NotificacionLog struct {
|
||||
gorm.Model
|
||||
ClienteID uint `json:"cliente_id" gorm:"column:cliente_id"`
|
||||
Cliente Cliente `json:"cliente" gorm:"foreignKey:ClienteID"`
|
||||
ReglaID uint `json:"regla_id" gorm:"column:regla_id"`
|
||||
Regla NotificacionRegla `json:"regla" gorm:"foreignKey:ReglaID"`
|
||||
ContratosIDs string `json:"contratos_ids" gorm:"column:contratos_ids;type:text"` // JSON array
|
||||
FechaEnvio time.Time `json:"fecha_envio" gorm:"column:fecha_envio"`
|
||||
Estado string `json:"estado" gorm:"column:estado;default:'pendiente'"` // enviado | fallido | pendiente
|
||||
ErrorMsg string `json:"error_msg" gorm:"column:error_msg;type:text"`
|
||||
Asunto string `json:"asunto" gorm:"column:asunto"`
|
||||
PreviewHTML string `json:"preview_html" gorm:"column:preview_html;type:text"`
|
||||
}
|
||||
|
||||
func (NotificacionLog) TableName() string { return "notificaciones_log" }
|
||||
|
||||
func GetAllNotificacionLogs(limit, offset int, clienteID uint, estado string) ([]NotificacionLog, int64, error) {
|
||||
var items []NotificacionLog
|
||||
var total int64
|
||||
db := app.Http.Database.DB.Model(&NotificacionLog{}).
|
||||
Preload("Cliente").Preload("Regla")
|
||||
if clienteID > 0 {
|
||||
db = db.Where("cliente_id = ?", clienteID)
|
||||
}
|
||||
if estado != "" {
|
||||
db = db.Where("estado = ?", estado)
|
||||
}
|
||||
if err := db.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if err := db.Order("created_at DESC").Limit(limit).Offset(offset).Find(&items).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return items, total, nil
|
||||
}
|
||||
|
||||
func GetNotificacionLogByID(id uint) (*NotificacionLog, error) {
|
||||
var item NotificacionLog
|
||||
if err := app.Http.Database.DB.Preload("Cliente").Preload("Regla").First(&item, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &item, nil
|
||||
}
|
||||
|
||||
// YaEnviadoHoy comprueba si ya se envió notificación de esta regla a este cliente hoy
|
||||
func YaEnviadoHoy(clienteID, reglaID uint) bool {
|
||||
var count int64
|
||||
today := time.Now().UTC().Truncate(24 * time.Hour)
|
||||
tomorrow := today.Add(24 * time.Hour)
|
||||
app.Http.Database.DB.Model(&NotificacionLog{}).
|
||||
Where("cliente_id = ? AND regla_id = ? AND estado = 'enviado' AND created_at >= ? AND created_at < ?",
|
||||
clienteID, reglaID, today, tomorrow).
|
||||
Count(&count)
|
||||
return count > 0
|
||||
}
|
||||
|
||||
func CreateNotificacionLog(n NotificacionLog) (*NotificacionLog, error) {
|
||||
if err := app.Http.Database.DB.Create(&n).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &n, nil
|
||||
}
|
||||
|
||||
func UpdateNotificacionLog(n NotificacionLog) error {
|
||||
return app.Http.Database.DB.Model(&n).Updates(map[string]interface{}{
|
||||
"estado": n.Estado,
|
||||
"error_msg": n.ErrorMsg,
|
||||
}).Error
|
||||
}
|
||||
|
||||
// Aliases simples para los controllers
|
||||
func GetAllLogs(limit, offset int) ([]NotificacionLog, int64, error) {
|
||||
return GetAllNotificacionLogs(limit, offset, 0, "")
|
||||
}
|
||||
|
||||
func GetLogByID(id uint) (*NotificacionLog, error) {
|
||||
return GetNotificacionLogByID(id)
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"github.com/sujit-baniya/fiber-boilerplate/app"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type NotificacionRegla struct {
|
||||
gorm.Model
|
||||
Nombre string `json:"nombre" gorm:"column:nombre"`
|
||||
DiasAntes int `json:"dias_antes" gorm:"column:dias_antes"`
|
||||
PlantillaID uint `json:"plantilla_id" gorm:"column:plantilla_id"`
|
||||
Plantilla PlantillaCorreo `json:"plantilla" gorm:"foreignKey:PlantillaID"`
|
||||
Activo bool `json:"activo" gorm:"column:activo;default:true"`
|
||||
AplicaA string `json:"aplica_a" gorm:"column:aplica_a;default:'todos'"` // todos | renovable | unico
|
||||
}
|
||||
|
||||
func (NotificacionRegla) TableName() string { return "notificacion_reglas" }
|
||||
|
||||
func GetAllReglas() ([]NotificacionRegla, error) {
|
||||
var items []NotificacionRegla
|
||||
if err := app.Http.Database.DB.Preload("Plantilla").Order("dias_antes DESC").Find(&items).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func GetReglasActivas() ([]NotificacionRegla, error) {
|
||||
var items []NotificacionRegla
|
||||
if err := app.Http.Database.DB.Preload("Plantilla").
|
||||
Where("activo = ?", true).Order("dias_antes DESC").Find(&items).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func GetReglaByID(id uint) (*NotificacionRegla, error) {
|
||||
var item NotificacionRegla
|
||||
if err := app.Http.Database.DB.Preload("Plantilla").First(&item, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &item, nil
|
||||
}
|
||||
|
||||
func CreateRegla(r NotificacionRegla) error {
|
||||
return app.Http.Database.DB.Create(&r).Error
|
||||
}
|
||||
|
||||
func UpdateRegla(r NotificacionRegla) error {
|
||||
return app.Http.Database.DB.Model(&r).Updates(map[string]interface{}{
|
||||
"nombre": r.Nombre,
|
||||
"dias_antes": r.DiasAntes,
|
||||
"plantilla_id": r.PlantillaID,
|
||||
"activo": r.Activo,
|
||||
"aplica_a": r.AplicaA,
|
||||
}).Error
|
||||
}
|
||||
|
||||
func DeleteRegla(id uint) error {
|
||||
var r NotificacionRegla
|
||||
if err := app.Http.Database.DB.First(&r, id).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return app.Http.Database.DB.Delete(&r).Error
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"github.com/sujit-baniya/fiber-boilerplate/app"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type PlantillaCorreo struct {
|
||||
gorm.Model
|
||||
Nombre string `json:"nombre" gorm:"column:nombre"`
|
||||
Asunto string `json:"asunto" gorm:"column:asunto"`
|
||||
CuerpoHTML string `json:"cuerpo_html" gorm:"column:cuerpo_html;type:text"`
|
||||
Tipo string `json:"tipo" gorm:"column:tipo;default:'renovacion'"` // renovacion | vencimiento | pago | personalizado
|
||||
}
|
||||
|
||||
func (PlantillaCorreo) TableName() string { return "plantillas_correo" }
|
||||
|
||||
func GetAllPlantillas(limit, offset int, search string) ([]PlantillaCorreo, int64, error) {
|
||||
var items []PlantillaCorreo
|
||||
var total int64
|
||||
db := app.Http.Database.DB.Model(&PlantillaCorreo{})
|
||||
if search != "" {
|
||||
db = db.Where("nombre ILIKE ? OR asunto ILIKE ?", "%"+search+"%", "%"+search+"%")
|
||||
}
|
||||
if err := db.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if err := db.Order("nombre ASC").Limit(limit).Offset(offset).Find(&items).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return items, total, nil
|
||||
}
|
||||
|
||||
func GetAllPlantillasSelect() ([]PlantillaCorreo, error) {
|
||||
var items []PlantillaCorreo
|
||||
if err := app.Http.Database.DB.Select("id, nombre, tipo").Order("nombre ASC").Find(&items).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func GetPlantillaByID(id uint) (*PlantillaCorreo, error) {
|
||||
var item PlantillaCorreo
|
||||
if err := app.Http.Database.DB.First(&item, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &item, nil
|
||||
}
|
||||
|
||||
func CreatePlantilla(p PlantillaCorreo) error {
|
||||
return app.Http.Database.DB.Create(&p).Error
|
||||
}
|
||||
|
||||
func UpdatePlantilla(id uint, updates map[string]interface{}) error {
|
||||
return app.Http.Database.DB.Model(&PlantillaCorreo{}).Where("id = ?", id).Updates(updates).Error
|
||||
}
|
||||
|
||||
func DeletePlantilla(id uint) error {
|
||||
var p PlantillaCorreo
|
||||
if err := app.Http.Database.DB.First(&p, id).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return app.Http.Database.DB.Delete(&p).Error
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/sujit-baniya/fiber-boilerplate/app"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Servicio struct {
|
||||
gorm.Model
|
||||
Nombre string `json:"nombre" gorm:"column:nombre"`
|
||||
Descripcion string `json:"descripcion" gorm:"column:descripcion"`
|
||||
Precio float64 `json:"precio" gorm:"column:precio"`
|
||||
Moneda string `json:"moneda" gorm:"column:moneda;default:'COP'"`
|
||||
Tipo string `json:"tipo" gorm:"column:tipo;default:'renovable'"` // renovable | unico
|
||||
Periodicidad string `json:"periodicidad" gorm:"column:periodicidad"` // mensual | trimestral | semestral | anual
|
||||
Activo bool `json:"activo" gorm:"column:activo;default:true"`
|
||||
}
|
||||
|
||||
func (Servicio) TableName() string { return "servicios" }
|
||||
|
||||
func GetAllServicios(limit, offset int, search string) ([]Servicio, int64, error) {
|
||||
var items []Servicio
|
||||
var total int64
|
||||
db := app.Http.Database.DB.Model(&Servicio{})
|
||||
if search != "" {
|
||||
db = db.Where("nombre ILIKE ? OR descripcion ILIKE ?", "%"+search+"%", "%"+search+"%")
|
||||
}
|
||||
if err := db.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if err := db.Order("created_at DESC").Limit(limit).Offset(offset).Find(&items).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return items, total, nil
|
||||
}
|
||||
|
||||
func GetAllServiciosSelect() ([]Servicio, error) {
|
||||
var items []Servicio
|
||||
if err := app.Http.Database.DB.Where("activo = ?", true).Order("nombre ASC").Find(&items).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func GetServicioByID(id uint) (*Servicio, error) {
|
||||
var item Servicio
|
||||
if err := app.Http.Database.DB.First(&item, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &item, nil
|
||||
}
|
||||
|
||||
func CreateServicio(s Servicio) error {
|
||||
return app.Http.Database.DB.Create(&s).Error
|
||||
}
|
||||
|
||||
func UpdateServicio(s Servicio) error {
|
||||
return app.Http.Database.DB.Model(&s).Updates(s).Error
|
||||
}
|
||||
|
||||
func DeleteServicio(id uint) error {
|
||||
var s Servicio
|
||||
if err := app.Http.Database.DB.First(&s, id).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := app.Http.Database.DB.Delete(&s).Error; err != nil {
|
||||
log.Printf("Error deleting servicio: %v", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"github.com/sujit-baniya/fiber-boilerplate/app"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type SmtpConfig struct {
|
||||
gorm.Model
|
||||
Host string `json:"host" gorm:"column:host"`
|
||||
Port int `json:"port" gorm:"column:port;default:587"`
|
||||
Username string `json:"username" gorm:"column:username"`
|
||||
Password string `json:"password" gorm:"column:password"` // cifrado AES
|
||||
Encryption string `json:"encryption" gorm:"column:encryption;default:'tls'"`
|
||||
FromAddress string `json:"from_address" gorm:"column:from_address"`
|
||||
FromName string `json:"from_name" gorm:"column:from_name"`
|
||||
Activo bool `json:"activo" gorm:"column:activo;default:true"`
|
||||
}
|
||||
|
||||
func (SmtpConfig) TableName() string { return "smtp_config" }
|
||||
|
||||
func GetSmtpConfig() (*SmtpConfig, error) {
|
||||
var item SmtpConfig
|
||||
if err := app.Http.Database.DB.Where("activo = ?", true).First(&item).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &item, nil
|
||||
}
|
||||
|
||||
func SaveSmtpConfig(s SmtpConfig) error {
|
||||
// Desactivar config previa
|
||||
app.Http.Database.DB.Model(&SmtpConfig{}).Where("activo = ?", true).
|
||||
Update("activo", false)
|
||||
s.Activo = true
|
||||
if s.ID > 0 {
|
||||
return app.Http.Database.DB.Model(&s).Updates(map[string]interface{}{
|
||||
"host": s.Host,
|
||||
"port": s.Port,
|
||||
"username": s.Username,
|
||||
"password": s.Password,
|
||||
"encryption": s.Encryption,
|
||||
"from_address": s.FromAddress,
|
||||
"from_name": s.FromName,
|
||||
"activo": true,
|
||||
}).Error
|
||||
}
|
||||
return app.Http.Database.DB.Create(&s).Error
|
||||
}
|
||||
@@ -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