144 lines
3.7 KiB
Go
144 lines
3.7 KiB
Go
package scheduler
|
|
|
|
import (
|
|
"context"
|
|
"log"
|
|
"slices"
|
|
"time"
|
|
|
|
"cotizador/internal/db"
|
|
"cotizador/internal/domain"
|
|
"cotizador/internal/notify"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
// GenerarCobros idempotently creates missing PagoRecurrente rows up to `hasta` (defaults to today MX).
|
|
// Returns the IDs of newly inserted PagoRecurrente rows.
|
|
func GenerarCobros(ctx context.Context, pool *pgxpool.Pool, programaID string, hasta *time.Time) ([]string, error) {
|
|
limite := domain.HoyCalendario()
|
|
if hasta != nil {
|
|
y, m, d := domain.ACalendario(*hasta)
|
|
limite = time.Date(y, m, d, 0, 0, 0, 0, time.UTC)
|
|
}
|
|
|
|
query := `
|
|
SELECT "id", "monto", "frecuencia", "diaSemana", "diaMes", "fechaInicio", "fechaFin"
|
|
FROM "ProgramaPago"
|
|
WHERE "activo" = true
|
|
`
|
|
var args []any
|
|
if programaID != "" {
|
|
query += ` AND "id" = $1`
|
|
args = append(args, programaID)
|
|
}
|
|
|
|
rows, err := pool.Query(ctx, query, args...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
type prog struct {
|
|
ID string
|
|
Monto float64
|
|
Frecuencia string
|
|
DiaSemana *int
|
|
DiaMes *int
|
|
FechaInicio time.Time
|
|
FechaFin *time.Time
|
|
}
|
|
var programas []prog
|
|
for rows.Next() {
|
|
var p prog
|
|
if err := rows.Scan(&p.ID, &p.Monto, &p.Frecuencia, &p.DiaSemana, &p.DiaMes, &p.FechaInicio, &p.FechaFin); err != nil {
|
|
continue
|
|
}
|
|
programas = append(programas, p)
|
|
}
|
|
|
|
var creados []string
|
|
for _, p := range programas {
|
|
fechas := domain.FechasPeriodo(domain.ProgramaCalendario{
|
|
Frecuencia: p.Frecuencia,
|
|
DiaSemana: p.DiaSemana,
|
|
DiaMes: p.DiaMes,
|
|
FechaInicio: p.FechaInicio,
|
|
FechaFin: p.FechaFin,
|
|
}, limite)
|
|
for _, f := range fechas {
|
|
newID := db.NewID()
|
|
var insertedID string
|
|
err := pool.QueryRow(ctx, `
|
|
INSERT INTO "PagoRecurrente" ("id", "programaId", "fecha", "monto", "estado", "createdAt", "updatedAt")
|
|
VALUES ($1, $2, $3, $4, 'pendiente', NOW(), NOW())
|
|
ON CONFLICT ("programaId", "fecha") DO NOTHING
|
|
RETURNING "id"
|
|
`, newID, p.ID, f, p.Monto).Scan(&insertedID)
|
|
if err == nil && insertedID != "" {
|
|
creados = append(creados, insertedID)
|
|
}
|
|
}
|
|
}
|
|
return creados, nil
|
|
}
|
|
|
|
// Start runs the recurring charges & reminder scheduler (20s initial delay, every 60 minutes).
|
|
func Start(ctx context.Context, pool *pgxpool.Pool, notifier *notify.Service) {
|
|
runOnce := func() {
|
|
cctx, cancel := context.WithTimeout(ctx, 2*time.Minute)
|
|
defer cancel()
|
|
|
|
nuevos, err := GenerarCobros(cctx, pool, "", nil)
|
|
if err != nil {
|
|
log.Printf("[scheduler] error generando cobros: %v", err)
|
|
return
|
|
}
|
|
|
|
var cubiertos []string
|
|
if domain.HoraMexico(time.Now()) >= domain.HoraRecordatorios {
|
|
res, err := notifier.EnviarRecordatoriosPendientes(cctx, "", false)
|
|
if err != nil {
|
|
log.Printf("[scheduler] error enviando recordatorios: %v", err)
|
|
} else if res != nil {
|
|
cubiertos = res.PagoIDsCubiertos
|
|
if res.ClientesNotificados > 0 || res.PagosVencidosEmit > 0 {
|
|
log.Printf("[scheduler] recordatorios=%d clientes (%d pagos), pago.vencido=%d", res.ClientesNotificados, res.PagosRecordados, res.PagosVencidosEmit)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Notify newly created charges not already covered by a reminder in this same tick
|
|
var porAvisar []string
|
|
for _, id := range nuevos {
|
|
if !slices.Contains(cubiertos, id) {
|
|
porAvisar = append(porAvisar, id)
|
|
}
|
|
}
|
|
if len(porAvisar) > 0 {
|
|
notifier.NotificarCobrosNuevos(cctx, porAvisar)
|
|
log.Printf("[scheduler] %d cobro(s) nuevo(s) generados y notificados", len(porAvisar))
|
|
}
|
|
}
|
|
|
|
go func() {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-time.After(20 * time.Second):
|
|
}
|
|
runOnce()
|
|
|
|
ticker := time.NewTicker(60 * time.Minute)
|
|
defer ticker.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-ticker.C:
|
|
runOnce()
|
|
}
|
|
}
|
|
}()
|
|
}
|