Files
cotizador/internal/domain/cobros_fechas.go
T

240 lines
6.1 KiB
Go

package domain
import (
"fmt"
"math"
"regexp"
"sort"
"strconv"
"strings"
"time"
)
const (
ZonaHoraria = "America/Mexico_City"
RecordatorioDiasDef = 3
HoraRecordatorios = 9
EstadoPagoPendiente = "pendiente"
EstadoPagoEnRevision = "en_revision"
EstadoPagoVerificado = "verificado"
EstadoPagoRechazado = "rechazado"
EstadoPagoAnulado = "anulado"
)
var EstadosPorPagar = []string{EstadoPagoPendiente, EstadoPagoRechazado}
func EsPorPagar(estado string) bool {
return estado == EstadoPagoPendiente || estado == EstadoPagoRechazado
}
func mexicoLocation() *time.Location {
loc, err := time.LoadLocation(ZonaHoraria)
if err != nil {
// Mexico City has been permanently UTC-6 since 2022 (no DST).
return time.FixedZone("America/Mexico_City", -6*3600)
}
return loc
}
var fechaISORe = regexp.MustCompile(`^(\d{4})-(\d{2})-(\d{2})$`)
// ParseFechaCalendario parses "YYYY-MM-DD" into UTC midnight calendar date.
func ParseFechaCalendario(iso string) (time.Time, error) {
m := fechaISORe.FindStringSubmatch(strings.TrimSpace(iso))
if m == nil {
return time.Time{}, fmt.Errorf("Fecha invalida: %s (se espera YYYY-MM-DD)", iso)
}
y, _ := strconv.Atoi(m[1])
mo, _ := strconv.Atoi(m[2])
d, _ := strconv.Atoi(m[3])
return time.Date(y, time.Month(mo), d, 0, 0, 0, 0, time.UTC), nil
}
// ACalendario extracts calendar (year, month, day) from UTC parts.
func ACalendario(t time.Time) (int, time.Month, int) {
u := t.UTC()
return u.Year(), u.Month(), u.Day()
}
// CalendarioDe converts a real timestamp to its America/Mexico_City calendar date (UTC midnight).
func CalendarioDe(instante time.Time) time.Time {
mx := instante.In(mexicoLocation())
return time.Date(mx.Year(), mx.Month(), mx.Day(), 0, 0, 0, 0, time.UTC)
}
func HoyCalendario() time.Time {
return CalendarioDe(time.Now())
}
func HoraMexico(instante time.Time) int {
return instante.In(mexicoLocation()).Hour()
}
// InstanteDePago returns noon in Mexico City (18:00 UTC) so CalendarioDe() maps back to the same day.
func InstanteDePago(fecha time.Time) time.Time {
y, m, d := ACalendario(fecha)
return time.Date(y, m, d, 18, 0, 0, 0, time.UTC)
}
func SumarDias(d time.Time, dias int) time.Time {
return d.UTC().AddDate(0, 0, dias)
}
func DiasDeAtraso(fecha, hoy time.Time) int {
diff := math.Round(hoy.UTC().Sub(fecha.UTC()).Hours() / 24.0)
if diff < 0 {
return 0
}
return int(diff)
}
func DiasHasta(fecha, hoy time.Time) int {
return int(math.Round(fecha.UTC().Sub(hoy.UTC()).Hours() / 24.0))
}
func DescribirVencimiento(fecha, hoy time.Time) string {
d := DiasHasta(fecha, hoy)
switch {
case d == 0:
return "vence hoy"
case d == 1:
return "mañana"
case d > 1:
return fmt.Sprintf("en %d días", d)
case d == -1:
return "hace 1 día"
default:
return fmt.Sprintf("hace %d días", -d)
}
}
var diasSemanaLargo = []string{
"Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado",
}
var diasSemanaCorto = []string{
"dom", "lun", "mar", "mié", "jue", "vie", "sáb",
}
var mesesCorto = []string{
"ene", "feb", "mar", "abr", "may", "jun",
"jul", "ago", "sep", "oct", "nov", "dic",
}
func FormatFechaCobro(date time.Time) string {
u := date.UTC()
return fmt.Sprintf("%s, %02d de %s de %d", diasSemanaLargo[int(u.Weekday())], u.Day(), mesesLargo[int(u.Month())-1], u.Year())
}
func FormatFechaBreve(date, hoy time.Time) string {
u := date.UTC()
anio := ""
if u.Year() != hoy.UTC().Year() {
anio = fmt.Sprintf(" %d", u.Year())
}
return fmt.Sprintf("%s %d %s%s", diasSemanaCorto[int(u.Weekday())], u.Day(), mesesCorto[int(u.Month())-1], anio)
}
func FormatFechaCorta(date time.Time) string {
y, m, d := ACalendario(date)
return fmt.Sprintf("%02d/%02d/%04d", d, int(m), y)
}
func FormatTotales(totales map[string]float64) string {
if len(totales) == 0 {
return "$0"
}
keys := make([]string, 0, len(totales))
for k := range totales {
keys = append(keys, k)
}
sort.Strings(keys)
partes := make([]string, 0, len(keys))
for _, k := range keys {
partes = append(partes, FormatMonto(totales[k], k))
}
return strings.Join(partes, " + ")
}
type ProgramaCalendario struct {
Frecuencia string
DiaSemana *int
DiaMes *int
FechaInicio time.Time
FechaFin *time.Time
}
func FechasPeriodo(p ProgramaCalendario, hasta time.Time) []time.Time {
iy, im, id := ACalendario(p.FechaInicio)
inicioD := time.Date(iy, im, id, 0, 0, 0, 0, time.UTC)
limite := hasta.UTC()
if p.FechaFin != nil {
fy, fm, fd := ACalendario(*p.FechaFin)
finD := time.Date(fy, fm, fd, 0, 0, 0, 0, time.UTC)
if finD.Before(limite) {
limite = finD
}
}
if inicioD.After(limite) {
return nil
}
var out []time.Time
switch p.Frecuencia {
case "semanal":
dia := int(inicioD.Weekday())
if p.DiaSemana != nil {
dia = *p.DiaSemana
}
d := inicioD
for guard := 0; int(d.Weekday()) != dia && guard < 7; guard++ {
d = SumarDias(d, 1)
}
for !d.After(limite) {
out = append(out, d)
d = SumarDias(d, 7)
}
case "quincenal":
mes := time.Date(inicioD.Year(), inicioD.Month(), 1, 0, 0, 0, 0, time.UTC)
for !mes.After(limite) {
for _, dia := range []int{1, 15} {
d := time.Date(mes.Year(), mes.Month(), dia, 0, 0, 0, 0, time.UTC)
if !d.Before(inicioD) && !d.After(limite) {
out = append(out, d)
}
}
mes = time.Date(mes.Year(), mes.Month()+1, 1, 0, 0, 0, 0, time.UTC)
}
default: // mensual
diaMes := 1
if p.DiaMes != nil {
diaMes = *p.DiaMes
}
mes := time.Date(inicioD.Year(), inicioD.Month(), 1, 0, 0, 0, 0, time.UTC)
for !mes.After(limite) {
ultimoDia := time.Date(mes.Year(), mes.Month()+1, 0, 0, 0, 0, 0, time.UTC).Day()
dia := diaMes
if dia > ultimoDia {
dia = ultimoDia
}
d := time.Date(mes.Year(), mes.Month(), dia, 0, 0, 0, 0, time.UTC)
if !d.Before(inicioD) && !d.After(limite) {
out = append(out, d)
}
mes = time.Date(mes.Year(), mes.Month()+1, 1, 0, 0, 0, 0, time.UTC)
}
}
return out
}
func ProximaFecha(p ProgramaCalendario, desde time.Time) *time.Time {
ventana := FechasPeriodo(p, SumarDias(desde, 366))
for _, f := range ventana {
if !f.Before(desde) {
v := f
return &v
}
}
return nil
}