feat: migrar backend unificado a Go 1.27 + SPA Vite embebido
This commit is contained in:
@@ -0,0 +1,146 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ActorInfo struct {
|
||||
Type string // "user" | "agent" | "enlace_firmado"
|
||||
Role string // "admin" | "asesor" | "cliente"
|
||||
Scopes []string
|
||||
}
|
||||
|
||||
type ValidarTransicionInput struct {
|
||||
Actual string
|
||||
Nuevo string
|
||||
Actor ActorInfo
|
||||
ViaEndpoint string // "aprobar" | "enlace_firmado" | "enviar" | "estado" | "put"
|
||||
AprobadaAt *time.Time
|
||||
}
|
||||
|
||||
type ValidarTransicionResult struct {
|
||||
OK bool
|
||||
Status int
|
||||
Error string
|
||||
}
|
||||
|
||||
func ValidarTransicionEstado(in ValidarTransicionInput) ValidarTransicionResult {
|
||||
if !EsEstadoCotizacionValido(in.Nuevo) {
|
||||
return ValidarTransicionResult{
|
||||
OK: false,
|
||||
Status: 400,
|
||||
Error: fmt.Sprintf("Estado invalido. Permitidos: %s", strings.Join(EstadosCotizacion, ", ")),
|
||||
}
|
||||
}
|
||||
|
||||
if in.Actual == in.Nuevo {
|
||||
return ValidarTransicionResult{OK: true}
|
||||
}
|
||||
|
||||
esAdminHumano := in.Actor.Type == "user" && in.Actor.Role == "admin"
|
||||
esStaffHumano := in.Actor.Type == "user" && in.Actor.Role != "cliente"
|
||||
esEnlaceFirmado := in.Actor.Type == "enlace_firmado" && in.ViaEndpoint == "enlace_firmado"
|
||||
esAgente := in.Actor.Type == "agent"
|
||||
|
||||
// REGLA DE HIERRO 1: Nadie salvo admin humano o enlace firmado de un solo uso puede aprobar.
|
||||
if in.Nuevo == "aprobada" {
|
||||
if !esAdminHumano && !esEnlaceFirmado {
|
||||
return ValidarTransicionResult{
|
||||
OK: false,
|
||||
Status: 403,
|
||||
Error: "Solo un administrador humano o el enlace firmado puede aprobar una cotizacion",
|
||||
}
|
||||
}
|
||||
if in.Actual != "borrador" {
|
||||
return ValidarTransicionResult{
|
||||
OK: false,
|
||||
Status: 409,
|
||||
Error: fmt.Sprintf("Solo se puede aprobar una cotizacion en borrador (estado actual: %s)", in.Actual),
|
||||
}
|
||||
}
|
||||
return ValidarTransicionResult{OK: true}
|
||||
}
|
||||
|
||||
// REGLA DE HIERRO 2: Nadie puede pasar a "enviada" sin estar previamente aprobada (con aprobadaAt).
|
||||
if in.Nuevo == "enviada" {
|
||||
if esAgente && in.ViaEndpoint != "enviar" {
|
||||
return ValidarTransicionResult{
|
||||
OK: false,
|
||||
Status: 403,
|
||||
Error: "Los agentes solo pueden enviar cotizaciones mediante POST /api/cotizaciones/:id/enviar",
|
||||
}
|
||||
}
|
||||
if in.Actual != "aprobada" || in.AprobadaAt == nil {
|
||||
return ValidarTransicionResult{
|
||||
OK: false,
|
||||
Status: 409,
|
||||
Error: "La cotizacion debe estar aprobada por el administrador antes de enviarse",
|
||||
}
|
||||
}
|
||||
if esAgente {
|
||||
if !slices.Contains(in.Actor.Scopes, "cotizaciones:enviar") {
|
||||
return ValidarTransicionResult{
|
||||
OK: false,
|
||||
Status: 403,
|
||||
Error: "El agente no tiene el alcance cotizaciones:enviar",
|
||||
}
|
||||
}
|
||||
return ValidarTransicionResult{OK: true}
|
||||
}
|
||||
if !esStaffHumano {
|
||||
return ValidarTransicionResult{
|
||||
OK: false,
|
||||
Status: 403,
|
||||
Error: "No autorizado para enviar cotizaciones",
|
||||
}
|
||||
}
|
||||
return ValidarTransicionResult{OK: true}
|
||||
}
|
||||
|
||||
// Reabrir a borrador: solo admin humano desde aprobada, rechazada o vencida.
|
||||
if in.Nuevo == "borrador" {
|
||||
if !esAdminHumano {
|
||||
return ValidarTransicionResult{
|
||||
OK: false,
|
||||
Status: 403,
|
||||
Error: "Solo un administrador humano puede regresar una cotizacion a borrador",
|
||||
}
|
||||
}
|
||||
if in.Actual != "aprobada" && in.Actual != "rechazada" && in.Actual != "vencida" {
|
||||
return ValidarTransicionResult{
|
||||
OK: false,
|
||||
Status: 409,
|
||||
Error: fmt.Sprintf("No se puede regresar a borrador desde el estado %s", in.Actual),
|
||||
}
|
||||
}
|
||||
return ValidarTransicionResult{OK: true}
|
||||
}
|
||||
|
||||
// Estados de cierre post-envio: aceptada | rechazada | vencida
|
||||
if in.Nuevo == "aceptada" || in.Nuevo == "rechazada" || in.Nuevo == "vencida" {
|
||||
if !esStaffHumano {
|
||||
return ValidarTransicionResult{
|
||||
OK: false,
|
||||
Status: 403,
|
||||
Error: "Solo el equipo humano puede marcar una cotizacion como aceptada, rechazada o vencida",
|
||||
}
|
||||
}
|
||||
if in.Actual != "enviada" {
|
||||
return ValidarTransicionResult{
|
||||
OK: false,
|
||||
Status: 409,
|
||||
Error: fmt.Sprintf("Solo se puede pasar a %s desde el estado enviada (estado actual: %s)", in.Nuevo, in.Actual),
|
||||
}
|
||||
}
|
||||
return ValidarTransicionResult{OK: true}
|
||||
}
|
||||
|
||||
return ValidarTransicionResult{
|
||||
OK: false,
|
||||
Status: 409,
|
||||
Error: fmt.Sprintf("Transicion no permitida de %s a %s", in.Actual, in.Nuevo),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,540 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
IVARate = 0.16
|
||||
TarifaHoraDefault = 700.0
|
||||
)
|
||||
|
||||
var ModelosCobro = map[string]string{
|
||||
"fijo": "Precio fijo",
|
||||
"horas": "Por horas",
|
||||
"retainer": "Retainer (minimo + adicionales)",
|
||||
"demanda": "Bajo demanda / por hora",
|
||||
}
|
||||
|
||||
var ModelosCobroTiempo = []string{"horas", "retainer", "demanda"}
|
||||
|
||||
var Fases = map[int]string{
|
||||
0: "FASE 0 - Auditoria / Acompanamiento",
|
||||
1: "FASE 1 - Setup e Infraestructura",
|
||||
2: "FASE 2 - Publicidad y Manejo",
|
||||
3: "FASE 3 - Contenido y SEO",
|
||||
}
|
||||
|
||||
var FasesShort = map[int]string{
|
||||
0: "FASE 0 - Auditoria",
|
||||
1: "FASE 1 - Setup e Infraestructura",
|
||||
2: "FASE 2 - Publicidad y Manejo",
|
||||
3: "FASE 3 - Contenido y SEO",
|
||||
}
|
||||
|
||||
type PlanBucefaloDef struct {
|
||||
Nivel string `json:"nivel"`
|
||||
Label string `json:"label"`
|
||||
Precio float64 `json:"precio"`
|
||||
}
|
||||
|
||||
var PlanesBucefalo = []PlanBucefaloDef{
|
||||
{Nivel: "basico", Label: "Basico", Precio: 1000},
|
||||
{Nivel: "estandar", Label: "Estandar", Precio: 3500},
|
||||
{Nivel: "premium", Label: "Premium", Precio: 4500},
|
||||
{Nivel: "empresarial", Label: "Empresarial", Precio: 7500},
|
||||
}
|
||||
|
||||
var EstadosCotizacion = []string{"borrador", "aprobada", "enviada", "aceptada", "rechazada", "vencida"}
|
||||
|
||||
var EstadosPagoHoras = []string{"por_pagar", "pagada"}
|
||||
|
||||
var NivelesServicio = []string{"Emprendedor", "PYME", "Empresario", "Corporativo"}
|
||||
|
||||
type MetaOpcion struct {
|
||||
Titulo string `json:"titulo,omitempty"`
|
||||
Descripcion string `json:"descripcion,omitempty"`
|
||||
NoIncluye string `json:"noIncluye,omitempty"`
|
||||
}
|
||||
|
||||
type ServicioCalc struct {
|
||||
Nombre string
|
||||
ModeloCobro string
|
||||
EsPersonalizado bool
|
||||
Horas *float64
|
||||
TarifaHora *float64
|
||||
MontoMinimo *float64
|
||||
HorasIncluidas *float64
|
||||
Opcion *string
|
||||
TipoPago string
|
||||
Precio float64
|
||||
Seleccionado bool
|
||||
}
|
||||
|
||||
type TotalesOpcion struct {
|
||||
TotalUnico float64 `json:"totalUnico"`
|
||||
TotalMensual float64 `json:"totalMensual"`
|
||||
Horas float64 `json:"horas"`
|
||||
}
|
||||
|
||||
type TotalesCotizacion struct {
|
||||
SubtotalUnico float64 `json:"subtotalUnico"`
|
||||
SubtotalMensual float64 `json:"subtotalMensual"`
|
||||
IVAUnico float64 `json:"ivaUnico"`
|
||||
IVAMensual float64 `json:"ivaMensual"`
|
||||
TotalUnico float64 `json:"totalUnico"`
|
||||
TotalMensual float64 `json:"totalMensual"`
|
||||
TotalPrimerAnio float64 `json:"totalPrimerAnio"`
|
||||
IncluyeIVA bool `json:"incluyeIva"`
|
||||
}
|
||||
|
||||
type FinanciamientoInput struct {
|
||||
Monto float64
|
||||
Meses int
|
||||
Tasa float64
|
||||
Comision float64
|
||||
IVA float64
|
||||
}
|
||||
|
||||
type FinanciamientoResult struct {
|
||||
PagoMensual float64 `json:"pagoMensual"`
|
||||
IVAMensual float64 `json:"ivaMensual"`
|
||||
TotalMensual float64 `json:"totalMensual"`
|
||||
ComisionTotal float64 `json:"comisionTotal"`
|
||||
GranTotal float64 `json:"granTotal"`
|
||||
}
|
||||
|
||||
type BucketHoras struct {
|
||||
Horas float64 `json:"horas"`
|
||||
Importe float64 `json:"importe"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type ResumenPagoHoras struct {
|
||||
PorPagar BucketHoras `json:"porPagar"`
|
||||
Pagada BucketHoras `json:"pagada"`
|
||||
Total BucketHoras `json:"total"`
|
||||
}
|
||||
|
||||
type RegistroHorasCalc struct {
|
||||
Horas float64
|
||||
TarifaHora float64
|
||||
EstadoPago string
|
||||
}
|
||||
|
||||
type PeriodoAgrupacion struct {
|
||||
Clave string `json:"clave"`
|
||||
Etiqueta string `json:"etiqueta"`
|
||||
}
|
||||
|
||||
func Round2(n float64) float64 {
|
||||
return math.Round(n*100) / 100
|
||||
}
|
||||
|
||||
func CalcularPrecioHoras(horas, tarifaHora float64) float64 {
|
||||
return Round2(horas * tarifaHora)
|
||||
}
|
||||
|
||||
func ConIVA(monto float64, incluirIVA bool) float64 {
|
||||
if incluirIVA {
|
||||
return Round2(monto * (1 + IVARate))
|
||||
}
|
||||
return Round2(monto)
|
||||
}
|
||||
|
||||
func BucefaloPrecio(nivel string) float64 {
|
||||
for _, p := range PlanesBucefalo {
|
||||
if p.Nivel == nivel {
|
||||
return p.Precio
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func EsEstadoCotizacionValido(estado string) bool {
|
||||
for _, e := range EstadosCotizacion {
|
||||
if e == estado {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func EsModeloTiempo(modelo string) bool {
|
||||
for _, m := range ModelosCobroTiempo {
|
||||
if m == modelo {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func EsCotizacionPorTiempo(servicios []ServicioCalc) bool {
|
||||
for _, s := range servicios {
|
||||
if EsModeloTiempo(s.ModeloCobro) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func TarifaHoraSugerida(servicios []ServicioCalc) float64 {
|
||||
for _, s := range servicios {
|
||||
if EsModeloTiempo(s.ModeloCobro) && s.TarifaHora != nil && *s.TarifaHora > 0 {
|
||||
return *s.TarifaHora
|
||||
}
|
||||
}
|
||||
return TarifaHoraDefault
|
||||
}
|
||||
|
||||
func DescribirRetainer(montoMinimo, horasIncluidas, tarifaHora float64) string {
|
||||
partes := []string{fmt.Sprintf("%s/mes", FormatCurrency(montoMinimo))}
|
||||
if horasIncluidas != 0 {
|
||||
partes = append(partes, fmt.Sprintf("incluye %s hr", formatTrimFloat(horasIncluidas)))
|
||||
}
|
||||
if tarifaHora != 0 {
|
||||
partes = append(partes, fmt.Sprintf("adicional %s/hr (se factura aparte)", FormatCurrency(tarifaHora)))
|
||||
}
|
||||
return strings.Join(partes, " · ")
|
||||
}
|
||||
|
||||
func DetalleModelo(s ServicioCalc) string {
|
||||
switch s.ModeloCobro {
|
||||
case "retainer":
|
||||
var mm, hi, th float64
|
||||
if s.MontoMinimo != nil {
|
||||
mm = *s.MontoMinimo
|
||||
}
|
||||
if s.HorasIncluidas != nil {
|
||||
hi = *s.HorasIncluidas
|
||||
}
|
||||
if s.TarifaHora != nil {
|
||||
th = *s.TarifaHora
|
||||
}
|
||||
return DescribirRetainer(mm, hi, th)
|
||||
case "demanda":
|
||||
var th float64
|
||||
if s.TarifaHora != nil {
|
||||
th = *s.TarifaHora
|
||||
}
|
||||
return fmt.Sprintf("%s/hr · segun consumo", FormatCurrency(th))
|
||||
default:
|
||||
if (s.ModeloCobro == "horas" || s.EsPersonalizado) && s.Horas != nil && *s.Horas != 0 && s.TarifaHora != nil && *s.TarifaHora != 0 {
|
||||
return fmt.Sprintf("%s h x %s/hr", formatTrimFloat(*s.Horas), FormatCurrency(*s.TarifaHora))
|
||||
}
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func PrecioDisplay(s ServicioCalc) string {
|
||||
if s.ModeloCobro == "demanda" {
|
||||
var th float64
|
||||
if s.TarifaHora != nil {
|
||||
th = *s.TarifaHora
|
||||
}
|
||||
return fmt.Sprintf("%s/hr", FormatCurrency(th))
|
||||
}
|
||||
return FormatCurrency(s.Precio)
|
||||
}
|
||||
|
||||
func NotaDemanda(servicios []ServicioCalc) string {
|
||||
var partes []string
|
||||
for _, s := range servicios {
|
||||
if s.ModeloCobro == "demanda" {
|
||||
nombre := strings.TrimSpace(s.Nombre)
|
||||
if nombre == "" {
|
||||
nombre = "Servicio"
|
||||
}
|
||||
var th float64
|
||||
if s.TarifaHora != nil {
|
||||
th = *s.TarifaHora
|
||||
}
|
||||
partes = append(partes, fmt.Sprintf("%s a %s/hr", nombre, FormatCurrency(th)))
|
||||
}
|
||||
}
|
||||
if len(partes) == 0 {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("+ Horas facturadas a fin de mes segun consumo (no incluidas en el total): %s.", strings.Join(partes, ", "))
|
||||
}
|
||||
|
||||
func CalcularTotalesOpcion(servicios []ServicioCalc, opcion string) TotalesOpcion {
|
||||
var totalUnico, totalMensual, horas float64
|
||||
for _, s := range servicios {
|
||||
op := ""
|
||||
if s.Opcion != nil {
|
||||
op = *s.Opcion
|
||||
}
|
||||
if op != "ambas" && op != opcion {
|
||||
continue
|
||||
}
|
||||
switch s.TipoPago {
|
||||
case "unico":
|
||||
totalUnico += s.Precio
|
||||
case "mensual":
|
||||
totalMensual += s.Precio
|
||||
}
|
||||
if s.Horas != nil {
|
||||
horas += *s.Horas
|
||||
}
|
||||
}
|
||||
return TotalesOpcion{
|
||||
TotalUnico: Round2(totalUnico),
|
||||
TotalMensual: Round2(totalMensual),
|
||||
Horas: Round2(horas),
|
||||
}
|
||||
}
|
||||
|
||||
func CalcularTotalesCotizacion(servicios []ServicioCalc, incluirIVA bool) TotalesCotizacion {
|
||||
var sumUnico, sumMensual float64
|
||||
for _, s := range servicios {
|
||||
if !s.Seleccionado {
|
||||
continue
|
||||
}
|
||||
switch s.TipoPago {
|
||||
case "unico":
|
||||
sumUnico += s.Precio
|
||||
case "mensual":
|
||||
sumMensual += s.Precio
|
||||
}
|
||||
}
|
||||
subtotalUnico := Round2(sumUnico)
|
||||
subtotalMensual := Round2(sumMensual)
|
||||
|
||||
var ivaUnico, ivaMensual float64
|
||||
if incluirIVA {
|
||||
ivaUnico = Round2(subtotalUnico * IVARate)
|
||||
ivaMensual = Round2(subtotalMensual * IVARate)
|
||||
}
|
||||
totalUnico := Round2(subtotalUnico + ivaUnico)
|
||||
totalMensual := Round2(subtotalMensual + ivaMensual)
|
||||
|
||||
return TotalesCotizacion{
|
||||
SubtotalUnico: subtotalUnico,
|
||||
SubtotalMensual: subtotalMensual,
|
||||
IVAUnico: ivaUnico,
|
||||
IVAMensual: ivaMensual,
|
||||
TotalUnico: totalUnico,
|
||||
TotalMensual: totalMensual,
|
||||
TotalPrimerAnio: Round2(totalUnico + totalMensual*12),
|
||||
IncluyeIVA: incluirIVA,
|
||||
}
|
||||
}
|
||||
|
||||
func CalcularVigencia(fecha time.Time) time.Time {
|
||||
vigencia := fecha
|
||||
diasHabiles := 0
|
||||
for diasHabiles < 15 {
|
||||
vigencia = vigencia.AddDate(0, 0, 1)
|
||||
wd := vigencia.Weekday()
|
||||
if wd != time.Sunday && wd != time.Saturday {
|
||||
diasHabiles++
|
||||
}
|
||||
}
|
||||
return vigencia
|
||||
}
|
||||
|
||||
func CalcularFinanciamiento(input FinanciamientoInput) FinanciamientoResult {
|
||||
comisionTotal := (input.Monto * input.Comision) / 100.0
|
||||
montoConComision := input.Monto + comisionTotal
|
||||
pagoMensual := montoConComision * (1.0 + input.Tasa) / float64(input.Meses)
|
||||
ivaMensual := pagoMensual * input.IVA
|
||||
totalMensual := pagoMensual + ivaMensual
|
||||
return FinanciamientoResult{
|
||||
PagoMensual: Round2(pagoMensual),
|
||||
IVAMensual: Round2(ivaMensual),
|
||||
TotalMensual: Round2(totalMensual),
|
||||
ComisionTotal: Round2(comisionTotal),
|
||||
GranTotal: Round2(totalMensual * float64(input.Meses)),
|
||||
}
|
||||
}
|
||||
|
||||
func GenerarNumeroCotizacion(asesorIniciales string, secuencia int, now time.Time) string {
|
||||
yy := fmt.Sprintf("%02d", now.Year()%100)
|
||||
mm := fmt.Sprintf("%02d", int(now.Month()))
|
||||
seq := fmt.Sprintf("%03d", secuencia)
|
||||
return fmt.Sprintf("UJ%s%s%s%s", yy, mm, asesorIniciales, seq)
|
||||
}
|
||||
|
||||
var horaRe = regexp.MustCompile(`^(\d{1,2}):(\d{2})$`)
|
||||
|
||||
func CalcularHorasRango(horaInicio, horaFin string) float64 {
|
||||
a := horaRe.FindStringSubmatch(horaInicio)
|
||||
b := horaRe.FindStringSubmatch(horaFin)
|
||||
if a == nil || b == nil {
|
||||
return 0
|
||||
}
|
||||
ah, _ := strconv.Atoi(a[1])
|
||||
am, _ := strconv.Atoi(a[2])
|
||||
bh, _ := strconv.Atoi(b[1])
|
||||
bm, _ := strconv.Atoi(b[2])
|
||||
ini := ah*60 + am
|
||||
fin := bh*60 + bm
|
||||
if fin <= ini {
|
||||
return 0
|
||||
}
|
||||
return Round2(float64(fin-ini) / 60.0)
|
||||
}
|
||||
|
||||
func FechaRegistroDesdeISO(fechaISO string) (time.Time, error) {
|
||||
t, err := time.Parse("2006-01-02", strings.TrimSpace(fechaISO))
|
||||
if err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
return time.Date(t.Year(), t.Month(), t.Day(), 12, 0, 0, 0, time.UTC), nil
|
||||
}
|
||||
|
||||
func FormatFechaRegistro(date time.Time) string {
|
||||
u := date.UTC()
|
||||
return fmt.Sprintf("%02d/%02d/%04d", u.Day(), int(u.Month()), u.Year())
|
||||
}
|
||||
|
||||
var mesesLargo = []string{
|
||||
"enero", "febrero", "marzo", "abril", "mayo", "junio",
|
||||
"julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre",
|
||||
}
|
||||
|
||||
func lunesDeSemanaUTC(d time.Time) time.Time {
|
||||
u := d.UTC()
|
||||
r := time.Date(u.Year(), u.Month(), u.Day(), 0, 0, 0, 0, time.UTC)
|
||||
wd := int(r.Weekday()) // 0 = Sunday
|
||||
offset := 1 - wd
|
||||
if wd == 0 {
|
||||
offset = -6
|
||||
}
|
||||
return r.AddDate(0, 0, offset)
|
||||
}
|
||||
|
||||
func PeriodoAgrupacionDe(fecha time.Time, modo string) PeriodoAgrupacion {
|
||||
u := fecha.UTC()
|
||||
y, m, d := u.Year(), int(u.Month()), u.Day()
|
||||
switch modo {
|
||||
case "mes":
|
||||
return PeriodoAgrupacion{
|
||||
Clave: fmt.Sprintf("%04d-%02d", y, m),
|
||||
Etiqueta: fmt.Sprintf("%s %d", mesesLargo[m-1], y),
|
||||
}
|
||||
case "semana":
|
||||
lunes := lunesDeSemanaUTC(u)
|
||||
domingo := lunes.AddDate(0, 0, 6)
|
||||
clave := fmt.Sprintf("%04d-%02d-%02d", lunes.Year(), int(lunes.Month()), lunes.Day())
|
||||
etiqueta := fmt.Sprintf("Semana %02d/%02d - %02d/%02d", lunes.Day(), int(lunes.Month()), domingo.Day(), int(domingo.Month()))
|
||||
return PeriodoAgrupacion{Clave: clave, Etiqueta: etiqueta}
|
||||
default:
|
||||
return PeriodoAgrupacion{
|
||||
Clave: fmt.Sprintf("%04d-%02d-%02d", y, m, d),
|
||||
Etiqueta: FormatFechaRegistro(u),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func EsPagada(estadoPago string) bool {
|
||||
return estadoPago == "pagada"
|
||||
}
|
||||
|
||||
func CalcularResumenPagoHoras(registros []RegistroHorasCalc) ResumenPagoHoras {
|
||||
var r ResumenPagoHoras
|
||||
for _, x := range registros {
|
||||
importe := x.Horas * x.TarifaHora
|
||||
if EsPagada(x.EstadoPago) {
|
||||
r.Pagada.Horas += x.Horas
|
||||
r.Pagada.Importe += importe
|
||||
r.Pagada.Count++
|
||||
} else {
|
||||
r.PorPagar.Horas += x.Horas
|
||||
r.PorPagar.Importe += importe
|
||||
r.PorPagar.Count++
|
||||
}
|
||||
r.Total.Horas += x.Horas
|
||||
r.Total.Importe += importe
|
||||
r.Total.Count++
|
||||
}
|
||||
r.PorPagar.Horas = Round2(r.PorPagar.Horas)
|
||||
r.PorPagar.Importe = Round2(r.PorPagar.Importe)
|
||||
r.Pagada.Horas = Round2(r.Pagada.Horas)
|
||||
r.Pagada.Importe = Round2(r.Pagada.Importe)
|
||||
r.Total.Horas = Round2(r.Total.Horas)
|
||||
r.Total.Importe = Round2(r.Total.Importe)
|
||||
return r
|
||||
}
|
||||
|
||||
var sanitizeFileRe = regexp.MustCompile(`[^\w\s.\-]`)
|
||||
var multiSpaceRe = regexp.MustCompile(`\s+`)
|
||||
|
||||
func SanitizeFilename(name string) string {
|
||||
s := sanitizeFileRe.ReplaceAllString(name, "")
|
||||
s = multiSpaceRe.ReplaceAllString(s, " ")
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
|
||||
// FormatCurrency formats MXN like Intl.NumberFormat("es-MX", {style:"currency", currency:"MXN", minFrac:0, maxFrac:2}).
|
||||
func FormatCurrency(amount float64) string {
|
||||
return FormatMonto(amount, "MXN")
|
||||
}
|
||||
|
||||
// FormatMonto formats currency matching es-MX formatting: "$4,500", "$4,500.50", "US$25" / "USD 25".
|
||||
func FormatMonto(amount float64, moneda string) string {
|
||||
neg := amount < 0
|
||||
abs := math.Abs(amount)
|
||||
rounded := Round2(abs)
|
||||
intPart := int64(rounded)
|
||||
fracPart := int(math.Round((rounded - float64(intPart)) * 100))
|
||||
if fracPart == 100 {
|
||||
intPart++
|
||||
fracPart = 0
|
||||
}
|
||||
|
||||
intStr := addCommas(intPart)
|
||||
numStr := intStr
|
||||
if fracPart > 0 {
|
||||
numStr = fmt.Sprintf("%s.%02d", intStr, fracPart)
|
||||
}
|
||||
|
||||
prefix := "$"
|
||||
if moneda != "" && !strings.EqualFold(moneda, "MXN") {
|
||||
prefix = strings.ToUpper(moneda) + " "
|
||||
}
|
||||
if neg {
|
||||
return "-" + prefix + numStr
|
||||
}
|
||||
return prefix + numStr
|
||||
}
|
||||
|
||||
func FormatDateLongMX(d time.Time) string {
|
||||
return fmt.Sprintf("%02d de %s de %d", d.Day(), mesesLargo[int(d.Month())-1], d.Year())
|
||||
}
|
||||
|
||||
func FormatDateShort(d time.Time) string {
|
||||
return fmt.Sprintf("%02d/%02d/%04d", d.Day(), int(d.Month()), d.Year())
|
||||
}
|
||||
|
||||
func addCommas(n int64) string {
|
||||
s := strconv.FormatInt(n, 10)
|
||||
if len(s) <= 3 {
|
||||
return s
|
||||
}
|
||||
var out strings.Builder
|
||||
rem := len(s) % 3
|
||||
if rem > 0 {
|
||||
out.WriteString(s[:rem])
|
||||
if len(s) > rem {
|
||||
out.WriteByte(',')
|
||||
}
|
||||
}
|
||||
for i := rem; i < len(s); i += 3 {
|
||||
if i > rem {
|
||||
out.WriteByte(',')
|
||||
}
|
||||
out.WriteString(s[i : i+3])
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func formatTrimFloat(f float64) string {
|
||||
return strconv.FormatFloat(Round2(f), 'f', -1, 64)
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func floatPtr(v float64) *float64 { return &v }
|
||||
func strPtr(v string) *string { return &v }
|
||||
|
||||
func TestCalculatorsParity(t *testing.T) {
|
||||
if IVARate != 0.16 {
|
||||
t.Fatalf("expected IVARate 0.16, got %v", IVARate)
|
||||
}
|
||||
if len(EstadosCotizacion) != 6 {
|
||||
t.Fatalf("expected 6 estados, got %d", len(EstadosCotizacion))
|
||||
}
|
||||
|
||||
// Financing plans (3, 6, 9, 12 months)
|
||||
cases := []struct {
|
||||
meses int
|
||||
tasa float64
|
||||
monto float64
|
||||
wantComision float64
|
||||
wantPagoMes float64
|
||||
wantTotalMes float64
|
||||
}{
|
||||
{3, 0.077, 10000, 250, 3679.75, 4268.51},
|
||||
{6, 0.107, 10000, 250, 1891.13, 2193.71},
|
||||
{9, 0.137, 10000, 250, 1294.92, 1502.1},
|
||||
{12, 0.167, 10000, 250, 996.81, 1156.3},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
res := CalcularFinanciamiento(FinanciamientoInput{
|
||||
Monto: tc.monto, Meses: tc.meses, Tasa: tc.tasa, Comision: 2.5, IVA: 0.16,
|
||||
})
|
||||
if res.ComisionTotal != tc.wantComision {
|
||||
t.Errorf("%dm comisionTotal=%v want %v", tc.meses, res.ComisionTotal, tc.wantComision)
|
||||
}
|
||||
if res.PagoMensual != tc.wantPagoMes {
|
||||
t.Errorf("%dm pagoMensual=%v want %v", tc.meses, res.PagoMensual, tc.wantPagoMes)
|
||||
}
|
||||
if res.TotalMensual != tc.wantTotalMes {
|
||||
t.Errorf("%dm totalMensual=%v want %v", tc.meses, res.TotalMensual, tc.wantTotalMes)
|
||||
}
|
||||
}
|
||||
|
||||
// Totales cotizacion with mixed models & unselected item
|
||||
svcs := []ServicioCalc{
|
||||
{TipoPago: "unico", Precio: 15000, Seleccionado: true, ModeloCobro: "fijo"},
|
||||
{TipoPago: "mensual", Precio: 5000, Seleccionado: true, ModeloCobro: "retainer"},
|
||||
{TipoPago: "mensual", Precio: 0, Seleccionado: true, ModeloCobro: "demanda", TarifaHora: floatPtr(700)},
|
||||
{TipoPago: "unico", Precio: 99999, Seleccionado: false},
|
||||
}
|
||||
totCon := CalcularTotalesCotizacion(svcs, true)
|
||||
if totCon.SubtotalUnico != 15000 || totCon.SubtotalMensual != 5000 || totCon.TotalUnico != 17400 || totCon.TotalMensual != 5800 || totCon.TotalPrimerAnio != 87000 {
|
||||
t.Fatalf("unexpected totCon: %+v", totCon)
|
||||
}
|
||||
totSin := CalcularTotalesCotizacion(svcs, false)
|
||||
if totSin.IVAUnico != 0 || totSin.TotalUnico != 15000 || totSin.TotalPrimerAnio != 75000 {
|
||||
t.Fatalf("unexpected totSin: %+v", totSin)
|
||||
}
|
||||
|
||||
// Doble propuesta option totals
|
||||
doble := []ServicioCalc{
|
||||
{Opcion: strPtr("1"), TipoPago: "unico", Precio: 10000, Horas: floatPtr(10)},
|
||||
{Opcion: strPtr("2"), TipoPago: "unico", Precio: 20000, Horas: floatPtr(20)},
|
||||
{Opcion: strPtr("ambas"), TipoPago: "mensual", Precio: 3000, Horas: floatPtr(5)},
|
||||
}
|
||||
op1 := CalcularTotalesOpcion(doble, "1")
|
||||
op2 := CalcularTotalesOpcion(doble, "2")
|
||||
if op1.TotalUnico != 10000 || op1.TotalMensual != 3000 || op1.Horas != 15 {
|
||||
t.Fatalf("unexpected op1: %+v", op1)
|
||||
}
|
||||
if op2.TotalUnico != 20000 || op2.TotalMensual != 3000 || op2.Horas != 25 {
|
||||
t.Fatalf("unexpected op2: %+v", op2)
|
||||
}
|
||||
|
||||
// 15 business days vigencia: Mon 2026-06-01 -> Mon 2026-06-22
|
||||
start := time.Date(2026, 6, 1, 12, 0, 0, 0, time.UTC)
|
||||
vig := CalcularVigencia(start)
|
||||
if vig.Format("2006-01-02") != "2026-06-22" {
|
||||
t.Fatalf("expected vigencia 2026-06-22, got %s", vig.Format("2006-01-02"))
|
||||
}
|
||||
|
||||
// Hours range & summary
|
||||
if h := CalcularHorasRango("09:00", "13:30"); h != 4.5 {
|
||||
t.Fatalf("expected 4.5 hours, got %v", h)
|
||||
}
|
||||
resH := CalcularResumenPagoHoras([]RegistroHorasCalc{
|
||||
{Horas: 2, TarifaHora: 700, EstadoPago: "por_pagar"},
|
||||
{Horas: 3, TarifaHora: 700, EstadoPago: "pagada"},
|
||||
})
|
||||
if resH.PorPagar.Importe != 1400 || resH.Pagada.Importe != 2100 || resH.Total.Importe != 3500 {
|
||||
t.Fatalf("unexpected resumen horas: %+v", resH)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApprovalGuard(t *testing.T) {
|
||||
now := time.Now()
|
||||
agent := ActorInfo{Type: "agent", Scopes: []string{"cotizaciones:borrador", "cotizaciones:enviar"}}
|
||||
asesor := ActorInfo{Type: "user", Role: "asesor"}
|
||||
admin := ActorInfo{Type: "user", Role: "admin"}
|
||||
enlace := ActorInfo{Type: "enlace_firmado"}
|
||||
|
||||
// Agent cannot approve
|
||||
if r := ValidarTransicionEstado(ValidarTransicionInput{Actual: "borrador", Nuevo: "aprobada", Actor: agent, ViaEndpoint: "aprobar"}); r.OK || r.Status != 403 {
|
||||
t.Fatalf("agent approval should be 403, got %+v", r)
|
||||
}
|
||||
// Asesor cannot approve
|
||||
if r := ValidarTransicionEstado(ValidarTransicionInput{Actual: "borrador", Nuevo: "aprobada", Actor: asesor, ViaEndpoint: "aprobar"}); r.OK || r.Status != 403 {
|
||||
t.Fatalf("asesor approval should be 403, got %+v", r)
|
||||
}
|
||||
// Admin can approve borrador
|
||||
if r := ValidarTransicionEstado(ValidarTransicionInput{Actual: "borrador", Nuevo: "aprobada", Actor: admin, ViaEndpoint: "aprobar"}); !r.OK {
|
||||
t.Fatalf("admin approval should succeed, got %+v", r)
|
||||
}
|
||||
// Signed link can approve borrador
|
||||
if r := ValidarTransicionEstado(ValidarTransicionInput{Actual: "borrador", Nuevo: "aprobada", Actor: enlace, ViaEndpoint: "enlace_firmado"}); !r.OK {
|
||||
t.Fatalf("signed link approval should succeed, got %+v", r)
|
||||
}
|
||||
// Cannot send borrador
|
||||
if r := ValidarTransicionEstado(ValidarTransicionInput{Actual: "borrador", Nuevo: "enviada", Actor: agent, ViaEndpoint: "enviar"}); r.OK || r.Status != 409 {
|
||||
t.Fatalf("sending draft should be 409, got %+v", r)
|
||||
}
|
||||
// Agent cannot set enviada via PUT
|
||||
if r := ValidarTransicionEstado(ValidarTransicionInput{Actual: "aprobada", Nuevo: "enviada", Actor: agent, ViaEndpoint: "put", AprobadaAt: &now}); r.OK || r.Status != 403 {
|
||||
t.Fatalf("agent PUT enviada should be 403, got %+v", r)
|
||||
}
|
||||
// Agent can send approved quote via enviar
|
||||
if r := ValidarTransicionEstado(ValidarTransicionInput{Actual: "aprobada", Nuevo: "enviada", Actor: agent, ViaEndpoint: "enviar", AprobadaAt: &now}); !r.OK {
|
||||
t.Fatalf("agent enviar approved should succeed, got %+v", r)
|
||||
}
|
||||
// Agent cannot mark aceptada
|
||||
if r := ValidarTransicionEstado(ValidarTransicionInput{Actual: "enviada", Nuevo: "aceptada", Actor: agent, ViaEndpoint: "estado"}); r.OK || r.Status != 403 {
|
||||
t.Fatalf("agent aceptada should be 403, got %+v", r)
|
||||
}
|
||||
// Staff can mark aceptada
|
||||
if r := ValidarTransicionEstado(ValidarTransicionInput{Actual: "enviada", Nuevo: "aceptada", Actor: asesor, ViaEndpoint: "estado"}); !r.OK {
|
||||
t.Fatalf("asesor aceptada should succeed, got %+v", r)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSoloAdminRestriction(t *testing.T) {
|
||||
soloIDs := map[string]struct{}{"plan-mensual-crm-bucefalo-18": {}}
|
||||
|
||||
// Human admin allowed everything
|
||||
r1 := EvaluarRestriccionSoloAdmin(EvaluarSoloAdminInput{
|
||||
EsAgente: false,
|
||||
HasPlanBucefalo: true,
|
||||
Servicios: []ServicioDraftInput{{CatalogoID: "plan-mensual-crm-bucefalo-18", Nombre: "CRM Bucéfalo"}},
|
||||
SoloAdminCatalogIDs: soloIDs,
|
||||
})
|
||||
if !r1.OK {
|
||||
t.Fatalf("human admin should not be blocked: %+v", r1)
|
||||
}
|
||||
|
||||
// Agent blocked on planBucefalo, soloAdmin ID, bucefalo-* prefix, and custom name
|
||||
r2 := EvaluarRestriccionSoloAdmin(EvaluarSoloAdminInput{
|
||||
EsAgente: true,
|
||||
HasPlanBucefalo: true,
|
||||
Servicios: []ServicioDraftInput{
|
||||
{CatalogoID: "plan-mensual-crm-bucefalo-18"},
|
||||
{CatalogoID: "bucefalo-pro"},
|
||||
{Nombre: "Implementacion Bucéfalo Custom"},
|
||||
},
|
||||
SoloAdminCatalogIDs: soloIDs,
|
||||
})
|
||||
if r2.OK || len(r2.ItemsBloqueados) != 4 {
|
||||
t.Fatalf("expected 4 blocked items, got %+v", r2)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFechasPeriodo(t *testing.T) {
|
||||
ini, _ := ParseFechaCalendario("2026-07-01")
|
||||
fin, _ := ParseFechaCalendario("2026-07-31")
|
||||
sab := 6
|
||||
fechas := FechasPeriodo(ProgramaCalendario{
|
||||
Frecuencia: "semanal",
|
||||
DiaSemana: &sab,
|
||||
FechaInicio: ini,
|
||||
FechaFin: &fin,
|
||||
}, fin)
|
||||
if len(fechas) != 4 || FormatFechaCorta(fechas[0]) != "04/07/2026" {
|
||||
t.Fatalf("expected 4 saturdays starting 04/07/2026, got %d (%v)", len(fechas), fechas)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type ServicioDraftInput struct {
|
||||
CatalogoID string
|
||||
Nombre string
|
||||
EsPersonalizado bool
|
||||
}
|
||||
|
||||
type EvaluarSoloAdminInput struct {
|
||||
EsAgente bool
|
||||
HasPlanBucefalo bool
|
||||
Servicios []ServicioDraftInput
|
||||
SoloAdminCatalogIDs map[string]struct{}
|
||||
}
|
||||
|
||||
type EvaluarSoloAdminResult struct {
|
||||
OK bool
|
||||
Motivos []string
|
||||
ItemsBloqueados []string
|
||||
}
|
||||
|
||||
var bucefaloRe = regexp.MustCompile(`(?i)buc[eé]falo`)
|
||||
var bucefaloPrefixRe = regexp.MustCompile(`(?i)^bucefalo-`)
|
||||
|
||||
func EvaluarRestriccionSoloAdmin(in EvaluarSoloAdminInput) EvaluarSoloAdminResult {
|
||||
if !in.EsAgente {
|
||||
return EvaluarSoloAdminResult{OK: true}
|
||||
}
|
||||
|
||||
var motivos []string
|
||||
var bloqueados []string
|
||||
|
||||
if in.HasPlanBucefalo {
|
||||
motivos = append(motivos, "planBucefalo esta reservado al administrador humano")
|
||||
bloqueados = append(bloqueados, "planBucefalo")
|
||||
}
|
||||
|
||||
for _, svc := range in.Servicios {
|
||||
cid := strings.TrimSpace(svc.CatalogoID)
|
||||
nombre := strings.TrimSpace(svc.Nombre)
|
||||
|
||||
if cid != "" && bucefaloPrefixRe.MatchString(cid) {
|
||||
motivos = append(motivos, fmt.Sprintf("catalogoId restringido (%s)", cid))
|
||||
bloqueados = append(bloqueados, cid)
|
||||
continue
|
||||
}
|
||||
if cid != "" {
|
||||
if _, ok := in.SoloAdminCatalogIDs[cid]; ok {
|
||||
motivos = append(motivos, fmt.Sprintf("servicio marcado soloAdmin (%s)", cid))
|
||||
bloqueados = append(bloqueados, cid)
|
||||
continue
|
||||
}
|
||||
}
|
||||
if nombre != "" && bucefaloRe.MatchString(nombre) {
|
||||
motivos = append(motivos, fmt.Sprintf("servicio restringido por marca soloAdmin (%s)", nombre))
|
||||
bloqueados = append(bloqueados, nombre)
|
||||
}
|
||||
}
|
||||
|
||||
return EvaluarSoloAdminResult{
|
||||
OK: len(motivos) == 0,
|
||||
Motivos: motivos,
|
||||
ItemsBloqueados: bloqueados,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user