feat: migrar backend unificado a Go 1.27 + SPA Vite embebido
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"cotizador/internal/db"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type Entry struct {
|
||||
ActorTipo string
|
||||
ActorID string
|
||||
ActorNombre string
|
||||
Accion string
|
||||
RecursoTipo string
|
||||
RecursoID string
|
||||
IP string
|
||||
RequestID string
|
||||
Exito bool
|
||||
Detalle any
|
||||
}
|
||||
|
||||
func ClientIP(r *http.Request) string {
|
||||
if r == nil {
|
||||
return ""
|
||||
}
|
||||
if xff := strings.TrimSpace(r.Header.Get("X-Forwarded-For")); xff != "" {
|
||||
parts := strings.Split(xff, ",")
|
||||
if len(parts) > 0 && strings.TrimSpace(parts[0]) != "" {
|
||||
return strings.TrimSpace(parts[0])
|
||||
}
|
||||
}
|
||||
if xri := strings.TrimSpace(r.Header.Get("X-Real-IP")); xri != "" {
|
||||
return xri
|
||||
}
|
||||
return r.RemoteAddr
|
||||
}
|
||||
|
||||
func RequestID(r *http.Request) string {
|
||||
if r == nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(r.Header.Get("X-Request-Id"))
|
||||
}
|
||||
|
||||
// Registrar writes an AuditLog row best-effort (never fails caller flow).
|
||||
func Registrar(ctx context.Context, pool *pgxpool.Pool, e Entry) {
|
||||
if pool == nil {
|
||||
return
|
||||
}
|
||||
var detalleBytes []byte
|
||||
if e.Detalle != nil {
|
||||
if b, err := json.Marshal(e.Detalle); err == nil {
|
||||
detalleBytes = b
|
||||
}
|
||||
}
|
||||
var actorID, recursoID, ip, reqID *string
|
||||
if e.ActorID != "" {
|
||||
v := e.ActorID
|
||||
actorID = &v
|
||||
}
|
||||
if e.RecursoID != "" {
|
||||
v := e.RecursoID
|
||||
recursoID = &v
|
||||
}
|
||||
if e.IP != "" {
|
||||
v := e.IP
|
||||
ip = &v
|
||||
}
|
||||
if e.RequestID != "" {
|
||||
v := e.RequestID
|
||||
reqID = &v
|
||||
}
|
||||
|
||||
_, err := pool.Exec(ctx, `
|
||||
INSERT INTO "AuditLog" ("id", "actorTipo", "actorId", "actorNombre", "accion", "recursoTipo", "recursoId", "ip", "requestId", "exito", "detalle")
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
|
||||
`, db.NewID(), e.ActorTipo, actorID, e.ActorNombre, e.Accion, e.RecursoTipo, recursoID, ip, reqID, e.Exito, detalleBytes)
|
||||
if err != nil {
|
||||
log.Printf("[audit] error escribiendo AuditLog (%s): %v", e.Accion, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,601 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/audit"
|
||||
"cotizador/internal/domain"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
const (
|
||||
SessionCookieName = "cotizador-session"
|
||||
SessionTTL = 7 * 24 * time.Hour
|
||||
APIKeyPrefix = "ujc_live_"
|
||||
)
|
||||
|
||||
// Exact 9 allowed agent scopes. NEVER add an approval scope.
|
||||
var AgentScopes = []string{
|
||||
"catalogo:leer",
|
||||
"clientes:leer",
|
||||
"clientes:escribir",
|
||||
"cotizaciones:leer",
|
||||
"cotizaciones:leer_aceptadas",
|
||||
"cotizaciones:borrador",
|
||||
"cotizaciones:enviar",
|
||||
"cobros:leer",
|
||||
"cobros:registrar",
|
||||
}
|
||||
|
||||
func IsValidScope(s string) bool {
|
||||
return slices.Contains(AgentScopes, s)
|
||||
}
|
||||
|
||||
type SessionPayload struct {
|
||||
UserID string `json:"userId"`
|
||||
Email string `json:"email"`
|
||||
Name string `json:"name"`
|
||||
Role string `json:"role"`
|
||||
ClienteID string `json:"clienteId,omitempty"`
|
||||
}
|
||||
|
||||
type jwtClaims struct {
|
||||
UserID string `json:"userId"`
|
||||
Email string `json:"email"`
|
||||
Name string `json:"name"`
|
||||
Role string `json:"role"`
|
||||
ClienteID string `json:"clienteId,omitempty"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
type Actor struct {
|
||||
Type string // "user" | "agent"
|
||||
UserID string
|
||||
Email string
|
||||
Name string
|
||||
Role string // "admin" | "asesor" | "cliente"
|
||||
ClienteID string
|
||||
KeyID string
|
||||
KeyNombre string
|
||||
Scopes []string
|
||||
RateLimitPerMin int
|
||||
RateHeaders map[string]string
|
||||
}
|
||||
|
||||
func (a *Actor) ToDomainActor() domain.ActorInfo {
|
||||
return domain.ActorInfo{
|
||||
Type: a.Type,
|
||||
Role: a.Role,
|
||||
Scopes: a.Scopes,
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Actor) AuditActor() (tipo, id, nombre string) {
|
||||
if a.Type == "agent" {
|
||||
return "agent", a.KeyID, a.KeyNombre
|
||||
}
|
||||
return "user", a.UserID, a.Email
|
||||
}
|
||||
|
||||
func (a *Actor) IsAdmin() bool {
|
||||
return a.Type == "user" && a.Role == "admin"
|
||||
}
|
||||
|
||||
func (a *Actor) IsStaff() bool {
|
||||
return a.Type == "user" && a.Role != "cliente"
|
||||
}
|
||||
|
||||
func (a *Actor) IsCliente() bool {
|
||||
return a.Type == "user" && a.Role == "cliente"
|
||||
}
|
||||
|
||||
func (a *Actor) IsAgent() bool {
|
||||
return a.Type == "agent"
|
||||
}
|
||||
|
||||
func (a *Actor) HasScopes(required []string, mode string) bool {
|
||||
if a.IsStaff() {
|
||||
return true
|
||||
}
|
||||
if !a.IsAgent() {
|
||||
return false
|
||||
}
|
||||
if len(required) == 0 {
|
||||
return true
|
||||
}
|
||||
if mode == "all" {
|
||||
for _, req := range required {
|
||||
if !slices.Contains(a.Scopes, req) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
for _, req := range required {
|
||||
if slices.Contains(a.Scopes, req) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// EsAgenteSoloAceptadas returns true when agent has cotizaciones:leer_aceptadas and NOT cotizaciones:leer.
|
||||
func (a *Actor) EsAgenteSoloAceptadas() bool {
|
||||
return a.IsAgent() &&
|
||||
slices.Contains(a.Scopes, "cotizaciones:leer_aceptadas") &&
|
||||
!slices.Contains(a.Scopes, "cotizaciones:leer")
|
||||
}
|
||||
|
||||
func (a *Actor) ApplyHeaders(w http.ResponseWriter) {
|
||||
for k, v := range a.RateHeaders {
|
||||
w.Header().Set(k, v)
|
||||
}
|
||||
}
|
||||
|
||||
func HashPassword(plain string) (string, error) {
|
||||
b, err := bcrypt.GenerateFromPassword([]byte(plain), 10)
|
||||
return string(b), err
|
||||
}
|
||||
|
||||
func ComparePassword(hash, plain string) bool {
|
||||
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(plain)) == nil
|
||||
}
|
||||
|
||||
func HashSecret(raw string) string {
|
||||
sum := sha256.Sum256([]byte(raw))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func GenerateAPIKey() (rawKey, prefijo, keyHash string) {
|
||||
var b [32]byte
|
||||
_, _ = rand.Read(b[:])
|
||||
rawKey = APIKeyPrefix + hex.EncodeToString(b[:])
|
||||
prefijo = rawKey[:14]
|
||||
keyHash = HashSecret(rawKey)
|
||||
return
|
||||
}
|
||||
|
||||
func GenerateRandomToken(numBytes int) (raw, hash string) {
|
||||
b := make([]byte, numBytes)
|
||||
_, _ = rand.Read(b)
|
||||
raw = hex.EncodeToString(b)
|
||||
hash = HashSecret(raw)
|
||||
return
|
||||
}
|
||||
|
||||
var nonDigitsRe = regexp.MustCompile(`\D+`)
|
||||
|
||||
// CoincideContacto matches exact email (case-insensitive) or last 10 digits of phone.
|
||||
func CoincideContacto(verificar string, clienteEmail, clienteTelefono string) bool {
|
||||
v := strings.TrimSpace(verificar)
|
||||
if v == "" {
|
||||
return false
|
||||
}
|
||||
if strings.Contains(v, "@") {
|
||||
return clienteEmail != "" && strings.EqualFold(v, strings.TrimSpace(clienteEmail))
|
||||
}
|
||||
digitsV := nonDigitsRe.ReplaceAllString(v, "")
|
||||
digitsC := nonDigitsRe.ReplaceAllString(clienteTelefono, "")
|
||||
if len(digitsV) < 7 || len(digitsC) < 7 {
|
||||
return false
|
||||
}
|
||||
if len(digitsV) > 10 {
|
||||
digitsV = digitsV[len(digitsV)-10:]
|
||||
}
|
||||
if len(digitsC) > 10 {
|
||||
digitsC = digitsC[len(digitsC)-10:]
|
||||
}
|
||||
return digitsV == digitsC
|
||||
}
|
||||
|
||||
// RateLimiter implements an in-memory 60-second sliding window per API key.
|
||||
type RateLimiter struct {
|
||||
mu sync.Mutex
|
||||
buckets map[string][]time.Time
|
||||
}
|
||||
|
||||
func NewRateLimiter() *RateLimiter {
|
||||
return &RateLimiter{buckets: make(map[string][]time.Time)}
|
||||
}
|
||||
|
||||
type RateLimitResult struct {
|
||||
Allowed bool
|
||||
Limit int
|
||||
Remaining int
|
||||
ResetUnix int64
|
||||
RetryAfter int
|
||||
}
|
||||
|
||||
func (rl *RateLimiter) Check(keyID string, limit int, now time.Time) RateLimitResult {
|
||||
if limit < 1 {
|
||||
limit = 60
|
||||
}
|
||||
windowStart := now.Add(-60 * time.Second)
|
||||
|
||||
rl.mu.Lock()
|
||||
defer rl.mu.Unlock()
|
||||
|
||||
existing := rl.buckets[keyID]
|
||||
kept := existing[:0]
|
||||
for _, ts := range existing {
|
||||
if ts.After(windowStart) {
|
||||
kept = append(kept, ts)
|
||||
}
|
||||
}
|
||||
|
||||
if len(kept) >= limit {
|
||||
rl.buckets[keyID] = kept
|
||||
oldest := kept[0]
|
||||
resetAt := oldest.Add(60 * time.Second)
|
||||
retrySec := int(time.Until(resetAt).Seconds())
|
||||
if now != (time.Time{}) {
|
||||
retrySec = int(resetAt.Sub(now).Seconds())
|
||||
}
|
||||
if retrySec < 1 {
|
||||
retrySec = 1
|
||||
}
|
||||
return RateLimitResult{
|
||||
Allowed: false,
|
||||
Limit: limit,
|
||||
Remaining: 0,
|
||||
ResetUnix: resetAt.Unix(),
|
||||
RetryAfter: retrySec,
|
||||
}
|
||||
}
|
||||
|
||||
kept = append(kept, now)
|
||||
rl.buckets[keyID] = kept
|
||||
resetAt := kept[0].Add(60 * time.Second)
|
||||
return RateLimitResult{
|
||||
Allowed: true,
|
||||
Limit: limit,
|
||||
Remaining: limit - len(kept),
|
||||
ResetUnix: resetAt.Unix(),
|
||||
}
|
||||
}
|
||||
|
||||
func BuildRateLimitHeaders(res RateLimitResult) map[string]string {
|
||||
h := map[string]string{
|
||||
"X-RateLimit-Limit": strconv.Itoa(res.Limit),
|
||||
"X-RateLimit-Remaining": strconv.Itoa(res.Remaining),
|
||||
"X-RateLimit-Reset": strconv.FormatInt(res.ResetUnix, 10),
|
||||
}
|
||||
if !res.Allowed {
|
||||
retry := res.RetryAfter
|
||||
if retry < 1 {
|
||||
retry = 1
|
||||
}
|
||||
h["Retry-After"] = strconv.Itoa(retry)
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
jwtSecret []byte
|
||||
isProduction bool
|
||||
pool *pgxpool.Pool
|
||||
limiter *RateLimiter
|
||||
}
|
||||
|
||||
func NewService(jwtSecret string, isProduction bool, pool *pgxpool.Pool) *Service {
|
||||
return &Service{
|
||||
jwtSecret: []byte(jwtSecret),
|
||||
isProduction: isProduction,
|
||||
pool: pool,
|
||||
limiter: NewRateLimiter(),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) SignSession(p SessionPayload) (string, error) {
|
||||
now := time.Now()
|
||||
claims := jwtClaims{
|
||||
UserID: p.UserID,
|
||||
Email: p.Email,
|
||||
Name: p.Name,
|
||||
Role: p.Role,
|
||||
ClienteID: p.ClienteID,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
IssuedAt: jwt.NewNumericDate(now),
|
||||
ExpiresAt: jwt.NewNumericDate(now.Add(SessionTTL)),
|
||||
},
|
||||
}
|
||||
tok := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return tok.SignedString(s.jwtSecret)
|
||||
}
|
||||
|
||||
func (s *Service) VerifySession(tokenStr string) (*SessionPayload, error) {
|
||||
if tokenStr == "" {
|
||||
return nil, errors.New("empty token")
|
||||
}
|
||||
tok, err := jwt.ParseWithClaims(tokenStr, &jwtClaims{}, func(t *jwt.Token) (any, error) {
|
||||
if t.Method.Alg() != jwt.SigningMethodHS256.Alg() {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
|
||||
}
|
||||
return s.jwtSecret, nil
|
||||
})
|
||||
if err != nil || !tok.Valid {
|
||||
return nil, errors.New("invalid token")
|
||||
}
|
||||
c, ok := tok.Claims.(*jwtClaims)
|
||||
if !ok || c.UserID == "" {
|
||||
return nil, errors.New("invalid claims")
|
||||
}
|
||||
role := c.Role
|
||||
if role == "" {
|
||||
role = "asesor"
|
||||
}
|
||||
return &SessionPayload{
|
||||
UserID: c.UserID,
|
||||
Email: c.Email,
|
||||
Name: c.Name,
|
||||
Role: role,
|
||||
ClienteID: c.ClienteID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Service) SetSessionCookie(w http.ResponseWriter, token string) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: SessionCookieName,
|
||||
Value: token,
|
||||
Path: "/",
|
||||
MaxAge: int(SessionTTL.Seconds()),
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
Secure: s.isProduction,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) ClearSessionCookie(w http.ResponseWriter) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: SessionCookieName,
|
||||
Value: "",
|
||||
Path: "/",
|
||||
MaxAge: -1,
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
Secure: s.isProduction,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) SessionFromRequest(r *http.Request) (*SessionPayload, bool) {
|
||||
c, err := r.Cookie(SessionCookieName)
|
||||
if err != nil || c.Value == "" {
|
||||
return nil, false
|
||||
}
|
||||
p, err := s.VerifySession(c.Value)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
return p, true
|
||||
}
|
||||
|
||||
func ExtractAPIKey(r *http.Request) string {
|
||||
if k := strings.TrimSpace(r.Header.Get("X-API-Key")); k != "" {
|
||||
return k
|
||||
}
|
||||
authz := strings.TrimSpace(r.Header.Get("Authorization"))
|
||||
if len(authz) > 7 && strings.EqualFold(authz[:7], "bearer ") {
|
||||
return strings.TrimSpace(authz[7:])
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type RequireOptions struct {
|
||||
AdminOnly bool
|
||||
StaffOnly bool
|
||||
AllowCliente bool
|
||||
Scopes []string
|
||||
ScopeMode string // "any" (default) | "all"
|
||||
AccionBloqueo string
|
||||
RecursoTipo string
|
||||
RecursoID string
|
||||
}
|
||||
|
||||
// RequireActor authenticates either cookie session (priority) or AgentApiKey,
|
||||
// enforces role/scope/rate-limit rules, logs failures to AuditLog, and writes the HTTP error response if denied.
|
||||
func (s *Service) RequireActor(w http.ResponseWriter, r *http.Request, opts RequireOptions) (*Actor, bool) {
|
||||
var actor *Actor
|
||||
|
||||
// 1. Cookie JWT takes priority
|
||||
if sess, ok := s.SessionFromRequest(r); ok {
|
||||
actor = &Actor{
|
||||
Type: "user",
|
||||
UserID: sess.UserID,
|
||||
Email: sess.Email,
|
||||
Name: sess.Name,
|
||||
Role: sess.Role,
|
||||
ClienteID: sess.ClienteID,
|
||||
}
|
||||
} else if rawKey := ExtractAPIKey(r); rawKey != "" {
|
||||
// 2. Agent API Key lookup via SHA-256
|
||||
keyHash := HashSecret(rawKey)
|
||||
var id, nombre string
|
||||
var scopes []string
|
||||
var rateLimit int
|
||||
var lastUsedAt *time.Time
|
||||
err := s.pool.QueryRow(r.Context(), `
|
||||
SELECT "id", "nombre", "scopes", "rateLimitPerMin", "lastUsedAt"
|
||||
FROM "AgentApiKey"
|
||||
WHERE "keyHash" = $1 AND "activo" = true AND "revokedAt" IS NULL
|
||||
`, keyHash).Scan(&id, &nombre, &scopes, &rateLimit, &lastUsedAt)
|
||||
if err != nil {
|
||||
if !errors.Is(err, pgx.ErrNoRows) {
|
||||
writeAuthJSON(w, http.StatusInternalServerError, map[string]any{"error": "Error validando credenciales"})
|
||||
return nil, false
|
||||
}
|
||||
audit.Registrar(r.Context(), s.pool, audit.Entry{
|
||||
ActorTipo: "agent",
|
||||
ActorNombre: "clave_invalida",
|
||||
Accion: "auth.api_key_invalida",
|
||||
RecursoTipo: firstOr(opts.RecursoTipo, "auth"),
|
||||
RecursoID: opts.RecursoID,
|
||||
IP: audit.ClientIP(r),
|
||||
RequestID: audit.RequestID(r),
|
||||
Exito: false,
|
||||
Detalle: map[string]any{"path": r.URL.Path, "method": r.Method},
|
||||
})
|
||||
writeAuthJSON(w, http.StatusUnauthorized, map[string]any{"error": "API key invalida o revocada"})
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// Rate limit check
|
||||
rlRes := s.limiter.Check(id, rateLimit, time.Now())
|
||||
headers := BuildRateLimitHeaders(rlRes)
|
||||
if !rlRes.Allowed {
|
||||
for k, v := range headers {
|
||||
w.Header().Set(k, v)
|
||||
}
|
||||
audit.Registrar(r.Context(), s.pool, audit.Entry{
|
||||
ActorTipo: "agent",
|
||||
ActorID: id,
|
||||
ActorNombre: nombre,
|
||||
Accion: "auth.rate_limit",
|
||||
RecursoTipo: firstOr(opts.RecursoTipo, "auth"),
|
||||
RecursoID: opts.RecursoID,
|
||||
IP: audit.ClientIP(r),
|
||||
RequestID: audit.RequestID(r),
|
||||
Exito: false,
|
||||
Detalle: map[string]any{"limit": rateLimit, "path": r.URL.Path},
|
||||
})
|
||||
writeAuthJSON(w, http.StatusTooManyRequests, map[string]any{"error": "Limite de peticiones por minuto excedido"})
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// Throttled async lastUsedAt update (>60s)
|
||||
if lastUsedAt == nil || time.Since(*lastUsedAt) > 60*time.Second {
|
||||
go func(keyID string) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
_, _ = s.pool.Exec(ctx, `UPDATE "AgentApiKey" SET "lastUsedAt" = NOW(), "updatedAt" = NOW() WHERE "id" = $1`, keyID)
|
||||
}(id)
|
||||
}
|
||||
|
||||
actor = &Actor{
|
||||
Type: "agent",
|
||||
KeyID: id,
|
||||
KeyNombre: nombre,
|
||||
Scopes: scopes,
|
||||
RateLimitPerMin: rateLimit,
|
||||
RateHeaders: headers,
|
||||
}
|
||||
} else {
|
||||
writeAuthJSON(w, http.StatusUnauthorized, map[string]any{"error": "No autenticado"})
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// Role / Scope enforcement
|
||||
if opts.AdminOnly && !actor.IsAdmin() {
|
||||
tipo, aid, anombre := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.pool, audit.Entry{
|
||||
ActorTipo: tipo,
|
||||
ActorID: aid,
|
||||
ActorNombre: anombre,
|
||||
Accion: firstOr(opts.AccionBloqueo, "auth.admin_requerido"),
|
||||
RecursoTipo: firstOr(opts.RecursoTipo, "auth"),
|
||||
RecursoID: opts.RecursoID,
|
||||
IP: audit.ClientIP(r),
|
||||
RequestID: audit.RequestID(r),
|
||||
Exito: false,
|
||||
Detalle: map[string]any{"path": r.URL.Path, "method": r.Method},
|
||||
})
|
||||
writeAuthJSON(w, http.StatusForbidden, map[string]any{"error": "Solo un administrador humano puede realizar esta accion"})
|
||||
return nil, false
|
||||
}
|
||||
|
||||
if opts.StaffOnly && !actor.IsStaff() {
|
||||
tipo, aid, anombre := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.pool, audit.Entry{
|
||||
ActorTipo: tipo,
|
||||
ActorID: aid,
|
||||
ActorNombre: anombre,
|
||||
Accion: firstOr(opts.AccionBloqueo, "auth.staff_requerido"),
|
||||
RecursoTipo: firstOr(opts.RecursoTipo, "auth"),
|
||||
RecursoID: opts.RecursoID,
|
||||
IP: audit.ClientIP(r),
|
||||
RequestID: audit.RequestID(r),
|
||||
Exito: false,
|
||||
Detalle: map[string]any{"path": r.URL.Path, "method": r.Method},
|
||||
})
|
||||
writeAuthJSON(w, http.StatusForbidden, map[string]any{"error": "Acceso exclusivo para equipo interno"})
|
||||
return nil, false
|
||||
}
|
||||
|
||||
if actor.IsCliente() && !opts.AllowCliente {
|
||||
writeAuthJSON(w, http.StatusForbidden, map[string]any{"error": "Acceso no permitido para cuentas de cliente"})
|
||||
return nil, false
|
||||
}
|
||||
|
||||
if len(opts.Scopes) > 0 && !actor.IsCliente() {
|
||||
mode := opts.ScopeMode
|
||||
if mode == "" {
|
||||
mode = "any"
|
||||
}
|
||||
if !actor.HasScopes(opts.Scopes, mode) {
|
||||
tipo, aid, anombre := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.pool, audit.Entry{
|
||||
ActorTipo: tipo,
|
||||
ActorID: aid,
|
||||
ActorNombre: anombre,
|
||||
Accion: firstOr(opts.AccionBloqueo, "auth.scope_insuficiente"),
|
||||
RecursoTipo: firstOr(opts.RecursoTipo, "auth"),
|
||||
RecursoID: opts.RecursoID,
|
||||
IP: audit.ClientIP(r),
|
||||
RequestID: audit.RequestID(r),
|
||||
Exito: false,
|
||||
Detalle: map[string]any{"requiredScopes": opts.Scopes, "path": r.URL.Path},
|
||||
})
|
||||
writeAuthJSON(w, http.StatusForbidden, map[string]any{
|
||||
"error": "Alcance insuficiente para esta operacion",
|
||||
"requiredScopes": opts.Scopes,
|
||||
})
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
|
||||
actor.ApplyHeaders(w)
|
||||
return actor, true
|
||||
}
|
||||
|
||||
// RequireCliente enforces a valid cookie session with role == "cliente" and non-empty clienteId.
|
||||
func (s *Service) RequireCliente(w http.ResponseWriter, r *http.Request) (*SessionPayload, bool) {
|
||||
sess, ok := s.SessionFromRequest(r)
|
||||
if !ok {
|
||||
writeAuthJSON(w, http.StatusUnauthorized, map[string]any{"error": "No autenticado"})
|
||||
return nil, false
|
||||
}
|
||||
if sess.Role != "cliente" || sess.ClienteID == "" {
|
||||
writeAuthJSON(w, http.StatusForbidden, map[string]any{"error": "Acceso exclusivo para clientes"})
|
||||
return nil, false
|
||||
}
|
||||
return sess, true
|
||||
}
|
||||
|
||||
func firstOr(v, fallback string) string {
|
||||
if v != "" {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func writeAuthJSON(w http.ResponseWriter, status int, payload any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(payload)
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestAPIKeyAndScopes(t *testing.T) {
|
||||
raw, pref, hash := GenerateAPIKey()
|
||||
if !strings.HasPrefix(raw, APIKeyPrefix) || len(raw) != 73 {
|
||||
t.Fatalf("unexpected raw key format: len=%d", len(raw))
|
||||
}
|
||||
if pref != raw[:14] || len(hash) != 64 || hash != HashSecret(raw) {
|
||||
t.Fatalf("hash/prefix mismatch")
|
||||
}
|
||||
if len(AgentScopes) != 9 {
|
||||
t.Fatalf("expected 9 scopes, got %d", len(AgentScopes))
|
||||
}
|
||||
for _, s := range AgentScopes {
|
||||
if strings.Contains(s, "aprobar") {
|
||||
t.Fatalf("approval scope must never exist: %s", s)
|
||||
}
|
||||
}
|
||||
|
||||
entrega := &Actor{Type: "agent", Scopes: []string{"cotizaciones:leer_aceptadas"}}
|
||||
if !entrega.EsAgenteSoloAceptadas() {
|
||||
t.Fatalf("expected EsAgenteSoloAceptadas=true")
|
||||
}
|
||||
ops := &Actor{Type: "agent", Scopes: []string{"cotizaciones:leer", "cotizaciones:leer_aceptadas"}}
|
||||
if ops.EsAgenteSoloAceptadas() {
|
||||
t.Fatalf("expected EsAgenteSoloAceptadas=false when cotizaciones:leer present")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRateLimiter(t *testing.T) {
|
||||
rl := NewRateLimiter()
|
||||
now := time.Now()
|
||||
for i := 0; i < 3; i++ {
|
||||
res := rl.Check("k1", 3, now.Add(time.Duration(i)*time.Second))
|
||||
if !res.Allowed {
|
||||
t.Fatalf("request %d should be allowed", i)
|
||||
}
|
||||
}
|
||||
blocked := rl.Check("k1", 3, now.Add(4*time.Second))
|
||||
if blocked.Allowed || blocked.Remaining != 0 {
|
||||
t.Fatalf("4th request should be blocked: %+v", blocked)
|
||||
}
|
||||
afterWindow := rl.Check("k1", 3, now.Add(65*time.Second))
|
||||
if !afterWindow.Allowed {
|
||||
t.Fatalf("request after 60s window should be allowed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCoincideContacto(t *testing.T) {
|
||||
if !CoincideContacto("[email protected]", "[email protected]", "") {
|
||||
t.Fatal("case-insensitive email should match")
|
||||
}
|
||||
if !CoincideContacto("+52 1 55 1234-5678", "", "5512345678") {
|
||||
t.Fatal("last 10 phone digits should match")
|
||||
}
|
||||
if CoincideContacto("[email protected]", "[email protected]", "5512345678") {
|
||||
t.Fatal("mismatched contact should fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestJWTSignAndVerify(t *testing.T) {
|
||||
svc := NewService("super-secret-test-key", false, nil)
|
||||
tok, err := svc.SignSession(SessionPayload{
|
||||
UserID: "u1", Email: "[email protected]", Name: "Admin", Role: "admin",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("sign failed: %v", err)
|
||||
}
|
||||
got, err := svc.VerifySession(tok)
|
||||
if err != nil || got.UserID != "u1" || got.Role != "admin" {
|
||||
t.Fatalf("verify failed: %+v, err=%v", got, err)
|
||||
}
|
||||
}
|
||||
+1131
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,399 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func runCLI(t *testing.T, args []string, stdin string) (int, string, string) {
|
||||
t.Helper()
|
||||
var stdout, stderr bytes.Buffer
|
||||
code := runWithIO(args, strings.NewReader(stdin), &stdout, &stderr)
|
||||
return code, stdout.String(), stderr.String()
|
||||
}
|
||||
|
||||
func TestEsquemaAndSchemaAlias(t *testing.T) {
|
||||
for _, cmd := range []string{"esquema", "schema"} {
|
||||
code, stdout, stderr := runCLI(t, []string{cmd}, "")
|
||||
if code != ExitOK {
|
||||
t.Fatalf("%s: expected exit 0, got %d (stderr=%s)", cmd, code, stderr)
|
||||
}
|
||||
if stderr != "" {
|
||||
t.Fatalf("%s: expected empty stderr, got %s", cmd, stderr)
|
||||
}
|
||||
|
||||
var doc map[string]any
|
||||
if err := json.Unmarshal([]byte(stdout), &doc); err != nil {
|
||||
t.Fatalf("%s: invalid JSON output: %v", cmd, err)
|
||||
}
|
||||
if doc["nombre"] != "cotizador" || doc["version"] != Version {
|
||||
t.Errorf("%s: unexpected nombre/version: %v / %v", cmd, doc["nombre"], doc["version"])
|
||||
}
|
||||
|
||||
cmds, ok := doc["comandos"].([]any)
|
||||
if !ok {
|
||||
t.Fatalf("%s: comandos missing or not array", cmd)
|
||||
}
|
||||
if len(cmds) != 30 {
|
||||
t.Fatalf("%s: expected 30 commands in esquema, got %d", cmd, len(cmds))
|
||||
}
|
||||
|
||||
// Verify all expected command names exist
|
||||
names := make(map[string]bool)
|
||||
for _, item := range cmds {
|
||||
m := item.(map[string]any)
|
||||
names[m["comando"].(string)] = true
|
||||
}
|
||||
required := []string{
|
||||
"login", "logout", "whoami",
|
||||
"servicios listar", "servicios ver", "servicios crear", "servicios editar",
|
||||
"servicios archivar", "servicios activar", "servicios eliminar",
|
||||
"categorias listar", "categorias crear",
|
||||
"paquetes listar", "paquetes ver",
|
||||
"clientes listar", "clientes crear", "clientes editar",
|
||||
"cotizaciones listar", "cotizaciones ver", "cotizaciones crear",
|
||||
"cotizaciones estado", "cotizaciones pdf", "cotizaciones excel", "cotizaciones eliminar",
|
||||
"horas listar", "horas registrar",
|
||||
"api", "esquema", "ayuda", "version",
|
||||
}
|
||||
for _, r := range required {
|
||||
if !names[r] {
|
||||
t.Errorf("%s: missing command %q in esquema", cmd, r)
|
||||
}
|
||||
}
|
||||
|
||||
codigos, ok := doc["codigosSalida"].(map[string]any)
|
||||
if !ok || len(codigos) != 8 {
|
||||
t.Errorf("%s: expected 8 codigosSalida (0..7), got %v", cmd, codigos)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVersionAndHelp(t *testing.T) {
|
||||
code, stdout, _ := runCLI(t, []string{"--version", "--compacto"}, "")
|
||||
if code != ExitOK {
|
||||
t.Fatalf("expected 0, got %d", code)
|
||||
}
|
||||
if strings.TrimSpace(stdout) != `{"version":"1.0.0"}` {
|
||||
t.Fatalf("unexpected compact version output: %q", stdout)
|
||||
}
|
||||
|
||||
code, stdout, _ = runCLI(t, []string{}, "")
|
||||
if code != ExitOK || !strings.Contains(stdout, "FLAGS GLOBALES") {
|
||||
t.Fatalf("empty args should print general help, got code=%d stdout=%q", code, stdout)
|
||||
}
|
||||
|
||||
code, stdout, _ = runCLI(t, []string{"servicios", "crear", "-h"}, "")
|
||||
if code != ExitOK || !strings.Contains(stdout, "POST /api/catalogo") {
|
||||
t.Fatalf("-h should print command help, got code=%d stdout=%q", code, stdout)
|
||||
}
|
||||
|
||||
code, stdout, _ = runCLI(t, []string{"ayuda", "cotizaciones", "crear"}, "")
|
||||
if code != ExitOK || !strings.Contains(stdout, "POST /api/cotizaciones") {
|
||||
t.Fatalf("ayuda <cmd> failed, got code=%d stdout=%q", code, stdout)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlagParsingAndUnknownFlags(t *testing.T) {
|
||||
// Unknown flag on valid command -> ExitUso (2) + JSON stderr
|
||||
code, stdout, stderr := runCLI(t, []string{"servicios", "listar", "--bandera-invalida", "123"}, "")
|
||||
if code != ExitUso {
|
||||
t.Fatalf("expected ExitUso (2), got %d", code)
|
||||
}
|
||||
if stdout != "" {
|
||||
t.Fatalf("expected empty stdout on error, got %q", stdout)
|
||||
}
|
||||
var errDoc map[string]any
|
||||
if err := json.Unmarshal([]byte(stderr), &errDoc); err != nil {
|
||||
t.Fatalf("expected JSON stderr, got %q: %v", stderr, err)
|
||||
}
|
||||
if errDoc["ok"] != false || int(errDoc["codigo"].(float64)) != ExitUso {
|
||||
t.Fatalf("unexpected error JSON: %+v", errDoc)
|
||||
}
|
||||
|
||||
// Flag belonging to another command -> ExitUso (2)
|
||||
code, _, stderr = runCLI(t, []string{"categorias", "listar", "--precio", "100"}, "")
|
||||
if code != ExitUso || !strings.Contains(stderr, "--precio") {
|
||||
t.Fatalf("expected ExitUso mentioning --precio, got code=%d stderr=%s", code, stderr)
|
||||
}
|
||||
|
||||
// Unknown command -> ExitUso (2)
|
||||
code, _, stderr = runCLI(t, []string{"noexiste"}, "")
|
||||
if code != ExitUso || !strings.Contains(stderr, "Comando desconocido") {
|
||||
t.Fatalf("expected ExitUso for unknown command, got code=%d stderr=%s", code, stderr)
|
||||
}
|
||||
|
||||
// Invalid --formato -> ExitUso (2)
|
||||
code, _, _ = runCLI(t, []string{"version", "--formato", "xml"}, "")
|
||||
if code != ExitUso {
|
||||
t.Fatalf("expected ExitUso for invalid --formato, got %d", code)
|
||||
}
|
||||
|
||||
// Destructive delete without --confirmar -> ExitUso (2)
|
||||
code, _, stderr = runCLI(t, []string{"servicios", "eliminar", "abc123"}, "")
|
||||
if code != ExitUso || !strings.Contains(stderr, "--confirmar") {
|
||||
t.Fatalf("expected ExitUso requiring --confirmar, got code=%d stderr=%s", code, stderr)
|
||||
}
|
||||
|
||||
// --no-compacto boolean negation
|
||||
pos, flags, err := parsearArgs([]string{"version", "--no-compacto", "--entregable=Uno", "--entregable", "Dos"}, append(flagsGlobales, flagsServicio...))
|
||||
if err != nil {
|
||||
t.Fatalf("parsearArgs failed: %v", err)
|
||||
}
|
||||
if len(pos) != 1 || pos[0] != "version" {
|
||||
t.Fatalf("unexpected positionals: %v", pos)
|
||||
}
|
||||
if !flags.Has("compacto") || flags.Bool("compacto") {
|
||||
t.Fatalf("expected compacto=false")
|
||||
}
|
||||
if got := flags.List("entregable"); len(got) != 2 || got[0] != "Uno" || got[1] != "Dos" {
|
||||
t.Fatalf("expected 2 repeatable entregables, got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDryRunWriteCommands(t *testing.T) {
|
||||
// 1. servicios crear --dry-run (with repeatable --entregable and formatted price)
|
||||
code, stdout, stderr := runCLI(t, []string{
|
||||
"servicios", "crear",
|
||||
"--url", "http://example.test",
|
||||
"--nombre", "Auditoria SEO",
|
||||
"--fase", "0",
|
||||
"--tipo-pago", "unico",
|
||||
"--precio", "$6,500",
|
||||
"--entregable", "Reporte PDF",
|
||||
"--entregable", "Sesion 1h",
|
||||
"--dry-run",
|
||||
}, "")
|
||||
if code != ExitOK {
|
||||
t.Fatalf("servicios crear --dry-run failed: code=%d stderr=%s", code, stderr)
|
||||
}
|
||||
var dr map[string]any
|
||||
if err := json.Unmarshal([]byte(stdout), &dr); err != nil {
|
||||
t.Fatalf("invalid dry-run JSON: %v", err)
|
||||
}
|
||||
if dr["dryRun"] != true || dr["metodo"] != "POST" || dr["url"] != "http://example.test/api/catalogo" {
|
||||
t.Fatalf("unexpected dry-run payload: %+v", dr)
|
||||
}
|
||||
cuerpo := dr["cuerpo"].(map[string]any)
|
||||
if cuerpo["nombre"] != "Auditoria SEO" || cuerpo["precioBase"].(float64) != 6500 {
|
||||
t.Fatalf("unexpected dry-run cuerpo: %+v", cuerpo)
|
||||
}
|
||||
|
||||
// 2. cotizaciones crear with --partida-horas and --dry-run
|
||||
code, stdout, stderr = runCLI(t, []string{
|
||||
"cotizaciones", "crear",
|
||||
"--url", "http://example.test",
|
||||
"--cliente", "Ana Ruiz",
|
||||
"--empresa", "Panaderia Sol",
|
||||
"--partida-horas", "Soporte tecnico|10|700",
|
||||
"--sin-iva",
|
||||
"--dry-run",
|
||||
}, "")
|
||||
if code != ExitOK {
|
||||
t.Fatalf("cotizaciones crear --dry-run failed: code=%d stderr=%s", code, stderr)
|
||||
}
|
||||
if err := json.Unmarshal([]byte(stdout), &dr); err != nil {
|
||||
t.Fatalf("invalid dry-run JSON: %v", err)
|
||||
}
|
||||
cuerpo = dr["cuerpo"].(map[string]any)
|
||||
if cuerpo["incluirIva"] != false {
|
||||
t.Errorf("expected incluirIva=false, got %v", cuerpo["incluirIva"])
|
||||
}
|
||||
partidas := cuerpo["servicios"].([]any)
|
||||
if len(partidas) != 1 {
|
||||
t.Fatalf("expected 1 partida, got %d", len(partidas))
|
||||
}
|
||||
p0 := partidas[0].(map[string]any)
|
||||
if p0["precio"].(float64) != 7000 || p0["modeloCobro"] != "horas" {
|
||||
t.Errorf("unexpected partida por horas: %+v", p0)
|
||||
}
|
||||
|
||||
// 3. servicios eliminar --dry-run works without --confirmar
|
||||
code, stdout, stderr = runCLI(t, []string{
|
||||
"servicios", "eliminar", "srv-123",
|
||||
"--url", "http://example.test",
|
||||
"--dry-run",
|
||||
}, "")
|
||||
if code != ExitOK {
|
||||
t.Fatalf("servicios eliminar --dry-run failed: code=%d stderr=%s", code, stderr)
|
||||
}
|
||||
if !strings.Contains(stdout, `"metodo": "DELETE"`) {
|
||||
t.Errorf("expected DELETE in dry-run output: %s", stdout)
|
||||
}
|
||||
|
||||
// 4. api POST with --datos from stdin and --dry-run
|
||||
code, stdout, stderr = runCLI(t, []string{
|
||||
"api", "POST", "api/cobros/recordatorios",
|
||||
"--url", "http://example.test",
|
||||
"--datos", "-",
|
||||
"--dry-run",
|
||||
}, `{"clienteId":"cli-1"}`)
|
||||
if code != ExitOK {
|
||||
t.Fatalf("api POST --datos - --dry-run failed: code=%d stderr=%s", code, stderr)
|
||||
}
|
||||
if !strings.Contains(stdout, `"clienteId": "cli-1"`) || !strings.Contains(stdout, "http://example.test/api/cobros/recordatorios") {
|
||||
t.Errorf("unexpected api dry-run output: %s", stdout)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionLoginAutoReauthAndExitCodes(t *testing.T) {
|
||||
tmpHome := t.TempDir()
|
||||
t.Setenv("COTIZADOR_HOME", tmpHome)
|
||||
t.Setenv("COTIZADOR_TOKEN", "")
|
||||
t.Setenv("COTIZADOR_EMAIL", "")
|
||||
t.Setenv("COTIZADOR_PASSWORD", "")
|
||||
|
||||
var loginCalls atomic.Int32
|
||||
var meCalls atomic.Int32
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.Method == http.MethodPost && r.URL.Path == "/api/auth/login":
|
||||
loginCalls.Add(1)
|
||||
var body map[string]string
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
if body["email"] == "[email protected]" {
|
||||
http.SetCookie(w, &http.Cookie{Name: "cotizador-session", Value: "tok-cli"})
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"user": map[string]any{"email": "[email protected]", "role": "cliente"}})
|
||||
return
|
||||
}
|
||||
if body["password"] != "secret" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"error": "Credenciales invalidas"})
|
||||
return
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: "cotizador-session", Value: "jwt-staff-token"})
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"user": map[string]any{"email": body["email"], "name": "Admin", "role": "admin"}})
|
||||
|
||||
case r.Method == http.MethodGet && r.URL.Path == "/api/auth/me":
|
||||
n := meCalls.Add(1)
|
||||
c, err := r.Cookie("cotizador-session")
|
||||
if err != nil || c.Value != "jwt-staff-token" || n == 2 {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"error": "No autenticado"})
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"user": map[string]any{"email": "[email protected]", "role": "admin"}})
|
||||
|
||||
case r.URL.Path == "/api/catalogo" && r.Method == http.MethodGet:
|
||||
_ = json.NewEncoder(w).Encode([]map[string]any{
|
||||
{"id": "s1", "nombre": "SEO Basico", "precioBase": 2900, "extra": map[string]any{"nested": "val"}},
|
||||
{"id": "s2", "nombre": "Google Ads", "precioBase": 4900, "extra": map[string]any{"nested": "val2"}},
|
||||
})
|
||||
|
||||
case r.URL.Path == "/api/test/400":
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"error": "invalido", "detalles": []string{"campo"}})
|
||||
case r.URL.Path == "/api/test/404":
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"error": "no existe"})
|
||||
case r.URL.Path == "/api/test/409":
|
||||
w.WriteHeader(http.StatusConflict)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"error": "duplicado"})
|
||||
case r.URL.Path == "/api/test/500":
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"error": "boom"})
|
||||
case r.URL.Path == "/api/cotizaciones/cot-1":
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"id": "cot-1", "numero": "UJ2605AG001"})
|
||||
case r.URL.Path == "/api/export/pdf/cot-1":
|
||||
w.Header().Set("Content-Type", "application/pdf")
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="UJ2605AG001.pdf"`)
|
||||
_, _ = w.Write([]byte("%PDF-1.4 mock"))
|
||||
default:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
// Cliente role rejected on login -> ExitAuth (3)
|
||||
code, _, _ := runCLI(t, []string{"login", "--url", srv.URL, "--email", "[email protected]", "--password", "x"}, "")
|
||||
if code != ExitAuth {
|
||||
t.Fatalf("expected ExitAuth for cliente role, got %d", code)
|
||||
}
|
||||
|
||||
// Staff login via --password-stdin persists sesiones.json
|
||||
code, stdout, stderr := runCLI(t, []string{"login", "--url", srv.URL, "--email", "[email protected]", "--password-stdin"}, "secret\n")
|
||||
if code != ExitOK {
|
||||
t.Fatalf("login failed: code=%d stderr=%s", code, stderr)
|
||||
}
|
||||
if !strings.Contains(stdout, `"ok": true`) {
|
||||
t.Fatalf("unexpected login stdout: %s", stdout)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(tmpHome, "sesiones.json")); err != nil {
|
||||
t.Fatalf("expected sesiones.json to be written: %v", err)
|
||||
}
|
||||
|
||||
// whoami uses saved cookie (meCalls == 1)
|
||||
code, stdout, stderr = runCLI(t, []string{"whoami", "--url", srv.URL}, "")
|
||||
if code != ExitOK || !strings.Contains(stdout, "[email protected]") {
|
||||
t.Fatalf("whoami failed: code=%d stdout=%s stderr=%s", code, stdout, stderr)
|
||||
}
|
||||
|
||||
// Auto-reauth on 401 when COTIZADOR_EMAIL/PASSWORD are set (meCalls == 2 returns 401, triggers login, retry meCalls == 3 succeeds)
|
||||
t.Setenv("COTIZADOR_EMAIL", "[email protected]")
|
||||
t.Setenv("COTIZADOR_PASSWORD", "secret")
|
||||
beforeLogins := loginCalls.Load()
|
||||
code, stdout, stderr = runCLI(t, []string{"whoami", "--url", srv.URL}, "")
|
||||
if code != ExitOK {
|
||||
t.Fatalf("auto-reauth whoami failed: code=%d stderr=%s", code, stderr)
|
||||
}
|
||||
if loginCalls.Load() != beforeLogins+1 {
|
||||
t.Fatalf("expected 1 auto-reauth login call, got delta %d", loginCalls.Load()-beforeLogins)
|
||||
}
|
||||
|
||||
// --campos + --formato tabla
|
||||
code, stdout, stderr = runCLI(t, []string{"servicios", "listar", "--url", srv.URL, "--campos", "id,nombre,extra.nested", "--formato", "tabla"}, "")
|
||||
if code != ExitOK {
|
||||
t.Fatalf("servicios listar tabla failed: code=%d stderr=%s", code, stderr)
|
||||
}
|
||||
if !strings.Contains(stdout, "SEO Basico") || !strings.Contains(stdout, "extra.nested") || !strings.Contains(stdout, "val2") {
|
||||
t.Fatalf("unexpected table output:\n%s", stdout)
|
||||
}
|
||||
|
||||
// Status-to-exit-code mapping
|
||||
cases := []struct {
|
||||
path string
|
||||
want int
|
||||
}{
|
||||
{"/api/test/400", ExitValidacion},
|
||||
{"/api/test/404", ExitNoEncontrado},
|
||||
{"/api/test/409", ExitConflicto},
|
||||
{"/api/test/500", ExitError},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
code, _, _ = runCLI(t, []string{"api", "GET", tc.path, "--url", srv.URL}, "")
|
||||
if code != tc.want {
|
||||
t.Errorf("%s: expected exit %d, got %d", tc.path, tc.want, code)
|
||||
}
|
||||
}
|
||||
|
||||
// Binary PDF download
|
||||
outPDF := filepath.Join(tmpHome, "out.pdf")
|
||||
code, stdout, stderr = runCLI(t, []string{"cotizaciones", "pdf", "cot-1", "--url", srv.URL, "--salida", outPDF}, "")
|
||||
if code != ExitOK {
|
||||
t.Fatalf("cotizaciones pdf failed: code=%d stderr=%s", code, stderr)
|
||||
}
|
||||
b, err := os.ReadFile(outPDF)
|
||||
if err != nil || string(b) != "%PDF-1.4 mock" {
|
||||
t.Fatalf("downloaded PDF mismatch: err=%v content=%q", err, string(b))
|
||||
}
|
||||
|
||||
// Logout removes saved session
|
||||
code, stdout, _ = runCLI(t, []string{"logout", "--url", srv.URL}, "")
|
||||
if code != ExitOK || !strings.Contains(stdout, `"sesionBorrada": true`) {
|
||||
t.Fatalf("logout failed: code=%d stdout=%s", code, stdout)
|
||||
}
|
||||
|
||||
// Network error -> ExitRed (7)
|
||||
code, _, stderr = runCLI(t, []string{"whoami", "--url", "http://127.0.0.1:1"}, "")
|
||||
if code != ExitRed {
|
||||
t.Fatalf("expected ExitRed (7) on unreachable port, got %d (stderr=%s)", code, stderr)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,145 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Port string
|
||||
Env string
|
||||
|
||||
// PostgreSQL (individual params matching docker-compose & existing .env)
|
||||
DBHost string
|
||||
DBPort int
|
||||
DBUser string
|
||||
DBPassword string
|
||||
DBName string
|
||||
|
||||
// Auth
|
||||
JWTSecret string
|
||||
|
||||
// Public URL (used in emails & push links; runtime env)
|
||||
AppURL string
|
||||
|
||||
// Seed
|
||||
RunSeed bool
|
||||
SeedAdminEmail string
|
||||
SeedAdminPassword string
|
||||
SeedAdminName string
|
||||
SeedAsesorEmail string
|
||||
SeedAsesorPass string
|
||||
SeedAsesorName string
|
||||
|
||||
// MiniMax AI (Anthropic-compatible endpoint)
|
||||
MinimaxAPIKey string
|
||||
MinimaxBaseURL string
|
||||
MinimaxModel string
|
||||
|
||||
// Web Push (VAPID)
|
||||
VAPIDPublicKey string
|
||||
VAPIDPrivateKey string
|
||||
VAPIDSubject string
|
||||
|
||||
// SMTP
|
||||
SMTPHost string
|
||||
SMTPPort int
|
||||
SMTPUser string
|
||||
SMTPPass string
|
||||
SMTPFrom string
|
||||
SMTPFromName string
|
||||
|
||||
// Cobros & Uploads
|
||||
CobrosRecordatorioDias int
|
||||
UploadDir string
|
||||
|
||||
// Notifications & Webhooks
|
||||
AdminNotifyEmail string
|
||||
WebhookN8NURL string
|
||||
WebhookN8NSecret string
|
||||
WebhookWhatsAppSendURL string
|
||||
}
|
||||
|
||||
func Load() (*Config, error) {
|
||||
_ = godotenv.Load()
|
||||
|
||||
dbName := firstNonEmpty(os.Getenv("DB_DATABASE"), os.Getenv("DB_NAME"), "cotizador_e3")
|
||||
dbPort := parseIntDefault(os.Getenv("DB_PORT"), 5432)
|
||||
smtpPort := parseIntDefault(os.Getenv("SMTP_PORT"), 587)
|
||||
recDias := parseIntDefault(os.Getenv("COBROS_RECORDATORIO_DIAS"), 3)
|
||||
|
||||
cfg := &Config{
|
||||
Port: firstNonEmpty(os.Getenv("PORT"), "3000"),
|
||||
Env: firstNonEmpty(os.Getenv("NODE_ENV"), os.Getenv("APP_ENV"), "production"),
|
||||
DBHost: firstNonEmpty(os.Getenv("DB_HOST"), "localhost"),
|
||||
DBPort: dbPort,
|
||||
DBUser: firstNonEmpty(os.Getenv("DB_USER"), "postgres"),
|
||||
DBPassword: firstNonEmpty(os.Getenv("DB_PASSWORD"), "postgres"),
|
||||
DBName: dbName,
|
||||
JWTSecret: strings.TrimSpace(os.Getenv("JWT_SECRET")),
|
||||
AppURL: strings.TrimRight(firstNonEmpty(os.Getenv("APP_URL"), "http://localhost:3000"), "/"),
|
||||
RunSeed: strings.EqualFold(strings.TrimSpace(os.Getenv("RUN_SEED")), "true"),
|
||||
SeedAdminEmail: firstNonEmpty(os.Getenv("SEED_ADMIN_EMAIL"), "[email protected]"),
|
||||
SeedAdminPassword: os.Getenv("SEED_ADMIN_PASSWORD"),
|
||||
SeedAdminName: firstNonEmpty(os.Getenv("SEED_ADMIN_NAME"), "Administrador"),
|
||||
SeedAsesorEmail: strings.TrimSpace(os.Getenv("SEED_ASESOR_EMAIL")),
|
||||
SeedAsesorPass: os.Getenv("SEED_ASESOR_PASSWORD"),
|
||||
SeedAsesorName: firstNonEmpty(os.Getenv("SEED_ASESOR_NAME"), "Asesor"),
|
||||
MinimaxAPIKey: strings.TrimSpace(os.Getenv("MINIMAX_API_KEY")),
|
||||
MinimaxBaseURL: strings.TrimRight(firstNonEmpty(os.Getenv("MINIMAX_BASE_URL"), "https://api.minimax.io/anthropic"), "/"),
|
||||
MinimaxModel: firstNonEmpty(os.Getenv("MINIMAX_MODEL"), "MiniMax-M3"),
|
||||
VAPIDPublicKey: strings.TrimSpace(os.Getenv("VAPID_PUBLIC_KEY")),
|
||||
VAPIDPrivateKey: strings.TrimSpace(os.Getenv("VAPID_PRIVATE_KEY")),
|
||||
VAPIDSubject: firstNonEmpty(os.Getenv("VAPID_SUBJECT"), "mailto:[email protected]"),
|
||||
SMTPHost: strings.TrimSpace(os.Getenv("SMTP_HOST")),
|
||||
SMTPPort: smtpPort,
|
||||
SMTPUser: strings.TrimSpace(os.Getenv("SMTP_USER")),
|
||||
SMTPPass: os.Getenv("SMTP_PASS"),
|
||||
SMTPFrom: firstNonEmpty(os.Getenv("SMTP_FROM"), os.Getenv("SMTP_USER")),
|
||||
SMTPFromName: firstNonEmpty(os.Getenv("SMTP_FROM_NAME"), "Uriel Jareth Consulting"),
|
||||
CobrosRecordatorioDias: recDias,
|
||||
UploadDir: firstNonEmpty(os.Getenv("UPLOAD_DIR"), "./uploads"),
|
||||
AdminNotifyEmail: strings.TrimSpace(os.Getenv("ADMIN_NOTIFY_EMAIL")),
|
||||
WebhookN8NURL: strings.TrimSpace(os.Getenv("WEBHOOK_N8N_URL")),
|
||||
WebhookN8NSecret: strings.TrimSpace(os.Getenv("WEBHOOK_N8N_SECRET")),
|
||||
WebhookWhatsAppSendURL: strings.TrimSpace(os.Getenv("WEBHOOK_WHATSAPP_SEND_URL")),
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (c *Config) RequireJWTSecret() error {
|
||||
if c.JWTSecret == "" {
|
||||
return fmt.Errorf("JWT_SECRET es obligatorio y no esta configurado")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Config) IsProduction() bool {
|
||||
return strings.EqualFold(c.Env, "production")
|
||||
}
|
||||
|
||||
func firstNonEmpty(vals ...string) string {
|
||||
for _, v := range vals {
|
||||
if strings.TrimSpace(v) != "" {
|
||||
return strings.TrimSpace(v)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func parseIntDefault(s string, def int) int {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return def
|
||||
}
|
||||
n, err := strconv.Atoi(s)
|
||||
if err != nil {
|
||||
return def
|
||||
}
|
||||
return n
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"embed"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"sort"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/config"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
var migrationsFS embed.FS
|
||||
|
||||
var idCounter uint64
|
||||
|
||||
// NewID generates a URL-safe, sortable, collision-resistant CUID-like identifier
|
||||
// (e.g. "c" + base36 timestamp + counter + random hex, 25 chars).
|
||||
func NewID() string {
|
||||
ts := strconv.FormatInt(time.Now().UnixMilli(), 36)
|
||||
cnt := strconv.FormatUint(atomic.AddUint64(&idCounter, 1)%1679616, 36)
|
||||
var b [8]byte
|
||||
_, _ = rand.Read(b[:])
|
||||
return "c" + ts + cnt + hex.EncodeToString(b[:])[:12]
|
||||
}
|
||||
|
||||
// Connect opens a pgxpool using individual connection parameters (matching the
|
||||
// existing Docker/Coolify environment without SCRAM URL-encoding issues).
|
||||
func Connect(ctx context.Context, cfg *config.Config) (*pgxpool.Pool, error) {
|
||||
poolCfg, err := pgxpool.ParseConfig("")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
poolCfg.ConnConfig.Host = cfg.DBHost
|
||||
poolCfg.ConnConfig.Port = uint16(cfg.DBPort)
|
||||
poolCfg.ConnConfig.User = cfg.DBUser
|
||||
poolCfg.ConnConfig.Password = cfg.DBPassword
|
||||
poolCfg.ConnConfig.Database = cfg.DBName
|
||||
poolCfg.MaxConns = 20
|
||||
poolCfg.MinConns = 2
|
||||
poolCfg.MaxConnLifetime = 30 * time.Minute
|
||||
poolCfg.MaxConnIdleTime = 5 * time.Minute
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, poolCfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error conectando a PostgreSQL: %w", err)
|
||||
}
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("error haciendo ping a PostgreSQL (%s:%d/%s): %w", cfg.DBHost, cfg.DBPort, cfg.DBName, err)
|
||||
}
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
// Migrate runs embedded idempotent SQL migrations and tracks applied files in `_go_migrations`.
|
||||
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
_, err := pool.Exec(ctx, `
|
||||
CREATE TABLE IF NOT EXISTS "_go_migrations" (
|
||||
"name" TEXT PRIMARY KEY,
|
||||
"appliedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error creando tabla _go_migrations: %w", err)
|
||||
}
|
||||
|
||||
entries, err := fs.ReadDir(migrationsFS, "migrations")
|
||||
if err != nil {
|
||||
return fmt.Errorf("error leyendo migraciones embebidas: %w", err)
|
||||
}
|
||||
sort.Slice(entries, func(i, j int) bool { return entries[i].Name() < entries[j].Name() })
|
||||
|
||||
for _, e := range entries {
|
||||
if e.IsDir() {
|
||||
continue
|
||||
}
|
||||
name := e.Name()
|
||||
var exists bool
|
||||
if err := pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM "_go_migrations" WHERE "name" = $1)`, name).Scan(&exists); err != nil {
|
||||
return fmt.Errorf("error verificando migracion %s: %w", name, err)
|
||||
}
|
||||
if exists {
|
||||
continue
|
||||
}
|
||||
|
||||
sqlBytes, err := migrationsFS.ReadFile("migrations/" + name)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error leyendo %s: %w", name, err)
|
||||
}
|
||||
tx, err := pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(ctx, string(sqlBytes)); err != nil {
|
||||
_ = tx.Rollback(ctx)
|
||||
return fmt.Errorf("error ejecutando migracion %s: %w", name, err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO "_go_migrations" ("name") VALUES ($1)`, name); err != nil {
|
||||
_ = tx.Rollback(ctx)
|
||||
return fmt.Errorf("error registrando migracion %s: %w", name, err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,478 @@
|
||||
-- Cotizador — Uriel Jareth Consulting
|
||||
-- Consolidated idempotent PostgreSQL schema matching Prisma's exact 25-table schema.
|
||||
-- Safe to run on both an empty database and an existing production database with live data.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "Cliente" (
|
||||
"id" TEXT NOT NULL,
|
||||
"nombre" TEXT NOT NULL,
|
||||
"empresa" TEXT,
|
||||
"puesto" TEXT,
|
||||
"email" TEXT,
|
||||
"telefono" TEXT,
|
||||
"rfc" TEXT,
|
||||
"archivado" BOOLEAN NOT NULL DEFAULT false,
|
||||
"archivadoAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "Cliente_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "User" (
|
||||
"id" TEXT NOT NULL,
|
||||
"email" TEXT NOT NULL,
|
||||
"password" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"role" TEXT NOT NULL DEFAULT 'asesor',
|
||||
"clienteId" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "User_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "Cotizacion" (
|
||||
"id" TEXT NOT NULL,
|
||||
"numero" TEXT NOT NULL,
|
||||
"fecha" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"vigencia" TIMESTAMP(3) NOT NULL,
|
||||
"moneda" TEXT NOT NULL DEFAULT 'MXN',
|
||||
"tipoCambio" TEXT NOT NULL DEFAULT 'NA',
|
||||
"proyecto" TEXT NOT NULL DEFAULT 'MKT Digital',
|
||||
"esquemaPago" TEXT NOT NULL DEFAULT 'Pago Unico/Mensual',
|
||||
"estado" TEXT NOT NULL DEFAULT 'borrador',
|
||||
"incluirBonos" BOOLEAN NOT NULL DEFAULT false,
|
||||
"incluirFinanciamiento" BOOLEAN NOT NULL DEFAULT false,
|
||||
"incluirIva" BOOLEAN NOT NULL DEFAULT true,
|
||||
"esDoble" BOOLEAN NOT NULL DEFAULT false,
|
||||
"opcionesMetadata" JSONB,
|
||||
"observaciones" TEXT,
|
||||
"observacionesInternas" TEXT,
|
||||
"clienteId" TEXT NOT NULL,
|
||||
"asesorId" TEXT NOT NULL,
|
||||
"aprobadaPorId" TEXT,
|
||||
"aprobadaAt" TIMESTAMP(3),
|
||||
"aprobacionMetodo" TEXT,
|
||||
"enviadaAt" TIMESTAMP(3),
|
||||
"enviadaPor" TEXT,
|
||||
"enviadaCanal" TEXT,
|
||||
"enviadaDestino" TEXT,
|
||||
"aceptadaAt" TIMESTAMP(3),
|
||||
"rechazadaAt" TIMESTAMP(3),
|
||||
"vencidaAt" TIMESTAMP(3),
|
||||
"creadaPorAgente" TEXT,
|
||||
"archivado" BOOLEAN NOT NULL DEFAULT false,
|
||||
"archivadoAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "Cotizacion_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "Categoria" (
|
||||
"id" TEXT NOT NULL,
|
||||
"nombre" TEXT NOT NULL,
|
||||
"descripcion" TEXT,
|
||||
"color" TEXT NOT NULL DEFAULT '#6b7280',
|
||||
"activo" BOOLEAN NOT NULL DEFAULT true,
|
||||
"orden" INTEGER NOT NULL DEFAULT 0,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "Categoria_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "Paquete" (
|
||||
"id" TEXT NOT NULL,
|
||||
"nombre" TEXT NOT NULL,
|
||||
"descripcion" TEXT,
|
||||
"activo" BOOLEAN NOT NULL DEFAULT true,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "Paquete_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "FasePaquete" (
|
||||
"id" TEXT NOT NULL,
|
||||
"paqueteId" TEXT NOT NULL,
|
||||
"nombre" TEXT NOT NULL,
|
||||
"orden" INTEGER NOT NULL DEFAULT 0,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "FasePaquete_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "ServicioCatalogo" (
|
||||
"id" TEXT NOT NULL,
|
||||
"nombre" TEXT NOT NULL,
|
||||
"descripcion" TEXT,
|
||||
"fase" INTEGER NOT NULL DEFAULT 1,
|
||||
"tipoPago" TEXT NOT NULL DEFAULT 'unico',
|
||||
"precioBase" DOUBLE PRECISION NOT NULL,
|
||||
"tiempoEntrega" TEXT NOT NULL DEFAULT '4 - 10 dias',
|
||||
"entregablesDefault" JSONB NOT NULL DEFAULT '[]',
|
||||
"categoriaId" TEXT,
|
||||
"variante" TEXT,
|
||||
"nivel" TEXT,
|
||||
"activo" BOOLEAN NOT NULL DEFAULT true,
|
||||
"soloAdmin" BOOLEAN NOT NULL DEFAULT false,
|
||||
"orden" INTEGER NOT NULL DEFAULT 0,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "ServicioCatalogo_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "ServicioPaquete" (
|
||||
"id" TEXT NOT NULL,
|
||||
"servicioCatalogoId" TEXT NOT NULL,
|
||||
"fasePaqueteId" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "ServicioPaquete_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "ServicioCotizado" (
|
||||
"id" TEXT NOT NULL,
|
||||
"cotizacionId" TEXT NOT NULL,
|
||||
"servicioCatalogoId" TEXT,
|
||||
"nombre" TEXT,
|
||||
"esPersonalizado" BOOLEAN NOT NULL DEFAULT false,
|
||||
"horas" DOUBLE PRECISION,
|
||||
"tarifaHora" DOUBLE PRECISION,
|
||||
"modeloCobro" TEXT NOT NULL DEFAULT 'fijo',
|
||||
"montoMinimo" DOUBLE PRECISION,
|
||||
"horasIncluidas" DOUBLE PRECISION,
|
||||
"opcion" TEXT,
|
||||
"fase" INTEGER NOT NULL,
|
||||
"tipoPago" TEXT NOT NULL,
|
||||
"precio" DOUBLE PRECISION NOT NULL,
|
||||
"tiempoEntrega" TEXT NOT NULL,
|
||||
"entregables" JSONB NOT NULL DEFAULT '[]',
|
||||
"beneficios" JSONB NOT NULL DEFAULT '[]',
|
||||
"notas" TEXT,
|
||||
"seleccionado" BOOLEAN NOT NULL DEFAULT true,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "ServicioCotizado_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "PlanBucefaloCotizacion" (
|
||||
"id" TEXT NOT NULL,
|
||||
"cotizacionId" TEXT NOT NULL,
|
||||
"nivel" TEXT NOT NULL DEFAULT 'basico',
|
||||
"precio" DOUBLE PRECISION NOT NULL,
|
||||
"seleccionado" BOOLEAN NOT NULL DEFAULT true,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "PlanBucefaloCotizacion_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "RegistroHoras" (
|
||||
"id" TEXT NOT NULL,
|
||||
"cotizacionId" TEXT NOT NULL,
|
||||
"fecha" TIMESTAMP(3) NOT NULL,
|
||||
"horaInicio" TEXT NOT NULL,
|
||||
"horaFin" TEXT NOT NULL,
|
||||
"horas" DOUBLE PRECISION NOT NULL,
|
||||
"tarifaHora" DOUBLE PRECISION NOT NULL DEFAULT 0,
|
||||
"descripcion" TEXT NOT NULL,
|
||||
"estadoPago" TEXT NOT NULL DEFAULT 'por_pagar',
|
||||
"fechaPago" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "RegistroHoras_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "PropuestaIA" (
|
||||
"id" TEXT NOT NULL,
|
||||
"cotizacionId" TEXT NOT NULL,
|
||||
"estado" TEXT NOT NULL DEFAULT 'borrador',
|
||||
"contenidoIA" JSONB NOT NULL,
|
||||
"contenidoEditado" JSONB,
|
||||
"transcripcion" TEXT,
|
||||
"traza" JSONB,
|
||||
"avisos" JSONB NOT NULL DEFAULT '[]',
|
||||
"modelo" TEXT NOT NULL,
|
||||
"aprobadaPor" TEXT,
|
||||
"aprobadaAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "PropuestaIA_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "Configuracion" (
|
||||
"id" TEXT NOT NULL,
|
||||
"clave" TEXT NOT NULL,
|
||||
"valor" TEXT NOT NULL,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "Configuracion_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "Bono" (
|
||||
"id" TEXT NOT NULL,
|
||||
"numero" INTEGER NOT NULL,
|
||||
"titulo" TEXT NOT NULL,
|
||||
"descripcion" TEXT NOT NULL,
|
||||
"activo" BOOLEAN NOT NULL DEFAULT true,
|
||||
CONSTRAINT "Bono_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "FinanciamientoPlan" (
|
||||
"id" TEXT NOT NULL,
|
||||
"meses" INTEGER NOT NULL,
|
||||
"tasa" DOUBLE PRECISION NOT NULL,
|
||||
"comision" DOUBLE PRECISION NOT NULL,
|
||||
"montoMinimo" DOUBLE PRECISION NOT NULL,
|
||||
"iva" DOUBLE PRECISION NOT NULL DEFAULT 0.16,
|
||||
CONSTRAINT "FinanciamientoPlan_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "ProgramaPago" (
|
||||
"id" TEXT NOT NULL,
|
||||
"clienteId" TEXT NOT NULL,
|
||||
"cotizacionId" TEXT,
|
||||
"concepto" TEXT NOT NULL,
|
||||
"monto" DOUBLE PRECISION NOT NULL,
|
||||
"moneda" TEXT NOT NULL DEFAULT 'MXN',
|
||||
"frecuencia" TEXT NOT NULL DEFAULT 'semanal',
|
||||
"diaSemana" INTEGER,
|
||||
"diaMes" INTEGER,
|
||||
"fechaInicio" TIMESTAMP(3) NOT NULL,
|
||||
"fechaFin" TIMESTAMP(3),
|
||||
"activo" BOOLEAN NOT NULL DEFAULT true,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "ProgramaPago_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "PagoRecurrente" (
|
||||
"id" TEXT NOT NULL,
|
||||
"programaId" TEXT NOT NULL,
|
||||
"fecha" TIMESTAMP(3) NOT NULL,
|
||||
"monto" DOUBLE PRECISION NOT NULL,
|
||||
"estado" TEXT NOT NULL DEFAULT 'pendiente',
|
||||
"verificadoAt" TIMESTAMP(3),
|
||||
"rechazadoAt" TIMESTAMP(3),
|
||||
"rechazoMotivo" TEXT,
|
||||
"ultimoRecordatorioAt" TIMESTAMP(3),
|
||||
"recordatoriosEnviados" INTEGER NOT NULL DEFAULT 0,
|
||||
"vencidoNotificadoAt" TIMESTAMP(3),
|
||||
"nota" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "PagoRecurrente_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "ComprobantePago" (
|
||||
"id" TEXT NOT NULL,
|
||||
"pagoId" TEXT NOT NULL,
|
||||
"archivoRuta" TEXT NOT NULL,
|
||||
"archivoNombre" TEXT NOT NULL,
|
||||
"mime" TEXT NOT NULL,
|
||||
"tamano" INTEGER NOT NULL,
|
||||
"subidoAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "ComprobantePago_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "SuscripcionPush" (
|
||||
"id" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"endpoint" TEXT NOT NULL,
|
||||
"p256dh" TEXT NOT NULL,
|
||||
"auth" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "SuscripcionPush_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "AgentApiKey" (
|
||||
"id" TEXT NOT NULL,
|
||||
"nombre" TEXT NOT NULL,
|
||||
"prefijo" TEXT NOT NULL,
|
||||
"keyHash" TEXT NOT NULL,
|
||||
"scopes" TEXT[],
|
||||
"rateLimitPerMin" INTEGER NOT NULL DEFAULT 60,
|
||||
"activo" BOOLEAN NOT NULL DEFAULT true,
|
||||
"revokedAt" TIMESTAMP(3),
|
||||
"lastUsedAt" TIMESTAMP(3),
|
||||
"createdById" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "AgentApiKey_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "AuditLog" (
|
||||
"id" TEXT NOT NULL,
|
||||
"actorTipo" TEXT NOT NULL,
|
||||
"actorId" TEXT,
|
||||
"actorNombre" TEXT NOT NULL,
|
||||
"accion" TEXT NOT NULL,
|
||||
"recursoTipo" TEXT NOT NULL,
|
||||
"recursoId" TEXT,
|
||||
"ip" TEXT,
|
||||
"requestId" TEXT,
|
||||
"exito" BOOLEAN NOT NULL DEFAULT true,
|
||||
"detalle" JSONB,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "AuditLog_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "ApprovalToken" (
|
||||
"id" TEXT NOT NULL,
|
||||
"cotizacionId" TEXT NOT NULL,
|
||||
"tokenHash" TEXT NOT NULL,
|
||||
"expiraAt" TIMESTAMP(3) NOT NULL,
|
||||
"usadoAt" TIMESTAMP(3),
|
||||
"usadoIp" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "ApprovalToken_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "IdempotencyKey" (
|
||||
"id" TEXT NOT NULL,
|
||||
"key" TEXT NOT NULL,
|
||||
"method" TEXT NOT NULL,
|
||||
"path" TEXT NOT NULL,
|
||||
"requestHash" TEXT NOT NULL,
|
||||
"statusCode" INTEGER NOT NULL,
|
||||
"responseBody" JSONB NOT NULL,
|
||||
"expiraAt" TIMESTAMP(3) NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "IdempotencyKey_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "WebhookEndpoint" (
|
||||
"id" TEXT NOT NULL,
|
||||
"nombre" TEXT NOT NULL,
|
||||
"url" TEXT NOT NULL,
|
||||
"secret" TEXT NOT NULL,
|
||||
"eventos" TEXT[],
|
||||
"activo" BOOLEAN NOT NULL DEFAULT true,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "WebhookEndpoint_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "WebhookDelivery" (
|
||||
"id" TEXT NOT NULL,
|
||||
"endpointId" TEXT,
|
||||
"url" TEXT NOT NULL,
|
||||
"evento" TEXT NOT NULL,
|
||||
"payload" JSONB NOT NULL,
|
||||
"statusCode" INTEGER,
|
||||
"exito" BOOLEAN NOT NULL DEFAULT false,
|
||||
"intentos" INTEGER NOT NULL DEFAULT 1,
|
||||
"error" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "WebhookDelivery_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- Ensure additive columns exist on older production DBs
|
||||
ALTER TABLE "Cliente" ADD COLUMN IF NOT EXISTS "puesto" TEXT;
|
||||
ALTER TABLE "Cliente" ADD COLUMN IF NOT EXISTS "archivado" BOOLEAN NOT NULL DEFAULT false;
|
||||
ALTER TABLE "Cliente" ADD COLUMN IF NOT EXISTS "archivadoAt" TIMESTAMP(3);
|
||||
|
||||
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "observacionesInternas" TEXT;
|
||||
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "aprobadaPorId" TEXT;
|
||||
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "aprobadaAt" TIMESTAMP(3);
|
||||
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "aprobacionMetodo" TEXT;
|
||||
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "enviadaAt" TIMESTAMP(3);
|
||||
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "enviadaPor" TEXT;
|
||||
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "enviadaCanal" TEXT;
|
||||
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "enviadaDestino" TEXT;
|
||||
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "aceptadaAt" TIMESTAMP(3);
|
||||
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "rechazadaAt" TIMESTAMP(3);
|
||||
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "vencidaAt" TIMESTAMP(3);
|
||||
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "creadaPorAgente" TEXT;
|
||||
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "archivado" BOOLEAN NOT NULL DEFAULT false;
|
||||
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "archivadoAt" TIMESTAMP(3);
|
||||
|
||||
ALTER TABLE "ServicioCatalogo" ADD COLUMN IF NOT EXISTS "soloAdmin" BOOLEAN NOT NULL DEFAULT false;
|
||||
ALTER TABLE "PagoRecurrente" ADD COLUMN IF NOT EXISTS "ultimoRecordatorioAt" TIMESTAMP(3);
|
||||
ALTER TABLE "PagoRecurrente" ADD COLUMN IF NOT EXISTS "recordatoriosEnviados" INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE "PagoRecurrente" ADD COLUMN IF NOT EXISTS "vencidoNotificadoAt" TIMESTAMP(3);
|
||||
ALTER TABLE "PagoRecurrente" ADD COLUMN IF NOT EXISTS "nota" TEXT;
|
||||
|
||||
-- Unique & regular indexes
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "User_email_key" ON "User"("email");
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "User_clienteId_key" ON "User"("clienteId");
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "Cliente_nombre_empresa_idx" ON "Cliente"("nombre", "empresa");
|
||||
CREATE INDEX IF NOT EXISTS "Cliente_archivado_idx" ON "Cliente"("archivado");
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "Cotizacion_numero_key" ON "Cotizacion"("numero");
|
||||
CREATE INDEX IF NOT EXISTS "Cotizacion_clienteId_idx" ON "Cotizacion"("clienteId");
|
||||
CREATE INDEX IF NOT EXISTS "Cotizacion_asesorId_idx" ON "Cotizacion"("asesorId");
|
||||
CREATE INDEX IF NOT EXISTS "Cotizacion_estado_idx" ON "Cotizacion"("estado");
|
||||
CREATE INDEX IF NOT EXISTS "Cotizacion_archivado_idx" ON "Cotizacion"("archivado");
|
||||
CREATE INDEX IF NOT EXISTS "Cotizacion_createdAt_idx" ON "Cotizacion"("createdAt");
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "Categoria_nombre_key" ON "Categoria"("nombre");
|
||||
CREATE INDEX IF NOT EXISTS "FasePaquete_paqueteId_idx" ON "FasePaquete"("paqueteId");
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "ServicioCatalogo_categoriaId_idx" ON "ServicioCatalogo"("categoriaId");
|
||||
CREATE INDEX IF NOT EXISTS "ServicioCatalogo_activo_fase_orden_idx" ON "ServicioCatalogo"("activo", "fase", "orden");
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "ServicioPaquete_servicioCatalogoId_fasePaqueteId_key" ON "ServicioPaquete"("servicioCatalogoId", "fasePaqueteId");
|
||||
CREATE INDEX IF NOT EXISTS "ServicioPaquete_fasePaqueteId_idx" ON "ServicioPaquete"("fasePaqueteId");
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "ServicioCotizado_cotizacionId_idx" ON "ServicioCotizado"("cotizacionId");
|
||||
CREATE INDEX IF NOT EXISTS "ServicioCotizado_servicioCatalogoId_idx" ON "ServicioCotizado"("servicioCatalogoId");
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "PlanBucefaloCotizacion_cotizacionId_key" ON "PlanBucefaloCotizacion"("cotizacionId");
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "RegistroHoras_cotizacionId_idx" ON "RegistroHoras"("cotizacionId");
|
||||
CREATE INDEX IF NOT EXISTS "RegistroHoras_fecha_idx" ON "RegistroHoras"("fecha");
|
||||
CREATE INDEX IF NOT EXISTS "RegistroHoras_estadoPago_idx" ON "RegistroHoras"("estadoPago");
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "PropuestaIA_cotizacionId_idx" ON "PropuestaIA"("cotizacionId");
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "Configuracion_clave_key" ON "Configuracion"("clave");
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "FinanciamientoPlan_meses_key" ON "FinanciamientoPlan"("meses");
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "ProgramaPago_clienteId_idx" ON "ProgramaPago"("clienteId");
|
||||
CREATE INDEX IF NOT EXISTS "ProgramaPago_activo_idx" ON "ProgramaPago"("activo");
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "PagoRecurrente_programaId_fecha_key" ON "PagoRecurrente"("programaId", "fecha");
|
||||
CREATE INDEX IF NOT EXISTS "PagoRecurrente_estado_idx" ON "PagoRecurrente"("estado");
|
||||
CREATE INDEX IF NOT EXISTS "PagoRecurrente_fecha_idx" ON "PagoRecurrente"("fecha");
|
||||
CREATE INDEX IF NOT EXISTS "PagoRecurrente_vencidoNotificadoAt_idx" ON "PagoRecurrente"("vencidoNotificadoAt");
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "ComprobantePago_pagoId_key" ON "ComprobantePago"("pagoId");
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "SuscripcionPush_endpoint_key" ON "SuscripcionPush"("endpoint");
|
||||
CREATE INDEX IF NOT EXISTS "SuscripcionPush_userId_idx" ON "SuscripcionPush"("userId");
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "AgentApiKey_nombre_key" ON "AgentApiKey"("nombre");
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "AgentApiKey_keyHash_key" ON "AgentApiKey"("keyHash");
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "AuditLog_createdAt_idx" ON "AuditLog"("createdAt");
|
||||
CREATE INDEX IF NOT EXISTS "AuditLog_accion_idx" ON "AuditLog"("accion");
|
||||
CREATE INDEX IF NOT EXISTS "AuditLog_recursoTipo_recursoId_idx" ON "AuditLog"("recursoTipo", "recursoId");
|
||||
CREATE INDEX IF NOT EXISTS "AuditLog_actorNombre_idx" ON "AuditLog"("actorNombre");
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "ApprovalToken_tokenHash_key" ON "ApprovalToken"("tokenHash");
|
||||
CREATE INDEX IF NOT EXISTS "ApprovalToken_cotizacionId_idx" ON "ApprovalToken"("cotizacionId");
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "IdempotencyKey_key_key" ON "IdempotencyKey"("key");
|
||||
CREATE INDEX IF NOT EXISTS "IdempotencyKey_expiraAt_idx" ON "IdempotencyKey"("expiraAt");
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "WebhookEndpoint_nombre_key" ON "WebhookEndpoint"("nombre");
|
||||
CREATE INDEX IF NOT EXISTS "WebhookDelivery_evento_idx" ON "WebhookDelivery"("evento");
|
||||
CREATE INDEX IF NOT EXISTS "WebhookDelivery_createdAt_idx" ON "WebhookDelivery"("createdAt");
|
||||
|
||||
-- Foreign keys (idempotent)
|
||||
DO $$ BEGIN ALTER TABLE "User" ADD CONSTRAINT "User_clienteId_fkey" FOREIGN KEY ("clienteId") REFERENCES "Cliente"("id") ON DELETE SET NULL ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "Cotizacion" ADD CONSTRAINT "Cotizacion_clienteId_fkey" FOREIGN KEY ("clienteId") REFERENCES "Cliente"("id") ON DELETE RESTRICT ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "Cotizacion" ADD CONSTRAINT "Cotizacion_asesorId_fkey" FOREIGN KEY ("asesorId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "FasePaquete" ADD CONSTRAINT "FasePaquete_paqueteId_fkey" FOREIGN KEY ("paqueteId") REFERENCES "Paquete"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "ServicioCatalogo" ADD CONSTRAINT "ServicioCatalogo_categoriaId_fkey" FOREIGN KEY ("categoriaId") REFERENCES "Categoria"("id") ON DELETE SET NULL ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "ServicioPaquete" ADD CONSTRAINT "ServicioPaquete_servicioCatalogoId_fkey" FOREIGN KEY ("servicioCatalogoId") REFERENCES "ServicioCatalogo"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "ServicioPaquete" ADD CONSTRAINT "ServicioPaquete_fasePaqueteId_fkey" FOREIGN KEY ("fasePaqueteId") REFERENCES "FasePaquete"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "ServicioCotizado" ADD CONSTRAINT "ServicioCotizado_cotizacionId_fkey" FOREIGN KEY ("cotizacionId") REFERENCES "Cotizacion"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "ServicioCotizado" ADD CONSTRAINT "ServicioCotizado_servicioCatalogoId_fkey" FOREIGN KEY ("servicioCatalogoId") REFERENCES "ServicioCatalogo"("id") ON DELETE SET NULL ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "PlanBucefaloCotizacion" ADD CONSTRAINT "PlanBucefaloCotizacion_cotizacionId_fkey" FOREIGN KEY ("cotizacionId") REFERENCES "Cotizacion"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "RegistroHoras" ADD CONSTRAINT "RegistroHoras_cotizacionId_fkey" FOREIGN KEY ("cotizacionId") REFERENCES "Cotizacion"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "PropuestaIA" ADD CONSTRAINT "PropuestaIA_cotizacionId_fkey" FOREIGN KEY ("cotizacionId") REFERENCES "Cotizacion"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "ProgramaPago" ADD CONSTRAINT "ProgramaPago_clienteId_fkey" FOREIGN KEY ("clienteId") REFERENCES "Cliente"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "ProgramaPago" ADD CONSTRAINT "ProgramaPago_cotizacionId_fkey" FOREIGN KEY ("cotizacionId") REFERENCES "Cotizacion"("id") ON DELETE SET NULL ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "PagoRecurrente" ADD CONSTRAINT "PagoRecurrente_programaId_fkey" FOREIGN KEY ("programaId") REFERENCES "ProgramaPago"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "ComprobantePago" ADD CONSTRAINT "ComprobantePago_pagoId_fkey" FOREIGN KEY ("pagoId") REFERENCES "PagoRecurrente"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "SuscripcionPush" ADD CONSTRAINT "SuscripcionPush_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "ApprovalToken" ADD CONSTRAINT "ApprovalToken_cotizacionId_fkey" FOREIGN KEY ("cotizacionId") REFERENCES "Cotizacion"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "WebhookDelivery" ADD CONSTRAINT "WebhookDelivery_endpointId_fkey" FOREIGN KEY ("endpointId") REFERENCES "WebhookEndpoint"("id") ON DELETE SET NULL ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
package excel
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/csv"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type CatalogoCSVRow struct {
|
||||
Nombre string
|
||||
Categoria string
|
||||
Fase int
|
||||
TipoPago string
|
||||
PrecioBase float64
|
||||
TiempoEntrega string
|
||||
Entregables []string
|
||||
Variante string
|
||||
}
|
||||
|
||||
var fasesExportCSV = map[int]string{
|
||||
0: "Auditoria",
|
||||
1: "Setup e Infraestructura",
|
||||
2: "Publicidad y Manejo",
|
||||
3: "Contenido y SEO",
|
||||
}
|
||||
|
||||
var fasesImportCSV = map[string]int{
|
||||
"0": 0,
|
||||
"fase 0": 0,
|
||||
"auditoria": 0,
|
||||
"auditoría": 0,
|
||||
"1": 1,
|
||||
"fase 1": 1,
|
||||
"setup e infraestructura": 1,
|
||||
"setup": 1,
|
||||
"infraestructura": 1,
|
||||
"2": 2,
|
||||
"fase 2": 2,
|
||||
"publicidad y manejo": 2,
|
||||
"publicidad": 2,
|
||||
"manejo": 2,
|
||||
"3": 3,
|
||||
"fase 3": 3,
|
||||
"contenido y seo": 3,
|
||||
"contenido": 3,
|
||||
"seo": 3,
|
||||
}
|
||||
|
||||
func ExportCatalogoCSV(rows []CatalogoCSVRow) ([]byte, error) {
|
||||
var buf bytes.Buffer
|
||||
w := csv.NewWriter(&buf)
|
||||
|
||||
if err := w.Write([]string{
|
||||
"Nombre",
|
||||
"Categoria",
|
||||
"Fase",
|
||||
"Tipo de Pago",
|
||||
"Precio Base",
|
||||
"Tiempo de Entrega",
|
||||
"Entregables",
|
||||
"Variante",
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, r := range rows {
|
||||
faseLabel, ok := fasesExportCSV[r.Fase]
|
||||
if !ok {
|
||||
faseLabel = fmt.Sprintf("Fase %d", r.Fase)
|
||||
}
|
||||
tipoLabel := "Mensual"
|
||||
if strings.EqualFold(strings.TrimSpace(r.TipoPago), "unico") {
|
||||
tipoLabel = "Pago Unico"
|
||||
}
|
||||
rec := []string{
|
||||
r.Nombre,
|
||||
r.Categoria,
|
||||
faseLabel,
|
||||
tipoLabel,
|
||||
strconv.FormatFloat(r.PrecioBase, 'f', -1, 64),
|
||||
r.TiempoEntrega,
|
||||
strings.Join(r.Entregables, " | "),
|
||||
r.Variante,
|
||||
}
|
||||
if err := w.Write(rec); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
w.Flush()
|
||||
if err := w.Error(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
func PlantillaCatalogoCSV() []byte {
|
||||
const tpl = `Nombre,Categoria,Fase,Tipo de Pago,Precio Base,Tiempo de Entrega,Entregables,Variante
|
||||
"SEO On-Page Basico","SEO","Setup e Infraestructura","unico",5000,"7 - 14 dias","Auditoria SEO | Optimizacion de meta tags | Mapa del sitio",
|
||||
"Manejo de Redes Sociales","Marketing","Publicidad y Manejo","mensual",8000,"Mensual","Publicaciones semanales | Reporte mensual | Gestion de comunidad","Basico"
|
||||
"Gestion de Google Ads","Paid Media","Publicidad y Manejo","mensual",5000,"Mensual","Configuracion de campanas | Reporte semanal",
|
||||
"Sitio Web Informativo","Desarrollo Web","Setup e Infraestructura","unico",15000,"15 - 30 dias","Diseno responsivo | Hasta 5 secciones | Formulario de contacto",
|
||||
"Automatizacion Email Marketing","Automatizaciones","Publicidad y Manejo","unico",8000,"10 - 15 dias","Configuracion de flujos | Plantillas de correo | Integracion CRM",
|
||||
"CRM Basico","CRM","Publicidad y Manejo","mensual",1000,"Mensual","CRM completo segun plan contratado","basico"
|
||||
|
||||
,,,,
|
||||
"CATEGORIAS DISPONIBLES: SEO / Marketing / Paid Media / Desarrollo Web / Automatizaciones / CRM",,,,,
|
||||
"FASES: Auditoria / Setup e Infraestructura / Publicidad y Manejo / Contenido y SEO",,,,,
|
||||
"TIPOS DE PAGO: unico / mensual",,,,,
|
||||
"ENTREGABLES: separar con | (pipe)",,,,,
|
||||
"VARIANTE: opcional (ej: Basico, Estandar, Premium)",,,,,
|
||||
`
|
||||
return []byte(tpl)
|
||||
}
|
||||
|
||||
func isInstructionLine(line string) bool {
|
||||
trimmed := strings.TrimSpace(line)
|
||||
if trimmed == "" {
|
||||
return true
|
||||
}
|
||||
unquoted := strings.ToUpper(strings.TrimPrefix(trimmed, `"`))
|
||||
for _, prefix := range []string{
|
||||
"CATEGORIAS",
|
||||
"CATEGORÍAS",
|
||||
"FASES:",
|
||||
"TIPOS DE PAGO",
|
||||
"TIPOS",
|
||||
"ENTREGABLES:",
|
||||
"VARIANTE:",
|
||||
} {
|
||||
if strings.HasPrefix(unquoted, prefix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func ParseCatalogoCSV(raw []byte) ([]CatalogoCSVRow, error) {
|
||||
// Strip UTF-8 BOM if present.
|
||||
raw = bytes.TrimPrefix(raw, []byte{0xEF, 0xBB, 0xBF})
|
||||
|
||||
text := strings.ReplaceAll(string(raw), "\r\n", "\n")
|
||||
rawLines := strings.Split(text, "\n")
|
||||
var kept []string
|
||||
for _, l := range rawLines {
|
||||
if isInstructionLine(l) {
|
||||
continue
|
||||
}
|
||||
kept = append(kept, l)
|
||||
}
|
||||
if len(kept) < 2 {
|
||||
return nil, errors.New("el CSV esta vacio o no tiene datos")
|
||||
}
|
||||
|
||||
r := csv.NewReader(strings.NewReader(strings.Join(kept, "\n")))
|
||||
r.FieldsPerRecord = -1
|
||||
r.LazyQuotes = true
|
||||
r.TrimLeadingSpace = true
|
||||
|
||||
// Skip header row.
|
||||
if _, err := r.Read(); err != nil {
|
||||
return nil, fmt.Errorf("error leyendo encabezado CSV: %w", err)
|
||||
}
|
||||
|
||||
var rows []CatalogoCSVRow
|
||||
for {
|
||||
rec, err := r.Read()
|
||||
if errors.Is(err, io.EOF) {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error leyendo CSV: %w", err)
|
||||
}
|
||||
if len(rec) < 5 {
|
||||
continue
|
||||
}
|
||||
|
||||
get := func(i int) string {
|
||||
if i >= len(rec) {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(rec[i])
|
||||
}
|
||||
|
||||
nombre := get(0)
|
||||
categoria := get(1)
|
||||
faseStr := strings.ToLower(get(2))
|
||||
tipoStr := strings.ToLower(get(3))
|
||||
precioStr := get(4)
|
||||
tiempoEntrega := get(5)
|
||||
entregablesStr := get(6)
|
||||
variante := get(7)
|
||||
|
||||
if nombre == "" || categoria == "" || tipoStr == "" || precioStr == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
fase, ok := fasesImportCSV[faseStr]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
var tipoPago string
|
||||
switch tipoStr {
|
||||
case "unico", "único", "pago unico", "pago único":
|
||||
tipoPago = "unico"
|
||||
case "mensual":
|
||||
tipoPago = "mensual"
|
||||
default:
|
||||
continue
|
||||
}
|
||||
|
||||
cleanedPrecio := strings.NewReplacer("$", "", ",", "", " ", "").Replace(precioStr)
|
||||
precioBase, err := strconv.ParseFloat(cleanedPrecio, 64)
|
||||
if err != nil || math.IsNaN(precioBase) || math.IsInf(precioBase, 0) || precioBase < 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
if tiempoEntrega == "" {
|
||||
tiempoEntrega = "7 - 14 dias"
|
||||
}
|
||||
|
||||
var entregables []string
|
||||
if entregablesStr != "" {
|
||||
for _, part := range strings.Split(entregablesStr, "|") {
|
||||
if p := strings.TrimSpace(part); p != "" {
|
||||
entregables = append(entregables, p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rows = append(rows, CatalogoCSVRow{
|
||||
Nombre: nombre,
|
||||
Categoria: categoria,
|
||||
Fase: fase,
|
||||
TipoPago: tipoPago,
|
||||
PrecioBase: precioBase,
|
||||
TiempoEntrega: tiempoEntrega,
|
||||
Entregables: entregables,
|
||||
Variante: variante,
|
||||
})
|
||||
}
|
||||
|
||||
if len(rows) == 0 {
|
||||
return nil, errors.New("no se encontraron filas validas. Verifica el formato del CSV")
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
@@ -0,0 +1,769 @@
|
||||
package excel
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/xuri/excelize/v2"
|
||||
|
||||
"cotizador/internal/domain"
|
||||
)
|
||||
|
||||
type ServicioExcel struct {
|
||||
Nombre string
|
||||
Fase int
|
||||
TipoPago string
|
||||
Precio float64
|
||||
TiempoEntrega string
|
||||
Entregables []string
|
||||
EsPersonalizado bool
|
||||
Horas *float64
|
||||
TarifaHora *float64
|
||||
ModeloCobro string
|
||||
MontoMinimo *float64
|
||||
HorasIncluidas *float64
|
||||
Opcion *string
|
||||
}
|
||||
|
||||
// CotizacionExcelData holds client-facing quotation data for Excel export.
|
||||
// ObservacionesInternas is intentionally NOT declared here so internal notes
|
||||
// can never leak into a client workbook.
|
||||
type CotizacionExcelData struct {
|
||||
RazonSocial string
|
||||
DomicilioFiscal string
|
||||
Numero string
|
||||
ClienteNombre string
|
||||
ClienteEmpresa string
|
||||
AsesorNombre string
|
||||
Fecha time.Time
|
||||
Vigencia time.Time
|
||||
Moneda string
|
||||
TipoCambio string
|
||||
Proyecto string
|
||||
EsquemaPago string
|
||||
Servicios []ServicioExcel
|
||||
EsDoble bool
|
||||
OpcionesMetadata map[string]domain.MetaOpcion
|
||||
PlanBucefaloNivel *string
|
||||
PlanBucefaloPrecio *float64
|
||||
ColorPrimario string
|
||||
ColorSecundario string
|
||||
IncluirIVA bool
|
||||
Observaciones *string
|
||||
}
|
||||
|
||||
var (
|
||||
hexRe = regexp.MustCompile(`^#?[0-9a-fA-F]{6}$`)
|
||||
invalidTabRe = regexp.MustCompile(`[/\\*?\[\]:]`)
|
||||
fasesExcelMap = map[int]string{
|
||||
0: "FASE 0",
|
||||
1: "FASE 1",
|
||||
2: "FASE 2",
|
||||
3: "FASE 3",
|
||||
}
|
||||
)
|
||||
|
||||
func cleanHex(v, fallback string) string {
|
||||
v = strings.TrimSpace(v)
|
||||
if !hexRe.MatchString(v) {
|
||||
v = fallback
|
||||
}
|
||||
return strings.ToUpper(strings.TrimPrefix(v, "#"))
|
||||
}
|
||||
|
||||
// tintLight blends ~10% of hex color onto white (#FFFFFF) for crisp light fills in Excel.
|
||||
func tintLight(hex6 string) string {
|
||||
r, _ := strconv.ParseInt(hex6[0:2], 16, 64)
|
||||
g, _ := strconv.ParseInt(hex6[2:4], 16, 64)
|
||||
b, _ := strconv.ParseInt(hex6[4:6], 16, 64)
|
||||
blend := func(c int64) int64 {
|
||||
return int64(math.Round(float64(c)*0.10 + 255.0*0.90))
|
||||
}
|
||||
return fmt.Sprintf("%02X%02X%02X", blend(r), blend(g), blend(b))
|
||||
}
|
||||
|
||||
func capitalize(s string) string {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return ""
|
||||
}
|
||||
r := []rune(s)
|
||||
r[0] = unicode.ToUpper(r[0])
|
||||
return string(r)
|
||||
}
|
||||
|
||||
func servicioExcelToCalc(s ServicioExcel) domain.ServicioCalc {
|
||||
return domain.ServicioCalc{
|
||||
Nombre: s.Nombre,
|
||||
ModeloCobro: s.ModeloCobro,
|
||||
EsPersonalizado: s.EsPersonalizado,
|
||||
Horas: s.Horas,
|
||||
TarifaHora: s.TarifaHora,
|
||||
MontoMinimo: s.MontoMinimo,
|
||||
HorasIncluidas: s.HorasIncluidas,
|
||||
Opcion: s.Opcion,
|
||||
TipoPago: s.TipoPago,
|
||||
Precio: s.Precio,
|
||||
Seleccionado: true,
|
||||
}
|
||||
}
|
||||
|
||||
func serviciosExcelToCalc(list []ServicioExcel) []domain.ServicioCalc {
|
||||
out := make([]domain.ServicioCalc, len(list))
|
||||
for i, s := range list {
|
||||
out[i] = servicioExcelToCalc(s)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func estimateRowHeight(text string, widthChars float64, fontSize float64) float64 {
|
||||
cpl := int(math.Floor(widthChars))
|
||||
if cpl < 8 {
|
||||
cpl = 8
|
||||
}
|
||||
lineH := 14.0
|
||||
switch {
|
||||
case fontSize <= 10:
|
||||
lineH = 14
|
||||
case fontSize <= 11:
|
||||
lineH = 15.5
|
||||
case fontSize <= 12:
|
||||
lineH = 17
|
||||
default:
|
||||
lineH = 20
|
||||
}
|
||||
lines := 0
|
||||
for _, seg := range strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n") {
|
||||
n := utf8.RuneCountInString(seg)
|
||||
l := int(math.Ceil(float64(n) / float64(cpl)))
|
||||
if l < 1 {
|
||||
l = 1
|
||||
}
|
||||
lines += l
|
||||
}
|
||||
h := math.Round(float64(lines)*lineH + 4)
|
||||
if h < 16 {
|
||||
return 16
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
func sanitizeSheetName(name string, used map[string]bool) string {
|
||||
cleaned := strings.TrimSpace(invalidTabRe.ReplaceAllString(name, ""))
|
||||
cleaned = strings.Trim(cleaned, "'")
|
||||
if cleaned == "" {
|
||||
cleaned = "Servicio"
|
||||
}
|
||||
runes := []rune(cleaned)
|
||||
if len(runes) > 31 {
|
||||
runes = runes[:31]
|
||||
}
|
||||
base := string(runes)
|
||||
candidate := base
|
||||
n := 2
|
||||
for used[strings.ToLower(candidate)] {
|
||||
suffix := fmt.Sprintf(" (%d)", n)
|
||||
maxBase := 31 - utf8.RuneCountInString(suffix)
|
||||
br := []rune(base)
|
||||
if len(br) > maxBase {
|
||||
br = br[:maxBase]
|
||||
}
|
||||
candidate = string(br) + suffix
|
||||
n++
|
||||
}
|
||||
used[strings.ToLower(candidate)] = true
|
||||
return candidate
|
||||
}
|
||||
|
||||
type styleSpec struct {
|
||||
bold bool
|
||||
italic bool
|
||||
size float64
|
||||
fontColor string
|
||||
fillColor string
|
||||
borderClr string
|
||||
horiz string
|
||||
vert string
|
||||
wrap bool
|
||||
numFmt string
|
||||
}
|
||||
|
||||
type wbHelper struct {
|
||||
f *excelize.File
|
||||
styles map[styleSpec]int
|
||||
}
|
||||
|
||||
func newWBHelper() *wbHelper {
|
||||
return &wbHelper{
|
||||
f: excelize.NewFile(),
|
||||
styles: make(map[styleSpec]int),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *wbHelper) styleID(s styleSpec) int {
|
||||
if id, ok := h.styles[s]; ok {
|
||||
return id
|
||||
}
|
||||
size := s.size
|
||||
if size <= 0 {
|
||||
size = 10
|
||||
}
|
||||
st := &excelize.Style{
|
||||
Font: &excelize.Font{
|
||||
Family: "Calibri",
|
||||
Size: size,
|
||||
Bold: s.bold,
|
||||
Italic: s.italic,
|
||||
Color: s.fontColor,
|
||||
},
|
||||
Alignment: &excelize.Alignment{
|
||||
Horizontal: s.horiz,
|
||||
Vertical: s.vert,
|
||||
WrapText: s.wrap,
|
||||
},
|
||||
}
|
||||
if s.fillColor != "" {
|
||||
st.Fill = excelize.Fill{
|
||||
Type: "pattern",
|
||||
Pattern: 1,
|
||||
Color: []string{s.fillColor},
|
||||
}
|
||||
}
|
||||
if s.borderClr != "" {
|
||||
st.Border = []excelize.Border{
|
||||
{Type: "top", Color: s.borderClr, Style: 1},
|
||||
{Type: "bottom", Color: s.borderClr, Style: 1},
|
||||
{Type: "left", Color: s.borderClr, Style: 1},
|
||||
{Type: "right", Color: s.borderClr, Style: 1},
|
||||
}
|
||||
}
|
||||
if s.numFmt != "" {
|
||||
nf := s.numFmt
|
||||
st.CustomNumFmt = &nf
|
||||
}
|
||||
id, err := h.f.NewStyle(st)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
h.styles[s] = id
|
||||
return id
|
||||
}
|
||||
|
||||
func (h *wbHelper) hideGrid(sheet string) {
|
||||
show := false
|
||||
_ = h.f.SetSheetView(sheet, 0, &excelize.ViewOptions{ShowGridLines: &show})
|
||||
}
|
||||
|
||||
func (h *wbHelper) setColWidths(sheet string, widths map[string]float64) {
|
||||
for col, w := range widths {
|
||||
_ = h.f.SetColWidth(sheet, col, col, w)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *wbHelper) ensureRowHeight(sheet string, row int, minH float64) {
|
||||
cur, _ := h.f.GetRowHeight(sheet, row)
|
||||
if cur < minH {
|
||||
_ = h.f.SetRowHeight(sheet, row, minH)
|
||||
}
|
||||
}
|
||||
|
||||
func sumWidths(widths map[string]float64, cols ...string) float64 {
|
||||
total := 0.0
|
||||
for _, c := range cols {
|
||||
if w, ok := widths[c]; ok {
|
||||
total += w
|
||||
} else {
|
||||
total += 8
|
||||
}
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
func BuildCotizacionExcel(data CotizacionExcelData) ([]byte, error) {
|
||||
primary := cleanHex(data.ColorPrimario, "0400C4")
|
||||
primaryLight := tintLight(primary)
|
||||
secondary := cleanHex(data.ColorSecundario, "0F172A")
|
||||
white := "FFFFFF"
|
||||
lightBG := "F8FAFC"
|
||||
muted := "64748B"
|
||||
borderColor := "E2E8F0"
|
||||
|
||||
wb := newWBHelper()
|
||||
defer wb.f.Close()
|
||||
|
||||
_ = wb.f.SetDocProps(&excelize.DocProperties{
|
||||
Creator: "Cotizador — Uriel Jareth Consulting",
|
||||
Created: time.Now().UTC().Format(time.RFC3339),
|
||||
})
|
||||
|
||||
const resumenSheet = "HOJA RESUMEN"
|
||||
_ = wb.f.SetSheetName("Sheet1", resumenSheet)
|
||||
resumenWidths := map[string]float64{
|
||||
"A": 3, "B": 18, "C": 26, "D": 13, "E": 16, "F": 22,
|
||||
"G": 6, "H": 6, "I": 6, "J": 6, "K": 16,
|
||||
}
|
||||
wb.setColWidths(resumenSheet, resumenWidths)
|
||||
wb.hideGrid(resumenSheet)
|
||||
|
||||
// Common styles.
|
||||
stBanner1 := wb.styleID(styleSpec{bold: true, size: 16, fontColor: white, fillColor: primary, vert: "center"})
|
||||
stBanner2 := wb.styleID(styleSpec{bold: true, size: 11, fontColor: white, fillColor: secondary, vert: "center"})
|
||||
stLabel := wb.styleID(styleSpec{bold: true, size: 10, fontColor: muted, vert: "top"})
|
||||
stValueWrap := wb.styleID(styleSpec{size: 10, vert: "top", wrap: true})
|
||||
stDate := wb.styleID(styleSpec{size: 10, vert: "top", numFmt: "DD/MM/YYYY"})
|
||||
stHeaderL := wb.styleID(styleSpec{bold: true, size: 10, fontColor: white, fillColor: primary, borderClr: primary, horiz: "left", vert: "center"})
|
||||
stHeaderR := wb.styleID(styleSpec{bold: true, size: 10, fontColor: white, fillColor: primary, borderClr: primary, horiz: "right", vert: "center"})
|
||||
stFase := wb.styleID(styleSpec{bold: true, size: 11, fontColor: primary, fillColor: primaryLight, vert: "center"})
|
||||
stSmall := wb.styleID(styleSpec{italic: true, size: 9, fontColor: muted, vert: "top", wrap: true})
|
||||
stIvaNote := wb.styleID(styleSpec{size: 9, fontColor: muted})
|
||||
stObsTitle := wb.styleID(styleSpec{bold: true, size: 10, fontColor: primary})
|
||||
stOpBanner := wb.styleID(styleSpec{bold: true, size: 12, fontColor: white, fillColor: secondary, vert: "center"})
|
||||
stCompBanner := wb.styleID(styleSpec{bold: true, size: 12, fontColor: white, fillColor: primary, vert: "center"})
|
||||
|
||||
// ── Banner ──
|
||||
_ = wb.f.MergeCell(resumenSheet, "B2", "K2")
|
||||
_ = wb.f.SetCellValue(resumenSheet, "B2", data.RazonSocial)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, "A2", "K2", stBanner1)
|
||||
_ = wb.f.SetRowHeight(resumenSheet, 2, 28)
|
||||
|
||||
_ = wb.f.MergeCell(resumenSheet, "B3", "K3")
|
||||
_ = wb.f.SetCellValue(resumenSheet, "B3", data.Numero)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, "A3", "K3", stBanner2)
|
||||
_ = wb.f.SetRowHeight(resumenSheet, 3, 20)
|
||||
|
||||
// ── Info cliente / proyecto ──
|
||||
infoStart := 5
|
||||
empresa := data.ClienteEmpresa
|
||||
if strings.TrimSpace(empresa) == "" {
|
||||
empresa = "—"
|
||||
}
|
||||
type infoPair struct{ l1, v1, l2, v2 string }
|
||||
infoRows := []infoPair{
|
||||
{"En atención a:", data.ClienteNombre, "Empresa:", empresa},
|
||||
{"Proyecto:", data.Proyecto, "Moneda:", data.Moneda},
|
||||
{"Asesor:", data.AsesorNombre, "Tipo de Cambio:", data.TipoCambio},
|
||||
{"Fecha:", "", "Esquema de Pago:", data.EsquemaPago},
|
||||
}
|
||||
for i, ip := range infoRows {
|
||||
r := infoStart + i
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", r), ip.l1)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", r), fmt.Sprintf("B%d", r), stLabel)
|
||||
if ip.v1 != "" {
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("C%d", r), ip.v1)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("C%d", r), fmt.Sprintf("C%d", r), stValueWrap)
|
||||
wb.ensureRowHeight(resumenSheet, r, estimateRowHeight(ip.v1, resumenWidths["C"], 10))
|
||||
}
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("E%d", r), ip.l2)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("E%d", r), fmt.Sprintf("E%d", r), stLabel)
|
||||
if ip.v2 != "" {
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("F%d", r), ip.v2)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("F%d", r), fmt.Sprintf("F%d", r), stValueWrap)
|
||||
wb.ensureRowHeight(resumenSheet, r, estimateRowHeight(ip.v2, resumenWidths["F"], 10))
|
||||
}
|
||||
}
|
||||
|
||||
if !data.Fecha.IsZero() {
|
||||
fUTC := time.Date(data.Fecha.Year(), data.Fecha.Month(), data.Fecha.Day(), 0, 0, 0, 0, time.UTC)
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("C%d", infoStart+3), fUTC)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("C%d", infoStart+3), fmt.Sprintf("C%d", infoStart+3), stDate)
|
||||
}
|
||||
|
||||
vigRow := infoStart + 4
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", vigRow), "Vigencia:")
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", vigRow), fmt.Sprintf("B%d", vigRow), stLabel)
|
||||
if !data.Vigencia.IsZero() {
|
||||
vUTC := time.Date(data.Vigencia.Year(), data.Vigencia.Month(), data.Vigencia.Day(), 0, 0, 0, 0, time.UTC)
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("C%d", vigRow), vUTC)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("C%d", vigRow), fmt.Sprintf("C%d", vigRow), stDate)
|
||||
}
|
||||
|
||||
// ── Tabla de servicios ──
|
||||
tableStart := infoStart + 6
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("D%d", tableStart), fmt.Sprintf("J%d", tableStart))
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", tableStart), fmt.Sprintf("J%d", tableStart), stHeaderL)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("K%d", tableStart), fmt.Sprintf("K%d", tableStart), stHeaderR)
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", tableStart), "Fase")
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("C%d", tableStart), "Tipo de Pago")
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("D%d", tableStart), "Servicio")
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("K%d", tableStart), "Precio")
|
||||
_ = wb.f.SetRowHeight(resumenSheet, tableStart, 24)
|
||||
|
||||
var unicos, mensuales []ServicioExcel
|
||||
for _, s := range data.Servicios {
|
||||
if s.TipoPago == "mensual" {
|
||||
mensuales = append(mensuales, s)
|
||||
} else {
|
||||
unicos = append(unicos, s)
|
||||
}
|
||||
}
|
||||
|
||||
servWidth := sumWidths(resumenWidths, "D", "E", "F", "G", "H", "I", "J")
|
||||
fullWidth := sumWidths(resumenWidths, "B", "C", "D", "E", "F", "G", "H", "I", "J", "K")
|
||||
row := tableStart + 1
|
||||
|
||||
writeTotalRow := func(label string, amount float64, fontSize float64) {
|
||||
stLbl := wb.styleID(styleSpec{bold: true, size: fontSize, fillColor: primaryLight, borderClr: primary, horiz: "left", vert: "center"})
|
||||
stAmt := wb.styleID(styleSpec{bold: true, size: fontSize, fillColor: primaryLight, borderClr: primary, horiz: "right", vert: "center", numFmt: "$#,##0.00"})
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("J%d", row))
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), label)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("J%d", row), stLbl)
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("K%d", row), amount)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("K%d", row), fmt.Sprintf("K%d", row), stAmt)
|
||||
_ = wb.f.SetRowHeight(resumenSheet, row, 20)
|
||||
row++
|
||||
}
|
||||
|
||||
writeIvaNote := func() {
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("J%d", row))
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), "(+ IVA)")
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("J%d", row), stIvaNote)
|
||||
row++
|
||||
}
|
||||
|
||||
drawServiceRows := func(servs []ServicioExcel) {
|
||||
currentFase := -1
|
||||
for _, serv := range servs {
|
||||
if serv.Fase != currentFase {
|
||||
currentFase = serv.Fase
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row))
|
||||
fLbl := fasesExcelMap[serv.Fase]
|
||||
if fLbl == "" {
|
||||
fLbl = fmt.Sprintf("FASE %d", serv.Fase)
|
||||
}
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), fLbl)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stFase)
|
||||
_ = wb.f.SetRowHeight(resumenSheet, row, 20)
|
||||
row++
|
||||
}
|
||||
bg := white
|
||||
if row%2 == 0 {
|
||||
bg = lightBG
|
||||
}
|
||||
stCell := wb.styleID(styleSpec{size: 10, fillColor: bg, borderClr: borderColor, horiz: "left", vert: "top"})
|
||||
stCellWrap := wb.styleID(styleSpec{size: 10, fillColor: bg, borderClr: borderColor, horiz: "left", vert: "top", wrap: true})
|
||||
stPrice := wb.styleID(styleSpec{size: 10, fillColor: bg, borderClr: borderColor, horiz: "right", vert: "top", numFmt: "$#,##0.00"})
|
||||
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("D%d", row), fmt.Sprintf("J%d", row))
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("C%d", row), stCell)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("D%d", row), fmt.Sprintf("J%d", row), stCellWrap)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("K%d", row), fmt.Sprintf("K%d", row), stPrice)
|
||||
|
||||
tipo := "Único"
|
||||
if serv.TipoPago == "mensual" {
|
||||
tipo = "Mensual"
|
||||
}
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("C%d", row), tipo)
|
||||
|
||||
detalle := domain.DetalleModelo(servicioExcelToCalc(serv))
|
||||
servText := serv.Nombre
|
||||
if detalle != "" {
|
||||
servText = fmt.Sprintf("%s — %s", serv.Nombre, detalle)
|
||||
}
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("D%d", row), servText)
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("K%d", row), serv.Precio)
|
||||
wb.ensureRowHeight(resumenSheet, row, estimateRowHeight(servText, servWidth, 10))
|
||||
row++
|
||||
}
|
||||
}
|
||||
|
||||
writeOpcionBanner := func(op string) {
|
||||
meta := data.OpcionesMetadata[op]
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row))
|
||||
tit := "OPCIÓN " + op
|
||||
if strings.TrimSpace(meta.Titulo) != "" {
|
||||
tit += ": " + meta.Titulo
|
||||
}
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), tit)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stOpBanner)
|
||||
_ = wb.f.SetRowHeight(resumenSheet, row, 22)
|
||||
row++
|
||||
if strings.TrimSpace(meta.Descripcion) != "" {
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row))
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), meta.Descripcion)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stValueWrap)
|
||||
wb.ensureRowHeight(resumenSheet, row, estimateRowHeight(meta.Descripcion, fullWidth, 10))
|
||||
row++
|
||||
}
|
||||
if strings.TrimSpace(meta.NoIncluye) != "" {
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row))
|
||||
txt := "No incluye: " + meta.NoIncluye
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), txt)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stSmall)
|
||||
wb.ensureRowHeight(resumenSheet, row, estimateRowHeight(txt, fullWidth, 9))
|
||||
row++
|
||||
}
|
||||
}
|
||||
|
||||
sumPrices := func(list []ServicioExcel) float64 {
|
||||
tot := 0.0
|
||||
for _, s := range list {
|
||||
tot += s.Precio
|
||||
}
|
||||
return domain.Round2(tot)
|
||||
}
|
||||
|
||||
if data.EsDoble {
|
||||
filterOp := func(list []ServicioExcel, op string) []ServicioExcel {
|
||||
var out []ServicioExcel
|
||||
for _, s := range list {
|
||||
if s.Opcion != nil && (*s.Opcion == op || *s.Opcion == "ambas") {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
for _, op := range []string{"1", "2"} {
|
||||
u := filterOp(unicos, op)
|
||||
me := filterOp(mensuales, op)
|
||||
writeOpcionBanner(op)
|
||||
combined := make([]ServicioExcel, 0, len(u)+len(me))
|
||||
combined = append(combined, u...)
|
||||
combined = append(combined, me...)
|
||||
drawServiceRows(combined)
|
||||
row++
|
||||
writeTotalRow(fmt.Sprintf("Total Pago Único - Opción %s", op), sumPrices(u), 11)
|
||||
writeIvaNote()
|
||||
writeTotalRow(fmt.Sprintf("Total Pago Mensual - Opción %s", op), sumPrices(me), 11)
|
||||
writeIvaNote()
|
||||
row++
|
||||
}
|
||||
|
||||
calcs := serviciosExcelToCalc(data.Servicios)
|
||||
t1 := domain.CalcularTotalesOpcion(calcs, "1")
|
||||
t2 := domain.CalcularTotalesOpcion(calcs, "2")
|
||||
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row))
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), "COMPARATIVA DE OPCIONES")
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stCompBanner)
|
||||
_ = wb.f.SetRowHeight(resumenSheet, row, 22)
|
||||
row++
|
||||
|
||||
compRow := func(lab, v1, v2 string, bold bool) {
|
||||
stL := wb.styleID(styleSpec{bold: bold, size: 10, borderClr: borderColor, horiz: "left", vert: "center"})
|
||||
stR := wb.styleID(styleSpec{bold: bold, size: 10, borderClr: borderColor, horiz: "right", vert: "center"})
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("F%d", row))
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), lab)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("F%d", row), stL)
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("G%d", row), fmt.Sprintf("H%d", row))
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("G%d", row), v1)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("G%d", row), fmt.Sprintf("H%d", row), stR)
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("I%d", row), fmt.Sprintf("K%d", row))
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("I%d", row), v2)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("I%d", row), fmt.Sprintf("K%d", row), stR)
|
||||
row++
|
||||
}
|
||||
|
||||
t1Tit := data.OpcionesMetadata["1"].Titulo
|
||||
t2Tit := data.OpcionesMetadata["2"].Titulo
|
||||
op1Lbl := "Opción 1"
|
||||
if t1Tit != "" {
|
||||
op1Lbl += " - " + t1Tit
|
||||
}
|
||||
op2Lbl := "Opción 2"
|
||||
if t2Tit != "" {
|
||||
op2Lbl += " - " + t2Tit
|
||||
}
|
||||
compRow("Concepto", op1Lbl, op2Lbl, true)
|
||||
ivaLbl := ""
|
||||
if data.IncluirIVA {
|
||||
ivaLbl = " (c/IVA)"
|
||||
}
|
||||
compRow("Total único"+ivaLbl, domain.FormatCurrency(domain.ConIVA(t1.TotalUnico, data.IncluirIVA)), domain.FormatCurrency(domain.ConIVA(t2.TotalUnico, data.IncluirIVA)), false)
|
||||
compRow("Total mensual"+ivaLbl, domain.FormatCurrency(domain.ConIVA(t1.TotalMensual, data.IncluirIVA)), domain.FormatCurrency(domain.ConIVA(t2.TotalMensual, data.IncluirIVA)), false)
|
||||
compRow("Horas estimadas", fmt.Sprintf("%g h", t1.Horas), fmt.Sprintf("%g h", t2.Horas), false)
|
||||
row++
|
||||
} else {
|
||||
combined := make([]ServicioExcel, 0, len(unicos)+len(mensuales))
|
||||
combined = append(combined, unicos...)
|
||||
combined = append(combined, mensuales...)
|
||||
drawServiceRows(combined)
|
||||
row++
|
||||
writeTotalRow("Total Pago Único", sumPrices(unicos), 11)
|
||||
writeIvaNote()
|
||||
writeTotalRow("Total Pago Mensual", sumPrices(mensuales), 11)
|
||||
writeIvaNote()
|
||||
row++
|
||||
}
|
||||
|
||||
if data.PlanBucefaloNivel != nil && strings.TrimSpace(*data.PlanBucefaloNivel) != "" {
|
||||
nivel := strings.TrimSpace(*data.PlanBucefaloNivel)
|
||||
precio := domain.BucefaloPrecio(strings.ToLower(nivel))
|
||||
if data.PlanBucefaloPrecio != nil {
|
||||
precio = *data.PlanBucefaloPrecio
|
||||
}
|
||||
writeTotalRow("CRM Bucéfalo - "+capitalize(nivel), precio, 10)
|
||||
row++
|
||||
}
|
||||
|
||||
notaResumen := "Todos los precios son en Moneda Nacional (MX), los precios no incluyen IVA. Vigencia de 15 días hábiles."
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row))
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), notaResumen)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stSmall)
|
||||
wb.ensureRowHeight(resumenSheet, row, estimateRowHeight(notaResumen, fullWidth, 9))
|
||||
|
||||
// Observaciones del cliente (solo cliente, nunca observaciones internas).
|
||||
if data.Observaciones != nil && strings.TrimSpace(*data.Observaciones) != "" {
|
||||
row += 2
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row))
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), "OBSERVACIONES")
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stObsTitle)
|
||||
row++
|
||||
texto := strings.TrimSpace(*data.Observaciones)
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row))
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), texto)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stSmall)
|
||||
wb.ensureRowHeight(resumenSheet, row, estimateRowHeight(texto, fullWidth, 9))
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// HOJAS DETALLADAS POR SERVICIO
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
usedNames := map[string]bool{
|
||||
strings.ToLower(resumenSheet): true,
|
||||
}
|
||||
detailWidths := map[string]float64{
|
||||
"A": 3, "B": 16, "C": 30, "D": 8, "E": 4,
|
||||
"F": 18, "G": 22, "H": 6, "I": 6, "J": 16,
|
||||
}
|
||||
stDetBanner := wb.styleID(styleSpec{bold: true, size: 14, fontColor: white, fillColor: primary, vert: "center", wrap: true})
|
||||
stBoldWrap := wb.styleID(styleSpec{bold: true, size: 10, vert: "top", wrap: true})
|
||||
stServTit := wb.styleID(styleSpec{bold: true, size: 12, fontColor: primary, vert: "top", wrap: true})
|
||||
stEntHead := wb.styleID(styleSpec{bold: true, size: 10, fontColor: white, fillColor: primary, vert: "center"})
|
||||
stTotLbl := wb.styleID(styleSpec{bold: true, size: 11, fillColor: primaryLight, borderClr: primary, horiz: "left", vert: "center"})
|
||||
stTotVal := wb.styleID(styleSpec{bold: true, size: 11, fillColor: primaryLight, borderClr: primary, horiz: "right", vert: "center", numFmt: "$#,##0.00"})
|
||||
stRazon := wb.styleID(styleSpec{bold: true, size: 10, fontColor: primary})
|
||||
|
||||
for _, serv := range data.Servicios {
|
||||
tabName := sanitizeSheetName(serv.Nombre, usedNames)
|
||||
_, _ = wb.f.NewSheet(tabName)
|
||||
wb.setColWidths(tabName, detailWidths)
|
||||
wb.hideGrid(tabName)
|
||||
|
||||
fLbl := fasesExcelMap[serv.Fase]
|
||||
if fLbl == "" {
|
||||
fLbl = fmt.Sprintf("FASE %d", serv.Fase)
|
||||
}
|
||||
bannerText := fmt.Sprintf("%s — %s", fLbl, serv.Nombre)
|
||||
_ = wb.f.MergeCell(tabName, "B1", "J1")
|
||||
_ = wb.f.SetCellValue(tabName, "B1", bannerText)
|
||||
_ = wb.f.SetCellStyle(tabName, "A1", "J1", stDetBanner)
|
||||
bh := estimateRowHeight(bannerText, sumWidths(detailWidths, "B", "C", "D", "E", "F", "G", "H", "I", "J"), 14)
|
||||
if bh < 30 {
|
||||
bh = 30
|
||||
}
|
||||
_ = wb.f.SetRowHeight(tabName, 1, bh)
|
||||
|
||||
cValW := sumWidths(detailWidths, "C", "D")
|
||||
gValW := sumWidths(detailWidths, "G", "H")
|
||||
entW := sumWidths(detailWidths, "B", "C", "D", "E", "F", "G", "H", "I", "J")
|
||||
|
||||
r := 3
|
||||
clienteDisp := data.ClienteEmpresa
|
||||
if strings.TrimSpace(clienteDisp) == "" {
|
||||
clienteDisp = data.ClienteNombre
|
||||
}
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), "Cliente:")
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("B%d", r), stLabel)
|
||||
_ = wb.f.MergeCell(tabName, fmt.Sprintf("C%d", r), fmt.Sprintf("D%d", r))
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("C%d", r), clienteDisp)
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("C%d", r), fmt.Sprintf("D%d", r), stBoldWrap)
|
||||
wb.ensureRowHeight(tabName, r, estimateRowHeight(clienteDisp, cValW, 10))
|
||||
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("F%d", r), "No. Cotización:")
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("F%d", r), fmt.Sprintf("F%d", r), stLabel)
|
||||
_ = wb.f.MergeCell(tabName, fmt.Sprintf("G%d", r), fmt.Sprintf("H%d", r))
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("G%d", r), data.Numero)
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("G%d", r), fmt.Sprintf("H%d", r), stBoldWrap)
|
||||
r += 2
|
||||
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), "Servicio:")
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("B%d", r), stLabel)
|
||||
_ = wb.f.MergeCell(tabName, fmt.Sprintf("C%d", r), fmt.Sprintf("D%d", r))
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("C%d", r), serv.Nombre)
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("C%d", r), fmt.Sprintf("D%d", r), stServTit)
|
||||
wb.ensureRowHeight(tabName, r, estimateRowHeight(serv.Nombre, cValW, 12))
|
||||
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("F%d", r), "Tiempo de Entrega:")
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("F%d", r), fmt.Sprintf("F%d", r), stLabel)
|
||||
_ = wb.f.MergeCell(tabName, fmt.Sprintf("G%d", r), fmt.Sprintf("H%d", r))
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("G%d", r), serv.TiempoEntrega)
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("G%d", r), fmt.Sprintf("H%d", r), stValueWrap)
|
||||
wb.ensureRowHeight(tabName, r, estimateRowHeight(serv.TiempoEntrega, gValW, 10))
|
||||
r += 2
|
||||
|
||||
detalleServ := domain.DetalleModelo(servicioExcelToCalc(serv))
|
||||
if detalleServ != "" {
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), "Detalle:")
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("B%d", r), stLabel)
|
||||
_ = wb.f.MergeCell(tabName, fmt.Sprintf("C%d", r), fmt.Sprintf("J%d", r))
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("C%d", r), detalleServ)
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("C%d", r), fmt.Sprintf("J%d", r), stValueWrap)
|
||||
wb.ensureRowHeight(tabName, r, estimateRowHeight(detalleServ, sumWidths(detailWidths, "C", "D", "E", "F", "G", "H", "I", "J"), 10))
|
||||
r += 2
|
||||
}
|
||||
|
||||
// Entregables header
|
||||
_ = wb.f.MergeCell(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("J%d", r))
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), "Entregables")
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("J%d", r), stEntHead)
|
||||
_ = wb.f.SetRowHeight(tabName, r, 22)
|
||||
r++
|
||||
|
||||
for i, ent := range serv.Entregables {
|
||||
er := r + i
|
||||
bg := white
|
||||
if i%2 == 1 {
|
||||
bg = lightBG
|
||||
}
|
||||
stEnt := wb.styleID(styleSpec{size: 10, fillColor: bg, borderClr: borderColor, horiz: "left", vert: "top", wrap: true})
|
||||
txt := fmt.Sprintf("%d. %s", i+1, ent)
|
||||
_ = wb.f.MergeCell(tabName, fmt.Sprintf("B%d", er), fmt.Sprintf("J%d", er))
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", er), txt)
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", er), fmt.Sprintf("J%d", er), stEnt)
|
||||
wb.ensureRowHeight(tabName, er, estimateRowHeight(txt, entW, 10))
|
||||
}
|
||||
r += len(serv.Entregables) + 1
|
||||
|
||||
tipoTot := "Único"
|
||||
if serv.TipoPago == "mensual" {
|
||||
tipoTot = "Mensual"
|
||||
}
|
||||
_ = wb.f.MergeCell(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("H%d", r))
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), "Total Pago "+tipoTot)
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("H%d", r), stTotLbl)
|
||||
_ = wb.f.MergeCell(tabName, fmt.Sprintf("I%d", r), fmt.Sprintf("J%d", r))
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("I%d", r), serv.Precio)
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("I%d", r), fmt.Sprintf("J%d", r), stTotVal)
|
||||
_ = wb.f.SetRowHeight(tabName, r, 20)
|
||||
r++
|
||||
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), "(+ IVA)")
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("B%d", r), stIvaNote)
|
||||
r += 2
|
||||
|
||||
notaDetalle := "Esta cotización tiene una vigencia de 15 días hábiles. Todos los precios en MXN, precios + IVA."
|
||||
_ = wb.f.MergeCell(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("J%d", r))
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), notaDetalle)
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("J%d", r), stSmall)
|
||||
wb.ensureRowHeight(tabName, r, estimateRowHeight(notaDetalle, entW, 9))
|
||||
r += 2
|
||||
|
||||
// Brand decision: never print domicilio fiscal in generated documents.
|
||||
_ = wb.f.MergeCell(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("J%d", r))
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), data.RazonSocial)
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("J%d", r), stRazon)
|
||||
}
|
||||
|
||||
buf, err := wb.f.WriteToBuffer()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
package excel
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xuri/excelize/v2"
|
||||
|
||||
"cotizador/internal/domain"
|
||||
)
|
||||
|
||||
func f64(v float64) *float64 { return &v }
|
||||
func str(v string) *string { return &v }
|
||||
|
||||
func TestCotizacionExcelDataHasNoObservacionesInternas(t *testing.T) {
|
||||
rt := reflect.TypeOf(CotizacionExcelData{})
|
||||
for i := 0; i < rt.NumField(); i++ {
|
||||
name := strings.ToLower(rt.Field(i).Name)
|
||||
if strings.Contains(name, "interna") {
|
||||
t.Fatalf("CotizacionExcelData must never declare internal observations field, found %q", rt.Field(i).Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func sheetContains(t *testing.T, f *excelize.File, sheet, substr string) bool {
|
||||
t.Helper()
|
||||
rows, err := f.GetRows(sheet)
|
||||
if err != nil {
|
||||
t.Fatalf("GetRows(%s): %v", sheet, err)
|
||||
}
|
||||
for _, row := range rows {
|
||||
for _, cell := range row {
|
||||
if strings.Contains(cell, substr) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func TestBuildCotizacionExcelSingle(t *testing.T) {
|
||||
fecha := time.Date(2026, 5, 10, 0, 0, 0, 0, time.UTC)
|
||||
vigencia := domain.CalcularVigencia(fecha)
|
||||
obs := "Nota visible para el cliente con acentos: diseño y año."
|
||||
|
||||
raw, err := BuildCotizacionExcel(CotizacionExcelData{
|
||||
RazonSocial: "URIEL JARETH CONSULTING",
|
||||
DomicilioFiscal: "DOMICILIO_SECRETO_NO_IMPRIMIR 123",
|
||||
Numero: "UJ2605UR001",
|
||||
ClienteNombre: "Sofía Ramírez",
|
||||
ClienteEmpresa: "Ramírez Diseño S.A.",
|
||||
AsesorNombre: "Uriel Jareth",
|
||||
Fecha: fecha,
|
||||
Vigencia: vigencia,
|
||||
Moneda: "MXN",
|
||||
TipoCambio: "N/A",
|
||||
Proyecto: "Sitio Web y Campañas",
|
||||
EsquemaPago: "50/50",
|
||||
Servicios: []ServicioExcel{
|
||||
{
|
||||
Nombre: "Auditoría SEO / Técnica: [2026]*?",
|
||||
Fase: 0,
|
||||
TipoPago: "unico",
|
||||
Precio: 6000,
|
||||
TiempoEntrega: "7 días",
|
||||
Entregables: []string{"Diagnóstico técnico", "Roadmap SEO"},
|
||||
ModeloCobro: "fijo",
|
||||
},
|
||||
{
|
||||
Nombre: "Desarrollo Custom",
|
||||
Fase: 1,
|
||||
TipoPago: "unico",
|
||||
Precio: 14000,
|
||||
TiempoEntrega: "15 días",
|
||||
Entregables: []string{"Frontend", "Backend"},
|
||||
ModeloCobro: "horas",
|
||||
EsPersonalizado: true,
|
||||
Horas: f64(20),
|
||||
TarifaHora: f64(700),
|
||||
},
|
||||
{
|
||||
Nombre: "Retainer Mensual",
|
||||
Fase: 2,
|
||||
TipoPago: "mensual",
|
||||
Precio: 7500,
|
||||
TiempoEntrega: "Mensual",
|
||||
Entregables: []string{"Soporte", "Reportes"},
|
||||
ModeloCobro: "retainer",
|
||||
MontoMinimo: f64(7500),
|
||||
HorasIncluidas: f64(10),
|
||||
TarifaHora: f64(700),
|
||||
},
|
||||
{
|
||||
Nombre: "Desarrollo Custom", // duplicate tab name test
|
||||
Fase: 3,
|
||||
TipoPago: "mensual",
|
||||
Precio: 0,
|
||||
TiempoEntrega: "Bajo demanda",
|
||||
ModeloCobro: "demanda",
|
||||
TarifaHora: f64(700),
|
||||
},
|
||||
},
|
||||
PlanBucefaloNivel: str("premium"), // nil price -> falls back to domain.BucefaloPrecio (4500)
|
||||
ColorPrimario: "#0400C4",
|
||||
ColorSecundario: "#0F172A",
|
||||
IncluirIVA: true,
|
||||
Observaciones: &obs,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("BuildCotizacionExcel error: %v", err)
|
||||
}
|
||||
|
||||
f, err := excelize.OpenReader(bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
t.Fatalf("excelize.OpenReader error: %v", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
sheets := f.GetSheetList()
|
||||
if len(sheets) != 5 {
|
||||
t.Fatalf("expected 5 sheets (1 resumen + 4 services), got %d: %v", len(sheets), sheets)
|
||||
}
|
||||
if sheets[0] != "HOJA RESUMEN" {
|
||||
t.Fatalf("expected first sheet HOJA RESUMEN, got %q", sheets[0])
|
||||
}
|
||||
|
||||
// Verify key values in HOJA RESUMEN
|
||||
if v, _ := f.GetCellValue("HOJA RESUMEN", "B2"); v != "URIEL JARETH CONSULTING" {
|
||||
t.Errorf("B2 = %q, want URIEL JARETH CONSULTING", v)
|
||||
}
|
||||
if v, _ := f.GetCellValue("HOJA RESUMEN", "B3"); v != "UJ2605UR001" {
|
||||
t.Errorf("B3 = %q, want UJ2605UR001", v)
|
||||
}
|
||||
if !sheetContains(t, f, "HOJA RESUMEN", "20 h x $700/hr") {
|
||||
t.Errorf("HOJA RESUMEN missing horas DetalleModelo")
|
||||
}
|
||||
if !sheetContains(t, f, "HOJA RESUMEN", "segun consumo") {
|
||||
t.Errorf("HOJA RESUMEN missing demanda DetalleModelo")
|
||||
}
|
||||
if !sheetContains(t, f, "HOJA RESUMEN", "CRM Bucéfalo - Premium") {
|
||||
t.Errorf("HOJA RESUMEN missing Plan Bucéfalo row")
|
||||
}
|
||||
if !sheetContains(t, f, "HOJA RESUMEN", obs) {
|
||||
t.Errorf("HOJA RESUMEN missing Observaciones")
|
||||
}
|
||||
|
||||
// Verify DomicilioFiscal is NEVER printed on any sheet.
|
||||
for _, s := range sheets {
|
||||
if sheetContains(t, f, s, "DOMICILIO_SECRETO_NO_IMPRIMIR") {
|
||||
t.Fatalf("sheet %q leaked DomicilioFiscal", s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildCotizacionExcelDoblePropuesta(t *testing.T) {
|
||||
fecha := time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC)
|
||||
raw, err := BuildCotizacionExcel(CotizacionExcelData{
|
||||
RazonSocial: "URIEL JARETH CONSULTING",
|
||||
Numero: "UJ2606UR002",
|
||||
ClienteNombre: "Luis Torres",
|
||||
ClienteEmpresa: "Torres Corp",
|
||||
AsesorNombre: "Uriel Jareth",
|
||||
Fecha: fecha,
|
||||
Vigencia: domain.CalcularVigencia(fecha),
|
||||
Moneda: "MXN",
|
||||
Proyecto: "Escalamiento",
|
||||
EsquemaPago: "Mensual",
|
||||
EsDoble: true,
|
||||
IncluirIVA: true,
|
||||
OpcionesMetadata: map[string]domain.MetaOpcion{
|
||||
"1": {Titulo: "Básico", Descripcion: "Plan inicial", NoIncluye: "Video"},
|
||||
"2": {Titulo: "Pro", Descripcion: "Plan avanzado", NoIncluye: "Pauta"},
|
||||
},
|
||||
Servicios: []ServicioExcel{
|
||||
{Nombre: "HOJA RESUMEN", Fase: 0, TipoPago: "unico", Precio: 5000, TiempoEntrega: "5 días", Opcion: str("ambas"), Horas: f64(5)},
|
||||
{Nombre: "Landing", Fase: 1, TipoPago: "unico", Precio: 10000, TiempoEntrega: "10 días", Opcion: str("1"), Horas: f64(10)},
|
||||
{Nombre: "Web Pro", Fase: 1, TipoPago: "unico", Precio: 20000, TiempoEntrega: "20 días", Opcion: str("2"), Horas: f64(25)},
|
||||
{Nombre: "Ads", Fase: 2, TipoPago: "mensual", Precio: 8000, TiempoEntrega: "Mensual", Opcion: str("ambas")},
|
||||
},
|
||||
PlanBucefaloNivel: str("basico"),
|
||||
PlanBucefaloPrecio: f64(1200),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("BuildCotizacionExcel doble error: %v", err)
|
||||
}
|
||||
|
||||
f, err := excelize.OpenReader(bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
t.Fatalf("OpenReader error: %v", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
if !sheetContains(t, f, "HOJA RESUMEN", "OPCIÓN 1: Básico") {
|
||||
t.Errorf("missing OPCIÓN 1 banner")
|
||||
}
|
||||
if !sheetContains(t, f, "HOJA RESUMEN", "OPCIÓN 2: Pro") {
|
||||
t.Errorf("missing OPCIÓN 2 banner")
|
||||
}
|
||||
if !sheetContains(t, f, "HOJA RESUMEN", "COMPARATIVA DE OPCIONES") {
|
||||
t.Errorf("missing COMPARATIVA DE OPCIONES")
|
||||
}
|
||||
// Opción 1 único = (5000+10000)*1.16 = $17,400; Opción 2 único = (5000+20000)*1.16 = $29,000
|
||||
if !sheetContains(t, f, "HOJA RESUMEN", "$17,400") || !sheetContains(t, f, "HOJA RESUMEN", "$29,000") {
|
||||
t.Errorf("expected IVA-adjusted comparative totals $17,400 and $29,000")
|
||||
}
|
||||
if !sheetContains(t, f, "HOJA RESUMEN", "15 h") || !sheetContains(t, f, "HOJA RESUMEN", "30 h") {
|
||||
t.Errorf("expected comparative hours 15 h and 30 h")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCatalogoCSVExportPlantillaAndParse(t *testing.T) {
|
||||
// 1. Plantilla parses cleanly into 6 rows.
|
||||
tpl := PlantillaCatalogoCSV()
|
||||
parsedTpl, err := ParseCatalogoCSV(tpl)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseCatalogoCSV(PlantillaCatalogoCSV()) error: %v", err)
|
||||
}
|
||||
if len(parsedTpl) != 6 {
|
||||
t.Fatalf("expected 6 rows from plantilla, got %d", len(parsedTpl))
|
||||
}
|
||||
if parsedTpl[0].Nombre != "SEO On-Page Basico" || parsedTpl[0].Fase != 1 || parsedTpl[0].TipoPago != "unico" || parsedTpl[0].PrecioBase != 5000 {
|
||||
t.Errorf("unexpected first plantilla row: %+v", parsedTpl[0])
|
||||
}
|
||||
if len(parsedTpl[0].Entregables) != 3 {
|
||||
t.Errorf("expected 3 entregables in first row, got %v", parsedTpl[0].Entregables)
|
||||
}
|
||||
|
||||
// 2. Round-trip ExportCatalogoCSV -> ParseCatalogoCSV (including commas, quotes, BOM).
|
||||
orig := []CatalogoCSVRow{
|
||||
{
|
||||
Nombre: `Auditoría "Pro", Web & SEO`,
|
||||
Categoria: "SEO",
|
||||
Fase: 0,
|
||||
TipoPago: "unico",
|
||||
PrecioBase: 4500.5,
|
||||
TiempoEntrega: "5 - 7 días",
|
||||
Entregables: []string{"Informe técnico", "Sesión de entrega"},
|
||||
Variante: "Premium",
|
||||
},
|
||||
{
|
||||
Nombre: "Gestión de Redes",
|
||||
Categoria: "Marketing",
|
||||
Fase: 2,
|
||||
TipoPago: "mensual",
|
||||
PrecioBase: 8000,
|
||||
TiempoEntrega: "Mensual",
|
||||
Entregables: []string{"Calendario editorial", "Reporte mensual"},
|
||||
Variante: "",
|
||||
},
|
||||
}
|
||||
exported, err := ExportCatalogoCSV(orig)
|
||||
if err != nil {
|
||||
t.Fatalf("ExportCatalogoCSV error: %v", err)
|
||||
}
|
||||
|
||||
// Prepend UTF-8 BOM to verify BOM stripping too.
|
||||
withBOM := append([]byte{0xEF, 0xBB, 0xBF}, exported...)
|
||||
roundTrip, err := ParseCatalogoCSV(withBOM)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseCatalogoCSV round-trip error: %v", err)
|
||||
}
|
||||
if !reflect.DeepEqual(roundTrip, orig) {
|
||||
t.Fatalf("round-trip mismatch:\ngot: %+v\nwant: %+v", roundTrip, orig)
|
||||
}
|
||||
|
||||
// 3. Error cases.
|
||||
if _, err := ParseCatalogoCSV([]byte("Nombre,Categoria,Fase,Tipo de Pago,Precio Base\n")); err == nil {
|
||||
t.Errorf("expected error for header-only CSV")
|
||||
}
|
||||
if _, err := ParseCatalogoCSV([]byte("Nombre,Categoria,Fase,Tipo de Pago,Precio Base\nFoo,Bar,Invalida,unico,-5\n")); err == nil {
|
||||
t.Errorf("expected error when no valid rows exist")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,497 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/audit"
|
||||
"cotizador/internal/auth"
|
||||
"cotizador/internal/db"
|
||||
"cotizador/internal/webhooks"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *Server) handleAgentKeysList(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "agent_key"}); !ok {
|
||||
return
|
||||
}
|
||||
rows, err := s.Pool.Query(r.Context(), `
|
||||
SELECT "id", "nombre", "prefijo", "scopes", "rateLimitPerMin", "activo", "revokedAt", "lastUsedAt", "createdById", "createdAt", "updatedAt"
|
||||
FROM "AgentApiKey"
|
||||
ORDER BY "createdAt" DESC
|
||||
`)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error listando claves de agente")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
keys := []map[string]any{}
|
||||
for rows.Next() {
|
||||
var id, nombre, prefijo string
|
||||
var scopes []string
|
||||
var rateLimit int
|
||||
var activo bool
|
||||
var revokedAt, lastUsedAt *time.Time
|
||||
var createdByID *string
|
||||
var createdAt, updatedAt time.Time
|
||||
if rows.Scan(&id, &nombre, &prefijo, &scopes, &rateLimit, &activo, &revokedAt, &lastUsedAt, &createdByID, &createdAt, &updatedAt) == nil {
|
||||
keys = append(keys, map[string]any{
|
||||
"id": id,
|
||||
"nombre": nombre,
|
||||
"prefijo": prefijo,
|
||||
"scopes": scopes,
|
||||
"rateLimitPerMin": rateLimit,
|
||||
"activo": activo,
|
||||
"revokedAt": revokedAt,
|
||||
"lastUsedAt": lastUsedAt,
|
||||
"createdById": createdByID,
|
||||
"createdAt": createdAt,
|
||||
"updatedAt": updatedAt,
|
||||
})
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": keys, "scopesDisponibles": auth.AgentScopes})
|
||||
}
|
||||
|
||||
func (s *Server) handleAgentKeysCreate(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "agent_key"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Nombre string `json:"nombre"`
|
||||
Scopes []string `json:"scopes"`
|
||||
RateLimitPerMin *int `json:"rateLimitPerMin"`
|
||||
}
|
||||
if err := decodeJSON(r, &body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "JSON invalido")
|
||||
return
|
||||
}
|
||||
nombre := strings.TrimSpace(body.Nombre)
|
||||
if nombre == "" || len(body.Scopes) == 0 {
|
||||
writeError(w, http.StatusBadRequest, "nombre y scopes son requeridos")
|
||||
return
|
||||
}
|
||||
for _, sc := range body.Scopes {
|
||||
if !auth.IsValidScope(sc) {
|
||||
writeError(w, http.StatusBadRequest, fmt.Sprintf("Scope invalido o no permitido: %s", sc))
|
||||
return
|
||||
}
|
||||
}
|
||||
rl := 60
|
||||
if body.RateLimitPerMin != nil {
|
||||
rl = *body.RateLimitPerMin
|
||||
if rl < 1 || rl > 1000 {
|
||||
writeError(w, http.StatusBadRequest, "rateLimitPerMin debe estar entre 1 y 1000")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
rawKey, prefijo, keyHash := auth.GenerateAPIKey()
|
||||
id := db.NewID()
|
||||
_, err := s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "AgentApiKey" ("id", "nombre", "prefijo", "keyHash", "scopes", "rateLimitPerMin", "activo", "createdById", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, $5, $6, true, $7, NOW(), NOW())
|
||||
`, id, nombre, prefijo, keyHash, body.Scopes, rl, actor.UserID)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "duplicate") || strings.Contains(err.Error(), "23505") {
|
||||
writeError(w, http.StatusConflict, "Ya existe una clave con ese nombre")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "Error creando clave de agente")
|
||||
return
|
||||
}
|
||||
|
||||
tipo, aid, anom := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
||||
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
||||
Accion: "agent_key.crear", RecursoTipo: "agent_key", RecursoID: id,
|
||||
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
||||
Detalle: map[string]any{"nombre": nombre, "scopes": body.Scopes, "rateLimitPerMin": rl},
|
||||
})
|
||||
|
||||
writeJSON(w, http.StatusCreated, map[string]any{
|
||||
"id": id,
|
||||
"nombre": nombre,
|
||||
"prefijo": prefijo,
|
||||
"rawKey": rawKey,
|
||||
"scopes": body.Scopes,
|
||||
"rateLimitPerMin": rl,
|
||||
"activo": true,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleAgentKeysRotate(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "agent_key"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
rawKey, prefijo, keyHash := auth.GenerateAPIKey()
|
||||
|
||||
var nombre string
|
||||
err := s.Pool.QueryRow(r.Context(), `
|
||||
UPDATE "AgentApiKey"
|
||||
SET "prefijo" = $1, "keyHash" = $2, "activo" = true, "revokedAt" = NULL, "updatedAt" = NOW()
|
||||
WHERE "id" = $3
|
||||
RETURNING "nombre"
|
||||
`, prefijo, keyHash, id).Scan(&nombre)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "Clave no encontrada")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "Error rotando clave")
|
||||
return
|
||||
}
|
||||
|
||||
tipo, aid, anom := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
||||
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
||||
Accion: "agent_key.rotar", RecursoTipo: "agent_key", RecursoID: id,
|
||||
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
||||
Detalle: map[string]any{"nombre": nombre, "prefijo": prefijo},
|
||||
})
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"id": id,
|
||||
"nombre": nombre,
|
||||
"prefijo": prefijo,
|
||||
"rawKey": rawKey,
|
||||
"activo": true,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleAgentKeysRevoke(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "agent_key"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
var nombre string
|
||||
err := s.Pool.QueryRow(r.Context(), `
|
||||
UPDATE "AgentApiKey"
|
||||
SET "activo" = false, "revokedAt" = NOW(), "updatedAt" = NOW()
|
||||
WHERE "id" = $1
|
||||
RETURNING "nombre"
|
||||
`, id).Scan(&nombre)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "Clave no encontrada")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "Error revocando clave")
|
||||
return
|
||||
}
|
||||
|
||||
tipo, aid, anom := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
||||
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
||||
Accion: "agent_key.revocar", RecursoTipo: "agent_key", RecursoID: id,
|
||||
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
||||
Detalle: map[string]any{"nombre": nombre},
|
||||
})
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": id, "activo": false})
|
||||
}
|
||||
|
||||
func (s *Server) handleAuditLogs(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "audit_log"}); !ok {
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
page := parseIntQuery(r, "page", 1, 1, 10000)
|
||||
limit := parseIntQuery(r, "limit", 50, 1, 200)
|
||||
offset := (page - 1) * limit
|
||||
|
||||
conds := []string{"1=1"}
|
||||
args := []any{}
|
||||
addArg := func(v any) string {
|
||||
args = append(args, v)
|
||||
return fmt.Sprintf("$%d", len(args))
|
||||
}
|
||||
if v := strings.TrimSpace(q.Get("accion")); v != "" {
|
||||
conds = append(conds, `"accion" = `+addArg(v))
|
||||
}
|
||||
if v := strings.TrimSpace(q.Get("actorNombre")); v != "" {
|
||||
conds = append(conds, `"actorNombre" ILIKE `+addArg("%"+v+"%"))
|
||||
}
|
||||
if v := strings.TrimSpace(q.Get("recursoId")); v != "" {
|
||||
conds = append(conds, `"recursoId" = `+addArg(v))
|
||||
}
|
||||
whereSQL := strings.Join(conds, " AND ")
|
||||
|
||||
var total int
|
||||
_ = s.Pool.QueryRow(r.Context(), `SELECT COUNT(*) FROM "AuditLog" WHERE `+whereSQL, args...).Scan(&total)
|
||||
|
||||
limArg := addArg(limit)
|
||||
offArg := addArg(offset)
|
||||
rows, err := s.Pool.Query(r.Context(), `
|
||||
SELECT "id", "actorTipo", "actorId", "actorNombre", "accion", "recursoTipo", "recursoId", "ip", "requestId", "exito", "detalle", "createdAt"
|
||||
FROM "AuditLog"
|
||||
WHERE `+whereSQL+`
|
||||
ORDER BY "createdAt" DESC
|
||||
LIMIT `+limArg+` OFFSET `+offArg, args...)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error consultando auditoria")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
data := []map[string]any{}
|
||||
for rows.Next() {
|
||||
var id, actorTipo, actorNombre, accion, recursoTipo string
|
||||
var actorID, recursoID, ip, reqID *string
|
||||
var exito bool
|
||||
var detalle []byte
|
||||
var createdAt time.Time
|
||||
if rows.Scan(&id, &actorTipo, &actorID, &actorNombre, &accion, &recursoTipo, &recursoID, &ip, &reqID, &exito, &detalle, &createdAt) == nil {
|
||||
var det any
|
||||
if len(detalle) > 0 {
|
||||
_ = json.Unmarshal(detalle, &det)
|
||||
}
|
||||
data = append(data, map[string]any{
|
||||
"id": id, "actorTipo": actorTipo, "actorId": actorID, "actorNombre": actorNombre,
|
||||
"accion": accion, "recursoTipo": recursoTipo, "recursoId": recursoID,
|
||||
"ip": ip, "requestId": reqID, "exito": exito, "detalle": det, "createdAt": createdAt,
|
||||
})
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"data": data,
|
||||
"meta": map[string]any{"total": total, "page": page, "limit": limit},
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleWebhooksList(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "webhook"}); !ok {
|
||||
return
|
||||
}
|
||||
rows, err := s.Pool.Query(r.Context(), `
|
||||
SELECT "id", "nombre", "url", "eventos", "activo", "createdAt", "updatedAt"
|
||||
FROM "WebhookEndpoint"
|
||||
ORDER BY "createdAt" DESC
|
||||
`)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error listando webhooks")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
list := []map[string]any{}
|
||||
for rows.Next() {
|
||||
var id, nombre, urlStr string
|
||||
var eventos []string
|
||||
var activo bool
|
||||
var createdAt, updatedAt time.Time
|
||||
if rows.Scan(&id, &nombre, &urlStr, &eventos, &activo, &createdAt, &updatedAt) == nil {
|
||||
list = append(list, map[string]any{
|
||||
"id": id, "nombre": nombre, "url": urlStr, "eventos": eventos,
|
||||
"activo": activo, "createdAt": createdAt, "updatedAt": updatedAt,
|
||||
})
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": list, "eventosDisponibles": webhooks.EventosOficiales})
|
||||
}
|
||||
|
||||
func (s *Server) handleWebhooksCreate(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "webhook"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Nombre string `json:"nombre"`
|
||||
URL string `json:"url"`
|
||||
Secret string `json:"secret"`
|
||||
Eventos []string `json:"eventos"`
|
||||
}
|
||||
if err := decodeJSON(r, &body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "JSON invalido")
|
||||
return
|
||||
}
|
||||
nombre := strings.TrimSpace(body.Nombre)
|
||||
urlStr := strings.TrimSpace(body.URL)
|
||||
if nombre == "" || urlStr == "" || len(body.Eventos) == 0 {
|
||||
writeError(w, http.StatusBadRequest, "nombre, url y eventos son requeridos")
|
||||
return
|
||||
}
|
||||
for _, ev := range body.Eventos {
|
||||
if !webhooks.EsEventoValido(ev) {
|
||||
writeError(w, http.StatusBadRequest, fmt.Sprintf("Evento invalido: %s", ev))
|
||||
return
|
||||
}
|
||||
}
|
||||
secret := strings.TrimSpace(body.Secret)
|
||||
if secret == "" {
|
||||
var b [24]byte
|
||||
_, _ = rand.Read(b[:])
|
||||
secret = "whsec_" + hex.EncodeToString(b[:])
|
||||
}
|
||||
|
||||
id := db.NewID()
|
||||
_, err := s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "WebhookEndpoint" ("id", "nombre", "url", "secret", "eventos", "activo", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, $5, true, NOW(), NOW())
|
||||
`, id, nombre, urlStr, secret, body.Eventos)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "23505") || strings.Contains(err.Error(), "duplicate") {
|
||||
writeError(w, http.StatusConflict, "Ya existe un webhook con ese nombre")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "Error creando webhook")
|
||||
return
|
||||
}
|
||||
|
||||
tipo, aid, anom := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
||||
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
||||
Accion: "webhook.crear", RecursoTipo: "webhook", RecursoID: id,
|
||||
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
||||
Detalle: map[string]any{"nombre": nombre, "url": urlStr, "eventos": body.Eventos},
|
||||
})
|
||||
|
||||
writeJSON(w, http.StatusCreated, map[string]any{
|
||||
"id": id, "nombre": nombre, "url": urlStr, "secret": secret, "eventos": body.Eventos, "activo": true,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleWebhooksDelete(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "webhook"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
tag, err := s.Pool.Exec(r.Context(), `DELETE FROM "WebhookEndpoint" WHERE "id" = $1`, id)
|
||||
if err != nil || tag.RowsAffected() == 0 {
|
||||
writeError(w, http.StatusNotFound, "Webhook no encontrado")
|
||||
return
|
||||
}
|
||||
tipo, aid, anom := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
||||
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
||||
Accion: "webhook.eliminar", RecursoTipo: "webhook", RecursoID: id,
|
||||
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
||||
})
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||
}
|
||||
|
||||
func (s *Server) handleWebhooksDeliveries(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "webhook"}); !ok {
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
limit := parseIntQuery(r, "limit", 50, 1, 200)
|
||||
conds := []string{"1=1"}
|
||||
args := []any{}
|
||||
if ev := strings.TrimSpace(q.Get("evento")); ev != "" {
|
||||
args = append(args, ev)
|
||||
conds = append(conds, fmt.Sprintf(`"evento" = $%d`, len(args)))
|
||||
}
|
||||
if eid := strings.TrimSpace(q.Get("endpointId")); eid != "" {
|
||||
args = append(args, eid)
|
||||
conds = append(conds, fmt.Sprintf(`"endpointId" = $%d`, len(args)))
|
||||
}
|
||||
args = append(args, limit)
|
||||
rows, err := s.Pool.Query(r.Context(), fmt.Sprintf(`
|
||||
SELECT "id", "endpointId", "url", "evento", "payload", "statusCode", "exito", "intentos", "error", "createdAt"
|
||||
FROM "WebhookDelivery"
|
||||
WHERE %s
|
||||
ORDER BY "createdAt" DESC
|
||||
LIMIT $%d
|
||||
`, strings.Join(conds, " AND "), len(args)), args...)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error consultando entregas de webhooks")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
list := []map[string]any{}
|
||||
for rows.Next() {
|
||||
var id, urlStr, evento string
|
||||
var endpointID, errStr *string
|
||||
var payload []byte
|
||||
var statusCode *int
|
||||
var exito bool
|
||||
var intentos int
|
||||
var createdAt time.Time
|
||||
if rows.Scan(&id, &endpointID, &urlStr, &evento, &payload, &statusCode, &exito, &intentos, &errStr, &createdAt) == nil {
|
||||
var p any
|
||||
_ = json.Unmarshal(payload, &p)
|
||||
list = append(list, map[string]any{
|
||||
"id": id, "endpointId": endpointID, "url": urlStr, "evento": evento,
|
||||
"payload": p, "statusCode": statusCode, "exito": exito, "intentos": intentos,
|
||||
"error": errStr, "createdAt": createdAt,
|
||||
})
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": list})
|
||||
}
|
||||
|
||||
var configAllowedKeys = map[string]bool{
|
||||
"razon_social": true,
|
||||
"rfc": true,
|
||||
"domicilio_fiscal": true,
|
||||
"banco_nacional": true,
|
||||
"cuenta_nacional": true,
|
||||
"clabe_interbancaria": true,
|
||||
"clabe_nacional": true,
|
||||
"banco_internacional": true,
|
||||
"cuenta_internacional": true,
|
||||
"cuenta_internacional_swift": true,
|
||||
"swift": true,
|
||||
"routing_number": true,
|
||||
"hora_centinela": true,
|
||||
"anualidad_hosting": true,
|
||||
"iva": true,
|
||||
"terminos_condiciones": true,
|
||||
"no_incluye": true,
|
||||
"notas_adicionales": true,
|
||||
"nota_legal": true,
|
||||
"color_primario": true,
|
||||
"color_secundario": true,
|
||||
"logo_base64": true,
|
||||
"email_facturacion": true,
|
||||
"telefono_contacto": true,
|
||||
}
|
||||
|
||||
func (s *Server) handleConfiguracionGet(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "configuracion"}); !ok {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, s.getAllConfigMap(r.Context()))
|
||||
}
|
||||
|
||||
func (s *Server) handleConfiguracionPut(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "configuracion"}); !ok {
|
||||
return
|
||||
}
|
||||
var body map[string]string
|
||||
if err := decodeJSON(r, &body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "JSON invalido")
|
||||
return
|
||||
}
|
||||
for k, v := range body {
|
||||
if !configAllowedKeys[k] {
|
||||
continue
|
||||
}
|
||||
_, err := s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "Configuracion" ("id", "clave", "valor", "updatedAt")
|
||||
VALUES ($1, $2, $3, NOW())
|
||||
ON CONFLICT ("clave") DO UPDATE SET "valor" = EXCLUDED."valor", "updatedAt" = NOW()
|
||||
`, db.NewID(), k, v)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error guardando configuracion")
|
||||
return
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, s.getAllConfigMap(r.Context()))
|
||||
}
|
||||
@@ -0,0 +1,540 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/audit"
|
||||
"cotizador/internal/auth"
|
||||
"cotizador/internal/domain"
|
||||
"cotizador/internal/webhooks"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
|
||||
defer cancel()
|
||||
var one int
|
||||
if err := s.Pool.QueryRow(ctx, "SELECT 1").Scan(&one); err != nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{
|
||||
"status": "error",
|
||||
"db": "disconnected",
|
||||
"version": "3.0.0-go",
|
||||
})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"status": "ok",
|
||||
"db": "connected",
|
||||
"runtime": "go",
|
||||
"version": "3.0.0-go",
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleOpenAPI(w http.ResponseWriter, r *http.Request) {
|
||||
serverURL := s.Cfg.AppURL
|
||||
if serverURL == "" {
|
||||
serverURL = "https://cotizador.urieljareth.org"
|
||||
}
|
||||
spec := map[string]any{
|
||||
"openapi": "3.1.0",
|
||||
"info": map[string]any{
|
||||
"title": "Cotizador — Uriel Jareth Consulting API",
|
||||
"version": "3.0.0",
|
||||
"description": "API unificada en Go para agentes de IA y operacion comercial de Uriel Jareth Consulting. " +
|
||||
"Autenticacion por cookie JWT (usuarios humanos) o X-API-Key / Bearer ujc_live_* (agentes con alcances granulares). " +
|
||||
"Ningun agente puede aprobar cotizaciones: la aprobacion es exclusivamente humana (panel admin o enlace firmado de un solo uso).",
|
||||
},
|
||||
"servers": []map[string]any{{"url": serverURL}},
|
||||
"components": map[string]any{
|
||||
"securitySchemes": map[string]any{
|
||||
"ApiKeyAuth": map[string]any{"type": "apiKey", "in": "header", "name": "X-API-Key"},
|
||||
"BearerAuth": map[string]any{"type": "http", "scheme": "bearer"},
|
||||
"CookieAuth": map[string]any{"type": "apiKey", "in": "cookie", "name": auth.SessionCookieName},
|
||||
},
|
||||
"schemas": map[string]any{
|
||||
"AgentScope": map[string]any{"type": "string", "enum": auth.AgentScopes},
|
||||
"EstadoCotizacion": map[string]any{"type": "string", "enum": domain.EstadosCotizacion},
|
||||
"WebhookEvent": map[string]any{"type": "string", "enum": webhooks.EventosOficiales},
|
||||
},
|
||||
},
|
||||
"security": []map[string]any{{"ApiKeyAuth": []any{}}, {"BearerAuth": []any{}}, {"CookieAuth": []any{}}},
|
||||
"paths": map[string]any{
|
||||
"/api/health": map[string]any{"get": map[string]any{"summary": "Estado de salud del servicio y BD", "security": []any{}}},
|
||||
"/api/catalogo": map[string]any{"get": map[string]any{"summary": "Listar catalogo de servicios (scope: catalogo:leer)"}, "post": map[string]any{"summary": "Crear servicio (staff)"}},
|
||||
"/api/catalogo/{id}": map[string]any{"get": map[string]any{"summary": "Detalle de servicio (scope: catalogo:leer; 403 si soloAdmin para agentes)"}},
|
||||
"/api/categorias": map[string]any{"get": map[string]any{"summary": "Listar categorias (scope: catalogo:leer)"}},
|
||||
"/api/paquetes": map[string]any{"get": map[string]any{"summary": "Listar paquetes activos (scope: catalogo:leer)"}},
|
||||
"/api/clientes": map[string]any{"get": map[string]any{"summary": "Listar clientes (scope: clientes:leer)"}, "post": map[string]any{"summary": "Crear cliente (scope: clientes:escribir, idempotente)"}},
|
||||
"/api/clientes/{id}": map[string]any{"patch": map[string]any{"summary": "Actualizar cliente (scope: clientes:escribir)"}},
|
||||
"/api/clientes/{id}/archivar": map[string]any{"post": map[string]any{"summary": "Archivar/desarchivar cliente (staff)"}},
|
||||
"/api/cotizaciones": map[string]any{"get": map[string]any{"summary": "Listar cotizaciones (cotizaciones:leer | cotizaciones:leer_aceptadas)"}, "post": map[string]any{"summary": "Crear borrador (cotizaciones:borrador, idempotente)"}},
|
||||
"/api/cotizaciones/{id}": map[string]any{"get": map[string]any{"summary": "Detalle cotizacion (?verificarContacto=...)"}, "put": map[string]any{"summary": "Editar borrador"}, "delete": map[string]any{"summary": "Eliminar cotizacion (staff)"}},
|
||||
"/api/cotizaciones/{id}/solicitar-aprobacion": map[string]any{"post": map[string]any{"summary": "Reenviar enlace de aprobacion a Jareth"}},
|
||||
"/api/cotizaciones/{id}/aprobar": map[string]any{"post": map[string]any{"summary": "Aprobar cotizacion (EXCLUSIVO admin humano)"}},
|
||||
"/api/cotizaciones/{id}/enviar": map[string]any{"post": map[string]any{"summary": "Enviar cotizacion aprobada (cotizaciones:enviar, idempotente)"}},
|
||||
"/api/cotizaciones/{id}/estado": map[string]any{"patch": map[string]any{"summary": "Cambiar estado (staff)"}},
|
||||
"/api/cotizaciones/{id}/precio": map[string]any{"patch": map[string]any{"summary": "Actualizar precio de partida"}},
|
||||
"/api/aprobar/{token}": map[string]any{"get": map[string]any{"summary": "Resumen de aprobacion firmado", "security": []any{}}, "post": map[string]any{"summary": "Confirmar aprobacion de un solo uso", "security": []any{}}},
|
||||
"/api/cobros/programas": map[string]any{"get": map[string]any{"summary": "Listar programas recurrentes (cobros:leer)"}},
|
||||
"/api/cobros/pagos": map[string]any{"get": map[string]any{"summary": "Listar cobros recurrentes (cobros:leer)"}},
|
||||
"/api/cobros/pagos/{id}/registrar": map[string]any{"post": map[string]any{"summary": "Registrar pago manual (cobros:registrar, idempotente)"}},
|
||||
"/api/export/pdf/{id}": map[string]any{"get": map[string]any{"summary": "Exportar PDF de cotizacion"}},
|
||||
"/api/agent-keys": map[string]any{"get": map[string]any{"summary": "Listar claves de agente (admin)"}, "post": map[string]any{"summary": "Crear clave de agente (admin)"}},
|
||||
"/api/audit-logs": map[string]any{"get": map[string]any{"summary": "Consultar auditoria (admin)"}},
|
||||
"/api/webhooks": map[string]any{"get": map[string]any{"summary": "Listar webhooks (admin)"}, "post": map[string]any{"summary": "Registrar webhook (admin)"}},
|
||||
},
|
||||
}
|
||||
writeJSON(w, http.StatusOK, spec)
|
||||
}
|
||||
|
||||
func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := decodeJSON(r, &body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "Datos de acceso invalidos")
|
||||
return
|
||||
}
|
||||
email := strings.ToLower(strings.TrimSpace(body.Email))
|
||||
if email == "" || body.Password == "" {
|
||||
writeError(w, http.StatusBadRequest, "Email y contrasena requeridos")
|
||||
return
|
||||
}
|
||||
|
||||
var id, dbEmail, passHash, name, role string
|
||||
var clienteID *string
|
||||
err := s.Pool.QueryRow(r.Context(), `
|
||||
SELECT "id", "email", "password", "name", "role", "clienteId"
|
||||
FROM "User"
|
||||
WHERE LOWER("email") = $1
|
||||
LIMIT 1
|
||||
`, email).Scan(&id, &dbEmail, &passHash, &name, &role, &clienteID)
|
||||
if err != nil || !auth.ComparePassword(passHash, body.Password) {
|
||||
writeError(w, http.StatusUnauthorized, "Credenciales invalidas")
|
||||
return
|
||||
}
|
||||
if role == "" {
|
||||
role = "asesor"
|
||||
}
|
||||
cid := ""
|
||||
if clienteID != nil {
|
||||
cid = *clienteID
|
||||
}
|
||||
|
||||
payload := auth.SessionPayload{
|
||||
UserID: id,
|
||||
Email: dbEmail,
|
||||
Name: name,
|
||||
Role: role,
|
||||
ClienteID: cid,
|
||||
}
|
||||
tok, err := s.Auth.SignSession(payload)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error generando sesion")
|
||||
return
|
||||
}
|
||||
s.Auth.SetSessionCookie(w, tok)
|
||||
|
||||
respUser := map[string]any{
|
||||
"id": id,
|
||||
"userId": id,
|
||||
"email": dbEmail,
|
||||
"name": name,
|
||||
"role": role,
|
||||
}
|
||||
if cid != "" {
|
||||
respUser["clienteId"] = cid
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"user": respUser})
|
||||
}
|
||||
|
||||
func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
|
||||
s.Auth.ClearSessionCookie(w)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||
}
|
||||
|
||||
// handleMe returns the authenticated cookie session user (for both staff and cliente).
|
||||
func (s *Server) handleMe(w http.ResponseWriter, r *http.Request) {
|
||||
sess, ok := s.Auth.SessionFromRequest(r)
|
||||
if !ok {
|
||||
writeError(w, http.StatusUnauthorized, "No autenticado")
|
||||
return
|
||||
}
|
||||
user := map[string]any{
|
||||
"userId": sess.UserID,
|
||||
"email": sess.Email,
|
||||
"name": sess.Name,
|
||||
"role": sess.Role,
|
||||
}
|
||||
if sess.ClienteID != "" {
|
||||
user["clienteId"] = sess.ClienteID
|
||||
if s.Pool != nil {
|
||||
var clienteNombre string
|
||||
if err := s.Pool.QueryRow(r.Context(), `SELECT "nombre" FROM "Cliente" WHERE "id" = $1`, sess.ClienteID).Scan(&clienteNombre); err == nil {
|
||||
user["clienteNombre"] = clienteNombre
|
||||
}
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"user": user})
|
||||
}
|
||||
|
||||
// handleAsesores returns safe staff user list + next quote sequence for CotizacionForm.
|
||||
func (s *Server) handleAsesores(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "asesor"}); !ok {
|
||||
return
|
||||
}
|
||||
rows, err := s.Pool.Query(r.Context(), `
|
||||
SELECT "id", "name", "email", "role"
|
||||
FROM "User"
|
||||
WHERE "role" <> 'cliente'
|
||||
ORDER BY "name" ASC
|
||||
`)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error cargando asesores")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
asesores := []map[string]any{}
|
||||
for rows.Next() {
|
||||
var id, name, email, role string
|
||||
if rows.Scan(&id, &name, &email, &role) == nil {
|
||||
asesores = append(asesores, map[string]any{
|
||||
"id": id,
|
||||
"name": name,
|
||||
"email": email,
|
||||
"role": role,
|
||||
"iniciales": asesorInitials(name),
|
||||
})
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"asesores": asesores,
|
||||
"nextSeq": s.nextCotizacionSeq(r.Context()),
|
||||
})
|
||||
}
|
||||
|
||||
// handleDashboard provides summary counts + 10 recent quotes for the SPA dashboard.
|
||||
func (s *Server) handleDashboard(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "dashboard"}); !ok {
|
||||
return
|
||||
}
|
||||
ctx := r.Context()
|
||||
var totalCot, totalCli, totalSvc int
|
||||
_ = s.Pool.QueryRow(ctx, `SELECT COUNT(*) FROM "Cotizacion" WHERE "archivado" = false`).Scan(&totalCot)
|
||||
_ = s.Pool.QueryRow(ctx, `SELECT COUNT(*) FROM "Cliente" WHERE "archivado" = false`).Scan(&totalCli)
|
||||
_ = s.Pool.QueryRow(ctx, `SELECT COUNT(*) FROM "ServicioCatalogo" WHERE "activo" = true`).Scan(&totalSvc)
|
||||
|
||||
rows, err := s.Pool.Query(ctx, `
|
||||
SELECT q."id", q."numero", q."fecha", q."vigencia", q."proyecto", q."estado",
|
||||
q."moneda", q."esDoble", q."incluirIva",
|
||||
c."id", c."nombre", COALESCE(c."empresa", '')
|
||||
FROM "Cotizacion" q
|
||||
JOIN "Cliente" c ON c."id" = q."clienteId"
|
||||
WHERE q."archivado" = false
|
||||
ORDER BY q."createdAt" DESC
|
||||
LIMIT 10
|
||||
`)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error cargando dashboard")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
recientes := []map[string]any{}
|
||||
var cotIDs []string
|
||||
for rows.Next() {
|
||||
var id, numero, proyecto, estado, moneda, cid, cnombre, cempresa string
|
||||
var fecha, vigencia time.Time
|
||||
var esDoble, incluirIva bool
|
||||
if rows.Scan(&id, &numero, &fecha, &vigencia, &proyecto, &estado, &moneda, &esDoble, &incluirIva, &cid, &cnombre, &cempresa) == nil {
|
||||
cotIDs = append(cotIDs, id)
|
||||
recientes = append(recientes, map[string]any{
|
||||
"id": id,
|
||||
"numero": numero,
|
||||
"fecha": fecha,
|
||||
"vigencia": vigencia,
|
||||
"proyecto": proyecto,
|
||||
"estado": estado,
|
||||
"moneda": moneda,
|
||||
"esDoble": esDoble,
|
||||
"incluirIva": incluirIva,
|
||||
"cliente": map[string]any{
|
||||
"id": cid,
|
||||
"nombre": cnombre,
|
||||
"empresa": nullableStr(cempresa),
|
||||
},
|
||||
"servicios": []any{},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if len(cotIDs) > 0 {
|
||||
svcRows, err := s.Pool.Query(ctx, `
|
||||
SELECT "cotizacionId", "tipoPago", "precio", "seleccionado", "opcion"
|
||||
FROM "ServicioCotizado"
|
||||
WHERE "cotizacionId" = ANY($1)
|
||||
`, cotIDs)
|
||||
if err == nil {
|
||||
defer svcRows.Close()
|
||||
byCot := map[string][]map[string]any{}
|
||||
for svcRows.Next() {
|
||||
var qid, tipoPago string
|
||||
var precio float64
|
||||
var sel bool
|
||||
var opcion *string
|
||||
if svcRows.Scan(&qid, &tipoPago, &precio, &sel, &opcion) == nil {
|
||||
byCot[qid] = append(byCot[qid], map[string]any{
|
||||
"tipoPago": tipoPago,
|
||||
"precio": precio,
|
||||
"seleccionado": sel,
|
||||
"opcion": opcion,
|
||||
})
|
||||
}
|
||||
}
|
||||
for _, item := range recientes {
|
||||
if svcs, ok := byCot[item["id"].(string)]; ok {
|
||||
item["servicios"] = svcs
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"totalCotizaciones": totalCot,
|
||||
"totalClientes": totalCli,
|
||||
"totalServicios": totalSvc,
|
||||
"cotizacionesRecientes": recientes,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleAprobarTokenGet(w http.ResponseWriter, r *http.Request) {
|
||||
rawToken := strings.TrimSpace(chi.URLParam(r, "token"))
|
||||
if rawToken == "" {
|
||||
writeError(w, http.StatusNotFound, "Enlace invalido")
|
||||
return
|
||||
}
|
||||
tokenHash := auth.HashSecret(rawToken)
|
||||
|
||||
var tokID, cotID, numero, proyecto, estado, moneda, cNombre string
|
||||
var cEmpresa, cEmail, creadaPorAgente *string
|
||||
var expiraAt time.Time
|
||||
var usadoAt *time.Time
|
||||
var incluirIva, esDoble bool
|
||||
var fecha, vigencia time.Time
|
||||
|
||||
err := s.Pool.QueryRow(r.Context(), `
|
||||
SELECT t."id", t."cotizacionId", t."expiraAt", t."usadoAt",
|
||||
q."numero", q."proyecto", q."estado", q."moneda", q."incluirIva", q."esDoble", q."fecha", q."vigencia", q."creadaPorAgente",
|
||||
c."nombre", c."empresa", c."email"
|
||||
FROM "ApprovalToken" t
|
||||
JOIN "Cotizacion" q ON q."id" = t."cotizacionId"
|
||||
JOIN "Cliente" c ON c."id" = q."clienteId"
|
||||
WHERE t."tokenHash" = $1
|
||||
`, tokenHash).Scan(&tokID, &cotID, &expiraAt, &usadoAt, &numero, &proyecto, &estado, &moneda, &incluirIva, &esDoble, &fecha, &vigencia, &creadaPorAgente, &cNombre, &cEmpresa, &cEmail)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "Enlace de aprobacion no encontrado")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "Error consultando enlace")
|
||||
return
|
||||
}
|
||||
|
||||
if usadoAt != nil {
|
||||
writeJSON(w, http.StatusGone, map[string]any{"error": "Este enlace ya fue utilizado", "usado": true})
|
||||
return
|
||||
}
|
||||
if time.Now().After(expiraAt) {
|
||||
writeJSON(w, http.StatusGone, map[string]any{"error": "Este enlace ha expirado", "expirado": true})
|
||||
return
|
||||
}
|
||||
|
||||
svcRows, _ := s.Pool.Query(r.Context(), `
|
||||
SELECT s."id", COALESCE(s."nombre", sc."nombre", 'Servicio'), s."fase", s."tipoPago", s."precio", s."tiempoEntrega", s."seleccionado", s."modeloCobro", s."opcion"
|
||||
FROM "ServicioCotizado" s
|
||||
LEFT JOIN "ServicioCatalogo" sc ON sc."id" = s."servicioCatalogoId"
|
||||
WHERE s."cotizacionId" = $1
|
||||
ORDER BY s."fase" ASC, s."createdAt" ASC
|
||||
`, cotID)
|
||||
partidas := []map[string]any{}
|
||||
var calcSvcs []domain.ServicioCalc
|
||||
if svcRows != nil {
|
||||
defer svcRows.Close()
|
||||
for svcRows.Next() {
|
||||
var sid, nom, tp, te, mc string
|
||||
var fase int
|
||||
var precio float64
|
||||
var sel bool
|
||||
var op *string
|
||||
if svcRows.Scan(&sid, &nom, &fase, &tp, &precio, &te, &sel, &mc, &op) == nil {
|
||||
partidas = append(partidas, map[string]any{
|
||||
"id": sid, "nombre": nom, "fase": fase, "tipoPago": tp, "precio": precio,
|
||||
"tiempoEntrega": te, "seleccionado": sel, "modeloCobro": mc, "opcion": op,
|
||||
})
|
||||
calcSvcs = append(calcSvcs, domain.ServicioCalc{
|
||||
Nombre: nom, TipoPago: tp, Precio: precio, Seleccionado: sel, ModeloCobro: mc, Opcion: op,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
totales := domain.CalcularTotalesCotizacion(calcSvcs, incluirIva)
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"cotizacion": map[string]any{
|
||||
"id": cotID,
|
||||
"numero": numero,
|
||||
"proyecto": proyecto,
|
||||
"estado": estado,
|
||||
"moneda": moneda,
|
||||
"incluirIva": incluirIva,
|
||||
"esDoble": esDoble,
|
||||
"fecha": fecha,
|
||||
"vigencia": vigencia,
|
||||
"creadaPorAgente": creadaPorAgente,
|
||||
"cliente": map[string]any{
|
||||
"nombre": cNombre,
|
||||
"empresa": cEmpresa,
|
||||
"email": cEmail,
|
||||
},
|
||||
"totales": totales,
|
||||
"partidas": partidas,
|
||||
"servicios": partidas,
|
||||
},
|
||||
"puedeAprobar": estado == "borrador",
|
||||
"totales": totales,
|
||||
"expiraAt": expiraAt,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleAprobarTokenPost(w http.ResponseWriter, r *http.Request) {
|
||||
rawToken := strings.TrimSpace(chi.URLParam(r, "token"))
|
||||
var body struct {
|
||||
Confirmar bool `json:"confirmar"`
|
||||
}
|
||||
if err := decodeJSON(r, &body); err != nil || !body.Confirmar {
|
||||
writeError(w, http.StatusBadRequest, "Se requiere confirmar: true para aprobar la cotizacion")
|
||||
return
|
||||
}
|
||||
tokenHash := auth.HashSecret(rawToken)
|
||||
ip := audit.ClientIP(r)
|
||||
|
||||
tx, err := s.Pool.Begin(r.Context())
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error iniciando transaccion")
|
||||
return
|
||||
}
|
||||
defer tx.Rollback(r.Context())
|
||||
|
||||
var tokID, cotID, estado, numero string
|
||||
var expiraAt time.Time
|
||||
var usadoAt *time.Time
|
||||
err = tx.QueryRow(r.Context(), `
|
||||
SELECT t."id", t."cotizacionId", t."expiraAt", t."usadoAt", q."estado", q."numero"
|
||||
FROM "ApprovalToken" t
|
||||
JOIN "Cotizacion" q ON q."id" = t."cotizacionId"
|
||||
WHERE t."tokenHash" = $1
|
||||
FOR UPDATE OF t, q
|
||||
`, tokenHash).Scan(&tokID, &cotID, &expiraAt, &usadoAt, &estado, &numero)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "Enlace de aprobacion no encontrado")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "Error validando enlace")
|
||||
return
|
||||
}
|
||||
if usadoAt != nil || time.Now().After(expiraAt) {
|
||||
writeError(w, http.StatusGone, "El enlace de aprobacion ya fue usado o expiro")
|
||||
return
|
||||
}
|
||||
|
||||
tr := domain.ValidarTransicionEstado(domain.ValidarTransicionInput{
|
||||
Actual: estado,
|
||||
Nuevo: "aprobada",
|
||||
Actor: domain.ActorInfo{Type: "enlace_firmado"},
|
||||
ViaEndpoint: "enlace_firmado",
|
||||
})
|
||||
if !tr.OK {
|
||||
writeError(w, tr.Status, tr.Error)
|
||||
return
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
if _, err := tx.Exec(r.Context(), `
|
||||
UPDATE "ApprovalToken" SET "usadoAt" = $1, "usadoIp" = $2 WHERE "id" = $3
|
||||
`, now, ip, tokID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error consumiendo enlace")
|
||||
return
|
||||
}
|
||||
// Invalidate sibling open tokens
|
||||
_, _ = tx.Exec(r.Context(), `
|
||||
UPDATE "ApprovalToken" SET "usadoAt" = $1 WHERE "cotizacionId" = $2 AND "usadoAt" IS NULL
|
||||
`, now, cotID)
|
||||
|
||||
if _, err := tx.Exec(r.Context(), `
|
||||
UPDATE "Cotizacion"
|
||||
SET "estado" = 'aprobada', "aprobadaAt" = $1, "aprobacionMetodo" = 'enlace_firmado', "updatedAt" = NOW()
|
||||
WHERE "id" = $2
|
||||
`, now, cotID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error aprobando cotizacion")
|
||||
return
|
||||
}
|
||||
if err := tx.Commit(r.Context()); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error confirmando aprobacion")
|
||||
return
|
||||
}
|
||||
|
||||
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
||||
ActorTipo: "system",
|
||||
ActorNombre: "enlace_firmado",
|
||||
Accion: "cotizacion.aprobar",
|
||||
RecursoTipo: "cotizacion",
|
||||
RecursoID: cotID,
|
||||
IP: ip,
|
||||
RequestID: audit.RequestID(r),
|
||||
Exito: true,
|
||||
Detalle: map[string]any{"numero": numero, "metodo": "enlace_firmado"},
|
||||
})
|
||||
|
||||
go s.Webhooks.Emitir(context.Background(), "cotizacion.aprobada", map[string]any{
|
||||
"cotizacionId": cotID,
|
||||
"numero": numero,
|
||||
"estado": "aprobada",
|
||||
"aprobacionMetodo": "enlace_firmado",
|
||||
"aprobadaAt": now.UTC().Format(time.RFC3339),
|
||||
})
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"ok": true,
|
||||
"cotizacionId": cotID,
|
||||
"numero": numero,
|
||||
"estado": "aprobada",
|
||||
"aprobadaAt": now,
|
||||
})
|
||||
}
|
||||
|
||||
func nullableStr(s string) *string {
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
return &s
|
||||
}
|
||||
|
||||
func parseJSONRawOrEmptyArray(raw []byte) any {
|
||||
if len(raw) == 0 {
|
||||
return []any{}
|
||||
}
|
||||
var v any
|
||||
if err := json.Unmarshal(raw, &v); err != nil {
|
||||
return []any{}
|
||||
}
|
||||
return v
|
||||
}
|
||||
@@ -0,0 +1,979 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"cotizador/internal/audit"
|
||||
"cotizador/internal/auth"
|
||||
"cotizador/internal/db"
|
||||
"cotizador/internal/excel"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *Server) queryServicioCatalogo(ctx context.Context, whereSQL string, args ...any) ([]map[string]any, error) {
|
||||
rows, err := s.Pool.Query(ctx, `
|
||||
SELECT sc."id", sc."nombre", sc."descripcion", sc."fase", sc."tipoPago", sc."precioBase",
|
||||
sc."tiempoEntrega", sc."entregablesDefault", sc."categoriaId", sc."variante", sc."nivel",
|
||||
sc."activo", sc."soloAdmin", sc."orden",
|
||||
c."nombre", c."color",
|
||||
(SELECT COUNT(*) FROM "ServicioCotizado" cot WHERE cot."servicioCatalogoId" = sc."id") AS en_cotizaciones
|
||||
FROM "ServicioCatalogo" sc
|
||||
LEFT JOIN "Categoria" c ON c."id" = sc."categoriaId"
|
||||
WHERE `+whereSQL+`
|
||||
ORDER BY sc."fase" ASC, sc."orden" ASC, sc."nombre" ASC
|
||||
`, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
out := []map[string]any{}
|
||||
for rows.Next() {
|
||||
var id, nombre, tipoPago, tiempoEntrega string
|
||||
var descripcion, categoriaID, variante, nivel, catNombre, catColor *string
|
||||
var fase, orden, enCot int
|
||||
var precioBase float64
|
||||
var entregablesRaw []byte
|
||||
var activo, soloAdmin bool
|
||||
if err := rows.Scan(
|
||||
&id, &nombre, &descripcion, &fase, &tipoPago, &precioBase,
|
||||
&tiempoEntrega, &entregablesRaw, &categoriaID, &variante, &nivel,
|
||||
&activo, &soloAdmin, &orden,
|
||||
&catNombre, &catColor, &enCot,
|
||||
); err != nil {
|
||||
continue
|
||||
}
|
||||
var entregables []string
|
||||
_ = json.Unmarshal(entregablesRaw, &entregables)
|
||||
if entregables == nil {
|
||||
entregables = []string{}
|
||||
}
|
||||
var catRel any
|
||||
if categoriaID != nil && catNombre != nil {
|
||||
catRel = map[string]any{"id": *categoriaID, "nombre": *catNombre, "color": catColor}
|
||||
}
|
||||
out = append(out, map[string]any{
|
||||
"id": id,
|
||||
"nombre": nombre,
|
||||
"descripcion": descripcion,
|
||||
"fase": fase,
|
||||
"tipoPago": tipoPago,
|
||||
"precioBase": precioBase,
|
||||
"tiempoEntrega": tiempoEntrega,
|
||||
"entregablesDefault": entregables,
|
||||
"categoriaId": categoriaID,
|
||||
"categoriaNombre": catNombre,
|
||||
"categoriaColor": catColor,
|
||||
"categoriaRel": catRel,
|
||||
"variante": variante,
|
||||
"nivel": nivel,
|
||||
"activo": activo,
|
||||
"soloAdmin": soloAdmin,
|
||||
"orden": orden,
|
||||
"enCotizaciones": enCot,
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *Server) handleCatalogoList(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"catalogo:leer"}, RecursoTipo: "catalogo"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
conds := []string{"1=1"}
|
||||
args := []any{}
|
||||
add := func(v any) string {
|
||||
args = append(args, v)
|
||||
return fmt.Sprintf("$%d", len(args))
|
||||
}
|
||||
|
||||
if actor.IsAgent() {
|
||||
conds = append(conds, `sc."soloAdmin" = false`)
|
||||
}
|
||||
if v := strings.TrimSpace(q.Get("q")); v != "" {
|
||||
p := add("%" + v + "%")
|
||||
conds = append(conds, fmt.Sprintf(`(sc."nombre" ILIKE %s OR COALESCE(sc."descripcion", '') ILIKE %s OR COALESCE(sc."variante", '') ILIKE %s)`, p, p, p))
|
||||
}
|
||||
if v := strings.TrimSpace(q.Get("fase")); v != "" {
|
||||
if f, err := strconv.Atoi(v); err == nil {
|
||||
conds = append(conds, `sc."fase" = `+add(f))
|
||||
}
|
||||
}
|
||||
if v := strings.TrimSpace(q.Get("tipoPago")); v != "" {
|
||||
conds = append(conds, `sc."tipoPago" = `+add(v))
|
||||
}
|
||||
if v := strings.TrimSpace(q.Get("categoriaId")); v != "" {
|
||||
conds = append(conds, `sc."categoriaId" = `+add(v))
|
||||
}
|
||||
if v := strings.TrimSpace(q.Get("activo")); v == "true" || v == "false" {
|
||||
conds = append(conds, `sc."activo" = `+add(v == "true"))
|
||||
}
|
||||
|
||||
list, err := s.queryServicioCatalogo(r.Context(), strings.Join(conds, " AND "), args...)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error listando catalogo")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, list)
|
||||
}
|
||||
|
||||
func (s *Server) handleCatalogoGet(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"catalogo:leer"}, RecursoTipo: "catalogo"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
list, err := s.queryServicioCatalogo(r.Context(), `sc."id" = $1`, id)
|
||||
if err != nil || len(list) == 0 {
|
||||
writeError(w, http.StatusNotFound, "Servicio no encontrado")
|
||||
return
|
||||
}
|
||||
svc := list[0]
|
||||
if actor.IsAgent() && svc["soloAdmin"] == true {
|
||||
tipo, aid, anom := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
||||
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
||||
Accion: "catalogo.solo_admin_bloqueado", RecursoTipo: "catalogo", RecursoID: id,
|
||||
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false,
|
||||
})
|
||||
writeError(w, http.StatusForbidden, "Servicio restringido para administradores")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, svc)
|
||||
}
|
||||
|
||||
func (s *Server) handleCatalogoCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "catalogo"}); !ok {
|
||||
return
|
||||
}
|
||||
var raw map[string]any
|
||||
if err := decodeJSON(r, &raw); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "JSON invalido")
|
||||
return
|
||||
}
|
||||
|
||||
var detalles []ValidationDetail
|
||||
nombre := strings.TrimSpace(asString(raw["nombre"]))
|
||||
if nombre == "" {
|
||||
detalles = append(detalles, ValidationDetail{Campo: "nombre", Mensaje: "El nombre es obligatorio"})
|
||||
}
|
||||
fase, faseOK := asInt(raw["fase"])
|
||||
if !faseOK || fase < 0 || fase > 3 {
|
||||
detalles = append(detalles, ValidationDetail{Campo: "fase", Mensaje: "La fase debe ser 0, 1, 2 o 3"})
|
||||
}
|
||||
tipoPago := strings.TrimSpace(asString(raw["tipoPago"]))
|
||||
if tipoPago != "unico" && tipoPago != "mensual" {
|
||||
detalles = append(detalles, ValidationDetail{Campo: "tipoPago", Mensaje: "tipoPago debe ser unico o mensual"})
|
||||
}
|
||||
precioBase, precioOK := asFloat(raw["precioBase"])
|
||||
if !precioOK || precioBase < 0 {
|
||||
detalles = append(detalles, ValidationDetail{Campo: "precioBase", Mensaje: "precioBase debe ser >= 0"})
|
||||
}
|
||||
if len(detalles) > 0 {
|
||||
writeValidationError(w, detalles)
|
||||
return
|
||||
}
|
||||
|
||||
var categoriaID *string
|
||||
if cid := strings.TrimSpace(asString(raw["categoriaId"])); cid != "" {
|
||||
var exists bool
|
||||
_ = s.Pool.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM "Categoria" WHERE "id" = $1)`, cid).Scan(&exists)
|
||||
if !exists {
|
||||
writeValidationError(w, []ValidationDetail{{Campo: "categoriaId", Mensaje: "La categoria no existe"}})
|
||||
return
|
||||
}
|
||||
categoriaID = &cid
|
||||
}
|
||||
|
||||
orden, hasOrden := asInt(raw["orden"])
|
||||
if !hasOrden {
|
||||
var maxOrden int
|
||||
_ = s.Pool.QueryRow(r.Context(), `SELECT COALESCE(MAX("orden"), 0) FROM "ServicioCatalogo" WHERE "fase" = $1`, fase).Scan(&maxOrden)
|
||||
orden = maxOrden + 1
|
||||
}
|
||||
|
||||
tiempoEntrega := firstNonEmptyStr(asString(raw["tiempoEntrega"]), "4 - 10 dias")
|
||||
entregables := asStringSlice(raw["entregablesDefault"])
|
||||
entJSON, _ := json.Marshal(entregables)
|
||||
|
||||
activo := true
|
||||
if v, ok := raw["activo"].(bool); ok {
|
||||
activo = v
|
||||
}
|
||||
soloAdmin := false
|
||||
if v, ok := raw["soloAdmin"].(bool); ok {
|
||||
soloAdmin = v
|
||||
}
|
||||
|
||||
id := db.NewID()
|
||||
_, err := s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "ServicioCatalogo" (
|
||||
"id", "nombre", "descripcion", "fase", "tipoPago", "precioBase",
|
||||
"tiempoEntrega", "entregablesDefault", "categoriaId", "variante", "nivel",
|
||||
"activo", "soloAdmin", "orden", "createdAt", "updatedAt"
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,NOW(),NOW())
|
||||
`, id, nombre, nullableTrim(asString(raw["descripcion"])), fase, tipoPago, precioBase,
|
||||
tiempoEntrega, entJSON, categoriaID, nullableTrim(asString(raw["variante"])), nullableTrim(asString(raw["nivel"])),
|
||||
activo, soloAdmin, orden)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error creando servicio")
|
||||
return
|
||||
}
|
||||
|
||||
list, _ := s.queryServicioCatalogo(r.Context(), `sc."id" = $1`, id)
|
||||
if len(list) == 1 {
|
||||
writeJSON(w, http.StatusCreated, list[0])
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]any{"id": id})
|
||||
}
|
||||
|
||||
func (s *Server) handleCatalogoPatch(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "catalogo"}); !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
var exists bool
|
||||
_ = s.Pool.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM "ServicioCatalogo" WHERE "id" = $1)`, id).Scan(&exists)
|
||||
if !exists {
|
||||
writeError(w, http.StatusNotFound, "Servicio no encontrado")
|
||||
return
|
||||
}
|
||||
|
||||
var raw map[string]any
|
||||
if err := decodeJSON(r, &raw); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "JSON invalido")
|
||||
return
|
||||
}
|
||||
|
||||
sets := []string{`"updatedAt" = NOW()`}
|
||||
args := []any{}
|
||||
add := func(col string, val any) {
|
||||
args = append(args, val)
|
||||
sets = append(sets, fmt.Sprintf(`"%s" = $%d`, col, len(args)))
|
||||
}
|
||||
|
||||
if v, ok := raw["nombre"]; ok {
|
||||
nom := strings.TrimSpace(asString(v))
|
||||
if nom == "" {
|
||||
writeValidationError(w, []ValidationDetail{{Campo: "nombre", Mensaje: "El nombre no puede estar vacio"}})
|
||||
return
|
||||
}
|
||||
add("nombre", nom)
|
||||
}
|
||||
if v, ok := raw["descripcion"]; ok {
|
||||
add("descripcion", nullableTrim(asString(v)))
|
||||
}
|
||||
if v, ok := raw["fase"]; ok {
|
||||
f, okInt := asInt(v)
|
||||
if !okInt || f < 0 || f > 3 {
|
||||
writeValidationError(w, []ValidationDetail{{Campo: "fase", Mensaje: "Fase invalida"}})
|
||||
return
|
||||
}
|
||||
add("fase", f)
|
||||
}
|
||||
if v, ok := raw["tipoPago"]; ok {
|
||||
tp := strings.TrimSpace(asString(v))
|
||||
if tp != "unico" && tp != "mensual" {
|
||||
writeValidationError(w, []ValidationDetail{{Campo: "tipoPago", Mensaje: "tipoPago invalido"}})
|
||||
return
|
||||
}
|
||||
add("tipoPago", tp)
|
||||
}
|
||||
if v, ok := raw["precioBase"]; ok {
|
||||
pb, okF := asFloat(v)
|
||||
if !okF || pb < 0 {
|
||||
writeValidationError(w, []ValidationDetail{{Campo: "precioBase", Mensaje: "precioBase invalido"}})
|
||||
return
|
||||
}
|
||||
add("precioBase", pb)
|
||||
}
|
||||
if v, ok := raw["tiempoEntrega"]; ok {
|
||||
add("tiempoEntrega", firstNonEmptyStr(asString(v), "4 - 10 dias"))
|
||||
}
|
||||
if v, ok := raw["entregablesDefault"]; ok {
|
||||
entJSON, _ := json.Marshal(asStringSlice(v))
|
||||
add("entregablesDefault", entJSON)
|
||||
}
|
||||
if v, ok := raw["categoriaId"]; ok {
|
||||
cid := strings.TrimSpace(asString(v))
|
||||
if cid == "" {
|
||||
add("categoriaId", nil)
|
||||
} else {
|
||||
var catOK bool
|
||||
_ = s.Pool.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM "Categoria" WHERE "id" = $1)`, cid).Scan(&catOK)
|
||||
if !catOK {
|
||||
writeValidationError(w, []ValidationDetail{{Campo: "categoriaId", Mensaje: "La categoria no existe"}})
|
||||
return
|
||||
}
|
||||
add("categoriaId", cid)
|
||||
}
|
||||
}
|
||||
if v, ok := raw["variante"]; ok {
|
||||
add("variante", nullableTrim(asString(v)))
|
||||
}
|
||||
if v, ok := raw["nivel"]; ok {
|
||||
add("nivel", nullableTrim(asString(v)))
|
||||
}
|
||||
if v, ok := raw["activo"].(bool); ok {
|
||||
add("activo", v)
|
||||
}
|
||||
if v, ok := raw["soloAdmin"].(bool); ok {
|
||||
add("soloAdmin", v)
|
||||
}
|
||||
if v, ok := raw["orden"]; ok {
|
||||
if ord, okInt := asInt(v); okInt {
|
||||
add("orden", ord)
|
||||
}
|
||||
}
|
||||
|
||||
args = append(args, id)
|
||||
_, err := s.Pool.Exec(r.Context(), fmt.Sprintf(`UPDATE "ServicioCatalogo" SET %s WHERE "id" = $%d`, strings.Join(sets, ", "), len(args)), args...)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error actualizando servicio")
|
||||
return
|
||||
}
|
||||
|
||||
list, _ := s.queryServicioCatalogo(r.Context(), `sc."id" = $1`, id)
|
||||
if len(list) == 1 {
|
||||
writeJSON(w, http.StatusOK, list[0])
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"id": id})
|
||||
}
|
||||
|
||||
func (s *Server) handleCatalogoDelete(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "catalogo"}); !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
var enCot int
|
||||
if err := s.Pool.QueryRow(r.Context(), `SELECT COUNT(*) FROM "ServicioCotizado" WHERE "servicioCatalogoId" = $1`, id).Scan(&enCot); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error verificando uso del servicio")
|
||||
return
|
||||
}
|
||||
if enCot > 0 {
|
||||
tag, err := s.Pool.Exec(r.Context(), `UPDATE "ServicioCatalogo" SET "activo" = false, "updatedAt" = NOW() WHERE "id" = $1`, id)
|
||||
if err != nil || tag.RowsAffected() == 0 {
|
||||
writeError(w, http.StatusNotFound, "Servicio no encontrado")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "archivado": true, "enCotizaciones": enCot})
|
||||
return
|
||||
}
|
||||
tag, err := s.Pool.Exec(r.Context(), `DELETE FROM "ServicioCatalogo" WHERE "id" = $1`, id)
|
||||
if err != nil || tag.RowsAffected() == 0 {
|
||||
writeError(w, http.StatusNotFound, "Servicio no encontrado")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "eliminado": true})
|
||||
}
|
||||
|
||||
func (s *Server) handleCategoriasList(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"catalogo:leer"}, RecursoTipo: "categoria"}); !ok {
|
||||
return
|
||||
}
|
||||
rows, err := s.Pool.Query(r.Context(), `
|
||||
SELECT c."id", c."nombre", c."descripcion", c."color", c."activo", c."orden",
|
||||
(SELECT COUNT(*) FROM "ServicioCatalogo" sc WHERE sc."categoriaId" = c."id") AS servicios_count
|
||||
FROM "Categoria" c
|
||||
ORDER BY c."orden" ASC, c."nombre" ASC
|
||||
`)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error listando categorias")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
list := []map[string]any{}
|
||||
for rows.Next() {
|
||||
var id, nombre, color string
|
||||
var desc *string
|
||||
var activo bool
|
||||
var orden, cnt int
|
||||
if rows.Scan(&id, &nombre, &desc, &color, &activo, &orden, &cnt) == nil {
|
||||
list = append(list, map[string]any{
|
||||
"id": id, "nombre": nombre, "descripcion": desc, "color": color, "activo": activo, "orden": orden,
|
||||
"_count": map[string]any{"servicios": cnt},
|
||||
})
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, list)
|
||||
}
|
||||
|
||||
func (s *Server) handleCategoriasCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "categoria"}); !ok {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Nombre string `json:"nombre"`
|
||||
Descripcion *string `json:"descripcion"`
|
||||
Color string `json:"color"`
|
||||
Orden *int `json:"orden"`
|
||||
}
|
||||
if err := decodeJSON(r, &body); err != nil || strings.TrimSpace(body.Nombre) == "" {
|
||||
writeError(w, http.StatusBadRequest, "El nombre es obligatorio")
|
||||
return
|
||||
}
|
||||
color := firstNonEmptyStr(body.Color, "#6b7280")
|
||||
orden := 0
|
||||
if body.Orden != nil {
|
||||
orden = *body.Orden
|
||||
} else {
|
||||
_ = s.Pool.QueryRow(r.Context(), `SELECT COALESCE(MAX("orden"), 0) + 1 FROM "Categoria"`).Scan(&orden)
|
||||
}
|
||||
id := db.NewID()
|
||||
_, err := s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "Categoria" ("id", "nombre", "descripcion", "color", "activo", "orden", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, true, $5, NOW(), NOW())
|
||||
`, id, strings.TrimSpace(body.Nombre), body.Descripcion, color, orden)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "23505") {
|
||||
writeError(w, http.StatusConflict, "Ya existe una categoria con ese nombre")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "Error creando categoria")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]any{
|
||||
"id": id, "nombre": strings.TrimSpace(body.Nombre), "descripcion": body.Descripcion, "color": color, "activo": true, "orden": orden,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleCategoriasUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "categoria"}); !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
var body struct {
|
||||
Nombre *string `json:"nombre"`
|
||||
Descripcion *string `json:"descripcion"`
|
||||
Color *string `json:"color"`
|
||||
Activo *bool `json:"activo"`
|
||||
Orden *int `json:"orden"`
|
||||
}
|
||||
if err := decodeJSON(r, &body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "JSON invalido")
|
||||
return
|
||||
}
|
||||
sets := []string{`"updatedAt" = NOW()`}
|
||||
args := []any{}
|
||||
add := func(col string, val any) {
|
||||
args = append(args, val)
|
||||
sets = append(sets, fmt.Sprintf(`"%s" = $%d`, col, len(args)))
|
||||
}
|
||||
if body.Nombre != nil {
|
||||
add("nombre", strings.TrimSpace(*body.Nombre))
|
||||
}
|
||||
if body.Descripcion != nil {
|
||||
add("descripcion", *body.Descripcion)
|
||||
}
|
||||
if body.Color != nil {
|
||||
add("color", *body.Color)
|
||||
}
|
||||
if body.Activo != nil {
|
||||
add("activo", *body.Activo)
|
||||
}
|
||||
if body.Orden != nil {
|
||||
add("orden", *body.Orden)
|
||||
}
|
||||
args = append(args, id)
|
||||
var nombre, color string
|
||||
var desc *string
|
||||
var activo bool
|
||||
var orden int
|
||||
err := s.Pool.QueryRow(r.Context(), fmt.Sprintf(`
|
||||
UPDATE "Categoria" SET %s WHERE "id" = $%d
|
||||
RETURNING "nombre", "descripcion", "color", "activo", "orden"
|
||||
`, strings.Join(sets, ", "), len(args)), args...).Scan(&nombre, &desc, &color, &activo, &orden)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "Categoria no encontrada")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "Error actualizando categoria")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"id": id, "nombre": nombre, "descripcion": desc, "color": color, "activo": activo, "orden": orden})
|
||||
}
|
||||
|
||||
func (s *Server) handleCategoriasDelete(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "categoria"}); !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
var cnt int
|
||||
_ = s.Pool.QueryRow(r.Context(), `SELECT COUNT(*) FROM "ServicioCatalogo" WHERE "categoriaId" = $1`, id).Scan(&cnt)
|
||||
if cnt > 0 {
|
||||
writeError(w, http.StatusConflict, "No se puede eliminar una categoria con servicios asociados")
|
||||
return
|
||||
}
|
||||
tag, err := s.Pool.Exec(r.Context(), `DELETE FROM "Categoria" WHERE "id" = $1`, id)
|
||||
if err != nil || tag.RowsAffected() == 0 {
|
||||
writeError(w, http.StatusNotFound, "Categoria no encontrada")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||
}
|
||||
|
||||
func (s *Server) loadPaqueteFull(ctx context.Context, paqueteID string, hideSoloAdmin bool) (map[string]any, error) {
|
||||
var id, nombre string
|
||||
var desc *string
|
||||
var activo bool
|
||||
err := s.Pool.QueryRow(ctx, `SELECT "id", "nombre", "descripcion", "activo" FROM "Paquete" WHERE "id" = $1`, paqueteID).Scan(&id, &nombre, &desc, &activo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
faseRows, err := s.Pool.Query(ctx, `SELECT "id", "nombre", "orden" FROM "FasePaquete" WHERE "paqueteId" = $1 ORDER BY "orden" ASC`, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer faseRows.Close()
|
||||
|
||||
fases := []map[string]any{}
|
||||
for faseRows.Next() {
|
||||
var fid, fnom string
|
||||
var forden int
|
||||
if faseRows.Scan(&fid, &fnom, &forden) != nil {
|
||||
continue
|
||||
}
|
||||
filterAdmin := ""
|
||||
if hideSoloAdmin {
|
||||
filterAdmin = ` AND sc."soloAdmin" = false`
|
||||
}
|
||||
sRows, _ := s.Pool.Query(ctx, `
|
||||
SELECT sp."id", sp."servicioCatalogoId", sc."nombre", sc."descripcion", sc."fase", sc."tipoPago",
|
||||
sc."precioBase", sc."tiempoEntrega", sc."entregablesDefault", sc."categoriaId", sc."variante", sc."nivel", sc."soloAdmin",
|
||||
c."nombre", c."color"
|
||||
FROM "ServicioPaquete" sp
|
||||
JOIN "ServicioCatalogo" sc ON sc."id" = sp."servicioCatalogoId"
|
||||
LEFT JOIN "Categoria" c ON c."id" = sc."categoriaId"
|
||||
WHERE sp."fasePaqueteId" = $1 AND sc."activo" = true`+filterAdmin+`
|
||||
ORDER BY sc."orden" ASC, sc."nombre" ASC
|
||||
`, fid)
|
||||
svcs := []map[string]any{}
|
||||
if sRows != nil {
|
||||
for sRows.Next() {
|
||||
var spid, scid, snom, tp, te string
|
||||
var sdesc, cid, vari, niv, cnom, ccol *string
|
||||
var sfase int
|
||||
var pb float64
|
||||
var entRaw []byte
|
||||
var sadmin bool
|
||||
if sRows.Scan(&spid, &scid, &snom, &sdesc, &sfase, &tp, &pb, &te, &entRaw, &cid, &vari, &niv, &sadmin, &cnom, &ccol) == nil {
|
||||
var ent []string
|
||||
_ = json.Unmarshal(entRaw, &ent)
|
||||
if ent == nil {
|
||||
ent = []string{}
|
||||
}
|
||||
svcs = append(svcs, map[string]any{
|
||||
"id": spid,
|
||||
"servicioCatalogoId": scid,
|
||||
"fasePaqueteId": fid,
|
||||
"servicio": map[string]any{
|
||||
"id": scid, "nombre": snom, "descripcion": sdesc, "fase": sfase,
|
||||
"tipoPago": tp, "precioBase": pb, "tiempoEntrega": te,
|
||||
"entregablesDefault": ent, "categoriaId": cid, "variante": vari, "nivel": niv,
|
||||
"soloAdmin": sadmin, "categoriaNombre": cnom, "categoriaColor": ccol,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
sRows.Close()
|
||||
}
|
||||
fases = append(fases, map[string]any{
|
||||
"id": fid, "paqueteId": id, "nombre": fnom, "orden": forden, "servicios": svcs,
|
||||
})
|
||||
}
|
||||
return map[string]any{
|
||||
"id": id, "nombre": nombre, "descripcion": desc, "activo": activo, "fases": fases,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Server) handlePaquetesList(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"catalogo:leer"}, RecursoTipo: "paquete"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
rows, err := s.Pool.Query(r.Context(), `SELECT "id" FROM "Paquete" WHERE "activo" = true ORDER BY "createdAt" ASC`)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error listando paquetes")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
var ids []string
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if rows.Scan(&id) == nil {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
}
|
||||
list := []map[string]any{}
|
||||
for _, id := range ids {
|
||||
if p, err := s.loadPaqueteFull(r.Context(), id, actor.IsAgent()); err == nil {
|
||||
list = append(list, p)
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, list)
|
||||
}
|
||||
|
||||
func (s *Server) handlePaquetesGet(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"catalogo:leer"}, RecursoTipo: "paquete"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
p, err := s.loadPaqueteFull(r.Context(), id, actor.IsAgent())
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "Paquete no encontrado")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, p)
|
||||
}
|
||||
|
||||
func (s *Server) handlePaquetesCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "paquete"}); !ok {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Nombre string `json:"nombre"`
|
||||
Descripcion *string `json:"descripcion"`
|
||||
Fases []struct {
|
||||
Nombre string `json:"nombre"`
|
||||
Orden int `json:"orden"`
|
||||
} `json:"fases"`
|
||||
}
|
||||
if err := decodeJSON(r, &body); err != nil || strings.TrimSpace(body.Nombre) == "" {
|
||||
writeError(w, http.StatusBadRequest, "El nombre del paquete es obligatorio")
|
||||
return
|
||||
}
|
||||
id := db.NewID()
|
||||
_, err := s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "Paquete" ("id", "nombre", "descripcion", "activo", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, true, NOW(), NOW())
|
||||
`, id, strings.TrimSpace(body.Nombre), body.Descripcion)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error creando paquete")
|
||||
return
|
||||
}
|
||||
for i, f := range body.Fases {
|
||||
ord := f.Orden
|
||||
if ord == 0 {
|
||||
ord = i
|
||||
}
|
||||
_, _ = s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "FasePaquete" ("id", "paqueteId", "nombre", "orden", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, NOW(), NOW())
|
||||
`, db.NewID(), id, strings.TrimSpace(f.Nombre), ord)
|
||||
}
|
||||
p, _ := s.loadPaqueteFull(r.Context(), id, false)
|
||||
writeJSON(w, http.StatusCreated, p)
|
||||
}
|
||||
|
||||
func (s *Server) handlePaquetesUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "paquete"}); !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
var body struct {
|
||||
Nombre *string `json:"nombre"`
|
||||
Descripcion *string `json:"descripcion"`
|
||||
Activo *bool `json:"activo"`
|
||||
}
|
||||
if err := decodeJSON(r, &body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "JSON invalido")
|
||||
return
|
||||
}
|
||||
sets := []string{`"updatedAt" = NOW()`}
|
||||
args := []any{}
|
||||
add := func(col string, val any) {
|
||||
args = append(args, val)
|
||||
sets = append(sets, fmt.Sprintf(`"%s" = $%d`, col, len(args)))
|
||||
}
|
||||
if body.Nombre != nil {
|
||||
add("nombre", strings.TrimSpace(*body.Nombre))
|
||||
}
|
||||
if body.Descripcion != nil {
|
||||
add("descripcion", *body.Descripcion)
|
||||
}
|
||||
if body.Activo != nil {
|
||||
add("activo", *body.Activo)
|
||||
}
|
||||
args = append(args, id)
|
||||
tag, err := s.Pool.Exec(r.Context(), fmt.Sprintf(`UPDATE "Paquete" SET %s WHERE "id" = $%d`, strings.Join(sets, ", "), len(args)), args...)
|
||||
if err != nil || tag.RowsAffected() == 0 {
|
||||
writeError(w, http.StatusNotFound, "Paquete no encontrado")
|
||||
return
|
||||
}
|
||||
p, _ := s.loadPaqueteFull(r.Context(), id, false)
|
||||
writeJSON(w, http.StatusOK, p)
|
||||
}
|
||||
|
||||
func (s *Server) handlePaquetesDelete(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "paquete"}); !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
tag, err := s.Pool.Exec(r.Context(), `DELETE FROM "Paquete" WHERE "id" = $1`, id)
|
||||
if err != nil || tag.RowsAffected() == 0 {
|
||||
writeError(w, http.StatusNotFound, "Paquete no encontrado")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||
}
|
||||
|
||||
func (s *Server) handlePaquetesManage(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "paquete"}); !ok {
|
||||
return
|
||||
}
|
||||
paqueteID := chi.URLParam(r, "id")
|
||||
var body struct {
|
||||
Action string `json:"action"`
|
||||
FaseID string `json:"faseId"`
|
||||
FasePaqueteID string `json:"fasePaqueteId"`
|
||||
Nombre string `json:"nombre"`
|
||||
Orden *int `json:"orden"`
|
||||
ServicioCatalogoID string `json:"servicioCatalogoId"`
|
||||
}
|
||||
if err := decodeJSON(r, &body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "JSON invalido")
|
||||
return
|
||||
}
|
||||
fid := firstNonEmptyStr(body.FasePaqueteID, body.FaseID)
|
||||
|
||||
switch body.Action {
|
||||
case "addFase":
|
||||
ord := 0
|
||||
if body.Orden != nil {
|
||||
ord = *body.Orden
|
||||
} else {
|
||||
_ = s.Pool.QueryRow(r.Context(), `SELECT COALESCE(MAX("orden"), -1) + 1 FROM "FasePaquete" WHERE "paqueteId" = $1`, paqueteID).Scan(&ord)
|
||||
}
|
||||
_, err := s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "FasePaquete" ("id", "paqueteId", "nombre", "orden", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, NOW(), NOW())
|
||||
`, db.NewID(), paqueteID, strings.TrimSpace(body.Nombre), ord)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error agregando fase")
|
||||
return
|
||||
}
|
||||
case "updateFase":
|
||||
if body.Nombre != "" {
|
||||
_, _ = s.Pool.Exec(r.Context(), `UPDATE "FasePaquete" SET "nombre" = $1, "updatedAt" = NOW() WHERE "id" = $2`, strings.TrimSpace(body.Nombre), fid)
|
||||
}
|
||||
if body.Orden != nil {
|
||||
_, _ = s.Pool.Exec(r.Context(), `UPDATE "FasePaquete" SET "orden" = $1, "updatedAt" = NOW() WHERE "id" = $2`, *body.Orden, fid)
|
||||
}
|
||||
case "deleteFase":
|
||||
_, _ = s.Pool.Exec(r.Context(), `DELETE FROM "FasePaquete" WHERE "id" = $1`, fid)
|
||||
case "addServicio":
|
||||
_, _ = s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "ServicioPaquete" ("id", "servicioCatalogoId", "fasePaqueteId", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, NOW(), NOW())
|
||||
ON CONFLICT ("servicioCatalogoId", "fasePaqueteId") DO NOTHING
|
||||
`, db.NewID(), body.ServicioCatalogoID, fid)
|
||||
case "removeServicio":
|
||||
_, _ = s.Pool.Exec(r.Context(), `
|
||||
DELETE FROM "ServicioPaquete" WHERE "servicioCatalogoId" = $1 AND "fasePaqueteId" = $2
|
||||
`, body.ServicioCatalogoID, fid)
|
||||
default:
|
||||
writeError(w, http.StatusBadRequest, "Accion invalida")
|
||||
return
|
||||
}
|
||||
|
||||
p, err := s.loadPaqueteFull(r.Context(), paqueteID, false)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "Paquete no encontrado")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, p)
|
||||
}
|
||||
|
||||
func (s *Server) handleExportCatalogoCSV(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "catalogo"}); !ok {
|
||||
return
|
||||
}
|
||||
list, err := s.queryServicioCatalogo(r.Context(), `sc."activo" = true`)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error exportando catalogo")
|
||||
return
|
||||
}
|
||||
rows := make([]excel.CatalogoCSVRow, 0, len(list))
|
||||
for _, it := range list {
|
||||
cat := ""
|
||||
if c, ok := it["categoriaNombre"].(*string); ok && c != nil {
|
||||
cat = *c
|
||||
}
|
||||
vari := ""
|
||||
if v, ok := it["variante"].(*string); ok && v != nil {
|
||||
vari = *v
|
||||
}
|
||||
ent, _ := it["entregablesDefault"].([]string)
|
||||
rows = append(rows, excel.CatalogoCSVRow{
|
||||
Nombre: asString(it["nombre"]),
|
||||
Categoria: cat,
|
||||
Fase: it["fase"].(int),
|
||||
TipoPago: asString(it["tipoPago"]),
|
||||
PrecioBase: it["precioBase"].(float64),
|
||||
TiempoEntrega: asString(it["tiempoEntrega"]),
|
||||
Entregables: ent,
|
||||
Variante: vari,
|
||||
})
|
||||
}
|
||||
csvBytes, err := excel.ExportCatalogoCSV(rows)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error generando CSV")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="catalogo-servicios.csv"`)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(csvBytes)
|
||||
}
|
||||
|
||||
func (s *Server) handleExportCatalogoPlantilla(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "catalogo"}); !ok {
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="plantilla-catalogo.csv"`)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(excel.PlantillaCatalogoCSV())
|
||||
}
|
||||
|
||||
func (s *Server) handleImportCatalogoCSV(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "catalogo"}); !ok {
|
||||
return
|
||||
}
|
||||
if err := r.ParseMultipartForm(10 << 20); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "Error leyendo archivo multipart")
|
||||
return
|
||||
}
|
||||
file, _, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "Se requiere el archivo en el campo 'file'")
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
raw, err := io.ReadAll(io.LimitReader(file, 10<<20))
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "No se pudo leer el archivo")
|
||||
return
|
||||
}
|
||||
rows, err := excel.ParseCatalogoCSV(raw)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
catMap := map[string]string{}
|
||||
cRows, _ := s.Pool.Query(r.Context(), `SELECT "id", LOWER("nombre") FROM "Categoria" WHERE "activo" = true`)
|
||||
if cRows != nil {
|
||||
for cRows.Next() {
|
||||
var cid, cnom string
|
||||
if cRows.Scan(&cid, &cnom) == nil {
|
||||
catMap[cnom] = cid
|
||||
}
|
||||
}
|
||||
cRows.Close()
|
||||
}
|
||||
|
||||
imported := 0
|
||||
for i, row := range rows {
|
||||
var catID *string
|
||||
if id, ok := catMap[strings.ToLower(strings.TrimSpace(row.Categoria))]; ok {
|
||||
cid := id
|
||||
catID = &cid
|
||||
}
|
||||
entJSON, _ := json.Marshal(row.Entregables)
|
||||
_, err := s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "ServicioCatalogo" (
|
||||
"id", "nombre", "fase", "tipoPago", "precioBase", "tiempoEntrega",
|
||||
"entregablesDefault", "categoriaId", "variante", "activo", "soloAdmin", "orden", "createdAt", "updatedAt"
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,true,false,$10,NOW(),NOW())
|
||||
`, db.NewID(), row.Nombre, row.Fase, row.TipoPago, row.PrecioBase, firstNonEmptyStr(row.TiempoEntrega, "4 - 10 dias"),
|
||||
entJSON, catID, nullableTrim(row.Variante), i+1)
|
||||
if err == nil {
|
||||
imported++
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "importados": imported})
|
||||
}
|
||||
|
||||
func asString(v any) string {
|
||||
if v == nil {
|
||||
return ""
|
||||
}
|
||||
s, ok := v.(string)
|
||||
if ok {
|
||||
return s
|
||||
}
|
||||
return fmt.Sprintf("%v", v)
|
||||
}
|
||||
|
||||
func nullableTrim(s string) *string {
|
||||
t := strings.TrimSpace(s)
|
||||
if t == "" {
|
||||
return nil
|
||||
}
|
||||
return &t
|
||||
}
|
||||
|
||||
func asInt(v any) (int, bool) {
|
||||
switch x := v.(type) {
|
||||
case float64:
|
||||
return int(x), true
|
||||
case int:
|
||||
return x, true
|
||||
case string:
|
||||
n, err := strconv.Atoi(strings.TrimSpace(x))
|
||||
return n, err == nil
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
func asFloat(v any) (float64, bool) {
|
||||
switch x := v.(type) {
|
||||
case float64:
|
||||
return x, true
|
||||
case int:
|
||||
return float64(x), true
|
||||
case string:
|
||||
f, err := strconv.ParseFloat(strings.TrimSpace(x), 64)
|
||||
return f, err == nil
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
func asStringSlice(v any) []string {
|
||||
if v == nil {
|
||||
return []string{}
|
||||
}
|
||||
switch arr := v.(type) {
|
||||
case []string:
|
||||
return arr
|
||||
case []any:
|
||||
out := make([]string, 0, len(arr))
|
||||
for _, item := range arr {
|
||||
if s := strings.TrimSpace(asString(item)); s != "" {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
return out
|
||||
default:
|
||||
return []string{}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,438 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/db"
|
||||
"cotizador/internal/domain"
|
||||
"cotizador/internal/uploads"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *Server) handleClienteResumen(w http.ResponseWriter, r *http.Request) {
|
||||
sess, ok := s.Auth.RequireCliente(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := r.Context()
|
||||
cid := sess.ClienteID
|
||||
hoy := domain.HoyCalendario()
|
||||
inicioMes := time.Date(hoy.Year(), hoy.Month(), 1, 0, 0, 0, 0, time.UTC)
|
||||
|
||||
var nombre string
|
||||
var empresa, email *string
|
||||
if err := s.Pool.QueryRow(ctx, `SELECT "nombre", "empresa", "email" FROM "Cliente" WHERE "id" = $1`, cid).Scan(&nombre, &empresa, &email); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "Cliente no encontrado")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "Error cargando perfil")
|
||||
return
|
||||
}
|
||||
|
||||
var totalCot, pagosPendientes, pagosEnRevision, pagosVerificadosMes int
|
||||
_ = s.Pool.QueryRow(ctx, `SELECT COUNT(*) FROM "Cotizacion" WHERE "clienteId" = $1 AND "archivado" = false`, cid).Scan(&totalCot)
|
||||
_ = s.Pool.QueryRow(ctx, `
|
||||
SELECT COUNT(*) FROM "PagoRecurrente" p JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
WHERE pr."clienteId" = $1 AND p."estado" IN ('pendiente', 'rechazado')
|
||||
`, cid).Scan(&pagosPendientes)
|
||||
_ = s.Pool.QueryRow(ctx, `
|
||||
SELECT COUNT(*) FROM "PagoRecurrente" p JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
WHERE pr."clienteId" = $1 AND p."estado" = 'en_revision'
|
||||
`, cid).Scan(&pagosEnRevision)
|
||||
_ = s.Pool.QueryRow(ctx, `
|
||||
SELECT COUNT(*) FROM "PagoRecurrente" p JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
WHERE pr."clienteId" = $1 AND p."estado" = 'verificado' AND COALESCE(p."verificadoAt", p."fecha") >= $2
|
||||
`, cid, inicioMes).Scan(&pagosVerificadosMes)
|
||||
|
||||
// Pending balance + oldest unpaid date
|
||||
saldoPendiente := map[string]float64{}
|
||||
var masAntiguo *time.Time
|
||||
pendRows, _ := s.Pool.Query(ctx, `
|
||||
SELECT p."fecha", p."monto", pr."moneda"
|
||||
FROM "PagoRecurrente" p
|
||||
JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
WHERE pr."clienteId" = $1 AND p."estado" IN ('pendiente', 'rechazado')
|
||||
ORDER BY p."fecha" ASC
|
||||
`, cid)
|
||||
if pendRows != nil {
|
||||
for pendRows.Next() {
|
||||
var fecha time.Time
|
||||
var monto float64
|
||||
var mon string
|
||||
if pendRows.Scan(&fecha, &monto, &mon) == nil {
|
||||
saldoPendiente[mon] = domain.Round2(saldoPendiente[mon] + monto)
|
||||
if masAntiguo == nil || fecha.Before(*masAntiguo) {
|
||||
t := fecha
|
||||
masAntiguo = &t
|
||||
}
|
||||
}
|
||||
}
|
||||
pendRows.Close()
|
||||
}
|
||||
|
||||
// Upcoming scheduled charges from active programs
|
||||
proximos := []map[string]any{}
|
||||
progRows, _ := s.Pool.Query(ctx, `
|
||||
SELECT "concepto", "monto", "moneda", "frecuencia", "diaSemana", "diaMes", "fechaInicio", "fechaFin"
|
||||
FROM "ProgramaPago"
|
||||
WHERE "clienteId" = $1 AND "activo" = true
|
||||
ORDER BY "createdAt" DESC
|
||||
`, cid)
|
||||
if progRows != nil {
|
||||
for progRows.Next() {
|
||||
var conc, mon, frec string
|
||||
var monto float64
|
||||
var ds, dm *int
|
||||
var fIni time.Time
|
||||
var fFin *time.Time
|
||||
if progRows.Scan(&conc, &monto, &mon, &frec, &ds, &dm, &fIni, &fFin) == nil {
|
||||
if prox := domain.ProximaFecha(domain.ProgramaCalendario{
|
||||
Frecuencia: frec, DiaSemana: ds, DiaMes: dm, FechaInicio: fIni, FechaFin: fFin,
|
||||
}, hoy); prox != nil {
|
||||
proximos = append(proximos, map[string]any{
|
||||
"fecha": *prox,
|
||||
"monto": monto,
|
||||
"moneda": mon,
|
||||
"concepto": conc,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
progRows.Close()
|
||||
}
|
||||
|
||||
// Recent cotizaciones
|
||||
cRows, _ := s.Pool.Query(ctx, `
|
||||
SELECT "id", "numero", "proyecto", "estado", "fecha", "vigencia", "moneda", "esDoble", "incluirIva"
|
||||
FROM "Cotizacion"
|
||||
WHERE "clienteId" = $1 AND "archivado" = false
|
||||
ORDER BY "createdAt" DESC
|
||||
LIMIT 5
|
||||
`, cid)
|
||||
cotRecientes := []map[string]any{}
|
||||
if cRows != nil {
|
||||
for cRows.Next() {
|
||||
var qid, num, proy, est, mon string
|
||||
var fecha, vig time.Time
|
||||
var esDoble, incIva bool
|
||||
if cRows.Scan(&qid, &num, &proy, &est, &fecha, &vig, &mon, &esDoble, &incIva) == nil {
|
||||
cotRecientes = append(cotRecientes, s.enrichClienteCotSummary(ctx, qid, num, proy, est, mon, fecha, vig, esDoble, incIva))
|
||||
}
|
||||
}
|
||||
cRows.Close()
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"cliente": map[string]any{"id": cid, "nombre": nombre, "empresa": empresa, "email": email},
|
||||
"cotizacionesActivas": totalCot,
|
||||
"cotizaciones": cotRecientes,
|
||||
"pagos": map[string]any{
|
||||
"pendientes": pagosPendientes,
|
||||
"saldoPendiente": saldoPendiente,
|
||||
"masAntiguo": masAntiguo,
|
||||
"enRevision": pagosEnRevision,
|
||||
"verificadosMes": pagosVerificadosMes,
|
||||
"proximos": proximos,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) enrichClienteCotSummary(ctx context.Context, qid, num, proy, est, mon string, fecha, vig time.Time, esDoble, incIva bool) map[string]any {
|
||||
full, _, err := s.loadCotizacionFull(ctx, qid, true)
|
||||
var tot domain.TotalesCotizacion
|
||||
var totalesOpciones map[string]any
|
||||
if err == nil {
|
||||
tot = domain.CalcularTotalesCotizacion(full.ServiciosCalc, incIva)
|
||||
if esDoble {
|
||||
o1 := domain.CalcularTotalesOpcion(full.ServiciosCalc, "1")
|
||||
o2 := domain.CalcularTotalesOpcion(full.ServiciosCalc, "2")
|
||||
totalesOpciones = map[string]any{"1": o1, "2": o2}
|
||||
}
|
||||
}
|
||||
return map[string]any{
|
||||
"id": qid, "numero": num, "proyecto": proy, "estado": est, "moneda": mon,
|
||||
"fecha": fecha, "vigencia": vig, "esDoble": esDoble, "incluirIva": incIva,
|
||||
"totales": tot, "totalesOpciones": totalesOpciones,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) handleClienteCotizacionesList(w http.ResponseWriter, r *http.Request) {
|
||||
sess, ok := s.Auth.RequireCliente(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
rows, err := s.Pool.Query(r.Context(), `
|
||||
SELECT "id", "numero", "proyecto", "estado", "fecha", "vigencia", "moneda", "esDoble", "incluirIva"
|
||||
FROM "Cotizacion"
|
||||
WHERE "clienteId" = $1 AND "archivado" = false
|
||||
ORDER BY "createdAt" DESC
|
||||
`, sess.ClienteID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error cargando cotizaciones")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
list := []map[string]any{}
|
||||
for rows.Next() {
|
||||
var qid, num, proy, est, mon string
|
||||
var fecha, vig time.Time
|
||||
var esDoble, incIva bool
|
||||
if rows.Scan(&qid, &num, &proy, &est, &fecha, &vig, &mon, &esDoble, &incIva) == nil {
|
||||
list = append(list, s.enrichClienteCotSummary(r.Context(), qid, num, proy, est, mon, fecha, vig, esDoble, incIva))
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, list)
|
||||
}
|
||||
|
||||
func (s *Server) handleClienteCotizacionGet(w http.ResponseWriter, r *http.Request) {
|
||||
sess, ok := s.Auth.RequireCliente(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
full, jsonMap, err := s.loadCotizacionFull(r.Context(), id, true)
|
||||
if err != nil || full.ClienteID != sess.ClienteID {
|
||||
writeError(w, http.StatusNotFound, "Cotizacion no encontrada")
|
||||
return
|
||||
}
|
||||
// Never expose internal notes or registrosHoras to client view
|
||||
jsonMap["observacionesInternas"] = nil
|
||||
writeJSON(w, http.StatusOK, jsonMap)
|
||||
}
|
||||
|
||||
func (s *Server) handleClientePagosList(w http.ResponseWriter, r *http.Request) {
|
||||
sess, ok := s.Auth.RequireCliente(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := r.Context()
|
||||
|
||||
// Load programs belonging to client
|
||||
progRows, err := s.Pool.Query(ctx, `
|
||||
SELECT "id", "concepto", "monto", "moneda", "frecuencia", "diaSemana", "diaMes", "fechaInicio", "fechaFin", "activo"
|
||||
FROM "ProgramaPago"
|
||||
WHERE "clienteId" = $1
|
||||
ORDER BY "activo" DESC, "createdAt" DESC
|
||||
`, sess.ClienteID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error cargando pagos")
|
||||
return
|
||||
}
|
||||
defer progRows.Close()
|
||||
|
||||
programas := []map[string]any{}
|
||||
progByID := map[string]map[string]any{}
|
||||
for progRows.Next() {
|
||||
var pid, conc, mon, frec string
|
||||
var monto float64
|
||||
var ds, dm *int
|
||||
var fIni time.Time
|
||||
var fFin *time.Time
|
||||
var activo bool
|
||||
if progRows.Scan(&pid, &conc, &monto, &mon, &frec, &ds, &dm, &fIni, &fFin, &activo) == nil {
|
||||
pm := map[string]any{
|
||||
"id": pid, "concepto": conc, "monto": monto, "moneda": mon,
|
||||
"frecuencia": frec, "diaSemana": ds, "diaMes": dm,
|
||||
"fechaInicio": fIni, "fechaFin": fFin, "activo": activo,
|
||||
"pagos": []map[string]any{},
|
||||
}
|
||||
programas = append(programas, pm)
|
||||
progByID[pid] = pm
|
||||
}
|
||||
}
|
||||
|
||||
// Load payments (omitting internal `nota` for clients!)
|
||||
pRows, _ := s.Pool.Query(ctx, `
|
||||
SELECT p."id", p."programaId", p."fecha", p."monto", p."estado",
|
||||
p."verificadoAt", p."rechazadoAt", p."rechazoMotivo",
|
||||
pr."concepto", pr."moneda", pr."frecuencia",
|
||||
c."id", c."archivoNombre", c."mime", c."tamano", c."subidoAt"
|
||||
FROM "PagoRecurrente" p
|
||||
JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
LEFT JOIN "ComprobantePago" c ON c."pagoId" = p."id"
|
||||
WHERE pr."clienteId" = $1
|
||||
ORDER BY p."fecha" DESC
|
||||
`, sess.ClienteID)
|
||||
pagos := []map[string]any{}
|
||||
if pRows != nil {
|
||||
defer pRows.Close()
|
||||
for pRows.Next() {
|
||||
var id, progID, est, conc, mon, frec string
|
||||
var rmot, compID, compNom, compMime *string
|
||||
var fecha time.Time
|
||||
var monto float64
|
||||
var verifAt, rechAt, compSub *time.Time
|
||||
var compTam *int
|
||||
if pRows.Scan(&id, &progID, &fecha, &monto, &est, &verifAt, &rechAt, &rmot,
|
||||
&conc, &mon, &frec, &compID, &compNom, &compMime, &compTam, &compSub) == nil {
|
||||
var comp any
|
||||
if compID != nil {
|
||||
comp = map[string]any{
|
||||
"id": *compID, "pagoId": id, "archivoNombre": compNom, "mime": compMime, "tamano": compTam, "subidoAt": compSub,
|
||||
}
|
||||
}
|
||||
row := map[string]any{
|
||||
"id": id, "programaId": progID, "fecha": fecha, "monto": monto, "estado": est,
|
||||
"verificadoAt": verifAt, "rechazadoAt": rechAt, "rechazoMotivo": rmot,
|
||||
"programa": map[string]any{"id": progID, "concepto": conc, "moneda": mon, "frecuencia": frec},
|
||||
"comprobante": comp,
|
||||
}
|
||||
pagos = append(pagos, row)
|
||||
if pm, ok := progByID[progID]; ok {
|
||||
pm["pagos"] = append(pm["pagos"].([]map[string]any), row)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"pagos": pagos,
|
||||
"programas": programas,
|
||||
"bancaria": s.getConfigBancaria(ctx),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleClienteComprobanteUpload(w http.ResponseWriter, r *http.Request) {
|
||||
sess, ok := s.Auth.RequireCliente(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
pagoID := chi.URLParam(r, "id")
|
||||
|
||||
var estado, ownerClienteID string
|
||||
err := s.Pool.QueryRow(r.Context(), `
|
||||
SELECT p."estado", pr."clienteId"
|
||||
FROM "PagoRecurrente" p
|
||||
JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
WHERE p."id" = $1
|
||||
`, pagoID).Scan(&estado, &ownerClienteID)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "Cobro no encontrado")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "Error verificando cobro")
|
||||
return
|
||||
}
|
||||
if ownerClienteID != sess.ClienteID {
|
||||
writeError(w, http.StatusForbidden, "No tienes acceso a este cobro")
|
||||
return
|
||||
}
|
||||
if estado != domain.EstadoPagoPendiente && estado != domain.EstadoPagoRechazado {
|
||||
writeError(w, http.StatusConflict, "Solo puedes subir comprobante para cobros pendientes o rechazados")
|
||||
return
|
||||
}
|
||||
|
||||
if err := r.ParseMultipartForm(uploads.MaxFileSizeBytes + (1 << 20)); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "Error leyendo formulario de archivo")
|
||||
return
|
||||
}
|
||||
file, header, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "Se requiere el archivo en el campo 'file'")
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
raw, err := io.ReadAll(io.LimitReader(file, uploads.MaxFileSizeBytes+1))
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "Error leyendo archivo")
|
||||
return
|
||||
}
|
||||
saved, err := uploads.GuardarComprobante(s.Cfg.UploadDir, pagoID, header.Filename, header.Header.Get("Content-Type"), raw)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Remove previous comprobante if any
|
||||
var oldRuta string
|
||||
_ = s.Pool.QueryRow(r.Context(), `SELECT "archivoRuta" FROM "ComprobantePago" WHERE "pagoId" = $1`, pagoID).Scan(&oldRuta)
|
||||
if oldRuta != "" {
|
||||
_ = uploads.EliminarComprobante(s.Cfg.UploadDir, oldRuta)
|
||||
_, _ = s.Pool.Exec(r.Context(), `DELETE FROM "ComprobantePago" WHERE "pagoId" = $1`, pagoID)
|
||||
}
|
||||
|
||||
compID := db.NewID()
|
||||
_, err = s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "ComprobantePago" ("id", "pagoId", "archivoRuta", "archivoNombre", "mime", "tamano", "subidoAt")
|
||||
VALUES ($1, $2, $3, $4, $5, $6, NOW())
|
||||
`, compID, pagoID, saved.ArchivoRuta, saved.ArchivoNombre, saved.Mime, saved.Tamano)
|
||||
if err != nil {
|
||||
_ = uploads.EliminarComprobante(s.Cfg.UploadDir, saved.ArchivoRuta)
|
||||
writeError(w, http.StatusInternalServerError, "Error registrando comprobante")
|
||||
return
|
||||
}
|
||||
_, _ = s.Pool.Exec(r.Context(), `
|
||||
UPDATE "PagoRecurrente" SET "estado"='en_revision', "rechazoMotivo"=NULL, "updatedAt"=NOW() WHERE "id" = $1
|
||||
`, pagoID)
|
||||
|
||||
writeJSON(w, http.StatusCreated, map[string]any{
|
||||
"ok": true, "id": compID, "pagoId": pagoID, "estado": "en_revision",
|
||||
"archivoNombre": saved.ArchivoNombre, "mime": saved.Mime, "tamano": saved.Tamano,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleClientePushConfig(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireCliente(w, r); !ok {
|
||||
return
|
||||
}
|
||||
if !s.Notify.VAPIDConfigured() {
|
||||
writeError(w, http.StatusNotImplemented, "Notificaciones push no configuradas")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"publicKey": s.Cfg.VAPIDPublicKey})
|
||||
}
|
||||
|
||||
func (s *Server) handleClientePushSubscribe(w http.ResponseWriter, r *http.Request) {
|
||||
sess, ok := s.Auth.RequireCliente(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Endpoint string `json:"endpoint"`
|
||||
Keys struct {
|
||||
P256dh string `json:"p256dh"`
|
||||
Auth string `json:"auth"`
|
||||
} `json:"keys"`
|
||||
}
|
||||
if err := decodeJSON(r, &body); err != nil || strings.TrimSpace(body.Endpoint) == "" || body.Keys.P256dh == "" || body.Keys.Auth == "" {
|
||||
writeError(w, http.StatusBadRequest, "Suscripcion push invalida")
|
||||
return
|
||||
}
|
||||
_, err := s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "SuscripcionPush" ("id", "userId", "endpoint", "p256dh", "auth", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, $5, NOW(), NOW())
|
||||
ON CONFLICT ("endpoint") DO UPDATE SET "userId" = EXCLUDED."userId", "p256dh" = EXCLUDED."p256dh", "auth" = EXCLUDED."auth", "updatedAt" = NOW()
|
||||
`, db.NewID(), sess.UserID, strings.TrimSpace(body.Endpoint), body.Keys.P256dh, body.Keys.Auth)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error guardando suscripcion push")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||
}
|
||||
|
||||
func (s *Server) handleClientePushUnsubscribe(w http.ResponseWriter, r *http.Request) {
|
||||
sess, ok := s.Auth.RequireCliente(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Endpoint string `json:"endpoint"`
|
||||
}
|
||||
_ = decodeJSON(r, &body)
|
||||
if strings.TrimSpace(body.Endpoint) != "" {
|
||||
_, _ = s.Pool.Exec(r.Context(), `DELETE FROM "SuscripcionPush" WHERE "userId" = $1 AND "endpoint" = $2`, sess.UserID, strings.TrimSpace(body.Endpoint))
|
||||
} else {
|
||||
_, _ = s.Pool.Exec(r.Context(), `DELETE FROM "SuscripcionPush" WHERE "userId" = $1`, sess.UserID)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||
}
|
||||
@@ -0,0 +1,418 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/audit"
|
||||
"cotizador/internal/auth"
|
||||
"cotizador/internal/db"
|
||||
"cotizador/internal/idempotency"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *Server) queryClientes(ctx context.Context, whereSQL string, args ...any) ([]map[string]any, error) {
|
||||
rows, err := s.Pool.Query(ctx, `
|
||||
SELECT c."id", c."nombre", c."empresa", c."puesto", c."email", c."telefono", c."rfc",
|
||||
c."archivado", c."archivadoAt", c."createdAt", c."updatedAt",
|
||||
u."id", u."email",
|
||||
(SELECT COUNT(*) FROM "Cotizacion" q WHERE q."clienteId" = c."id" AND q."archivado" = false) AS cot_count,
|
||||
(SELECT COUNT(*) FROM "ProgramaPago" p WHERE p."clienteId" = c."id" AND p."activo" = true) AS prog_count
|
||||
FROM "Cliente" c
|
||||
LEFT JOIN "User" u ON u."clienteId" = c."id"
|
||||
WHERE `+whereSQL+`
|
||||
ORDER BY c."nombre" ASC
|
||||
`, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
list := []map[string]any{}
|
||||
for rows.Next() {
|
||||
var id, nombre string
|
||||
var empresa, puesto, email, telefono, rfc, uid, uemail *string
|
||||
var archivado bool
|
||||
var archivadoAt *time.Time
|
||||
var createdAt, updatedAt time.Time
|
||||
var cotCount, progCount int
|
||||
if rows.Scan(&id, &nombre, &empresa, &puesto, &email, &telefono, &rfc, &archivado, &archivadoAt, &createdAt, &updatedAt, &uid, &uemail, &cotCount, &progCount) == nil {
|
||||
var usuario any
|
||||
if uid != nil {
|
||||
usuario = map[string]any{"id": *uid, "email": uemail}
|
||||
}
|
||||
list = append(list, map[string]any{
|
||||
"id": id,
|
||||
"nombre": nombre,
|
||||
"empresa": empresa,
|
||||
"puesto": puesto,
|
||||
"email": email,
|
||||
"telefono": telefono,
|
||||
"rfc": rfc,
|
||||
"archivado": archivado,
|
||||
"archivadoAt": archivadoAt,
|
||||
"createdAt": createdAt,
|
||||
"updatedAt": updatedAt,
|
||||
"usuario": usuario,
|
||||
"_count": map[string]any{
|
||||
"cotizaciones": cotCount,
|
||||
"programasPago": progCount,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
return list, nil
|
||||
}
|
||||
|
||||
func (s *Server) clienteDuplicadoExiste(ctx context.Context, nombre, empresa, excludeID string) (bool, error) {
|
||||
empNorm := strings.ToLower(strings.TrimSpace(empresa))
|
||||
var exists bool
|
||||
err := s.Pool.QueryRow(ctx, `
|
||||
SELECT EXISTS(
|
||||
SELECT 1 FROM "Cliente"
|
||||
WHERE "archivado" = false
|
||||
AND LOWER(TRIM("nombre")) = LOWER(TRIM($1))
|
||||
AND LOWER(TRIM(COALESCE("empresa", ''))) = $2
|
||||
AND ($3 = '' OR "id" <> $3)
|
||||
)
|
||||
`, nombre, empNorm, excludeID).Scan(&exists)
|
||||
return exists, err
|
||||
}
|
||||
|
||||
func (s *Server) handleClientesList(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"clientes:leer"}, RecursoTipo: "cliente"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
conds := []string{"1=1"}
|
||||
args := []any{}
|
||||
add := func(v any) string {
|
||||
args = append(args, v)
|
||||
return fmt.Sprintf("$%d", len(args))
|
||||
}
|
||||
|
||||
incluirArchivados := !actor.IsAgent() && q.Get("incluirArchivados") == "true"
|
||||
if !incluirArchivados {
|
||||
conds = append(conds, `c."archivado" = false`)
|
||||
}
|
||||
if search := strings.TrimSpace(q.Get("q")); search != "" {
|
||||
p := add("%" + search + "%")
|
||||
conds = append(conds, fmt.Sprintf(`(c."nombre" ILIKE %s OR COALESCE(c."empresa", '') ILIKE %s OR COALESCE(c."email", '') ILIKE %s OR COALESCE(c."rfc", '') ILIKE %s)`, p, p, p, p))
|
||||
}
|
||||
|
||||
list, err := s.queryClientes(r.Context(), strings.Join(conds, " AND "), args...)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error listando clientes")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, list)
|
||||
}
|
||||
|
||||
func (s *Server) handleClientesCreate(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"clientes:escribir"}, RecursoTipo: "cliente"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
idempotency.Execute(r.Context(), s.Pool, w, r, actor, func(rawBody []byte) (int, any) {
|
||||
var body struct {
|
||||
Nombre string `json:"nombre"`
|
||||
Empresa *string `json:"empresa"`
|
||||
Puesto *string `json:"puesto"`
|
||||
Email *string `json:"email"`
|
||||
Telefono *string `json:"telefono"`
|
||||
RFC *string `json:"rfc"`
|
||||
}
|
||||
if err := json.Unmarshal(rawBody, &body); err != nil {
|
||||
return http.StatusBadRequest, map[string]any{"error": "JSON invalido"}
|
||||
}
|
||||
nombre := strings.TrimSpace(body.Nombre)
|
||||
if nombre == "" {
|
||||
return http.StatusBadRequest, map[string]any{
|
||||
"error": "Datos invalidos",
|
||||
"detalles": []ValidationDetail{{Campo: "nombre", Mensaje: "El nombre del cliente es obligatorio"}},
|
||||
}
|
||||
}
|
||||
empStr := ""
|
||||
if body.Empresa != nil {
|
||||
empStr = strings.TrimSpace(*body.Empresa)
|
||||
}
|
||||
dup, err := s.clienteDuplicadoExiste(r.Context(), nombre, empStr, "")
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, map[string]any{"error": "Error validando duplicado"}
|
||||
}
|
||||
if dup {
|
||||
return http.StatusConflict, map[string]any{"error": "Ya existe un cliente con el mismo nombre y empresa"}
|
||||
}
|
||||
|
||||
id := db.NewID()
|
||||
_, err = s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "Cliente" ("id", "nombre", "empresa", "puesto", "email", "telefono", "rfc", "archivado", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, false, NOW(), NOW())
|
||||
`, id, nombre, nullableTrim(empStr), trimPtr(body.Puesto), trimPtr(body.Email), trimPtr(body.Telefono), trimPtr(body.RFC))
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, map[string]any{"error": "Error creando cliente"}
|
||||
}
|
||||
|
||||
tipo, aid, anom := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
||||
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
||||
Accion: "cliente.crear", RecursoTipo: "cliente", RecursoID: id,
|
||||
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
||||
Detalle: map[string]any{"nombre": nombre, "empresa": empStr},
|
||||
})
|
||||
|
||||
list, _ := s.queryClientes(r.Context(), `c."id" = $1`, id)
|
||||
if len(list) == 1 {
|
||||
return http.StatusCreated, list[0]
|
||||
}
|
||||
return http.StatusCreated, map[string]any{"id": id, "nombre": nombre}
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleClientesUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"clientes:escribir"}, RecursoTipo: "cliente"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
var curNombre string
|
||||
var curEmpresa *string
|
||||
err := s.Pool.QueryRow(r.Context(), `SELECT "nombre", "empresa" FROM "Cliente" WHERE "id" = $1`, id).Scan(&curNombre, &curEmpresa)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "Cliente no encontrado")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "Error consultando cliente")
|
||||
return
|
||||
}
|
||||
|
||||
var raw map[string]any
|
||||
if err := decodeJSON(r, &raw); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "JSON invalido")
|
||||
return
|
||||
}
|
||||
|
||||
newNombre := curNombre
|
||||
if v, ok := raw["nombre"]; ok {
|
||||
newNombre = strings.TrimSpace(asString(v))
|
||||
if newNombre == "" {
|
||||
writeValidationError(w, []ValidationDetail{{Campo: "nombre", Mensaje: "El nombre no puede estar vacio"}})
|
||||
return
|
||||
}
|
||||
}
|
||||
newEmpresa := ""
|
||||
if curEmpresa != nil {
|
||||
newEmpresa = *curEmpresa
|
||||
}
|
||||
if v, ok := raw["empresa"]; ok {
|
||||
newEmpresa = strings.TrimSpace(asString(v))
|
||||
}
|
||||
|
||||
if dup, _ := s.clienteDuplicadoExiste(r.Context(), newNombre, newEmpresa, id); dup {
|
||||
writeError(w, http.StatusConflict, "Ya existe otro cliente con el mismo nombre y empresa")
|
||||
return
|
||||
}
|
||||
|
||||
sets := []string{`"updatedAt" = NOW()`}
|
||||
args := []any{}
|
||||
add := func(col string, val any) {
|
||||
args = append(args, val)
|
||||
sets = append(sets, fmt.Sprintf(`"%s" = $%d`, col, len(args)))
|
||||
}
|
||||
if _, ok := raw["nombre"]; ok {
|
||||
add("nombre", newNombre)
|
||||
}
|
||||
if _, ok := raw["empresa"]; ok {
|
||||
add("empresa", nullableTrim(newEmpresa))
|
||||
}
|
||||
if v, ok := raw["puesto"]; ok {
|
||||
add("puesto", nullableTrim(asString(v)))
|
||||
}
|
||||
if v, ok := raw["email"]; ok {
|
||||
add("email", nullableTrim(asString(v)))
|
||||
}
|
||||
if v, ok := raw["telefono"]; ok {
|
||||
add("telefono", nullableTrim(asString(v)))
|
||||
}
|
||||
if v, ok := raw["rfc"]; ok {
|
||||
add("rfc", nullableTrim(asString(v)))
|
||||
}
|
||||
args = append(args, id)
|
||||
_, err = s.Pool.Exec(r.Context(), fmt.Sprintf(`UPDATE "Cliente" SET %s WHERE "id" = $%d`, strings.Join(sets, ", "), len(args)), args...)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error actualizando cliente")
|
||||
return
|
||||
}
|
||||
|
||||
tipo, aid, anom := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
||||
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
||||
Accion: "cliente.actualizar", RecursoTipo: "cliente", RecursoID: id,
|
||||
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
||||
})
|
||||
|
||||
list, _ := s.queryClientes(r.Context(), `c."id" = $1`, id)
|
||||
if len(list) == 1 {
|
||||
writeJSON(w, http.StatusOK, list[0])
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"id": id})
|
||||
}
|
||||
|
||||
func (s *Server) handleClienteAccesoCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "cliente_acceso"}); !ok {
|
||||
return
|
||||
}
|
||||
clienteID := chi.URLParam(r, "id")
|
||||
var cliNombre string
|
||||
if err := s.Pool.QueryRow(r.Context(), `SELECT "nombre" FROM "Cliente" WHERE "id" = $1`, clienteID).Scan(&cliNombre); err != nil {
|
||||
writeError(w, http.StatusNotFound, "Cliente no encontrado")
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := decodeJSON(r, &body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "JSON invalido")
|
||||
return
|
||||
}
|
||||
email := strings.ToLower(strings.TrimSpace(body.Email))
|
||||
if email == "" || len(body.Password) < 6 {
|
||||
writeError(w, http.StatusBadRequest, "Email y contrasena (minimo 6 caracteres) requeridos")
|
||||
return
|
||||
}
|
||||
|
||||
hash, err := auth.HashPassword(body.Password)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error encriptando contrasena")
|
||||
return
|
||||
}
|
||||
|
||||
// Check if another user owns this email
|
||||
var conflict bool
|
||||
_ = s.Pool.QueryRow(r.Context(), `
|
||||
SELECT EXISTS(SELECT 1 FROM "User" WHERE LOWER("email") = $1 AND ("clienteId" IS NULL OR "clienteId" <> $2))
|
||||
`, email, clienteID).Scan(&conflict)
|
||||
if conflict {
|
||||
writeError(w, http.StatusConflict, "Ese correo ya esta en uso por otra cuenta")
|
||||
return
|
||||
}
|
||||
|
||||
var existingID string
|
||||
err = s.Pool.QueryRow(r.Context(), `SELECT "id" FROM "User" WHERE "clienteId" = $1`, clienteID).Scan(&existingID)
|
||||
if err == nil && existingID != "" {
|
||||
_, err = s.Pool.Exec(r.Context(), `
|
||||
UPDATE "User" SET "email" = $1, "password" = $2, "name" = $3, "role" = 'cliente', "updatedAt" = NOW()
|
||||
WHERE "id" = $4
|
||||
`, email, hash, cliNombre, existingID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error actualizando acceso")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": existingID, "email": email, "actualizado": true})
|
||||
return
|
||||
}
|
||||
|
||||
uid := db.NewID()
|
||||
_, err = s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "User" ("id", "email", "password", "name", "role", "clienteId", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, 'cliente', $5, NOW(), NOW())
|
||||
`, uid, email, hash, cliNombre, clienteID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error creando cuenta de cliente")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]any{"ok": true, "id": uid, "email": email})
|
||||
}
|
||||
|
||||
func (s *Server) handleClienteAccesoDelete(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "cliente_acceso"}); !ok {
|
||||
return
|
||||
}
|
||||
clienteID := chi.URLParam(r, "id")
|
||||
_, _ = s.Pool.Exec(r.Context(), `DELETE FROM "User" WHERE "clienteId" = $1 AND "role" = 'cliente'`, clienteID)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||
}
|
||||
|
||||
func (s *Server) handleClienteArchivar(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{
|
||||
StaffOnly: true,
|
||||
AccionBloqueo: "cliente.archivar_bloqueado",
|
||||
RecursoTipo: "cliente",
|
||||
})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
clienteID := chi.URLParam(r, "id")
|
||||
var body struct {
|
||||
Archivado *bool `json:"archivado"`
|
||||
IncluirCotizaciones *bool `json:"incluirCotizaciones"`
|
||||
}
|
||||
_ = decodeJSON(r, &body)
|
||||
archivado := true
|
||||
if body.Archivado != nil {
|
||||
archivado = *body.Archivado
|
||||
}
|
||||
incluirCot := true
|
||||
if body.IncluirCotizaciones != nil {
|
||||
incluirCot = *body.IncluirCotizaciones
|
||||
}
|
||||
|
||||
var archAt *time.Time
|
||||
if archivado {
|
||||
now := time.Now()
|
||||
archAt = &now
|
||||
}
|
||||
|
||||
tag, err := s.Pool.Exec(r.Context(), `
|
||||
UPDATE "Cliente" SET "archivado" = $1, "archivadoAt" = $2, "updatedAt" = NOW() WHERE "id" = $3
|
||||
`, archivado, archAt, clienteID)
|
||||
if err != nil || tag.RowsAffected() == 0 {
|
||||
writeError(w, http.StatusNotFound, "Cliente no encontrado")
|
||||
return
|
||||
}
|
||||
var cotAfectadas int64
|
||||
if incluirCot {
|
||||
ctag, _ := s.Pool.Exec(r.Context(), `
|
||||
UPDATE "Cotizacion" SET "archivado" = $1, "archivadoAt" = $2, "updatedAt" = NOW() WHERE "clienteId" = $3
|
||||
`, archivado, archAt, clienteID)
|
||||
cotAfectadas = ctag.RowsAffected()
|
||||
}
|
||||
|
||||
accion := "cliente.archivar"
|
||||
if !archivado {
|
||||
accion = "cliente.desarchivar"
|
||||
}
|
||||
tipo, aid, anom := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
||||
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
||||
Accion: accion, RecursoTipo: "cliente", RecursoID: clienteID,
|
||||
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
||||
Detalle: map[string]any{"archivado": archivado, "cotizacionesAfectadas": cotAfectadas},
|
||||
})
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"ok": true,
|
||||
"id": clienteID,
|
||||
"archivado": archivado,
|
||||
"cotizacionesAfectadas": cotAfectadas,
|
||||
})
|
||||
}
|
||||
|
||||
func trimPtr(p *string) *string {
|
||||
if p == nil {
|
||||
return nil
|
||||
}
|
||||
return nullableTrim(*p)
|
||||
}
|
||||
@@ -0,0 +1,701 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/audit"
|
||||
"cotizador/internal/auth"
|
||||
"cotizador/internal/db"
|
||||
"cotizador/internal/domain"
|
||||
"cotizador/internal/idempotency"
|
||||
"cotizador/internal/scheduler"
|
||||
"cotizador/internal/uploads"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *Server) queryProgramas(ctx context.Context) ([]map[string]any, error) {
|
||||
rows, err := s.Pool.Query(ctx, `
|
||||
SELECT p."id", p."clienteId", p."cotizacionId", p."concepto", p."monto", p."moneda",
|
||||
p."frecuencia", p."diaSemana", p."diaMes", p."fechaInicio", p."fechaFin", p."activo",
|
||||
p."createdAt", p."updatedAt",
|
||||
c."nombre", c."empresa", c."email",
|
||||
(SELECT COUNT(*) FROM "PagoRecurrente" pr WHERE pr."programaId" = p."id") AS pagos_count
|
||||
FROM "ProgramaPago" p
|
||||
JOIN "Cliente" c ON c."id" = p."clienteId"
|
||||
ORDER BY p."activo" DESC, p."createdAt" DESC
|
||||
`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
hoy := domain.HoyCalendario()
|
||||
list := []map[string]any{}
|
||||
for rows.Next() {
|
||||
var id, clienteID, concepto, moneda, frecuencia, cNombre string
|
||||
var cotID, cEmpresa, cEmail *string
|
||||
var monto float64
|
||||
var diaSemana, diaMes *int
|
||||
var fechaInicio, createdAt, updatedAt time.Time
|
||||
var fechaFin *time.Time
|
||||
var activo bool
|
||||
var pagosCount int
|
||||
if rows.Scan(&id, &clienteID, &cotID, &concepto, &monto, &moneda, &frecuencia, &diaSemana, &diaMes,
|
||||
&fechaInicio, &fechaFin, &activo, &createdAt, &updatedAt, &cNombre, &cEmpresa, &cEmail, &pagosCount) == nil {
|
||||
var prox *time.Time
|
||||
if activo {
|
||||
prox = domain.ProximaFecha(domain.ProgramaCalendario{
|
||||
Frecuencia: frecuencia, DiaSemana: diaSemana, DiaMes: diaMes,
|
||||
FechaInicio: fechaInicio, FechaFin: fechaFin,
|
||||
}, hoy)
|
||||
}
|
||||
list = append(list, map[string]any{
|
||||
"id": id, "clienteId": clienteID, "cotizacionId": cotID,
|
||||
"concepto": concepto, "monto": monto, "moneda": moneda,
|
||||
"frecuencia": frecuencia, "diaSemana": diaSemana, "diaMes": diaMes,
|
||||
"fechaInicio": fechaInicio, "fechaFin": fechaFin, "activo": activo,
|
||||
"proximaFecha": prox, "createdAt": createdAt, "updatedAt": updatedAt,
|
||||
"cliente": map[string]any{"id": clienteID, "nombre": cNombre, "empresa": cEmpresa, "email": cEmail},
|
||||
"pagosCount": pagosCount,
|
||||
"_count": map[string]any{"pagos": pagosCount},
|
||||
})
|
||||
}
|
||||
}
|
||||
return list, nil
|
||||
}
|
||||
|
||||
func (s *Server) handleCobrosResumen(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "cobros"}); !ok {
|
||||
return
|
||||
}
|
||||
ctx := r.Context()
|
||||
hoy := domain.HoyCalendario()
|
||||
|
||||
programas, err := s.queryProgramas(ctx)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error cargando programas")
|
||||
return
|
||||
}
|
||||
|
||||
// Clientes for dropdown
|
||||
cRows, _ := s.Pool.Query(ctx, `SELECT "id", "nombre", "empresa" FROM "Cliente" WHERE "archivado" = false ORDER BY "nombre" ASC`)
|
||||
clientes := []map[string]any{}
|
||||
if cRows != nil {
|
||||
for cRows.Next() {
|
||||
var cid, cnom string
|
||||
var cemp *string
|
||||
if cRows.Scan(&cid, &cnom, &cemp) == nil {
|
||||
clientes = append(clientes, map[string]any{"id": cid, "nombre": cnom, "empresa": cemp})
|
||||
}
|
||||
}
|
||||
cRows.Close()
|
||||
}
|
||||
|
||||
// Pagos en revision
|
||||
revPagos, _ := s.queryPagos(ctx, `p."estado" = 'en_revision'`, nil)
|
||||
|
||||
// Pagos por cobrar (pendiente | rechazado, fecha <= hoy, including inactive programs)
|
||||
porCobrarRows, _ := s.Pool.Query(ctx, `
|
||||
SELECT p."id", p."programaId", p."fecha", p."monto", p."estado", p."ultimoRecordatorioAt", p."recordatoriosEnviados",
|
||||
pr."concepto", pr."moneda",
|
||||
c."id", c."nombre", c."empresa", c."email",
|
||||
(SELECT COUNT(*) FROM "SuscripcionPush" sp JOIN "User" u ON u."id" = sp."userId" WHERE u."clienteId" = c."id") AS push_count
|
||||
FROM "PagoRecurrente" p
|
||||
JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
JOIN "Cliente" c ON c."id" = pr."clienteId"
|
||||
WHERE p."estado" IN ('pendiente', 'rechazado') AND p."fecha" <= $1
|
||||
ORDER BY c."nombre" ASC, p."fecha" ASC
|
||||
`, hoy)
|
||||
|
||||
type saldoClient struct {
|
||||
ClienteID string
|
||||
ClienteNombre string
|
||||
ClienteEmpresa *string
|
||||
ClienteEmail *string
|
||||
Contactable bool
|
||||
Totales map[string]float64
|
||||
MasAntigua time.Time
|
||||
UltimoRecordatorio *time.Time
|
||||
PagosCount int
|
||||
}
|
||||
saldoMap := map[string]*saldoClient{}
|
||||
var saldoOrder []string
|
||||
if porCobrarRows != nil {
|
||||
for porCobrarRows.Next() {
|
||||
var pid, prid, estado, concepto, moneda, cid, cnom string
|
||||
var cemp, cemail *string
|
||||
var fecha time.Time
|
||||
var monto float64
|
||||
var ultRec *time.Time
|
||||
var recCnt, pushCnt int
|
||||
if porCobrarRows.Scan(&pid, &prid, &fecha, &monto, &estado, &ultRec, &recCnt, &concepto, &moneda, &cid, &cnom, &cemp, &cemail, &pushCnt) == nil {
|
||||
sc, ok := saldoMap[cid]
|
||||
if !ok {
|
||||
sc = &saldoClient{
|
||||
ClienteID: cid, ClienteNombre: cnom, ClienteEmpresa: cemp, ClienteEmail: cemail,
|
||||
Contactable: (cemail != nil && strings.TrimSpace(*cemail) != "") || pushCnt > 0,
|
||||
Totales: map[string]float64{},
|
||||
MasAntigua: fecha,
|
||||
}
|
||||
saldoMap[cid] = sc
|
||||
saldoOrder = append(saldoOrder, cid)
|
||||
}
|
||||
if fecha.Before(sc.MasAntigua) {
|
||||
sc.MasAntigua = fecha
|
||||
}
|
||||
sc.Totales[moneda] = domain.Round2(sc.Totales[moneda] + monto)
|
||||
if ultRec != nil && (sc.UltimoRecordatorio == nil || ultRec.After(*sc.UltimoRecordatorio)) {
|
||||
t := *ultRec
|
||||
sc.UltimoRecordatorio = &t
|
||||
}
|
||||
sc.PagosCount++
|
||||
}
|
||||
}
|
||||
porCobrarRows.Close()
|
||||
}
|
||||
|
||||
saldos := make([]map[string]any, 0, len(saldoOrder))
|
||||
for _, cid := range saldoOrder {
|
||||
sc := saldoMap[cid]
|
||||
saldos = append(saldos, map[string]any{
|
||||
"clienteId": sc.ClienteID,
|
||||
"nombre": sc.ClienteNombre,
|
||||
"empresa": sc.ClienteEmpresa,
|
||||
"pagos": sc.PagosCount,
|
||||
"totales": sc.Totales,
|
||||
"masAntigua": sc.MasAntigua,
|
||||
"diasAtraso": domain.DiasDeAtraso(sc.MasAntigua, hoy),
|
||||
"ultimoRecordatorio": sc.UltimoRecordatorio,
|
||||
"contactable": sc.Contactable,
|
||||
})
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"programas": programas,
|
||||
"clientes": clientes,
|
||||
"pagosEnRevision": revPagos,
|
||||
"saldos": saldos,
|
||||
"diasRecordatorio": s.Cfg.CobrosRecordatorioDias,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleProgramasList(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"cobros:leer"}, RecursoTipo: "programa_pago"}); !ok {
|
||||
return
|
||||
}
|
||||
list, err := s.queryProgramas(r.Context())
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error listando programas")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, list)
|
||||
}
|
||||
|
||||
func (s *Server) handleProgramasCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "programa_pago"}); !ok {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
ClienteID string `json:"clienteId"`
|
||||
CotizacionID *string `json:"cotizacionId"`
|
||||
Concepto string `json:"concepto"`
|
||||
Monto float64 `json:"monto"`
|
||||
Moneda string `json:"moneda"`
|
||||
Frecuencia string `json:"frecuencia"`
|
||||
DiaSemana *int `json:"diaSemana"`
|
||||
DiaMes *int `json:"diaMes"`
|
||||
FechaInicio string `json:"fechaInicio"`
|
||||
FechaFin *string `json:"fechaFin"`
|
||||
}
|
||||
if err := decodeJSON(r, &body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "JSON invalido")
|
||||
return
|
||||
}
|
||||
if body.ClienteID == "" || strings.TrimSpace(body.Concepto) == "" || body.Monto <= 0 {
|
||||
writeError(w, http.StatusBadRequest, "clienteId, concepto y monto > 0 son obligatorios")
|
||||
return
|
||||
}
|
||||
fIni, err := domain.ParseFechaCalendario(body.FechaInicio)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
var fFin *time.Time
|
||||
if body.FechaFin != nil && strings.TrimSpace(*body.FechaFin) != "" {
|
||||
t, err := domain.ParseFechaCalendario(*body.FechaFin)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
fFin = &t
|
||||
}
|
||||
frec := firstNonEmptyStr(body.Frecuencia, "semanal")
|
||||
mon := firstNonEmptyStr(body.Moneda, "MXN")
|
||||
|
||||
id := db.NewID()
|
||||
_, err = s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "ProgramaPago" (
|
||||
"id", "clienteId", "cotizacionId", "concepto", "monto", "moneda",
|
||||
"frecuencia", "diaSemana", "diaMes", "fechaInicio", "fechaFin", "activo", "createdAt", "updatedAt"
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,true,NOW(),NOW())
|
||||
`, id, body.ClienteID, trimPtr(body.CotizacionID), strings.TrimSpace(body.Concepto), body.Monto, mon,
|
||||
frec, body.DiaSemana, body.DiaMes, fIni, fFin)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error creando programa de pago")
|
||||
return
|
||||
}
|
||||
|
||||
// Generate initial due charges right away
|
||||
if nuevos, err := scheduler.GenerarCobros(r.Context(), s.Pool, id, nil); err == nil && len(nuevos) > 0 {
|
||||
go s.Notify.NotificarCobrosNuevos(context.Background(), nuevos)
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, map[string]any{"id": id, "ok": true})
|
||||
}
|
||||
|
||||
func (s *Server) handleProgramasUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "programa_pago"}); !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
var raw map[string]any
|
||||
if err := decodeJSON(r, &raw); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "JSON invalido")
|
||||
return
|
||||
}
|
||||
sets := []string{`"updatedAt" = NOW()`}
|
||||
args := []any{}
|
||||
add := func(col string, val any) {
|
||||
args = append(args, val)
|
||||
sets = append(sets, fmt.Sprintf(`"%s" = $%d`, col, len(args)))
|
||||
}
|
||||
if v, ok := raw["concepto"]; ok {
|
||||
add("concepto", strings.TrimSpace(asString(v)))
|
||||
}
|
||||
if v, ok := raw["monto"]; ok {
|
||||
if m, okF := asFloat(v); okF && m > 0 {
|
||||
add("monto", m)
|
||||
}
|
||||
}
|
||||
if v, ok := raw["moneda"]; ok {
|
||||
add("moneda", strings.TrimSpace(asString(v)))
|
||||
}
|
||||
if v, ok := raw["frecuencia"]; ok {
|
||||
add("frecuencia", strings.TrimSpace(asString(v)))
|
||||
}
|
||||
if v, ok := raw["diaSemana"]; ok {
|
||||
if n, okI := asInt(v); okI {
|
||||
add("diaSemana", n)
|
||||
} else {
|
||||
add("diaSemana", nil)
|
||||
}
|
||||
}
|
||||
if v, ok := raw["diaMes"]; ok {
|
||||
if n, okI := asInt(v); okI {
|
||||
add("diaMes", n)
|
||||
} else {
|
||||
add("diaMes", nil)
|
||||
}
|
||||
}
|
||||
if v, ok := raw["fechaFin"]; ok {
|
||||
sVal := strings.TrimSpace(asString(v))
|
||||
if sVal == "" {
|
||||
add("fechaFin", nil)
|
||||
} else if t, err := domain.ParseFechaCalendario(sVal); err == nil {
|
||||
add("fechaFin", t)
|
||||
}
|
||||
}
|
||||
if v, ok := raw["activo"].(bool); ok {
|
||||
add("activo", v)
|
||||
}
|
||||
args = append(args, id)
|
||||
tag, err := s.Pool.Exec(r.Context(), fmt.Sprintf(`UPDATE "ProgramaPago" SET %s WHERE "id" = $%d`, strings.Join(sets, ", "), len(args)), args...)
|
||||
if err != nil || tag.RowsAffected() == 0 {
|
||||
writeError(w, http.StatusNotFound, "Programa no encontrado")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": id})
|
||||
}
|
||||
|
||||
func (s *Server) handleCobrosGenerar(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "cobros"}); !ok {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
ProgramaID string `json:"programaId"`
|
||||
Hasta string `json:"hasta"`
|
||||
}
|
||||
_ = decodeJSON(r, &body)
|
||||
var hasta *time.Time
|
||||
if strings.TrimSpace(body.Hasta) != "" {
|
||||
t, err := domain.ParseFechaCalendario(body.Hasta)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
hasta = &t
|
||||
}
|
||||
nuevos, err := scheduler.GenerarCobros(r.Context(), s.Pool, body.ProgramaID, hasta)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error generando cobros")
|
||||
return
|
||||
}
|
||||
if len(nuevos) > 0 {
|
||||
go s.Notify.NotificarCobrosNuevos(context.Background(), nuevos)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "generados": len(nuevos), "ids": nuevos})
|
||||
}
|
||||
|
||||
func (s *Server) queryPagos(ctx context.Context, whereSQL string, args []any) ([]map[string]any, error) {
|
||||
rows, err := s.Pool.Query(ctx, `
|
||||
SELECT p."id", p."programaId", p."fecha", p."monto", p."estado",
|
||||
p."verificadoAt", p."rechazadoAt", p."rechazoMotivo",
|
||||
p."ultimoRecordatorioAt", p."recordatoriosEnviados", p."nota",
|
||||
pr."concepto", pr."moneda", pr."frecuencia", pr."clienteId",
|
||||
c."nombre", c."empresa", c."email",
|
||||
comp."id", comp."archivoNombre", comp."mime", comp."tamano", comp."subidoAt"
|
||||
FROM "PagoRecurrente" p
|
||||
JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
JOIN "Cliente" c ON c."id" = pr."clienteId"
|
||||
LEFT JOIN "ComprobantePago" comp ON comp."pagoId" = p."id"
|
||||
WHERE `+whereSQL+`
|
||||
ORDER BY p."fecha" DESC
|
||||
`, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
list := []map[string]any{}
|
||||
for rows.Next() {
|
||||
var id, progID, estado, concepto, moneda, frec, cid, cnom string
|
||||
var rechazoMotivo, nota, cemp, cemail, compID, compNom, compMime *string
|
||||
var fecha time.Time
|
||||
var monto float64
|
||||
var verifAt, rechAt, ultRec, compSub *time.Time
|
||||
var recCnt int
|
||||
var compTam *int
|
||||
if rows.Scan(&id, &progID, &fecha, &monto, &estado, &verifAt, &rechAt, &rechazoMotivo,
|
||||
&ultRec, &recCnt, ¬a, &concepto, &moneda, &frec, &cid, &cnom, &cemp, &cemail,
|
||||
&compID, &compNom, &compMime, &compTam, &compSub) == nil {
|
||||
var comp any
|
||||
if compID != nil {
|
||||
comp = map[string]any{
|
||||
"id": *compID, "pagoId": id, "archivoNombre": compNom, "mime": compMime, "tamano": compTam, "subidoAt": compSub,
|
||||
}
|
||||
}
|
||||
list = append(list, map[string]any{
|
||||
"id": id, "programaId": progID, "fecha": fecha, "monto": monto, "estado": estado,
|
||||
"verificadoAt": verifAt, "rechazadoAt": rechAt, "rechazoMotivo": rechazoMotivo,
|
||||
"ultimoRecordatorioAt": ultRec, "recordatoriosEnviados": recCnt, "nota": nota,
|
||||
"programa": map[string]any{
|
||||
"id": progID, "concepto": concepto, "moneda": moneda, "frecuencia": frec, "clienteId": cid,
|
||||
"cliente": map[string]any{"id": cid, "nombre": cnom, "empresa": cemp, "email": cemail},
|
||||
},
|
||||
"comprobante": comp,
|
||||
})
|
||||
}
|
||||
}
|
||||
return list, nil
|
||||
}
|
||||
|
||||
func (s *Server) handlePagosList(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"cobros:leer"}, RecursoTipo: "pago"}); !ok {
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
conds := []string{"1=1"}
|
||||
args := []any{}
|
||||
add := func(v any) string {
|
||||
args = append(args, v)
|
||||
return fmt.Sprintf("$%d", len(args))
|
||||
}
|
||||
if est := strings.TrimSpace(q.Get("estado")); est != "" {
|
||||
if est == "por_pagar" {
|
||||
conds = append(conds, `p."estado" IN ('pendiente', 'rechazado')`)
|
||||
} else {
|
||||
conds = append(conds, `p."estado" = `+add(est))
|
||||
}
|
||||
}
|
||||
if cid := strings.TrimSpace(q.Get("clienteId")); cid != "" {
|
||||
conds = append(conds, `pr."clienteId" = `+add(cid))
|
||||
}
|
||||
if pid := strings.TrimSpace(q.Get("programaId")); pid != "" {
|
||||
conds = append(conds, `p."programaId" = `+add(pid))
|
||||
}
|
||||
if d := strings.TrimSpace(q.Get("desde")); d != "" {
|
||||
if t, err := domain.ParseFechaCalendario(d); err == nil {
|
||||
conds = append(conds, `p."fecha" >= `+add(t))
|
||||
}
|
||||
}
|
||||
if h := strings.TrimSpace(q.Get("hasta")); h != "" {
|
||||
if t, err := domain.ParseFechaCalendario(h); err == nil {
|
||||
conds = append(conds, `p."fecha" <= `+add(t))
|
||||
}
|
||||
}
|
||||
list, err := s.queryPagos(r.Context(), strings.Join(conds, " AND "), args)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error listando pagos")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, list)
|
||||
}
|
||||
|
||||
func (s *Server) handlePagoAprobar(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "pago"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
var estado string
|
||||
var monto float64
|
||||
if err := s.Pool.QueryRow(r.Context(), `SELECT "estado", "monto" FROM "PagoRecurrente" WHERE "id" = $1`, id).Scan(&estado, &monto); err != nil {
|
||||
writeError(w, http.StatusNotFound, "Cobro no encontrado")
|
||||
return
|
||||
}
|
||||
if estado != domain.EstadoPagoEnRevision {
|
||||
writeError(w, http.StatusConflict, "Solo se pueden aprobar cobros en revision")
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
_, err := s.Pool.Exec(r.Context(), `
|
||||
UPDATE "PagoRecurrente" SET "estado"='verificado', "verificadoAt"=$1, "rechazadoAt"=NULL, "rechazoMotivo"=NULL, "updatedAt"=NOW()
|
||||
WHERE "id" = $2
|
||||
`, now, id)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error aprobando comprobante")
|
||||
return
|
||||
}
|
||||
|
||||
tipo, aid, anom := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
||||
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
||||
Accion: "pago.aprobar_comprobante", RecursoTipo: "pago", RecursoID: id,
|
||||
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
||||
})
|
||||
go s.Notify.NotificarVerificacion(context.Background(), id)
|
||||
go s.Webhooks.Emitir(context.Background(), "pago.registrado", map[string]any{
|
||||
"pagoId": id, "monto": monto, "metodo": "comprobante_verificado", "verificadoAt": now.UTC().Format(time.RFC3339),
|
||||
})
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": id, "estado": "verificado", "verificadoAt": now})
|
||||
}
|
||||
|
||||
func (s *Server) handlePagoRechazar(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "pago"}); !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
var body struct {
|
||||
Motivo string `json:"motivo"`
|
||||
}
|
||||
_ = decodeJSON(r, &body)
|
||||
motivo := strings.TrimSpace(body.Motivo)
|
||||
if motivo == "" {
|
||||
writeError(w, http.StatusBadRequest, "El motivo del rechazo es obligatorio")
|
||||
return
|
||||
}
|
||||
|
||||
var ruta string
|
||||
_ = s.Pool.QueryRow(r.Context(), `SELECT "archivoRuta" FROM "ComprobantePago" WHERE "pagoId" = $1`, id).Scan(&ruta)
|
||||
if ruta != "" {
|
||||
_ = uploads.EliminarComprobante(s.Cfg.UploadDir, ruta)
|
||||
_, _ = s.Pool.Exec(r.Context(), `DELETE FROM "ComprobantePago" WHERE "pagoId" = $1`, id)
|
||||
}
|
||||
|
||||
tag, err := s.Pool.Exec(r.Context(), `
|
||||
UPDATE "PagoRecurrente" SET "estado"='rechazado', "rechazadoAt"=NOW(), "rechazoMotivo"=$1, "updatedAt"=NOW()
|
||||
WHERE "id" = $2
|
||||
`, motivo, id)
|
||||
if err != nil || tag.RowsAffected() == 0 {
|
||||
writeError(w, http.StatusNotFound, "Cobro no encontrado")
|
||||
return
|
||||
}
|
||||
go s.Notify.NotificarRechazo(context.Background(), id, motivo)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": id, "estado": "rechazado"})
|
||||
}
|
||||
|
||||
func (s *Server) handlePagoRegistrar(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"cobros:registrar"}, RecursoTipo: "pago"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
idempotency.Execute(r.Context(), s.Pool, w, r, actor, func(rawBody []byte) (int, any) {
|
||||
var body struct {
|
||||
Fecha string `json:"fecha"`
|
||||
Nota *string `json:"nota"`
|
||||
}
|
||||
if err := json.Unmarshal(rawBody, &body); err != nil {
|
||||
return http.StatusBadRequest, map[string]any{"error": "JSON invalido"}
|
||||
}
|
||||
hoy := domain.HoyCalendario()
|
||||
fPago := hoy
|
||||
if strings.TrimSpace(body.Fecha) != "" {
|
||||
t, err := domain.ParseFechaCalendario(body.Fecha)
|
||||
if err != nil {
|
||||
return http.StatusBadRequest, map[string]any{"error": err.Error()}
|
||||
}
|
||||
if t.After(hoy) {
|
||||
return http.StatusBadRequest, map[string]any{"error": "La fecha de pago no puede ser futura"}
|
||||
}
|
||||
fPago = t
|
||||
}
|
||||
|
||||
var estado string
|
||||
var monto float64
|
||||
if err := s.Pool.QueryRow(r.Context(), `SELECT "estado", "monto" FROM "PagoRecurrente" WHERE "id" = $1`, id).Scan(&estado, &monto); err != nil {
|
||||
return http.StatusNotFound, map[string]any{"error": "Cobro no encontrado"}
|
||||
}
|
||||
if estado != domain.EstadoPagoPendiente && estado != domain.EstadoPagoRechazado {
|
||||
return http.StatusConflict, map[string]any{"error": "Solo se pueden registrar cobros pendientes o rechazados"}
|
||||
}
|
||||
|
||||
verifAt := domain.InstanteDePago(fPago)
|
||||
_, err := s.Pool.Exec(r.Context(), `
|
||||
UPDATE "PagoRecurrente"
|
||||
SET "estado"='verificado', "verificadoAt"=$1, "nota"=$2, "rechazadoAt"=NULL, "rechazoMotivo"=NULL, "updatedAt"=NOW()
|
||||
WHERE "id" = $3
|
||||
`, verifAt, trimPtr(body.Nota), id)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, map[string]any{"error": "Error registrando pago"}
|
||||
}
|
||||
|
||||
tipo, aid, anom := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
||||
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
||||
Accion: "pago.registrar", RecursoTipo: "pago", RecursoID: id,
|
||||
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
||||
Detalle: map[string]any{"fecha": fPago.Format("2006-01-02"), "nota": body.Nota},
|
||||
})
|
||||
go s.Notify.NotificarVerificacion(context.Background(), id)
|
||||
go s.Webhooks.Emitir(context.Background(), "pago.registrado", map[string]any{
|
||||
"pagoId": id, "monto": monto, "metodo": "registro_manual", "verificadoAt": verifAt.UTC().Format(time.RFC3339),
|
||||
})
|
||||
return http.StatusOK, map[string]any{"ok": true, "id": id, "estado": "verificado", "verificadoAt": verifAt}
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handlePagoAnular(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "pago"}); !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
var body struct {
|
||||
Motivo string `json:"motivo"`
|
||||
}
|
||||
_ = decodeJSON(r, &body)
|
||||
motivo := strings.TrimSpace(body.Motivo)
|
||||
if motivo == "" {
|
||||
writeError(w, http.StatusBadRequest, "El motivo es obligatorio")
|
||||
return
|
||||
}
|
||||
var estado string
|
||||
if err := s.Pool.QueryRow(r.Context(), `SELECT "estado" FROM "PagoRecurrente" WHERE "id" = $1`, id).Scan(&estado); err != nil {
|
||||
writeError(w, http.StatusNotFound, "Cobro no encontrado")
|
||||
return
|
||||
}
|
||||
if estado != domain.EstadoPagoPendiente && estado != domain.EstadoPagoRechazado {
|
||||
writeError(w, http.StatusConflict, "Solo se pueden anular cobros pendientes o rechazados")
|
||||
return
|
||||
}
|
||||
_, _ = s.Pool.Exec(r.Context(), `UPDATE "PagoRecurrente" SET "estado"='anulado', "nota"=$1, "updatedAt"=NOW() WHERE "id" = $2`, motivo, id)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": id, "estado": "anulado"})
|
||||
}
|
||||
|
||||
func (s *Server) handlePagoReabrir(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "pago"}); !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
var estado string
|
||||
var hasComp bool
|
||||
err := s.Pool.QueryRow(r.Context(), `
|
||||
SELECT p."estado", EXISTS(SELECT 1 FROM "ComprobantePago" c WHERE c."pagoId" = p."id")
|
||||
FROM "PagoRecurrente" p WHERE p."id" = $1
|
||||
`, id).Scan(&estado, &hasComp)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "Cobro no encontrado")
|
||||
return
|
||||
}
|
||||
if estado == domain.EstadoPagoVerificado && hasComp {
|
||||
writeError(w, http.StatusConflict, "No se puede reabrir un cobro verificado con comprobante")
|
||||
return
|
||||
}
|
||||
if estado != domain.EstadoPagoVerificado && estado != domain.EstadoPagoAnulado {
|
||||
writeError(w, http.StatusConflict, "Solo se pueden reabrir cobros anulados o registrados manualmente")
|
||||
return
|
||||
}
|
||||
_, _ = s.Pool.Exec(r.Context(), `
|
||||
UPDATE "PagoRecurrente" SET "estado"='pendiente', "verificadoAt"=NULL, "nota"=NULL, "updatedAt"=NOW() WHERE "id" = $1
|
||||
`, id)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": id, "estado": "pendiente"})
|
||||
}
|
||||
|
||||
func (s *Server) handleCobrosRecordatorios(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "cobros"}); !ok {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
ClienteID string `json:"clienteId"`
|
||||
}
|
||||
_ = decodeJSON(r, &body)
|
||||
res, err := s.Notify.EnviarRecordatoriosPendientes(r.Context(), strings.TrimSpace(body.ClienteID), true)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error enviando recordatorios")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, res)
|
||||
}
|
||||
|
||||
func (s *Server) handleComprobanteGet(w http.ResponseWriter, r *http.Request) {
|
||||
sess, ok := s.Auth.SessionFromRequest(r)
|
||||
if !ok {
|
||||
writeError(w, http.StatusUnauthorized, "No autenticado")
|
||||
return
|
||||
}
|
||||
pagoID := chi.URLParam(r, "pagoId")
|
||||
var ruta, nombre, mime, ownerClienteID string
|
||||
err := s.Pool.QueryRow(r.Context(), `
|
||||
SELECT c."archivoRuta", c."archivoNombre", c."mime", pr."clienteId"
|
||||
FROM "ComprobantePago" c
|
||||
JOIN "PagoRecurrente" p ON p."id" = c."pagoId"
|
||||
JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
WHERE c."pagoId" = $1
|
||||
`, pagoID).Scan(&ruta, &nombre, &mime, &ownerClienteID)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "Comprobante no encontrado")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "Error consultando comprobante")
|
||||
return
|
||||
}
|
||||
if sess.Role == "cliente" && sess.ClienteID != ownerClienteID {
|
||||
writeError(w, http.StatusForbidden, "No tienes acceso a este comprobante")
|
||||
return
|
||||
}
|
||||
absPath, err := uploads.RutaAbsoluta(s.Cfg.UploadDir, ruta)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusForbidden, "Ruta invalida")
|
||||
return
|
||||
}
|
||||
data, err := os.ReadFile(absPath)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "Archivo no encontrado en disco")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", mime)
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, domain.SanitizeFilename(nombre)))
|
||||
w.Header().Set("Cache-Control", "private, no-store")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(data)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,649 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/audit"
|
||||
"cotizador/internal/auth"
|
||||
"cotizador/internal/db"
|
||||
"cotizador/internal/domain"
|
||||
"cotizador/internal/excel"
|
||||
"cotizador/internal/pdf"
|
||||
"cotizador/internal/propuesta"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *Server) loadBonosPDF(ctx context.Context) []pdf.BonoPDF {
|
||||
rows, err := s.Pool.Query(ctx, `SELECT "numero", "descripcion" FROM "Bono" WHERE "activo" = true ORDER BY "numero" ASC`)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []pdf.BonoPDF
|
||||
for rows.Next() {
|
||||
var b pdf.BonoPDF
|
||||
if rows.Scan(&b.Numero, &b.Descripcion) == nil {
|
||||
out = append(out, b)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Server) buildQuotePDFBytes(ctx context.Context, full *cotizacionFull) ([]byte, error) {
|
||||
branding := s.getConfigBranding(ctx)
|
||||
var bonos []pdf.BonoPDF
|
||||
if full.IncluirBonos {
|
||||
bonos = s.loadBonosPDF(ctx)
|
||||
}
|
||||
return pdf.GenerateCotizacionPDF(pdf.CotizacionPDFData{
|
||||
Numero: full.Numero,
|
||||
ClienteNombre: full.ClienteNombre,
|
||||
ClienteEmpresa: derefStr(full.ClienteEmpresa),
|
||||
AsesorNombre: full.AsesorName,
|
||||
Fecha: full.Fecha,
|
||||
Vigencia: full.Vigencia,
|
||||
Moneda: full.Moneda,
|
||||
TipoCambio: full.TipoCambio,
|
||||
Proyecto: full.Proyecto,
|
||||
EsquemaPago: full.EsquemaPago,
|
||||
Servicios: full.ServiciosPDF,
|
||||
EsDoble: full.EsDoble,
|
||||
OpcionesMetadata: full.OpcionesMetadata,
|
||||
PlanBucefaloNivel: full.PlanBucefaloNv,
|
||||
PlanBucefaloPrecio: full.PlanBucefaloPr,
|
||||
IncluirBonos: full.IncluirBonos,
|
||||
Bonos: bonos,
|
||||
IncluirIVA: full.IncluirIVA,
|
||||
Observaciones: full.Observaciones,
|
||||
ConfigBancaria: s.getConfigBancaria(ctx),
|
||||
ColorPrimario: branding.ColorPrimario,
|
||||
ColorSecundario: branding.ColorSecundario,
|
||||
LogoBase64: branding.LogoBase64,
|
||||
LogoMime: branding.LogoMime,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleExportPDFByID(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{
|
||||
AllowCliente: true,
|
||||
Scopes: []string{"cotizaciones:leer", "cotizaciones:enviar", "cotizaciones:leer_aceptadas"},
|
||||
RecursoTipo: "cotizacion_pdf",
|
||||
})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
full, _, err := s.loadCotizacionFull(r.Context(), id, true)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "Cotizacion no encontrada")
|
||||
return
|
||||
}
|
||||
if actor.IsCliente() && full.ClienteID != actor.ClienteID {
|
||||
writeError(w, http.StatusNotFound, "Cotizacion no encontrada")
|
||||
return
|
||||
}
|
||||
if actor.EsAgenteSoloAceptadas() && full.Estado != "aceptada" {
|
||||
tipo, aid, anom := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
||||
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
||||
Accion: "cotizacion.export_pdf_bloqueado", RecursoTipo: "cotizacion", RecursoID: id,
|
||||
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false,
|
||||
})
|
||||
writeError(w, http.StatusForbidden, "Solo puedes exportar PDF de cotizaciones aceptadas")
|
||||
return
|
||||
}
|
||||
|
||||
pdfBytes, err := s.buildQuotePDFBytes(r.Context(), full)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error generando PDF: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/pdf")
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="Cotizacion_%s.pdf"`, domain.SanitizeFilename(full.Numero)))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(pdfBytes)
|
||||
}
|
||||
|
||||
type draftExportBody struct {
|
||||
Draft *draftExportPayload `json:"draft"`
|
||||
draftExportPayload
|
||||
}
|
||||
|
||||
type draftExportPayload struct {
|
||||
Numero string `json:"numero"`
|
||||
ClienteNombre string `json:"clienteNombre"`
|
||||
ClienteEmpresa string `json:"clienteEmpresa"`
|
||||
AsesorNombre string `json:"asesorNombre"`
|
||||
Fecha string `json:"fecha"`
|
||||
Vigencia string `json:"vigencia"`
|
||||
Moneda string `json:"moneda"`
|
||||
TipoCambio string `json:"tipoCambio"`
|
||||
Proyecto string `json:"proyecto"`
|
||||
EsquemaPago string `json:"esquemaPago"`
|
||||
IncluirBonos bool `json:"incluirBonos"`
|
||||
IncluirIVA *bool `json:"incluirIva"`
|
||||
EsDoble bool `json:"esDoble"`
|
||||
OpcionesMetadata map[string]domain.MetaOpcion `json:"opcionesMetadata"`
|
||||
Observaciones *string `json:"observaciones"`
|
||||
PlanBucefaloNivel *string `json:"planBucefaloNivel"`
|
||||
PlanBucefaloPrecio *float64 `json:"planBucefaloPrecio"`
|
||||
PlanBucefalo *struct {
|
||||
Nivel string `json:"nivel"`
|
||||
Precio *float64 `json:"precio"`
|
||||
Seleccionado *bool `json:"seleccionado"`
|
||||
} `json:"planBucefalo"`
|
||||
Servicios []servicioInputDTO `json:"servicios"`
|
||||
}
|
||||
|
||||
func (s *Server) handleExportPDFDraft(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "cotizacion_pdf"}); !ok {
|
||||
return
|
||||
}
|
||||
var wrap draftExportBody
|
||||
if err := decodeJSON(r, &wrap); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "Borrador invalido")
|
||||
return
|
||||
}
|
||||
d := wrap.draftExportPayload
|
||||
if wrap.Draft != nil {
|
||||
d = *wrap.Draft
|
||||
}
|
||||
fecha := time.Now()
|
||||
if t, err := parseFlexibleDate(d.Fecha); err == nil {
|
||||
fecha = t
|
||||
}
|
||||
vigencia := domain.CalcularVigencia(fecha)
|
||||
if t, err := parseFlexibleDate(d.Vigencia); err == nil {
|
||||
vigencia = t
|
||||
}
|
||||
incluirIVA := true
|
||||
if d.IncluirIVA != nil {
|
||||
incluirIVA = *d.IncluirIVA
|
||||
}
|
||||
svcs := make([]pdf.ServicioPDF, 0, len(d.Servicios))
|
||||
for _, sv := range d.Servicios {
|
||||
if sv.Seleccionado != nil && !*sv.Seleccionado {
|
||||
continue
|
||||
}
|
||||
svcs = append(svcs, pdf.ServicioPDF{
|
||||
Nombre: firstNonEmptyStr(derefStr(sv.Nombre), "Servicio"), Fase: sv.Fase,
|
||||
TipoPago: firstNonEmptyStr(sv.TipoPago, "unico"), Precio: sv.Precio,
|
||||
TiempoEntrega: firstNonEmptyStr(sv.TiempoEntrega, "4 - 10 dias"),
|
||||
Entregables: nonNilSlice(sv.Entregables), EsPersonalizado: sv.EsPersonalizado,
|
||||
Horas: sv.Horas, TarifaHora: sv.TarifaHora, ModeloCobro: firstNonEmptyStr(sv.ModeloCobro, "fijo"),
|
||||
MontoMinimo: sv.MontoMinimo, HorasIncluidas: sv.HorasIncluidas, Opcion: sv.Opcion,
|
||||
})
|
||||
}
|
||||
pbNivel, pbPrecio := resolveDraftBucefalo(d)
|
||||
branding := s.getConfigBranding(r.Context())
|
||||
var bonos []pdf.BonoPDF
|
||||
if d.IncluirBonos {
|
||||
bonos = s.loadBonosPDF(r.Context())
|
||||
}
|
||||
pdfBytes, err := pdf.GenerateCotizacionPDF(pdf.CotizacionPDFData{
|
||||
Numero: firstNonEmptyStr(d.Numero, "BORRADOR"),
|
||||
ClienteNombre: firstNonEmptyStr(d.ClienteNombre, "Cliente"),
|
||||
ClienteEmpresa: d.ClienteEmpresa,
|
||||
AsesorNombre: firstNonEmptyStr(d.AsesorNombre, "Asesor"),
|
||||
Fecha: fecha,
|
||||
Vigencia: vigencia,
|
||||
Moneda: firstNonEmptyStr(d.Moneda, "MXN"),
|
||||
TipoCambio: firstNonEmptyStr(d.TipoCambio, "NA"),
|
||||
Proyecto: firstNonEmptyStr(d.Proyecto, "MKT Digital"),
|
||||
EsquemaPago: firstNonEmptyStr(d.EsquemaPago, "Pago Unico/Mensual"),
|
||||
Servicios: svcs,
|
||||
EsDoble: d.EsDoble,
|
||||
OpcionesMetadata: d.OpcionesMetadata,
|
||||
PlanBucefaloNivel: pbNivel,
|
||||
PlanBucefaloPrecio: pbPrecio,
|
||||
IncluirBonos: d.IncluirBonos,
|
||||
Bonos: bonos,
|
||||
IncluirIVA: incluirIVA,
|
||||
Observaciones: d.Observaciones,
|
||||
ConfigBancaria: s.getConfigBancaria(r.Context()),
|
||||
ColorPrimario: branding.ColorPrimario,
|
||||
ColorSecundario: branding.ColorSecundario,
|
||||
LogoBase64: branding.LogoBase64,
|
||||
LogoMime: branding.LogoMime,
|
||||
})
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error generando PDF de borrador")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/pdf")
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="Cotizacion_%s.pdf"`, domain.SanitizeFilename(firstNonEmptyStr(d.Numero, "BORRADOR"))))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(pdfBytes)
|
||||
}
|
||||
|
||||
func (s *Server) handleExportExcelByID(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "cotizacion_excel"}); !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
full, _, err := s.loadCotizacionFull(r.Context(), id, true)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "Cotizacion no encontrada")
|
||||
return
|
||||
}
|
||||
cfgMap := s.getAllConfigMap(r.Context())
|
||||
svcs := make([]excel.ServicioExcel, 0, len(full.ServiciosPDF))
|
||||
for _, sv := range full.ServiciosPDF {
|
||||
svcs = append(svcs, excel.ServicioExcel{
|
||||
Nombre: sv.Nombre, Fase: sv.Fase, TipoPago: sv.TipoPago, Precio: sv.Precio,
|
||||
TiempoEntrega: sv.TiempoEntrega, Entregables: sv.Entregables,
|
||||
EsPersonalizado: sv.EsPersonalizado, Horas: sv.Horas, TarifaHora: sv.TarifaHora,
|
||||
ModeloCobro: sv.ModeloCobro, MontoMinimo: sv.MontoMinimo, HorasIncluidas: sv.HorasIncluidas, Opcion: sv.Opcion,
|
||||
})
|
||||
}
|
||||
var pbPrecio *float64
|
||||
if full.PlanBucefaloNv != nil {
|
||||
p := full.PlanBucefaloPr
|
||||
pbPrecio = &p
|
||||
}
|
||||
xlsxBytes, err := excel.BuildCotizacionExcel(excel.CotizacionExcelData{
|
||||
RazonSocial: firstNonEmptyStr(cfgMap["razon_social"], "Uriel Jareth Consulting"),
|
||||
DomicilioFiscal: cfgMap["domicilio_fiscal"],
|
||||
Numero: full.Numero,
|
||||
ClienteNombre: full.ClienteNombre,
|
||||
ClienteEmpresa: derefStr(full.ClienteEmpresa),
|
||||
AsesorNombre: full.AsesorName,
|
||||
Fecha: full.Fecha,
|
||||
Vigencia: full.Vigencia,
|
||||
Moneda: full.Moneda,
|
||||
TipoCambio: full.TipoCambio,
|
||||
Proyecto: full.Proyecto,
|
||||
EsquemaPago: full.EsquemaPago,
|
||||
Servicios: svcs,
|
||||
EsDoble: full.EsDoble,
|
||||
OpcionesMetadata: full.OpcionesMetadata,
|
||||
PlanBucefaloNivel: full.PlanBucefaloNv,
|
||||
PlanBucefaloPrecio: pbPrecio,
|
||||
ColorPrimario: firstNonEmptyStr(cfgMap["color_primario"], "#0400C4"),
|
||||
ColorSecundario: firstNonEmptyStr(cfgMap["color_secundario"], "#0F172A"),
|
||||
IncluirIVA: full.IncluirIVA,
|
||||
Observaciones: full.Observaciones,
|
||||
})
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error generando Excel")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="Cotizacion_%s.xlsx"`, domain.SanitizeFilename(full.Numero)))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(xlsxBytes)
|
||||
}
|
||||
|
||||
func (s *Server) handleExportExcelDraft(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "cotizacion_excel"}); !ok {
|
||||
return
|
||||
}
|
||||
var wrap draftExportBody
|
||||
if err := decodeJSON(r, &wrap); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "Borrador invalido")
|
||||
return
|
||||
}
|
||||
d := wrap.draftExportPayload
|
||||
if wrap.Draft != nil {
|
||||
d = *wrap.Draft
|
||||
}
|
||||
fecha := time.Now()
|
||||
if t, err := parseFlexibleDate(d.Fecha); err == nil {
|
||||
fecha = t
|
||||
}
|
||||
vigencia := domain.CalcularVigencia(fecha)
|
||||
if t, err := parseFlexibleDate(d.Vigencia); err == nil {
|
||||
vigencia = t
|
||||
}
|
||||
incluirIVA := true
|
||||
if d.IncluirIVA != nil {
|
||||
incluirIVA = *d.IncluirIVA
|
||||
}
|
||||
svcs := make([]excel.ServicioExcel, 0, len(d.Servicios))
|
||||
for _, sv := range d.Servicios {
|
||||
if sv.Seleccionado != nil && !*sv.Seleccionado {
|
||||
continue
|
||||
}
|
||||
svcs = append(svcs, excel.ServicioExcel{
|
||||
Nombre: firstNonEmptyStr(derefStr(sv.Nombre), "Servicio"), Fase: sv.Fase,
|
||||
TipoPago: firstNonEmptyStr(sv.TipoPago, "unico"), Precio: sv.Precio,
|
||||
TiempoEntrega: firstNonEmptyStr(sv.TiempoEntrega, "4 - 10 dias"),
|
||||
Entregables: nonNilSlice(sv.Entregables), EsPersonalizado: sv.EsPersonalizado,
|
||||
Horas: sv.Horas, TarifaHora: sv.TarifaHora, ModeloCobro: firstNonEmptyStr(sv.ModeloCobro, "fijo"),
|
||||
MontoMinimo: sv.MontoMinimo, HorasIncluidas: sv.HorasIncluidas, Opcion: sv.Opcion,
|
||||
})
|
||||
}
|
||||
pbNivel, pbPrecioVal := resolveDraftBucefalo(d)
|
||||
var pbPrecio *float64
|
||||
if pbNivel != nil {
|
||||
pbPrecio = &pbPrecioVal
|
||||
}
|
||||
cfgMap := s.getAllConfigMap(r.Context())
|
||||
xlsxBytes, err := excel.BuildCotizacionExcel(excel.CotizacionExcelData{
|
||||
RazonSocial: firstNonEmptyStr(cfgMap["razon_social"], "Uriel Jareth Consulting"),
|
||||
DomicilioFiscal: cfgMap["domicilio_fiscal"],
|
||||
Numero: firstNonEmptyStr(d.Numero, "BORRADOR"),
|
||||
ClienteNombre: firstNonEmptyStr(d.ClienteNombre, "Cliente"),
|
||||
ClienteEmpresa: d.ClienteEmpresa,
|
||||
AsesorNombre: firstNonEmptyStr(d.AsesorNombre, "Asesor"),
|
||||
Fecha: fecha,
|
||||
Vigencia: vigencia,
|
||||
Moneda: firstNonEmptyStr(d.Moneda, "MXN"),
|
||||
TipoCambio: firstNonEmptyStr(d.TipoCambio, "NA"),
|
||||
Proyecto: firstNonEmptyStr(d.Proyecto, "MKT Digital"),
|
||||
EsquemaPago: firstNonEmptyStr(d.EsquemaPago, "Pago Unico/Mensual"),
|
||||
Servicios: svcs,
|
||||
EsDoble: d.EsDoble,
|
||||
OpcionesMetadata: d.OpcionesMetadata,
|
||||
PlanBucefaloNivel: pbNivel,
|
||||
PlanBucefaloPrecio: pbPrecio,
|
||||
ColorPrimario: firstNonEmptyStr(cfgMap["color_primario"], "#0400C4"),
|
||||
ColorSecundario: firstNonEmptyStr(cfgMap["color_secundario"], "#0F172A"),
|
||||
IncluirIVA: incluirIVA,
|
||||
Observaciones: d.Observaciones,
|
||||
})
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error generando Excel de borrador")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="Cotizacion_%s.xlsx"`, domain.SanitizeFilename(firstNonEmptyStr(d.Numero, "BORRADOR"))))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(xlsxBytes)
|
||||
}
|
||||
|
||||
func resolveDraftBucefalo(d draftExportPayload) (*string, float64) {
|
||||
if d.PlanBucefalo != nil {
|
||||
if d.PlanBucefalo.Seleccionado != nil && !*d.PlanBucefalo.Seleccionado {
|
||||
return nil, 0
|
||||
}
|
||||
nv := d.PlanBucefalo.Nivel
|
||||
pr := domain.BucefaloPrecio(nv)
|
||||
if d.PlanBucefalo.Precio != nil {
|
||||
pr = *d.PlanBucefalo.Precio
|
||||
}
|
||||
return &nv, pr
|
||||
}
|
||||
if d.PlanBucefaloNivel != nil && *d.PlanBucefaloNivel != "" {
|
||||
pr := domain.BucefaloPrecio(*d.PlanBucefaloNivel)
|
||||
if d.PlanBucefaloPrecio != nil {
|
||||
pr = *d.PlanBucefaloPrecio
|
||||
}
|
||||
return d.PlanBucefaloNivel, pr
|
||||
}
|
||||
return nil, 0
|
||||
}
|
||||
|
||||
// ── Propuesta Consultiva IA ──────────────────────────────────────────────────
|
||||
|
||||
func (s *Server) handlePropuestaIAGet(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "propuesta_ia"}); !ok {
|
||||
return
|
||||
}
|
||||
cotID := chi.URLParam(r, "id")
|
||||
var id, estado, modelo string
|
||||
var contenidoIA, contenidoEditado, traza, avisos []byte
|
||||
var transcripcion, aprobadaPor *string
|
||||
var aprobadaAt *time.Time
|
||||
var createdAt, updatedAt time.Time
|
||||
|
||||
err := s.Pool.QueryRow(r.Context(), `
|
||||
SELECT "id", "estado", "contenidoIA", "contenidoEditado", "transcripcion", "traza", "avisos",
|
||||
"modelo", "aprobadaPor", "aprobadaAt", "createdAt", "updatedAt"
|
||||
FROM "PropuestaIA"
|
||||
WHERE "cotizacionId" = $1
|
||||
ORDER BY "createdAt" DESC
|
||||
LIMIT 1
|
||||
`, cotID).Scan(&id, &estado, &contenidoIA, &contenidoEditado, &transcripcion, &traza, &avisos,
|
||||
&modelo, &aprobadaPor, &aprobadaAt, &createdAt, &updatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"propuesta": nil})
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "Error cargando propuesta IA")
|
||||
return
|
||||
}
|
||||
|
||||
var cIA, cEd, tr, av any
|
||||
_ = json.Unmarshal(contenidoIA, &cIA)
|
||||
if len(contenidoEditado) > 0 {
|
||||
_ = json.Unmarshal(contenidoEditado, &cEd)
|
||||
}
|
||||
if len(traza) > 0 {
|
||||
_ = json.Unmarshal(traza, &tr)
|
||||
}
|
||||
_ = json.Unmarshal(avisos, &av)
|
||||
if av == nil {
|
||||
av = []any{}
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"propuesta": map[string]any{
|
||||
"id": id, "cotizacionId": cotID, "estado": estado,
|
||||
"contenidoIA": cIA, "contenidoEditado": cEd, "transcripcion": transcripcion,
|
||||
"traza": tr, "avisos": av, "modelo": modelo,
|
||||
"aprobadaPor": aprobadaPor, "aprobadaAt": aprobadaAt,
|
||||
"createdAt": createdAt, "updatedAt": updatedAt,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handlePropuestaIACreate(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "propuesta_ia"}); !ok {
|
||||
return
|
||||
}
|
||||
cotID := chi.URLParam(r, "id")
|
||||
var body struct {
|
||||
Transcripcion string `json:"transcripcion"`
|
||||
NotasAdicionales string `json:"notasAdicionales"`
|
||||
}
|
||||
_ = decodeJSON(r, &body)
|
||||
|
||||
res, err := propuesta.GenerarPropuesta(r.Context(), s.Cfg, s.Pool, propuesta.GenerarInput{
|
||||
CotizacionID: cotID,
|
||||
Transcripcion: body.Transcripcion,
|
||||
NotasAdicionales: body.NotasAdicionales,
|
||||
})
|
||||
if err != nil {
|
||||
status := http.StatusInternalServerError
|
||||
if strings.Contains(err.Error(), "doble") || strings.Contains(err.Error(), "partidas") || strings.Contains(err.Error(), "MINIMAX_API_KEY") {
|
||||
status = http.StatusBadRequest
|
||||
}
|
||||
writeError(w, status, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
cJSON, _ := json.Marshal(res.Contenido)
|
||||
tJSON, _ := json.Marshal(res.Traza)
|
||||
aJSON, _ := json.Marshal(res.Avisos)
|
||||
|
||||
id := db.NewID()
|
||||
_, err = s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "PropuestaIA" ("id", "cotizacionId", "estado", "contenidoIA", "transcripcion", "traza", "avisos", "modelo", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, 'borrador', $3, $4, $5, $6, $7, NOW(), NOW())
|
||||
`, id, cotID, cJSON, nullableTrim(body.Transcripcion), tJSON, aJSON, res.Modelo)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error guardando propuesta IA")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, map[string]any{
|
||||
"propuesta": map[string]any{
|
||||
"id": id, "cotizacionId": cotID, "estado": "borrador",
|
||||
"contenidoIA": res.Contenido, "contenidoEditado": nil,
|
||||
"transcripcion": nullableTrim(body.Transcripcion),
|
||||
"traza": res.Traza, "avisos": res.Avisos, "modelo": res.Modelo,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handlePropuestaIAPatch(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "propuesta_ia"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
cotID := chi.URLParam(r, "id")
|
||||
var body struct {
|
||||
ContenidoEditado map[string]any `json:"contenidoEditado"`
|
||||
Estado string `json:"estado"`
|
||||
}
|
||||
if err := decodeJSON(r, &body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "JSON invalido")
|
||||
return
|
||||
}
|
||||
|
||||
var propID string
|
||||
var transcripcion *string
|
||||
var contenidoIA []byte
|
||||
err := s.Pool.QueryRow(r.Context(), `
|
||||
SELECT "id", "transcripcion", "contenidoIA" FROM "PropuestaIA"
|
||||
WHERE "cotizacionId" = $1 ORDER BY "createdAt" DESC LIMIT 1
|
||||
`, cotID).Scan(&propID, &transcripcion, &contenidoIA)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "Propuesta IA no encontrada")
|
||||
return
|
||||
}
|
||||
|
||||
contenido := body.ContenidoEditado
|
||||
if contenido == nil {
|
||||
_ = json.Unmarshal(contenidoIA, &contenido)
|
||||
}
|
||||
|
||||
full, _, _ := s.loadCotizacionFull(r.Context(), cotID, false)
|
||||
econ, err := propuesta.CargarEconomiaCotizacion(r.Context(), s.Pool, cotID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error cargando economia de cotizacion")
|
||||
return
|
||||
}
|
||||
fuentesCliente := derefStr(transcripcion)
|
||||
if full != nil && full.Observaciones != nil {
|
||||
fuentesCliente += "\n" + *full.Observaciones
|
||||
}
|
||||
notasInternas := ""
|
||||
if full != nil && full.ObservacionesInternas != nil {
|
||||
notasInternas = *full.ObservacionesInternas
|
||||
}
|
||||
avisos := propuesta.ValidarPropuesta(contenido, econ, fuentesCliente, notasInternas)
|
||||
|
||||
cEdJSON, _ := json.Marshal(contenido)
|
||||
avJSON, _ := json.Marshal(avisos)
|
||||
estado := "borrador"
|
||||
var aprobadaPor *string
|
||||
var aprobadaAt *time.Time
|
||||
if body.Estado == "aprobada" {
|
||||
if propuesta.HayBloqueantes(avisos) {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"error": "Hay avisos bloqueantes pendientes por resolver", "avisos": avisos})
|
||||
return
|
||||
}
|
||||
estado = "aprobada"
|
||||
ap := actor.Email
|
||||
aprobadaPor = &ap
|
||||
now := time.Now()
|
||||
aprobadaAt = &now
|
||||
}
|
||||
|
||||
_, err = s.Pool.Exec(r.Context(), `
|
||||
UPDATE "PropuestaIA"
|
||||
SET "contenidoEditado" = $1, "avisos" = $2, "estado" = $3, "aprobadaPor" = COALESCE($4, "aprobadaPor"), "aprobadaAt" = COALESCE($5, "aprobadaAt"), "updatedAt" = NOW()
|
||||
WHERE "id" = $6
|
||||
`, cEdJSON, avJSON, estado, aprobadaPor, aprobadaAt, propID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error actualizando propuesta IA")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"ok": true, "id": propID, "estado": estado, "contenidoEditado": contenido, "avisos": avisos,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handlePropuestaIAPDF(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "propuesta_ia"}); !ok {
|
||||
return
|
||||
}
|
||||
cotID := chi.URLParam(r, "id")
|
||||
anexo := r.URL.Query().Get("anexo") == "1"
|
||||
|
||||
full, _, err := s.loadCotizacionFull(r.Context(), cotID, false)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "Cotizacion no encontrada")
|
||||
return
|
||||
}
|
||||
|
||||
var contenidoIA, contenidoEditado, avisosRaw []byte
|
||||
err = s.Pool.QueryRow(r.Context(), `
|
||||
SELECT "contenidoIA", "contenidoEditado", "avisos"
|
||||
FROM "PropuestaIA" WHERE "cotizacionId" = $1 ORDER BY "createdAt" DESC LIMIT 1
|
||||
`, cotID).Scan(&contenidoIA, &contenidoEditado, &avisosRaw)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "No existe una propuesta IA generada para esta cotizacion")
|
||||
return
|
||||
}
|
||||
|
||||
var avisos []propuesta.Aviso
|
||||
_ = json.Unmarshal(avisosRaw, &avisos)
|
||||
if !anexo && propuesta.HayBloqueantes(avisos) {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"error": "Resuelve los avisos bloqueantes antes de exportar el PDF para el cliente", "avisos": avisos})
|
||||
return
|
||||
}
|
||||
|
||||
var contenido map[string]any
|
||||
if len(contenidoEditado) > 0 {
|
||||
_ = json.Unmarshal(contenidoEditado, &contenido)
|
||||
} else {
|
||||
_ = json.Unmarshal(contenidoIA, &contenido)
|
||||
}
|
||||
|
||||
econ, err := propuesta.CargarEconomiaCotizacion(r.Context(), s.Pool, cotID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error cargando economia")
|
||||
return
|
||||
}
|
||||
econBytes, _ := json.Marshal(econ)
|
||||
var econMap map[string]any
|
||||
_ = json.Unmarshal(econBytes, &econMap)
|
||||
|
||||
branding := s.getConfigBranding(r.Context())
|
||||
in := pdf.PropuestaPDFInput{
|
||||
CotizacionNumero: full.Numero,
|
||||
ClienteNombre: full.ClienteNombre,
|
||||
ClienteEmpresa: derefStr(full.ClienteEmpresa),
|
||||
Proyecto: full.Proyecto,
|
||||
Moneda: full.Moneda,
|
||||
Fecha: full.Fecha,
|
||||
Contenido: contenido,
|
||||
Economia: econMap,
|
||||
ColorPrimario: branding.ColorPrimario,
|
||||
ColorSecundario: branding.ColorSecundario,
|
||||
LogoBase64: branding.LogoBase64,
|
||||
LogoMime: branding.LogoMime,
|
||||
}
|
||||
|
||||
var pdfBytes []byte
|
||||
var filename string
|
||||
if anexo {
|
||||
pdfBytes, err = pdf.GenerarAnexoInternoPDF(in)
|
||||
filename = fmt.Sprintf("AnexoInterno_%s.pdf", domain.SanitizeFilename(full.Numero))
|
||||
} else {
|
||||
pdfBytes, err = pdf.GenerarPropuestaPDF(in)
|
||||
filename = fmt.Sprintf("PropuestaConsultiva_%s.pdf", domain.SanitizeFilename(full.Numero))
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error generando PDF de propuesta IA: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/pdf")
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, filename))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(pdfBytes)
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"cotizador/internal/auth"
|
||||
"cotizador/internal/config"
|
||||
)
|
||||
|
||||
func newTestServer(t *testing.T) (*Server, http.Handler) {
|
||||
t.Helper()
|
||||
cfg := &config.Config{
|
||||
Port: "3000",
|
||||
AppURL: "https://cotizador.urieljareth.org",
|
||||
JWTSecret: "test-secret-key-for-httpapi-tests-32b",
|
||||
}
|
||||
authSvc := auth.NewService(cfg.JWTSecret, false, nil)
|
||||
srv := NewServer(cfg, nil, authSvc, nil, nil)
|
||||
return srv, srv.Router()
|
||||
}
|
||||
|
||||
func makeCookie(t *testing.T, authSvc *auth.Service, sess auth.SessionPayload) *http.Cookie {
|
||||
t.Helper()
|
||||
tok, err := authSvc.SignSession(sess)
|
||||
if err != nil {
|
||||
t.Fatalf("SignSession: %v", err)
|
||||
}
|
||||
return &http.Cookie{Name: auth.SessionCookieName, Value: tok}
|
||||
}
|
||||
|
||||
func TestOpenAPIAndSPARouting(t *testing.T) {
|
||||
_, router := newTestServer(t)
|
||||
|
||||
// 1. OpenAPI 3.1
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/openapi.json", nil)
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200 for /api/openapi.json, got %d", rec.Code)
|
||||
}
|
||||
var spec map[string]any
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &spec); err != nil {
|
||||
t.Fatalf("invalid openapi json: %v", err)
|
||||
}
|
||||
if spec["openapi"] != "3.1.0" {
|
||||
t.Fatalf("expected openapi 3.1.0, got %v", spec["openapi"])
|
||||
}
|
||||
if strings.Contains(rec.Body.String(), "cotizaciones:approve") {
|
||||
t.Fatal("iron-clad rule violation: openapi mentions cotizaciones:approve")
|
||||
}
|
||||
|
||||
// 2. Unknown /api/* route returns 404 JSON, NOT SPA HTML
|
||||
rec = httptest.NewRecorder()
|
||||
req = httptest.NewRequest(http.MethodGet, "/api/does-not-exist", nil)
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("expected 404 for unknown /api route, got %d", rec.Code)
|
||||
}
|
||||
if !strings.Contains(rec.Header().Get("Content-Type"), "application/json") {
|
||||
t.Fatalf("expected JSON content-type for unknown /api route, got %q", rec.Header().Get("Content-Type"))
|
||||
}
|
||||
|
||||
// 3. SPA routes serve HTML
|
||||
for _, p := range []string{"/", "/login", "/cotizaciones", "/cliente/pagos"} {
|
||||
rec = httptest.NewRecorder()
|
||||
req = httptest.NewRequest(http.MethodGet, p, nil)
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200 for SPA path %s, got %d", p, rec.Code)
|
||||
}
|
||||
if !strings.Contains(strings.ToLower(rec.Body.String()), "<html") && !strings.Contains(strings.ToLower(rec.Body.String()), "<!doctype html") {
|
||||
t.Fatalf("expected HTML body for SPA path %s", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProtectedRoutesRejectUnauthenticated(t *testing.T) {
|
||||
_, router := newTestServer(t)
|
||||
|
||||
cases := []struct {
|
||||
method string
|
||||
path string
|
||||
}{
|
||||
{http.MethodGet, "/api/auth/me"},
|
||||
{http.MethodGet, "/api/dashboard"},
|
||||
{http.MethodGet, "/api/asesores"},
|
||||
{http.MethodGet, "/api/configuracion"},
|
||||
{http.MethodPut, "/api/configuracion"},
|
||||
{http.MethodGet, "/api/catalogo"},
|
||||
{http.MethodPost, "/api/catalogo"},
|
||||
{http.MethodPut, "/api/categorias/cat-1"},
|
||||
{http.MethodDelete, "/api/categorias/cat-1"},
|
||||
{http.MethodGet, "/api/paquetes/paq-1"},
|
||||
{http.MethodPost, "/api/paquetes/paq-1/manage"},
|
||||
{http.MethodGet, "/api/clientes"},
|
||||
{http.MethodPost, "/api/clientes"},
|
||||
{http.MethodGet, "/api/cotizaciones"},
|
||||
{http.MethodPost, "/api/cotizaciones"},
|
||||
{http.MethodPost, "/api/cotizaciones/q1/aprobar"},
|
||||
{http.MethodPost, "/api/cotizaciones/q1/enviar"},
|
||||
{http.MethodGet, "/api/cotizaciones/q1/horas"},
|
||||
{http.MethodPost, "/api/cotizaciones/q1/nota-horas"},
|
||||
{http.MethodPost, "/api/export/pdf"},
|
||||
{http.MethodGet, "/api/export/pdf/q1"},
|
||||
{http.MethodPost, "/api/export/excel"},
|
||||
{http.MethodGet, "/api/export/excel/q1"},
|
||||
{http.MethodGet, "/api/export/catalogo"},
|
||||
{http.MethodPost, "/api/import/catalogo"},
|
||||
{http.MethodGet, "/api/propuesta-ia/q1"},
|
||||
{http.MethodPost, "/api/propuesta-ia/q1"},
|
||||
{http.MethodPatch, "/api/propuesta-ia/q1"},
|
||||
{http.MethodGet, "/api/propuesta-ia/q1/pdf"},
|
||||
{http.MethodGet, "/api/cobros/resumen"},
|
||||
{http.MethodGet, "/api/cobros/programas"},
|
||||
{http.MethodGet, "/api/cobros/pagos"},
|
||||
{http.MethodGet, "/api/agent-keys"},
|
||||
{http.MethodGet, "/api/audit-logs"},
|
||||
{http.MethodGet, "/api/webhooks"},
|
||||
{http.MethodGet, "/api/cliente/resumen"},
|
||||
{http.MethodGet, "/api/cliente/cotizaciones"},
|
||||
{http.MethodGet, "/api/cliente/pagos"},
|
||||
{http.MethodGet, "/api/comprobantes/p1"},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(tc.method, tc.path, nil)
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Errorf("%s %s without auth: expected 401, got %d (body: %s)", tc.method, tc.path, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPanelAndRoleIsolation(t *testing.T) {
|
||||
srv, router := newTestServer(t)
|
||||
|
||||
clienteCookie := makeCookie(t, srv.Auth, auth.SessionPayload{
|
||||
UserID: "u-cli-1",
|
||||
Email: "[email protected]",
|
||||
Name: "Cliente Demo",
|
||||
Role: "cliente",
|
||||
ClienteID: "cli-1",
|
||||
})
|
||||
asesorCookie := makeCookie(t, srv.Auth, auth.SessionPayload{
|
||||
UserID: "u-ase-1",
|
||||
Email: "[email protected]",
|
||||
Name: "Asesor Demo",
|
||||
Role: "asesor",
|
||||
})
|
||||
adminCookie := makeCookie(t, srv.Auth, auth.SessionPayload{
|
||||
UserID: "u-adm-1",
|
||||
Email: "[email protected]",
|
||||
Name: "Uriel Admin",
|
||||
Role: "admin",
|
||||
})
|
||||
|
||||
// Cliente cannot access staff routes
|
||||
staffPaths := []struct{ method, path string }{
|
||||
{http.MethodGet, "/api/dashboard"},
|
||||
{http.MethodGet, "/api/cotizaciones"},
|
||||
{http.MethodGet, "/api/clientes"},
|
||||
{http.MethodGet, "/api/catalogo"},
|
||||
{http.MethodGet, "/api/cobros/programas"},
|
||||
{http.MethodGet, "/api/agent-keys"},
|
||||
{http.MethodGet, "/api/configuracion"},
|
||||
}
|
||||
for _, tc := range staffPaths {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(tc.method, tc.path, nil)
|
||||
req.AddCookie(clienteCookie)
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Errorf("cliente -> %s %s: expected 403, got %d", tc.method, tc.path, rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Staff (admin/asesor) cannot access /api/cliente/*
|
||||
clientePaths := []struct{ method, path string }{
|
||||
{http.MethodGet, "/api/cliente/resumen"},
|
||||
{http.MethodGet, "/api/cliente/cotizaciones"},
|
||||
{http.MethodGet, "/api/cliente/pagos"},
|
||||
{http.MethodGet, "/api/cliente/push/config"},
|
||||
{http.MethodPost, "/api/cliente/push/suscribir"},
|
||||
{http.MethodDelete, "/api/cliente/push/suscribir"},
|
||||
}
|
||||
for _, tc := range clientePaths {
|
||||
for _, ck := range []*http.Cookie{adminCookie, asesorCookie} {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(tc.method, tc.path, nil)
|
||||
req.AddCookie(ck)
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Errorf("staff -> %s %s: expected 403, got %d", tc.method, tc.path, rec.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Asesor cannot access strictly admin-only routes (including aprobar!)
|
||||
adminOnly := []struct{ method, path string }{
|
||||
{http.MethodPost, "/api/cotizaciones/q1/aprobar"},
|
||||
{http.MethodGet, "/api/agent-keys"},
|
||||
{http.MethodPost, "/api/agent-keys"},
|
||||
{http.MethodPost, "/api/agent-keys/k1/rotate"},
|
||||
{http.MethodPost, "/api/agent-keys/k1/revoke"},
|
||||
{http.MethodGet, "/api/audit-logs"},
|
||||
{http.MethodGet, "/api/webhooks"},
|
||||
{http.MethodPost, "/api/webhooks"},
|
||||
{http.MethodDelete, "/api/webhooks/w1"},
|
||||
{http.MethodGet, "/api/webhooks/deliveries"},
|
||||
}
|
||||
for _, tc := range adminOnly {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(tc.method, tc.path, nil)
|
||||
req.AddCookie(asesorCookie)
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Errorf("asesor -> %s %s: expected 403, got %d", tc.method, tc.path, rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// /api/auth/me works for both admin and cliente without DB
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
ck *http.Cookie
|
||||
role string
|
||||
}{
|
||||
{"admin", adminCookie, "admin"},
|
||||
{"cliente", clienteCookie, "cliente"},
|
||||
} {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/auth/me", nil)
|
||||
req.AddCookie(tc.ck)
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("/api/auth/me (%s): expected 200, got %d", tc.name, rec.Code)
|
||||
}
|
||||
var out map[string]any
|
||||
_ = json.Unmarshal(rec.Body.Bytes(), &out)
|
||||
u, _ := out["user"].(map[string]any)
|
||||
if u["role"] != tc.role {
|
||||
t.Fatalf("/api/auth/me (%s): expected role %s, got %v", tc.name, tc.role, u["role"])
|
||||
}
|
||||
}
|
||||
|
||||
// /api/auth/logout clears session cookie
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/auth/logout", nil)
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("/api/auth/logout: expected 200, got %d", rec.Code)
|
||||
}
|
||||
var cleared bool
|
||||
for _, c := range rec.Result().Cookies() {
|
||||
if c.Name == auth.SessionCookieName && c.MaxAge < 0 {
|
||||
cleared = true
|
||||
}
|
||||
}
|
||||
if !cleared {
|
||||
t.Fatal("expected logout to clear cotizador-session cookie")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/auth"
|
||||
"cotizador/internal/config"
|
||||
"cotizador/internal/domain"
|
||||
"cotizador/internal/notify"
|
||||
"cotizador/internal/spa"
|
||||
"cotizador/internal/webhooks"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
Cfg *config.Config
|
||||
Pool *pgxpool.Pool
|
||||
Auth *auth.Service
|
||||
Webhooks *webhooks.Dispatcher
|
||||
Notify *notify.Service
|
||||
}
|
||||
|
||||
func NewServer(cfg *config.Config, pool *pgxpool.Pool, authSvc *auth.Service, wh *webhooks.Dispatcher, notif *notify.Service) *Server {
|
||||
return &Server{
|
||||
Cfg: cfg,
|
||||
Pool: pool,
|
||||
Auth: authSvc,
|
||||
Webhooks: wh,
|
||||
Notify: notif,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) Router() http.Handler {
|
||||
r := chi.NewRouter()
|
||||
r.Use(middleware.RequestID)
|
||||
r.Use(middleware.RealIP)
|
||||
r.Use(middleware.Recoverer)
|
||||
|
||||
// API routes
|
||||
r.Route("/api", func(r chi.Router) {
|
||||
// Public
|
||||
r.Get("/health", s.handleHealth)
|
||||
r.Get("/openapi.json", s.handleOpenAPI)
|
||||
r.Post("/auth/login", s.handleLogin)
|
||||
r.Post("/auth/logout", s.handleLogout)
|
||||
r.Get("/auth/me", s.handleMe)
|
||||
r.Get("/aprobar/{token}", s.handleAprobarTokenGet)
|
||||
r.Post("/aprobar/{token}", s.handleAprobarTokenPost)
|
||||
|
||||
// SPA helpers (staff)
|
||||
r.Get("/dashboard", s.handleDashboard)
|
||||
r.Get("/asesores", s.handleAsesores)
|
||||
|
||||
// Admin control plane
|
||||
r.Get("/agent-keys", s.handleAgentKeysList)
|
||||
r.Post("/agent-keys", s.handleAgentKeysCreate)
|
||||
r.Post("/agent-keys/{id}/rotate", s.handleAgentKeysRotate)
|
||||
r.Post("/agent-keys/{id}/revoke", s.handleAgentKeysRevoke)
|
||||
r.Get("/audit-logs", s.handleAuditLogs)
|
||||
r.Get("/webhooks", s.handleWebhooksList)
|
||||
r.Post("/webhooks", s.handleWebhooksCreate)
|
||||
r.Delete("/webhooks/{id}", s.handleWebhooksDelete)
|
||||
r.Get("/webhooks/deliveries", s.handleWebhooksDeliveries)
|
||||
|
||||
// Configuracion
|
||||
r.Get("/configuracion", s.handleConfiguracionGet)
|
||||
r.Put("/configuracion", s.handleConfiguracionPut)
|
||||
|
||||
// Catalogo, Categorias, Paquetes
|
||||
r.Get("/catalogo", s.handleCatalogoList)
|
||||
r.Post("/catalogo", s.handleCatalogoCreate)
|
||||
r.Get("/catalogo/{id}", s.handleCatalogoGet)
|
||||
r.Patch("/catalogo/{id}", s.handleCatalogoPatch)
|
||||
r.Put("/catalogo/{id}", s.handleCatalogoPatch)
|
||||
r.Delete("/catalogo/{id}", s.handleCatalogoDelete)
|
||||
|
||||
r.Get("/categorias", s.handleCategoriasList)
|
||||
r.Post("/categorias", s.handleCategoriasCreate)
|
||||
r.Put("/categorias/{id}", s.handleCategoriasUpdate)
|
||||
r.Delete("/categorias/{id}", s.handleCategoriasDelete)
|
||||
|
||||
r.Get("/paquetes", s.handlePaquetesList)
|
||||
r.Post("/paquetes", s.handlePaquetesCreate)
|
||||
r.Get("/paquetes/{id}", s.handlePaquetesGet)
|
||||
r.Put("/paquetes/{id}", s.handlePaquetesUpdate)
|
||||
r.Delete("/paquetes/{id}", s.handlePaquetesDelete)
|
||||
r.Post("/paquetes/{id}/manage", s.handlePaquetesManage)
|
||||
|
||||
// Clientes
|
||||
r.Get("/clientes", s.handleClientesList)
|
||||
r.Post("/clientes", s.handleClientesCreate)
|
||||
r.Patch("/clientes/{id}", s.handleClientesUpdate)
|
||||
r.Post("/clientes/{id}/acceso", s.handleClienteAccesoCreate)
|
||||
r.Delete("/clientes/{id}/acceso", s.handleClienteAccesoDelete)
|
||||
r.Post("/clientes/{id}/archivar", s.handleClienteArchivar)
|
||||
|
||||
// Cotizaciones
|
||||
r.Get("/cotizaciones", s.handleCotizacionesList)
|
||||
r.Post("/cotizaciones", s.handleCotizacionesCreate)
|
||||
r.Get("/cotizaciones/{id}", s.handleCotizacionesGet)
|
||||
r.Put("/cotizaciones/{id}", s.handleCotizacionesUpdate)
|
||||
r.Delete("/cotizaciones/{id}", s.handleCotizacionesDelete)
|
||||
r.Post("/cotizaciones/{id}/solicitar-aprobacion", s.handleCotizacionSolicitarAprobacion)
|
||||
r.Post("/cotizaciones/{id}/aprobar", s.handleCotizacionAprobar)
|
||||
r.Post("/cotizaciones/{id}/enviar", s.handleCotizacionEnviar)
|
||||
r.Patch("/cotizaciones/{id}/estado", s.handleCotizacionEstado)
|
||||
r.Patch("/cotizaciones/{id}/precio", s.handleCotizacionPrecio)
|
||||
|
||||
// Registro de horas
|
||||
r.Get("/cotizaciones/{id}/horas", s.handleHorasList)
|
||||
r.Post("/cotizaciones/{id}/horas", s.handleHorasCreate)
|
||||
r.Put("/cotizaciones/{id}/horas/{registroId}", s.handleHorasUpdate)
|
||||
r.Patch("/cotizaciones/{id}/horas/{registroId}", s.handleHorasEstadoPago)
|
||||
r.Delete("/cotizaciones/{id}/horas/{registroId}", s.handleHorasDelete)
|
||||
r.Post("/cotizaciones/{id}/nota-horas", s.handleNotaHorasPDF)
|
||||
|
||||
// Cobros recurrentes & comprobantes
|
||||
r.Get("/cobros/resumen", s.handleCobrosResumen)
|
||||
r.Get("/cobros/programas", s.handleProgramasList)
|
||||
r.Post("/cobros/programas", s.handleProgramasCreate)
|
||||
r.Patch("/cobros/programas/{id}", s.handleProgramasUpdate)
|
||||
r.Post("/cobros/generar", s.handleCobrosGenerar)
|
||||
r.Get("/cobros/pagos", s.handlePagosList)
|
||||
r.Post("/cobros/pagos/{id}/aprobar", s.handlePagoAprobar)
|
||||
r.Post("/cobros/pagos/{id}/rechazar", s.handlePagoRechazar)
|
||||
r.Post("/cobros/pagos/{id}/registrar", s.handlePagoRegistrar)
|
||||
r.Post("/cobros/pagos/{id}/anular", s.handlePagoAnular)
|
||||
r.Post("/cobros/pagos/{id}/reabrir", s.handlePagoReabrir)
|
||||
r.Post("/cobros/recordatorios", s.handleCobrosRecordatorios)
|
||||
r.Get("/comprobantes/{pagoId}", s.handleComprobanteGet)
|
||||
|
||||
// Panel de cliente
|
||||
r.Get("/cliente/resumen", s.handleClienteResumen)
|
||||
r.Get("/cliente/cotizaciones", s.handleClienteCotizacionesList)
|
||||
r.Get("/cliente/cotizaciones/{id}", s.handleClienteCotizacionGet)
|
||||
r.Get("/cliente/pagos", s.handleClientePagosList)
|
||||
r.Post("/cliente/pagos/{id}/comprobante", s.handleClienteComprobanteUpload)
|
||||
r.Get("/cliente/push/config", s.handleClientePushConfig)
|
||||
r.Post("/cliente/push/suscribir", s.handleClientePushSubscribe)
|
||||
r.Delete("/cliente/push/suscribir", s.handleClientePushUnsubscribe)
|
||||
|
||||
// Exports, Imports & Propuesta IA
|
||||
r.Get("/export/pdf/{id}", s.handleExportPDFByID)
|
||||
r.Post("/export/pdf", s.handleExportPDFDraft)
|
||||
r.Get("/export/excel/{id}", s.handleExportExcelByID)
|
||||
r.Post("/export/excel", s.handleExportExcelDraft)
|
||||
r.Get("/export/catalogo", s.handleExportCatalogoCSV)
|
||||
r.Get("/export/catalogo/plantilla", s.handleExportCatalogoPlantilla)
|
||||
r.Post("/import/catalogo", s.handleImportCatalogoCSV)
|
||||
|
||||
r.Get("/propuesta-ia/{id}", s.handlePropuestaIAGet)
|
||||
r.Post("/propuesta-ia/{id}", s.handlePropuestaIACreate)
|
||||
r.Patch("/propuesta-ia/{id}", s.handlePropuestaIAPatch)
|
||||
r.Get("/propuesta-ia/{id}/pdf", s.handlePropuestaIAPDF)
|
||||
|
||||
// Explicit JSON 404 for unknown /api/* routes
|
||||
r.NotFound(func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusNotFound, map[string]any{"error": "Ruta API no encontrada"})
|
||||
})
|
||||
})
|
||||
|
||||
// Embedded Vite SPA for all non-API routes (including /sw.js, /favicon.ico, /login, /cliente/*, /aprobar/*)
|
||||
r.NotFound(spa.Handler().ServeHTTP)
|
||||
return r
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, payload any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(payload)
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, status int, msg string) {
|
||||
writeJSON(w, status, map[string]any{"error": msg})
|
||||
}
|
||||
|
||||
type ValidationDetail struct {
|
||||
Campo string `json:"campo"`
|
||||
Mensaje string `json:"mensaje"`
|
||||
}
|
||||
|
||||
func writeValidationError(w http.ResponseWriter, detalles []ValidationDetail) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]any{
|
||||
"error": "Datos invalidos",
|
||||
"detalles": detalles,
|
||||
})
|
||||
}
|
||||
|
||||
func decodeJSON(r *http.Request, dst any) error {
|
||||
dec := json.NewDecoder(r.Body)
|
||||
return dec.Decode(dst)
|
||||
}
|
||||
|
||||
func parseIntQuery(r *http.Request, name string, def, minV, maxV int) int {
|
||||
raw := strings.TrimSpace(r.URL.Query().Get(name))
|
||||
if raw == "" {
|
||||
return def
|
||||
}
|
||||
v, err := strconv.Atoi(raw)
|
||||
if err != nil {
|
||||
return def
|
||||
}
|
||||
if v < minV {
|
||||
return minV
|
||||
}
|
||||
if maxV > 0 && v > maxV {
|
||||
return maxV
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
type BrandingConfig struct {
|
||||
ColorPrimario string
|
||||
ColorSecundario string
|
||||
LogoBase64 string
|
||||
LogoMime string
|
||||
}
|
||||
|
||||
func (s *Server) getAllConfigMap(ctx context.Context) map[string]string {
|
||||
m := map[string]string{}
|
||||
rows, err := s.Pool.Query(ctx, `SELECT "clave", "valor" FROM "Configuracion"`)
|
||||
if err != nil {
|
||||
return m
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var k, v string
|
||||
if rows.Scan(&k, &v) == nil {
|
||||
m[k] = v
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func (s *Server) getConfigBranding(ctx context.Context) BrandingConfig {
|
||||
m := s.getAllConfigMap(ctx)
|
||||
b := BrandingConfig{
|
||||
ColorPrimario: firstNonEmptyStr(m["color_primario"], "#0400C4"),
|
||||
ColorSecundario: firstNonEmptyStr(m["color_secundario"], "#0F172A"),
|
||||
}
|
||||
if rawLogo := strings.TrimSpace(m["logo_base64"]); rawLogo != "" {
|
||||
if strings.HasPrefix(rawLogo, "data:") {
|
||||
// data:image/png;base64,XXXX
|
||||
if idx := strings.Index(rawLogo, ","); idx > 0 {
|
||||
meta := rawLogo[5:idx]
|
||||
b.LogoMime = strings.Split(meta, ";")[0]
|
||||
b.LogoBase64 = rawLogo[idx+1:]
|
||||
}
|
||||
} else if idx := strings.Index(rawLogo, ":"); idx > 0 && strings.Contains(rawLogo[:idx], "/") {
|
||||
// mime:base64
|
||||
b.LogoMime = rawLogo[:idx]
|
||||
b.LogoBase64 = rawLogo[idx+1:]
|
||||
} else {
|
||||
b.LogoMime = "image/png"
|
||||
b.LogoBase64 = rawLogo
|
||||
}
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func (s *Server) getConfigBancaria(ctx context.Context) map[string]string {
|
||||
m := s.getAllConfigMap(ctx)
|
||||
keys := []string{
|
||||
"razon_social", "rfc", "domicilio_fiscal",
|
||||
"banco_nacional", "cuenta_nacional", "clabe_interbancaria", "clabe_nacional",
|
||||
"banco_internacional", "cuenta_internacional", "cuenta_internacional_swift", "swift", "routing_number",
|
||||
"email_facturacion", "telefono_contacto",
|
||||
}
|
||||
out := map[string]string{}
|
||||
for _, k := range keys {
|
||||
if v, ok := m[k]; ok {
|
||||
out[k] = v
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
var seqDigitsRe = regexp.MustCompile(`(\d{3})$`)
|
||||
|
||||
func (s *Server) nextCotizacionSeq(ctx context.Context) int {
|
||||
var latest string
|
||||
err := s.Pool.QueryRow(ctx, `SELECT "numero" FROM "Cotizacion" ORDER BY "createdAt" DESC LIMIT 1`).Scan(&latest)
|
||||
if err != nil {
|
||||
return 1
|
||||
}
|
||||
if m := seqDigitsRe.FindStringSubmatch(latest); len(m) == 2 {
|
||||
if n, err := strconv.Atoi(m[1]); err == nil && n > 0 {
|
||||
return n + 1
|
||||
}
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
func asesorInitials(name string) string {
|
||||
parts := strings.Fields(strings.TrimSpace(name))
|
||||
if len(parts) == 0 {
|
||||
return "UJ"
|
||||
}
|
||||
if len(parts) == 1 {
|
||||
runes := []rune(strings.ToUpper(parts[0]))
|
||||
if len(runes) >= 2 {
|
||||
return string(runes[:2])
|
||||
}
|
||||
return string(runes) + "X"
|
||||
}
|
||||
r1 := []rune(strings.ToUpper(parts[0]))[0]
|
||||
r2 := []rune(strings.ToUpper(parts[1]))[0]
|
||||
return string([]rune{r1, r2})
|
||||
}
|
||||
|
||||
func (s *Server) siguienteNumeroCotizacion(ctx context.Context, asesorName string) string {
|
||||
ini := asesorInitials(asesorName)
|
||||
seq := s.nextCotizacionSeq(ctx)
|
||||
now := time.Now()
|
||||
for tries := 0; tries < 50; tries++ {
|
||||
candidate := domain.GenerarNumeroCotizacion(ini, seq+tries, now)
|
||||
var exists bool
|
||||
_ = s.Pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM "Cotizacion" WHERE "numero" = $1)`, candidate).Scan(&exists)
|
||||
if !exists {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
return fmt.Sprintf("UJ%02d%02d%s%03d", now.Year()%100, int(now.Month()), ini, seq+50)
|
||||
}
|
||||
|
||||
func firstNonEmptyStr(vals ...string) string {
|
||||
for _, v := range vals {
|
||||
if strings.TrimSpace(v) != "" {
|
||||
return strings.TrimSpace(v)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package idempotency
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/auth"
|
||||
"cotizador/internal/db"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
const TTL = 24 * time.Hour
|
||||
|
||||
type HandlerFunc func(rawBody []byte) (statusCode int, responseBody any)
|
||||
|
||||
// Execute wraps a mutating endpoint with Idempotency-Key support (24h TTL, SHA-256 body hash).
|
||||
func Execute(ctx context.Context, pool *pgxpool.Pool, w http.ResponseWriter, r *http.Request, actor *auth.Actor, fn HandlerFunc) {
|
||||
rawBody, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]any{"error": "No se pudo leer el cuerpo de la solicitud"})
|
||||
return
|
||||
}
|
||||
r.Body = io.NopCloser(bytes.NewReader(rawBody))
|
||||
|
||||
idemHeader := strings.TrimSpace(r.Header.Get("Idempotency-Key"))
|
||||
if idemHeader == "" {
|
||||
status, body := fn(rawBody)
|
||||
writeJSON(w, status, body)
|
||||
return
|
||||
}
|
||||
|
||||
actorKey := "user:" + actor.UserID
|
||||
if actor.IsAgent() {
|
||||
actorKey = "agent:" + actor.KeyID
|
||||
}
|
||||
composedKey := fmt.Sprintf("%s:%s:%s:%s", actorKey, r.Method, r.URL.Path, idemHeader)
|
||||
sum := sha256.Sum256(rawBody)
|
||||
reqHash := hex.EncodeToString(sum[:])
|
||||
|
||||
var existingHash string
|
||||
var existingStatus int
|
||||
var existingBody json.RawMessage
|
||||
var expiraAt time.Time
|
||||
err = pool.QueryRow(ctx, `
|
||||
SELECT "requestHash", "statusCode", "responseBody", "expiraAt"
|
||||
FROM "IdempotencyKey"
|
||||
WHERE "key" = $1
|
||||
`, composedKey).Scan(&existingHash, &existingStatus, &existingBody, &expiraAt)
|
||||
|
||||
if err == nil {
|
||||
if time.Now().After(expiraAt) {
|
||||
_, _ = pool.Exec(ctx, `DELETE FROM "IdempotencyKey" WHERE "key" = $1`, composedKey)
|
||||
} else {
|
||||
if existingHash != reqHash {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{
|
||||
"error": "Idempotency-Key ya fue usada con un cuerpo de solicitud distinto",
|
||||
})
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Header().Set("X-Idempotency-Replayed", "true")
|
||||
w.WriteHeader(existingStatus)
|
||||
_, _ = w.Write(existingBody)
|
||||
return
|
||||
}
|
||||
} else if !errors.Is(err, pgx.ErrNoRows) {
|
||||
// Fall through gracefully on lookup error
|
||||
}
|
||||
|
||||
status, body := fn(rawBody)
|
||||
bodyBytes, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
bodyBytes = []byte(`{}`)
|
||||
}
|
||||
|
||||
if status < 500 {
|
||||
_, _ = pool.Exec(ctx, `
|
||||
INSERT INTO "IdempotencyKey" ("id", "key", "method", "path", "requestHash", "statusCode", "responseBody", "expiraAt")
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
ON CONFLICT ("key") DO UPDATE SET
|
||||
"requestHash" = EXCLUDED."requestHash",
|
||||
"statusCode" = EXCLUDED."statusCode",
|
||||
"responseBody" = EXCLUDED."responseBody",
|
||||
"expiraAt" = EXCLUDED."expiraAt"
|
||||
`, db.NewID(), composedKey, r.Method, r.URL.Path, reqHash, status, bodyBytes, time.Now().Add(TTL))
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_, _ = w.Write(bodyBytes)
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, payload any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(payload)
|
||||
}
|
||||
@@ -0,0 +1,694 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html"
|
||||
"log"
|
||||
"mime/quotedprintable"
|
||||
"net"
|
||||
"net/smtp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/config"
|
||||
"cotizador/internal/domain"
|
||||
"cotizador/internal/webhooks"
|
||||
|
||||
webpush "github.com/SherClockHolmes/webpush-go"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type Attachment struct {
|
||||
Filename string
|
||||
ContentType string
|
||||
Content []byte
|
||||
}
|
||||
|
||||
type MailMessage struct {
|
||||
To string
|
||||
Subject string
|
||||
Text string
|
||||
HTML string
|
||||
Attachments []Attachment
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
cfg *config.Config
|
||||
pool *pgxpool.Pool
|
||||
webhooks *webhooks.Dispatcher
|
||||
}
|
||||
|
||||
func NewService(cfg *config.Config, pool *pgxpool.Pool, wh *webhooks.Dispatcher) *Service {
|
||||
return &Service{cfg: cfg, pool: pool, webhooks: wh}
|
||||
}
|
||||
|
||||
func (s *Service) SMTPConfigured() bool {
|
||||
return s != nil && s.cfg != nil && s.cfg.SMTPHost != "" && s.cfg.SMTPFrom != ""
|
||||
}
|
||||
|
||||
func (s *Service) VAPIDConfigured() bool {
|
||||
return s != nil && s.cfg != nil && s.cfg.VAPIDPublicKey != "" && s.cfg.VAPIDPrivateKey != ""
|
||||
}
|
||||
|
||||
func (s *Service) EnviarCorreo(msg MailMessage) bool {
|
||||
if !s.SMTPConfigured() {
|
||||
log.Printf("[email] SMTP no configurado; omitiendo correo a %s (%s)", msg.To, msg.Subject)
|
||||
return false
|
||||
}
|
||||
to := strings.TrimSpace(msg.To)
|
||||
if to == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
raw := buildMIMEMessage(s.cfg.SMTPFromName, s.cfg.SMTPFrom, to, msg)
|
||||
addr := fmt.Sprintf("%s:%d", s.cfg.SMTPHost, s.cfg.SMTPPort)
|
||||
|
||||
var err error
|
||||
if s.cfg.SMTPPort == 465 {
|
||||
err = sendSMTPImplicitTLS(addr, s.cfg.SMTPHost, s.cfg.SMTPUser, s.cfg.SMTPPass, s.cfg.SMTPFrom, to, raw)
|
||||
} else {
|
||||
err = sendSMTPStartTLS(addr, s.cfg.SMTPHost, s.cfg.SMTPUser, s.cfg.SMTPPass, s.cfg.SMTPFrom, to, raw)
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("[email] error enviando correo a %s: %v", to, err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func sendSMTPImplicitTLS(addr, host, user, pass, from, to string, raw []byte) error {
|
||||
dialer := &net.Dialer{Timeout: 10 * time.Second}
|
||||
conn, err := tls.DialWithDialer(dialer, "tcp", addr, &tls.Config{ServerName: host, MinVersion: tls.VersionTLS12})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
client, err := smtp.NewClient(conn, host)
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
return err
|
||||
}
|
||||
defer client.Close()
|
||||
if user != "" {
|
||||
if err := client.Auth(smtp.PlainAuth("", user, pass, host)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := client.Mail(from); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := client.Rcpt(to); err != nil {
|
||||
return err
|
||||
}
|
||||
w, err := client.Data()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := w.Write(raw); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return client.Quit()
|
||||
}
|
||||
|
||||
func sendSMTPStartTLS(addr, host, user, pass, from, to string, raw []byte) error {
|
||||
conn, err := net.DialTimeout("tcp", addr, 10*time.Second)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
client, err := smtp.NewClient(conn, host)
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
return err
|
||||
}
|
||||
defer client.Close()
|
||||
if ok, _ := client.Extension("STARTTLS"); ok {
|
||||
if err := client.StartTLS(&tls.Config{ServerName: host, MinVersion: tls.VersionTLS12}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if user != "" {
|
||||
if err := client.Auth(smtp.PlainAuth("", user, pass, host)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := client.Mail(from); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := client.Rcpt(to); err != nil {
|
||||
return err
|
||||
}
|
||||
w, err := client.Data()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := w.Write(raw); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return client.Quit()
|
||||
}
|
||||
|
||||
func buildMIMEMessage(fromName, fromAddr, to string, msg MailMessage) []byte {
|
||||
var buf bytes.Buffer
|
||||
fromHeader := fromAddr
|
||||
if fromName != "" {
|
||||
fromHeader = fmt.Sprintf("=?UTF-8?B?%s?= <%s>", base64.StdEncoding.EncodeToString([]byte(fromName)), fromAddr)
|
||||
}
|
||||
subjHeader := fmt.Sprintf("=?UTF-8?B?%s?=", base64.StdEncoding.EncodeToString([]byte(msg.Subject)))
|
||||
|
||||
fmt.Fprintf(&buf, "From: %s\r\n", fromHeader)
|
||||
fmt.Fprintf(&buf, "To: %s\r\n", to)
|
||||
fmt.Fprintf(&buf, "Subject: %s\r\n", subjHeader)
|
||||
fmt.Fprintf(&buf, "Date: %s\r\n", time.Now().Format(time.RFC1123Z))
|
||||
fmt.Fprintf(&buf, "MIME-Version: 1.0\r\n")
|
||||
|
||||
mixedBoundary := fmt.Sprintf("ujc-mixed-%d", time.Now().UnixNano())
|
||||
altBoundary := fmt.Sprintf("ujc-alt-%d", time.Now().UnixNano())
|
||||
|
||||
if len(msg.Attachments) > 0 {
|
||||
fmt.Fprintf(&buf, "Content-Type: multipart/mixed; boundary=%q\r\n\r\n", mixedBoundary)
|
||||
fmt.Fprintf(&buf, "--%s\r\n", mixedBoundary)
|
||||
}
|
||||
|
||||
fmt.Fprintf(&buf, "Content-Type: multipart/alternative; boundary=%q\r\n\r\n", altBoundary)
|
||||
|
||||
textBody := msg.Text
|
||||
if textBody == "" {
|
||||
textBody = "Consulta este mensaje en un cliente de correo compatible con HTML."
|
||||
}
|
||||
fmt.Fprintf(&buf, "--%s\r\n", altBoundary)
|
||||
fmt.Fprintf(&buf, "Content-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n")
|
||||
writeQP(&buf, textBody)
|
||||
fmt.Fprintf(&buf, "\r\n")
|
||||
|
||||
if msg.HTML != "" {
|
||||
fmt.Fprintf(&buf, "--%s\r\n", altBoundary)
|
||||
fmt.Fprintf(&buf, "Content-Type: text/html; charset=UTF-8\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n")
|
||||
writeQP(&buf, msg.HTML)
|
||||
fmt.Fprintf(&buf, "\r\n")
|
||||
}
|
||||
fmt.Fprintf(&buf, "--%s--\r\n", altBoundary)
|
||||
|
||||
for _, att := range msg.Attachments {
|
||||
fmt.Fprintf(&buf, "\r\n--%s\r\n", mixedBoundary)
|
||||
ct := att.ContentType
|
||||
if ct == "" {
|
||||
ct = "application/octet-stream"
|
||||
}
|
||||
fmt.Fprintf(&buf, "Content-Type: %s; name=%q\r\n", ct, att.Filename)
|
||||
fmt.Fprintf(&buf, "Content-Disposition: attachment; filename=%q\r\n", att.Filename)
|
||||
fmt.Fprintf(&buf, "Content-Transfer-Encoding: base64\r\n\r\n")
|
||||
enc := base64.StdEncoding.EncodeToString(att.Content)
|
||||
for i := 0; i < len(enc); i += 76 {
|
||||
end := i + 76
|
||||
if end > len(enc) {
|
||||
end = len(enc)
|
||||
}
|
||||
buf.WriteString(enc[i:end])
|
||||
buf.WriteString("\r\n")
|
||||
}
|
||||
}
|
||||
if len(msg.Attachments) > 0 {
|
||||
fmt.Fprintf(&buf, "--%s--\r\n", mixedBoundary)
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func writeQP(buf *bytes.Buffer, s string) {
|
||||
qw := quotedprintable.NewWriter(buf)
|
||||
_, _ = qw.Write([]byte(s))
|
||||
_ = qw.Close()
|
||||
}
|
||||
|
||||
// EnviarPush sends a Web Push notification to all subscriptions of userID. Returns number delivered.
|
||||
func (s *Service) EnviarPush(ctx context.Context, userID, titulo, cuerpo, urlPath string) int {
|
||||
if !s.VAPIDConfigured() || s.pool == nil || userID == "" {
|
||||
return 0
|
||||
}
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT "id", "endpoint", "p256dh", "auth"
|
||||
FROM "SuscripcionPush"
|
||||
WHERE "userId" = $1
|
||||
`, userID)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
payload, _ := json.Marshal(map[string]string{
|
||||
"titulo": titulo,
|
||||
"cuerpo": cuerpo,
|
||||
"url": urlPath,
|
||||
})
|
||||
|
||||
sent := 0
|
||||
var expiredIDs []string
|
||||
for rows.Next() {
|
||||
var id, endpoint, p256dh, authKey string
|
||||
if err := rows.Scan(&id, &endpoint, &p256dh, &authKey); err != nil {
|
||||
continue
|
||||
}
|
||||
sub := &webpush.Subscription{
|
||||
Endpoint: endpoint,
|
||||
Keys: webpush.Keys{
|
||||
P256dh: p256dh,
|
||||
Auth: authKey,
|
||||
},
|
||||
}
|
||||
resp, err := webpush.SendNotification(payload, sub, &webpush.Options{
|
||||
Subscriber: strings.TrimPrefix(s.cfg.VAPIDSubject, "mailto:"),
|
||||
VAPIDPublicKey: s.cfg.VAPIDPublicKey,
|
||||
VAPIDPrivateKey: s.cfg.VAPIDPrivateKey,
|
||||
TTL: 86400,
|
||||
})
|
||||
if err != nil {
|
||||
log.Printf("[push] error enviando a %s: %v", id, err)
|
||||
continue
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
if resp.StatusCode == 404 || resp.StatusCode == 410 {
|
||||
expiredIDs = append(expiredIDs, id)
|
||||
} else if resp.StatusCode >= 200 && resp.StatusCode < 300 {
|
||||
sent++
|
||||
}
|
||||
}
|
||||
|
||||
for _, id := range expiredIDs {
|
||||
_, _ = s.pool.Exec(ctx, `DELETE FROM "SuscripcionPush" WHERE "id" = $1`, id)
|
||||
}
|
||||
return sent
|
||||
}
|
||||
|
||||
func (s *Service) GetAdminEmail(ctx context.Context) string {
|
||||
if s.cfg != nil && s.cfg.AdminNotifyEmail != "" {
|
||||
return s.cfg.AdminNotifyEmail
|
||||
}
|
||||
if s.pool == nil {
|
||||
return ""
|
||||
}
|
||||
var email string
|
||||
_ = s.pool.QueryRow(ctx, `SELECT "email" FROM "User" WHERE "role" = 'admin' ORDER BY "createdAt" ASC LIMIT 1`).Scan(&email)
|
||||
return email
|
||||
}
|
||||
|
||||
func (s *Service) NotificarJarethBorrador(ctx context.Context, cotID, numero, clienteNombre, clienteEmpresa, proyecto, agenteNombre, approvalURL string, totalUnico, totalMensual float64) {
|
||||
adminEmail := s.GetAdminEmail(ctx)
|
||||
if adminEmail == "" {
|
||||
log.Printf("[notify] sin correo de administrador para notificar borrador %s", numero)
|
||||
return
|
||||
}
|
||||
portalURL := fmt.Sprintf("%s/cotizaciones/%s", s.cfg.AppURL, cotID)
|
||||
empresaTxt := ""
|
||||
if clienteEmpresa != "" {
|
||||
empresaTxt = fmt.Sprintf(" (%s)", clienteEmpresa)
|
||||
}
|
||||
subj := fmt.Sprintf("Aprobacion requerida: Cotizacion %s — %s", numero, clienteNombre)
|
||||
htmlBody := fmt.Sprintf(`
|
||||
<div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto;color:#0f172a">
|
||||
<h2 style="color:#0400C4">Nueva cotizacion pendiente de aprobacion</h2>
|
||||
<p>El agente <strong>%s</strong> preparo el borrador <strong>%s</strong>.</p>
|
||||
<ul>
|
||||
<li><strong>Cliente:</strong> %s%s</li>
|
||||
<li><strong>Proyecto:</strong> %s</li>
|
||||
<li><strong>Pago unico:</strong> %s</li>
|
||||
<li><strong>Pago mensual:</strong> %s</li>
|
||||
</ul>
|
||||
<p style="margin:24px 0">
|
||||
<a href="%s" style="background:#0400C4;color:#ffffff;padding:12px 20px;border-radius:8px;text-decoration:none;font-weight:bold">Revisar y aprobar cotizacion</a>
|
||||
</p>
|
||||
<p style="font-size:12px;color:#64748b">Tambien puedes revisarla en el panel: <a href="%s">%s</a></p>
|
||||
</div>
|
||||
`, html.EscapeString(agenteNombre), html.EscapeString(numero), html.EscapeString(clienteNombre), html.EscapeString(empresaTxt), html.EscapeString(proyecto), domain.FormatCurrency(totalUnico), domain.FormatCurrency(totalMensual), approvalURL, portalURL, portalURL)
|
||||
|
||||
textBody := fmt.Sprintf("Nueva cotizacion %s creada por %s para %s%s.\nAprobar: %s\nPanel: %s", numero, agenteNombre, clienteNombre, empresaTxt, approvalURL, portalURL)
|
||||
s.EnviarCorreo(MailMessage{To: adminEmail, Subject: subj, HTML: htmlBody, Text: textBody})
|
||||
}
|
||||
|
||||
func (s *Service) NotificarJarethWhatsAppFueraVentana(ctx context.Context, numero, clienteNombre, telefono string) {
|
||||
adminEmail := s.GetAdminEmail(ctx)
|
||||
if adminEmail == "" {
|
||||
return
|
||||
}
|
||||
subj := fmt.Sprintf("WhatsApp fuera de ventana 24h — Cotizacion %s", numero)
|
||||
body := fmt.Sprintf("No se pudo enviar la cotizacion %s a %s (%s) por WhatsApp porque excedio la ventana de 24 horas y no hubo fallback de correo.", numero, clienteNombre, telefono)
|
||||
s.EnviarCorreo(MailMessage{To: adminEmail, Subject: subj, Text: body, HTML: "<p>" + html.EscapeString(body) + "</p>"})
|
||||
}
|
||||
|
||||
func (s *Service) EnviarCotizacionPorCorreo(to, clienteNombre, numero, proyecto string, pdfBytes []byte) bool {
|
||||
subj := fmt.Sprintf("Cotizacion %s — Uriel Jareth Consulting", numero)
|
||||
htmlBody := fmt.Sprintf(`
|
||||
<div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto;color:#0f172a">
|
||||
<h2 style="color:#0400C4">Cotizacion %s</h2>
|
||||
<p>Hola %s,</p>
|
||||
<p>Adjuntamos la propuesta economica correspondiente al proyecto <strong>%s</strong>.</p>
|
||||
<p>Quedamos atentos a cualquier duda o comentario.</p>
|
||||
<p style="margin-top:24px;color:#64748b;font-size:13px">Uriel Jareth Consulting</p>
|
||||
</div>
|
||||
`, html.EscapeString(numero), html.EscapeString(clienteNombre), html.EscapeString(proyecto))
|
||||
textBody := fmt.Sprintf("Hola %s,\n\nAdjuntamos la cotizacion %s para el proyecto %s.\n\nSaludos,\nUriel Jareth Consulting", clienteNombre, numero, proyecto)
|
||||
return s.EnviarCorreo(MailMessage{
|
||||
To: to,
|
||||
Subject: subj,
|
||||
HTML: htmlBody,
|
||||
Text: textBody,
|
||||
Attachments: []Attachment{
|
||||
{
|
||||
Filename: fmt.Sprintf("Cotizacion_%s.pdf", domain.SanitizeFilename(numero)),
|
||||
ContentType: "application/pdf",
|
||||
Content: pdfBytes,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) NotificarCobrosNuevos(ctx context.Context, pagoIDs []string) {
|
||||
if s.pool == nil || len(pagoIDs) == 0 {
|
||||
return
|
||||
}
|
||||
for _, pid := range pagoIDs {
|
||||
var concepto, moneda, clienteNombre string
|
||||
var email, userID *string
|
||||
var monto float64
|
||||
var fecha time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT pr."concepto", pr."moneda", p."monto", p."fecha",
|
||||
c."nombre", c."email", u."id"
|
||||
FROM "PagoRecurrente" p
|
||||
JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
JOIN "Cliente" c ON c."id" = pr."clienteId"
|
||||
LEFT JOIN "User" u ON u."clienteId" = c."id"
|
||||
WHERE p."id" = $1
|
||||
`, pid).Scan(&concepto, &moneda, &monto, &fecha, &clienteNombre, &email, &userID)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
montoStr := domain.FormatMonto(monto, moneda)
|
||||
fechaStr := domain.FormatFechaCobro(fecha)
|
||||
urlPagos := fmt.Sprintf("%s/cliente/pagos", s.cfg.AppURL)
|
||||
|
||||
if email != nil && strings.TrimSpace(*email) != "" {
|
||||
s.EnviarCorreo(MailMessage{
|
||||
To: *email,
|
||||
Subject: fmt.Sprintf("Nuevo cobro programado: %s (%s)", concepto, montoStr),
|
||||
Text: fmt.Sprintf("Hola %s, tienes un cobro programado por %s (%s) con fecha %s. Sube tu comprobante en %s", clienteNombre, montoStr, concepto, fechaStr, urlPagos),
|
||||
HTML: fmt.Sprintf(`<div style="font-family:Arial,sans-serif;max-width:600px;color:#0f172a">
|
||||
<h2 style="color:#0400C4">Nuevo cobro programado</h2>
|
||||
<p>Hola %s,</p>
|
||||
<p>Se genero el cobro de <strong>%s</strong> por <strong>%s</strong> correspondiente al <strong>%s</strong>.</p>
|
||||
<p><a href="%s" style="background:#0400C4;color:#fff;padding:10px 16px;border-radius:6px;text-decoration:none">Ver y subir comprobante</a></p>
|
||||
</div>`, html.EscapeString(clienteNombre), html.EscapeString(concepto), montoStr, fechaStr, urlPagos),
|
||||
})
|
||||
}
|
||||
if userID != nil && *userID != "" {
|
||||
s.EnviarPush(ctx, *userID, "Nuevo cobro programado", fmt.Sprintf("%s — %s (%s)", concepto, montoStr, domain.FormatFechaCorta(fecha)), "/cliente/pagos")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) NotificarVerificacion(ctx context.Context, pagoID string) {
|
||||
if s.pool == nil {
|
||||
return
|
||||
}
|
||||
var concepto, moneda, clienteNombre string
|
||||
var email, userID *string
|
||||
var monto float64
|
||||
var fecha time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT pr."concepto", pr."moneda", p."monto", p."fecha",
|
||||
c."nombre", c."email", u."id"
|
||||
FROM "PagoRecurrente" p
|
||||
JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
JOIN "Cliente" c ON c."id" = pr."clienteId"
|
||||
LEFT JOIN "User" u ON u."clienteId" = c."id"
|
||||
WHERE p."id" = $1
|
||||
`, pagoID).Scan(&concepto, &moneda, &monto, &fecha, &clienteNombre, &email, &userID)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
montoStr := domain.FormatMonto(monto, moneda)
|
||||
fechaStr := domain.FormatFechaCobro(fecha)
|
||||
if email != nil && strings.TrimSpace(*email) != "" {
|
||||
s.EnviarCorreo(MailMessage{
|
||||
To: *email,
|
||||
Subject: fmt.Sprintf("Pago verificado: %s (%s)", concepto, montoStr),
|
||||
Text: fmt.Sprintf("Hola %s, confirmamos tu pago de %s por %s (%s). Gracias.", clienteNombre, montoStr, concepto, fechaStr),
|
||||
HTML: fmt.Sprintf(`<p>Hola %s,</p><p>Confirmamos que tu pago de <strong>%s</strong> por <strong>%s</strong> (%s) ha sido verificado. Gracias.</p>`, html.EscapeString(clienteNombre), montoStr, html.EscapeString(concepto), fechaStr),
|
||||
})
|
||||
}
|
||||
if userID != nil && *userID != "" {
|
||||
s.EnviarPush(ctx, *userID, "Pago verificado", fmt.Sprintf("%s — %s confirmado", concepto, montoStr), "/cliente/pagos")
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) NotificarRechazo(ctx context.Context, pagoID, motivo string) {
|
||||
if s.pool == nil {
|
||||
return
|
||||
}
|
||||
var concepto, moneda, clienteNombre string
|
||||
var email, userID *string
|
||||
var monto float64
|
||||
var fecha time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT pr."concepto", pr."moneda", p."monto", p."fecha",
|
||||
c."nombre", c."email", u."id"
|
||||
FROM "PagoRecurrente" p
|
||||
JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
JOIN "Cliente" c ON c."id" = pr."clienteId"
|
||||
LEFT JOIN "User" u ON u."clienteId" = c."id"
|
||||
WHERE p."id" = $1
|
||||
`, pagoID).Scan(&concepto, &moneda, &monto, &fecha, &clienteNombre, &email, &userID)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
montoStr := domain.FormatMonto(monto, moneda)
|
||||
urlPagos := fmt.Sprintf("%s/cliente/pagos", s.cfg.AppURL)
|
||||
if email != nil && strings.TrimSpace(*email) != "" {
|
||||
s.EnviarCorreo(MailMessage{
|
||||
To: *email,
|
||||
Subject: fmt.Sprintf("Comprobante rechazado: %s (%s)", concepto, montoStr),
|
||||
Text: fmt.Sprintf("Hola %s, tu comprobante para %s (%s) fue rechazado. Motivo: %s. Puedes subir uno nuevo en %s", clienteNombre, concepto, montoStr, motivo, urlPagos),
|
||||
HTML: fmt.Sprintf(`<p>Hola %s,</p><p>Tu comprobante para <strong>%s</strong> (%s) fue rechazado.</p><p><strong>Motivo:</strong> %s</p><p><a href="%s">Subir nuevo comprobante</a></p>`, html.EscapeString(clienteNombre), html.EscapeString(concepto), montoStr, html.EscapeString(motivo), urlPagos),
|
||||
})
|
||||
}
|
||||
if userID != nil && *userID != "" {
|
||||
s.EnviarPush(ctx, *userID, "Comprobante rechazado", fmt.Sprintf("%s: %s", concepto, motivo), "/cliente/pagos")
|
||||
}
|
||||
}
|
||||
|
||||
type RecordatoriosResult struct {
|
||||
ClientesNotificados int `json:"clientesNotificados"`
|
||||
PagosRecordados int `json:"pagosRecordados"`
|
||||
PagosVencidosEmit int `json:"pagosVencidosEmitidos"`
|
||||
PagoIDsCubiertos []string `json:"-"`
|
||||
}
|
||||
|
||||
// EnviarRecordatoriosPendientes sends one account-statement reminder per client for overdue/due charges
|
||||
// (estado in pendiente|rechazado, fecha <= hoy) and emits pago.vencido idempotently.
|
||||
func (s *Service) EnviarRecordatoriosPendientes(ctx context.Context, clienteIDFilter string, forzar bool) (*RecordatoriosResult, error) {
|
||||
if s.pool == nil {
|
||||
return &RecordatoriosResult{}, nil
|
||||
}
|
||||
hoy := domain.HoyCalendario()
|
||||
diasEspera := s.cfg.CobrosRecordatorioDias
|
||||
if !forzar && diasEspera <= 0 {
|
||||
return &RecordatoriosResult{}, nil
|
||||
}
|
||||
|
||||
args := []any{hoy}
|
||||
whereCliente := ""
|
||||
if clienteIDFilter != "" {
|
||||
whereCliente = ` AND c."id" = $2`
|
||||
args = append(args, clienteIDFilter)
|
||||
}
|
||||
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT p."id", p."programaId", p."fecha", p."monto", p."estado", p."ultimoRecordatorioAt",
|
||||
pr."concepto", pr."moneda",
|
||||
c."id", c."nombre", COALESCE(c."empresa", ''), COALESCE(c."email", ''), COALESCE(c."telefono", ''),
|
||||
COALESCE(u."id", '')
|
||||
FROM "PagoRecurrente" p
|
||||
JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
JOIN "Cliente" c ON c."id" = pr."clienteId"
|
||||
LEFT JOIN "User" u ON u."clienteId" = c."id"
|
||||
WHERE p."estado" IN ('pendiente', 'rechazado')
|
||||
AND p."fecha" <= $1`+whereCliente+`
|
||||
ORDER BY c."nombre" ASC, p."fecha" ASC
|
||||
`, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
type pagoRow struct {
|
||||
ID string
|
||||
ProgramaID string
|
||||
Fecha time.Time
|
||||
Monto float64
|
||||
Estado string
|
||||
UltimoRecordatorioAt *time.Time
|
||||
Concepto string
|
||||
Moneda string
|
||||
ClienteID string
|
||||
ClienteNombre string
|
||||
ClienteEmpresa string
|
||||
ClienteEmail string
|
||||
ClienteTelefono string
|
||||
UserID string
|
||||
}
|
||||
|
||||
byClient := map[string][]pagoRow{}
|
||||
var clientOrder []string
|
||||
var vencidosItems []webhooks.PagoVencidoItem
|
||||
|
||||
for rows.Next() {
|
||||
var r pagoRow
|
||||
if err := rows.Scan(
|
||||
&r.ID, &r.ProgramaID, &r.Fecha, &r.Monto, &r.Estado, &r.UltimoRecordatorioAt,
|
||||
&r.Concepto, &r.Moneda,
|
||||
&r.ClienteID, &r.ClienteNombre, &r.ClienteEmpresa, &r.ClienteEmail, &r.ClienteTelefono,
|
||||
&r.UserID,
|
||||
); err != nil {
|
||||
continue
|
||||
}
|
||||
if _, ok := byClient[r.ClienteID]; !ok {
|
||||
clientOrder = append(clientOrder, r.ClienteID)
|
||||
}
|
||||
byClient[r.ClienteID] = append(byClient[r.ClienteID], r)
|
||||
|
||||
atraso := domain.DiasDeAtraso(r.Fecha, hoy)
|
||||
if atraso > 0 {
|
||||
vencidosItems = append(vencidosItems, webhooks.PagoVencidoItem{
|
||||
PagoID: r.ID,
|
||||
ProgramaID: r.ProgramaID,
|
||||
ClienteID: r.ClienteID,
|
||||
ClienteNombre: r.ClienteNombre,
|
||||
ClienteEmpresa: r.ClienteEmpresa,
|
||||
ClienteEmail: r.ClienteEmail,
|
||||
ClienteTelefono: r.ClienteTelefono,
|
||||
Concepto: r.Concepto,
|
||||
Monto: r.Monto,
|
||||
Moneda: r.Moneda,
|
||||
Fecha: r.Fecha.UTC().Format("2006-01-02"),
|
||||
DiasAtraso: atraso,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Best-effort idempotent webhook emission for overdue payments
|
||||
res := &RecordatoriosResult{}
|
||||
if s.webhooks != nil && len(vencidosItems) > 0 {
|
||||
res.PagosVencidosEmit = s.webhooks.EmitirPagosVencidos(ctx, vencidosItems)
|
||||
}
|
||||
|
||||
// Load bank config for statement email
|
||||
bancaria := map[string]string{}
|
||||
cfgRows, err := s.pool.Query(ctx, `SELECT "clave", "valor" FROM "Configuracion"`)
|
||||
if err == nil {
|
||||
defer cfgRows.Close()
|
||||
for cfgRows.Next() {
|
||||
var k, v string
|
||||
if cfgRows.Scan(&k, &v) == nil {
|
||||
bancaria[k] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cutoff := time.Now().Add(-time.Duration(diasEspera) * 24 * time.Hour)
|
||||
for _, cid := range clientOrder {
|
||||
pagos := byClient[cid]
|
||||
if len(pagos) == 0 {
|
||||
continue
|
||||
}
|
||||
if !forzar {
|
||||
needsSend := false
|
||||
for _, p := range pagos {
|
||||
if p.UltimoRecordatorioAt == nil || p.UltimoRecordatorioAt.Before(cutoff) {
|
||||
needsSend = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !needsSend {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
first := pagos[0]
|
||||
totales := map[string]float64{}
|
||||
var rowsHTML strings.Builder
|
||||
var rowsText strings.Builder
|
||||
for _, p := range pagos {
|
||||
totales[p.Moneda] = domain.Round2(totales[p.Moneda] + p.Monto)
|
||||
fStr := domain.FormatFechaCorta(p.Fecha)
|
||||
mStr := domain.FormatMonto(p.Monto, p.Moneda)
|
||||
fmt.Fprintf(&rowsHTML, `<tr><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0">%s</td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0">%s</td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;text-align:right">%s</td></tr>`,
|
||||
html.EscapeString(fStr), html.EscapeString(p.Concepto), mStr)
|
||||
fmt.Fprintf(&rowsText, "- %s | %s | %s\n", fStr, p.Concepto, mStr)
|
||||
}
|
||||
|
||||
totalStr := domain.FormatTotales(totales)
|
||||
urlPagos := fmt.Sprintf("%s/cliente/pagos", s.cfg.AppURL)
|
||||
|
||||
bancoHTML := ""
|
||||
if bancaria["banco_nacional"] != "" || bancaria["clabe_nacional"] != "" {
|
||||
bancoHTML = fmt.Sprintf(`<div style="margin-top:16px;padding:12px;background:#f8fafc;border-radius:8px;font-size:13px">
|
||||
<strong>Datos bancarios</strong><br/>
|
||||
Banco: %s<br/>CLABE: %s<br/>Cuenta: %s<br/>Beneficiario: %s
|
||||
</div>`, html.EscapeString(bancaria["banco_nacional"]), html.EscapeString(bancaria["clabe_nacional"]), html.EscapeString(bancaria["cuenta_nacional"]), html.EscapeString(bancaria["razon_social"]))
|
||||
}
|
||||
|
||||
delivered := false
|
||||
if first.ClienteEmail != "" {
|
||||
ok := s.EnviarCorreo(MailMessage{
|
||||
To: first.ClienteEmail,
|
||||
Subject: fmt.Sprintf("Recordatorio de pagos pendientes (%s) — Uriel Jareth Consulting", totalStr),
|
||||
Text: fmt.Sprintf("Hola %s,\n\nTienes pagos pendientes por %s:\n%s\nPuedes subir tus comprobantes en: %s", first.ClienteNombre, totalStr, rowsText.String(), urlPagos),
|
||||
HTML: fmt.Sprintf(`<div style="font-family:Arial,sans-serif;max-width:600px;color:#0f172a">
|
||||
<h2 style="color:#0400C4">Estado de pagos pendientes</h2>
|
||||
<p>Hola %s,</p>
|
||||
<p>Tienes los siguientes pagos pendientes por un total de <strong>%s</strong>:</p>
|
||||
<table style="width:100%%;border-collapse:collapse;font-size:14px">
|
||||
<thead><tr style="background:#f1f5f9"><th style="padding:6px 8px;text-align:left">Fecha</th><th style="padding:6px 8px;text-align:left">Concepto</th><th style="padding:6px 8px;text-align:right">Monto</th></tr></thead>
|
||||
<tbody>%s</tbody>
|
||||
</table>
|
||||
%s
|
||||
<p style="margin-top:20px"><a href="%s" style="background:#0400C4;color:#fff;padding:10px 16px;border-radius:6px;text-decoration:none">Subir comprobante</a></p>
|
||||
</div>`, html.EscapeString(first.ClienteNombre), totalStr, rowsHTML.String(), bancoHTML, urlPagos),
|
||||
})
|
||||
if ok {
|
||||
delivered = true
|
||||
}
|
||||
}
|
||||
|
||||
if first.UserID != "" {
|
||||
if n := s.EnviarPush(ctx, first.UserID, "Pagos pendientes", fmt.Sprintf("Saldo pendiente: %s (%d cobro(s))", totalStr, len(pagos)), "/cliente/pagos"); n > 0 {
|
||||
delivered = true
|
||||
}
|
||||
}
|
||||
|
||||
if delivered {
|
||||
res.ClientesNotificados++
|
||||
for _, p := range pagos {
|
||||
_, _ = s.pool.Exec(ctx, `
|
||||
UPDATE "PagoRecurrente"
|
||||
SET "ultimoRecordatorioAt" = NOW(),
|
||||
"recordatoriosEnviados" = "recordatoriosEnviados" + 1,
|
||||
"updatedAt" = NOW()
|
||||
WHERE "id" = $1
|
||||
`, p.ID)
|
||||
res.PagosRecordados++
|
||||
res.PagoIDsCubiertos = append(res.PagoIDsCubiertos, p.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
@@ -0,0 +1,582 @@
|
||||
package pdf
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/domain"
|
||||
)
|
||||
|
||||
type ServicioPDF struct {
|
||||
Nombre string
|
||||
Fase int
|
||||
TipoPago string
|
||||
Precio float64
|
||||
TiempoEntrega string
|
||||
Entregables []string
|
||||
EsPersonalizado bool
|
||||
Horas *float64
|
||||
TarifaHora *float64
|
||||
ModeloCobro string
|
||||
MontoMinimo *float64
|
||||
HorasIncluidas *float64
|
||||
Opcion *string
|
||||
}
|
||||
|
||||
type BonoPDF struct {
|
||||
Numero int
|
||||
Descripcion string
|
||||
}
|
||||
|
||||
// CotizacionPDFData holds client-facing quotation data for PDF generation.
|
||||
// ObservacionesInternas is intentionally NOT declared here so internal notes
|
||||
// can never leak into a client document.
|
||||
type CotizacionPDFData struct {
|
||||
Numero string
|
||||
ClienteNombre string
|
||||
ClienteEmpresa string
|
||||
AsesorNombre string
|
||||
Fecha time.Time
|
||||
Vigencia time.Time
|
||||
Moneda string
|
||||
TipoCambio string
|
||||
Proyecto string
|
||||
EsquemaPago string
|
||||
Servicios []ServicioPDF
|
||||
EsDoble bool
|
||||
OpcionesMetadata map[string]domain.MetaOpcion
|
||||
PlanBucefaloNivel *string
|
||||
PlanBucefaloPrecio float64
|
||||
IncluirBonos bool
|
||||
Bonos []BonoPDF
|
||||
IncluirIVA bool
|
||||
Observaciones *string
|
||||
ConfigBancaria map[string]string
|
||||
ColorPrimario string
|
||||
ColorSecundario string
|
||||
LogoBase64 string
|
||||
LogoMime string
|
||||
}
|
||||
|
||||
func servicioPDFToCalc(s ServicioPDF) domain.ServicioCalc {
|
||||
return domain.ServicioCalc{
|
||||
Nombre: s.Nombre,
|
||||
ModeloCobro: s.ModeloCobro,
|
||||
EsPersonalizado: s.EsPersonalizado,
|
||||
Horas: s.Horas,
|
||||
TarifaHora: s.TarifaHora,
|
||||
MontoMinimo: s.MontoMinimo,
|
||||
HorasIncluidas: s.HorasIncluidas,
|
||||
Opcion: s.Opcion,
|
||||
TipoPago: s.TipoPago,
|
||||
Precio: s.Precio,
|
||||
Seleccionado: true,
|
||||
}
|
||||
}
|
||||
|
||||
func serviciosPDFToCalc(list []ServicioPDF) []domain.ServicioCalc {
|
||||
out := make([]domain.ServicioCalc, len(list))
|
||||
for i, s := range list {
|
||||
out[i] = servicioPDFToCalc(s)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func GenerateCotizacionPDF(data CotizacionPDFData) ([]byte, error) {
|
||||
primary := safeHex(data.ColorPrimario, defaultPrimary)
|
||||
dark := safeHex(data.ColorSecundario, defaultDark)
|
||||
|
||||
c := newCanvas(45, 55, 50, 50)
|
||||
logo := registerLogo(c.doc, "cot_logo", data.LogoBase64, data.LogoMime)
|
||||
|
||||
// Footer on every page.
|
||||
c.doc.SetFooterFunc(func() {
|
||||
c.hLine(c.L, c.L+c.W, c.ph-42, colorBorder, 0.5)
|
||||
c.drawSingleLine("Uriel Jareth Consulting", c.L, c.ph-35, c.W, "", 6.5, colorMuted, "C")
|
||||
c.drawSingleLine("urieljareth.com | [email protected] | (445) 182 9943", c.L, c.ph-26, c.W, "", 6.5, colorMuted, "C")
|
||||
})
|
||||
|
||||
fmtMoney := func(n float64) string {
|
||||
return formatMoney(n, data.Moneda)
|
||||
}
|
||||
|
||||
sectionTitle := func(title string, y float64) float64 {
|
||||
y = c.need(20, y)
|
||||
c.rectFill(c.L, y+1, 3, 9, primary)
|
||||
c.drawSingleLine(title, c.L+10, y, c.W-10, "B", 9, dark, "L")
|
||||
return y + 15
|
||||
}
|
||||
|
||||
// ── PAGE 1: COVER ──────────────────────────────
|
||||
c.doc.AddPage()
|
||||
c.rectFill(0, 0, c.pw, c.ph, colorWhite)
|
||||
|
||||
if logo.ok {
|
||||
logo.drawByHeight(c.doc, c.L, 55, 65)
|
||||
} else {
|
||||
c.drawSingleLine("UJ", c.L, 55, 48, "B", 28, primary, "L")
|
||||
c.drawSingleLine("Uriel Jareth Consulting", c.L+48, 70, c.W-48, "", 9, colorMuted, "L")
|
||||
}
|
||||
|
||||
barY := 130.0
|
||||
if logo.ok {
|
||||
barY = 145.0
|
||||
}
|
||||
c.rectFill(c.L, barY, c.W, 4, primary)
|
||||
|
||||
c.drawSingleLine("Cotización", c.L, barY+24, c.W, "B", 36, dark, "L")
|
||||
c.drawSingleLine(data.Numero, c.L, barY+68, c.W, "", 18, primary, "L")
|
||||
|
||||
iy := barY + 110
|
||||
cL := c.L
|
||||
cR := c.L + c.W*0.52
|
||||
colW := c.W * 0.46
|
||||
|
||||
type kv struct{ k, v string }
|
||||
infoL := []kv{{"Cliente", data.ClienteNombre}}
|
||||
if strings.TrimSpace(data.ClienteEmpresa) != "" {
|
||||
infoL = append(infoL, kv{"Empresa", data.ClienteEmpresa})
|
||||
}
|
||||
infoL = append(infoL,
|
||||
kv{"Proyecto", data.Proyecto},
|
||||
kv{"Asesor", data.AsesorNombre},
|
||||
)
|
||||
infoR := []kv{
|
||||
{"Fecha", domain.FormatDateLongMX(data.Fecha)},
|
||||
{"Vigencia", domain.FormatDateLongMX(data.Vigencia)},
|
||||
{"Moneda", data.Moneda},
|
||||
{"Esquema", data.EsquemaPago},
|
||||
}
|
||||
|
||||
maxRows := len(infoL)
|
||||
if len(infoR) > maxRows {
|
||||
maxRows = len(infoR)
|
||||
}
|
||||
for i := 0; i < maxRows; i++ {
|
||||
hL, hR := 0.0, 0.0
|
||||
if i < len(infoL) {
|
||||
c.drawSingleLine(infoL[i].k, cL, iy, colW, "", 9, colorMuted, "L")
|
||||
hL = c.drawText(infoL[i].v, cL, iy+12, colW, "", 11, dark, "L")
|
||||
}
|
||||
if i < len(infoR) {
|
||||
c.drawSingleLine(infoR[i].k, cR, iy, colW, "", 9, colorMuted, "L")
|
||||
hR = c.drawText(infoR[i].v, cR, iy+12, colW, "", 11, dark, "L")
|
||||
}
|
||||
step := hL
|
||||
if hR > step {
|
||||
step = hR
|
||||
}
|
||||
if step < 18 {
|
||||
step = 18
|
||||
}
|
||||
iy += 14 + step
|
||||
}
|
||||
|
||||
// ── PAGE 2+: HOJA RESUMEN ──────────────────────
|
||||
c.doc.AddPage()
|
||||
y := c.mTop
|
||||
|
||||
if logo.ok {
|
||||
logo.drawRightAlignedByHeight(c.doc, c.L+c.W, c.mTop-5, 22)
|
||||
}
|
||||
|
||||
c.rectFill(c.L, y, 4, 16, primary)
|
||||
c.drawSingleLine("Hoja Resumen", c.L+12, y, c.W-90, "B", 15, dark, "L")
|
||||
y += 26
|
||||
|
||||
enAtencion := data.ClienteEmpresa
|
||||
if strings.TrimSpace(enAtencion) == "" {
|
||||
enAtencion = data.ClienteNombre
|
||||
}
|
||||
c.drawSingleLine("En atención a: "+enAtencion, c.L, y, c.W*0.44, "", 8, colorMuted, "L")
|
||||
c.drawSingleLine("No. Cotización: "+data.Numero, c.L+c.W*0.45, y, c.W*0.55, "", 8, colorMuted, "L")
|
||||
y += 11
|
||||
c.drawSingleLine("Asesor: "+data.AsesorNombre, c.L, y, c.W*0.44, "", 8, colorMuted, "L")
|
||||
c.drawSingleLine(fmt.Sprintf("Fecha: %s | Moneda: %s", domain.FormatDateLongMX(data.Fecha), data.Moneda), c.L+c.W*0.45, y, c.W*0.55, "", 8, colorMuted, "L")
|
||||
y += 16
|
||||
|
||||
colNombre := c.L
|
||||
colTipo := c.L + c.W - 200
|
||||
colTiempo := c.L + c.W - 120
|
||||
colPrecio := c.L + c.W - 60
|
||||
nombreW := colTipo - colNombre - 16
|
||||
|
||||
drawTableHeader := func() {
|
||||
y = c.need(20, y)
|
||||
c.rowBg(y, 16, colorLightBG)
|
||||
c.drawSingleLine("Servicio", colNombre+6, y+4, nombreW, "B", 7, dark, "L")
|
||||
c.drawSingleLine("Tipo", colTipo+4, y+4, 72, "B", 7, dark, "L")
|
||||
c.drawSingleLine("Entrega", colTiempo+4, y+4, 56, "B", 7, dark, "L")
|
||||
c.drawSingleLine("Precio", colPrecio, y+4, 60, "B", 7, dark, "R")
|
||||
y += 18
|
||||
}
|
||||
|
||||
var unicos, mensuales []ServicioPDF
|
||||
for _, s := range data.Servicios {
|
||||
if s.TipoPago == "mensual" {
|
||||
mensuales = append(mensuales, s)
|
||||
} else {
|
||||
unicos = append(unicos, s)
|
||||
}
|
||||
}
|
||||
|
||||
drawSection := func(servicios []ServicioPDF, tipoLabel, tituloTotal string) {
|
||||
if len(servicios) == 0 {
|
||||
return
|
||||
}
|
||||
currentFase := -1
|
||||
for _, serv := range servicios {
|
||||
if serv.Fase != currentFase {
|
||||
currentFase = serv.Fase
|
||||
y = c.need(20, y)
|
||||
c.rectFill(c.L, y, c.W, 14, colorLightBG)
|
||||
faseLbl := domain.FasesShort[serv.Fase]
|
||||
if faseLbl == "" {
|
||||
faseLbl = fmt.Sprintf("FASE %d", serv.Fase)
|
||||
}
|
||||
c.drawSingleLine(faseLbl, c.L+6, y+3, c.W-12, "B", 7, primary, "L")
|
||||
y += 16
|
||||
}
|
||||
|
||||
detalle := domain.DetalleModelo(servicioPDFToCalc(serv))
|
||||
hNombre := c.textHeight(serv.Nombre, nombreW, "", 8)
|
||||
if hNombre < 11 {
|
||||
hNombre = 11
|
||||
}
|
||||
hTiempo := c.textHeight(serv.TiempoEntrega, 56, "", 7)
|
||||
rowTopH := hNombre
|
||||
if hTiempo > rowTopH {
|
||||
rowTopH = hTiempo
|
||||
}
|
||||
hDetalle := 0.0
|
||||
if detalle != "" {
|
||||
hDetalle = c.textHeight(detalle, nombreW-4, "I", 6.5) + 2
|
||||
}
|
||||
colW := c.W * 0.44
|
||||
half := (len(serv.Entregables) + 1) / 2
|
||||
entH := 0.0
|
||||
for i := 0; i < half; i++ {
|
||||
h1 := c.textHeight("• "+serv.Entregables[i], colW, "", 6.5)
|
||||
h2 := 0.0
|
||||
if i+half < len(serv.Entregables) {
|
||||
h2 = c.textHeight("• "+serv.Entregables[i+half], colW, "", 6.5)
|
||||
}
|
||||
if h2 > h1 {
|
||||
h1 = h2
|
||||
}
|
||||
entH += h1 + 1.5
|
||||
}
|
||||
|
||||
totalServH := rowTopH + 2 + hDetalle + entH + 6
|
||||
y = c.need(totalServH, y)
|
||||
|
||||
c.drawText(serv.Nombre, colNombre+6, y, nombreW, "", 8, dark, "L")
|
||||
c.drawSingleLine(tipoLabel, colTipo+4, y, 72, "", 7, colorMuted, "L")
|
||||
c.drawText(serv.TiempoEntrega, colTiempo+4, y, 56, "", 7, colorMuted, "L")
|
||||
c.drawSingleLine(fmtMoney(serv.Precio), colPrecio, y, 60, "B", 8, dark, "R")
|
||||
y += rowTopH + 2
|
||||
|
||||
if detalle != "" {
|
||||
dh := c.drawText(detalle, colNombre+10, y, nombreW-4, "I", 6.5, colorMuted, "L")
|
||||
y += dh + 2
|
||||
}
|
||||
|
||||
if len(serv.Entregables) > 0 {
|
||||
col1X := colNombre + 10
|
||||
col2X := colNombre + c.W*0.48
|
||||
for i := 0; i < half; i++ {
|
||||
h1 := c.drawText("• "+serv.Entregables[i], col1X, y, colW, "", 6.5, colorMuted, "L")
|
||||
h2 := 0.0
|
||||
if i+half < len(serv.Entregables) {
|
||||
h2 = c.drawText("• "+serv.Entregables[i+half], col2X, y, colW, "", 6.5, colorMuted, "L")
|
||||
}
|
||||
if h2 > h1 {
|
||||
h1 = h2
|
||||
}
|
||||
y += h1 + 1.5
|
||||
}
|
||||
}
|
||||
|
||||
c.hLine(colNombre+6, c.L+c.W, y, colorSubtleSep, 0.2)
|
||||
y += 4
|
||||
}
|
||||
|
||||
y += 3
|
||||
total := 0.0
|
||||
for _, s := range servicios {
|
||||
total += s.Precio
|
||||
}
|
||||
y = c.need(34, y)
|
||||
c.rowBg(y, 18, "#f8fafc")
|
||||
c.drawSingleLine(tituloTotal, colNombre+6, y+4, c.W-80, "B", 8.5, primary, "L")
|
||||
c.drawSingleLine(fmtMoney(total), colPrecio-20, y+4, 80, "B", 8.5, primary, "R")
|
||||
y += 22
|
||||
c.drawSingleLine("(Precios en Moneda Nacional, no incluyen IVA)", colNombre+6, y, c.W-12, "", 6.5, colorMuted, "L")
|
||||
y += 12
|
||||
}
|
||||
|
||||
drawOpcionHeader := func(op string) {
|
||||
meta := data.OpcionesMetadata[op]
|
||||
y = c.need(30, y)
|
||||
y += 4
|
||||
c.rectFill(c.L, y, c.W, 18, primary)
|
||||
title := "OPCIÓN " + op
|
||||
if strings.TrimSpace(meta.Titulo) != "" {
|
||||
title += ": " + meta.Titulo
|
||||
}
|
||||
c.drawSingleLine(title, c.L+8, y+3, c.W-16, "B", 10, colorWhite, "L")
|
||||
y += 22
|
||||
if strings.TrimSpace(meta.Descripcion) != "" {
|
||||
h := c.textHeight(meta.Descripcion, c.W-12, "", 7.5)
|
||||
y = c.need(h+4, y)
|
||||
c.drawText(meta.Descripcion, c.L+6, y, c.W-12, "", 7.5, dark, "L")
|
||||
y += h + 4
|
||||
}
|
||||
if strings.TrimSpace(meta.NoIncluye) != "" {
|
||||
lbl := "No incluye: " + meta.NoIncluye
|
||||
h := c.textHeight(lbl, c.W-12, "I", 7)
|
||||
y = c.need(h+4, y)
|
||||
c.drawText(lbl, c.L+6, y, c.W-12, "I", 7, colorMuted, "L")
|
||||
y += h + 6
|
||||
}
|
||||
}
|
||||
|
||||
drawComparativa := func() {
|
||||
calcs := serviciosPDFToCalc(data.Servicios)
|
||||
t1 := domain.CalcularTotalesOpcion(calcs, "1")
|
||||
t2 := domain.CalcularTotalesOpcion(calcs, "2")
|
||||
|
||||
y = c.need(90, y)
|
||||
y += 6
|
||||
c.rectFill(c.L, y+1, 3, 10, primary)
|
||||
c.drawSingleLine("Comparativa de opciones", c.L+10, y, c.W-10, "B", 10, dark, "L")
|
||||
y += 18
|
||||
|
||||
cLabel := c.L
|
||||
cOp1 := c.L + c.W*0.45
|
||||
cOp2 := c.L + c.W*0.72
|
||||
wOp1 := c.W*0.27 - 4
|
||||
wOp2 := c.W*0.28 - 4
|
||||
|
||||
t1Tit := data.OpcionesMetadata["1"].Titulo
|
||||
t2Tit := data.OpcionesMetadata["2"].Titulo
|
||||
op1Lbl := "Opción 1"
|
||||
if t1Tit != "" {
|
||||
op1Lbl += " - " + t1Tit
|
||||
}
|
||||
op2Lbl := "Opción 2"
|
||||
if t2Tit != "" {
|
||||
op2Lbl += " - " + t2Tit
|
||||
}
|
||||
|
||||
c.rowBg(y, 16, colorLightBG)
|
||||
c.drawSingleLine("Concepto", cLabel+6, y+4, c.W*0.43, "B", 7.5, dark, "L")
|
||||
c.drawSingleLine(op1Lbl, cOp1, y+4, wOp1, "B", 7.5, dark, "L")
|
||||
c.drawSingleLine(op2Lbl, cOp2, y+4, wOp2, "B", 7.5, dark, "L")
|
||||
y += 18
|
||||
|
||||
ivaLbl := ""
|
||||
if data.IncluirIVA {
|
||||
ivaLbl = " (c/IVA)"
|
||||
}
|
||||
type compRow struct{ lab, v1, v2 string }
|
||||
filas := []compRow{
|
||||
{"Total único" + ivaLbl, fmtMoney(domain.ConIVA(t1.TotalUnico, data.IncluirIVA)), fmtMoney(domain.ConIVA(t2.TotalUnico, data.IncluirIVA))},
|
||||
{"Total mensual" + ivaLbl, fmtMoney(domain.ConIVA(t1.TotalMensual, data.IncluirIVA)), fmtMoney(domain.ConIVA(t2.TotalMensual, data.IncluirIVA))},
|
||||
{"Horas estimadas", fmt.Sprintf("%g h", t1.Horas), fmt.Sprintf("%g h", t2.Horas)},
|
||||
}
|
||||
for _, f := range filas {
|
||||
y = c.need(14, y)
|
||||
c.drawSingleLine(f.lab, cLabel+6, y, c.W*0.43, "", 8, dark, "L")
|
||||
c.drawSingleLine(f.v1, cOp1, y, wOp1, "B", 8, dark, "L")
|
||||
c.drawSingleLine(f.v2, cOp2, y, wOp2, "B", 8, dark, "L")
|
||||
c.hLine(cLabel+6, c.L+c.W, y+12, colorSubtleSep, 0.2)
|
||||
y += 14
|
||||
}
|
||||
y += 8
|
||||
}
|
||||
|
||||
filterByOp := func(list []ServicioPDF, op string) []ServicioPDF {
|
||||
var out []ServicioPDF
|
||||
for _, s := range list {
|
||||
if s.Opcion != nil && (*s.Opcion == op || *s.Opcion == "ambas") {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
if data.EsDoble {
|
||||
for _, op := range []string{"1", "2"} {
|
||||
drawOpcionHeader(op)
|
||||
drawTableHeader()
|
||||
u := filterByOp(unicos, op)
|
||||
me := filterByOp(mensuales, op)
|
||||
if len(u) > 0 {
|
||||
drawSection(u, "Único", fmt.Sprintf("Total Pago Único - Opción %s", op))
|
||||
}
|
||||
if len(me) > 0 {
|
||||
drawSection(me, "Mensual", fmt.Sprintf("Total Pago Mensual - Opción %s", op))
|
||||
}
|
||||
}
|
||||
drawComparativa()
|
||||
} else {
|
||||
drawTableHeader()
|
||||
if len(unicos) > 0 {
|
||||
drawSection(unicos, "Único", "Total Pago Único")
|
||||
}
|
||||
if len(mensuales) > 0 {
|
||||
drawSection(mensuales, "Mensual", "Total Pago Mensual")
|
||||
}
|
||||
}
|
||||
|
||||
if data.PlanBucefaloNivel != nil && strings.TrimSpace(*data.PlanBucefaloNivel) != "" {
|
||||
y = c.need(20, y)
|
||||
nivel := strings.TrimSpace(*data.PlanBucefaloNivel)
|
||||
precio := data.PlanBucefaloPrecio
|
||||
if precio <= 0 {
|
||||
precio = domain.BucefaloPrecio(strings.ToLower(nivel))
|
||||
}
|
||||
c.rowBg(y, 16, colorLightBG)
|
||||
c.drawSingleLine("Plan Bucéfalo CRM - "+capitalize(nivel), colNombre+6, y+3, c.W-80, "B", 7.5, dark, "L")
|
||||
c.drawSingleLine(fmtMoney(precio), colPrecio-20, y+3, 80, "B", 7.5, dark, "R")
|
||||
y += 20
|
||||
}
|
||||
|
||||
if data.IncluirBonos {
|
||||
y = c.need(90, y)
|
||||
y += 4
|
||||
c.rectFill(c.L, y+1, 3, 10, primary)
|
||||
c.drawSingleLine("Bonos (Pago en una exhibición)", c.L+10, y, c.W-10, "B", 9, dark, "L")
|
||||
y += 16
|
||||
|
||||
respaldo := []string{
|
||||
"Bono 1: 30 min mensuales en servicios Centinela (Sitio Web)",
|
||||
"Bono 2: Workshop Estratégico de Buyer Persona",
|
||||
"Bono 3: Workshop de Propuestas de Valor y Oferta Irresistible",
|
||||
"Bono 4: 1 año de Membresía Premium",
|
||||
"Bono 5: Un mes gratis de Bucéfalo CRM, Marketing y Ventas",
|
||||
"Bono 6: Script de Ventas con más de 100 complementos",
|
||||
}
|
||||
var bonos []string
|
||||
if len(data.Bonos) > 0 {
|
||||
for _, b := range data.Bonos {
|
||||
bonos = append(bonos, fmt.Sprintf("Bono %d: %s", b.Numero, b.Descripcion))
|
||||
}
|
||||
} else {
|
||||
bonos = respaldo
|
||||
}
|
||||
for _, b := range bonos {
|
||||
txt := "• " + b
|
||||
h := c.textHeight(txt, c.W-16, "", 7.5)
|
||||
y = c.need(h+3, y)
|
||||
c.drawText(txt, c.L+8, y, c.W-16, "", 7.5, dark, "L")
|
||||
y += h + 3
|
||||
}
|
||||
}
|
||||
|
||||
// ── OBSERVACIONES (solo cliente) ───────────────
|
||||
if data.Observaciones != nil && strings.TrimSpace(*data.Observaciones) != "" {
|
||||
y += 6
|
||||
y = sectionTitle("Observaciones", y)
|
||||
raw := strings.ReplaceAll(*data.Observaciones, "\r\n", "\n")
|
||||
for _, p := range strings.Split(raw, "\n") {
|
||||
p = strings.TrimSpace(p)
|
||||
if p == "" {
|
||||
continue
|
||||
}
|
||||
lines := c.splitLines(p, c.W-4, "", 7.5)
|
||||
lh := lineHeight(7.5)
|
||||
for _, ln := range lines {
|
||||
y = c.need(lh+2, y)
|
||||
c.drawSingleLine(ln, c.L+2, y, c.W-4, "", 7.5, dark, "L")
|
||||
y += lh
|
||||
}
|
||||
y += 4
|
||||
}
|
||||
y += 4
|
||||
}
|
||||
|
||||
// ── T&C PAGE ───────────────────────────────────
|
||||
c.doc.AddPage()
|
||||
y = c.mTop
|
||||
|
||||
if logo.ok {
|
||||
logo.drawRightAlignedByHeight(c.doc, c.L+c.W, c.mTop-5, 22)
|
||||
}
|
||||
|
||||
c.rectFill(c.L, y, 4, 16, primary)
|
||||
c.drawSingleLine("Términos y Condiciones", c.L+12, y, c.W-90, "B", 15, dark, "L")
|
||||
y += 28
|
||||
|
||||
drawBullets := func(title string, items []string, yStart float64) float64 {
|
||||
yy := sectionTitle(title, yStart)
|
||||
for _, item := range items {
|
||||
txt := "• " + item
|
||||
h := c.textHeight(txt, c.W-4, "", 7.5)
|
||||
yy = c.need(h+4, yy)
|
||||
c.drawText(txt, c.L+2, yy, c.W-4, "", 7.5, dark, "L")
|
||||
yy += h + 4
|
||||
}
|
||||
return yy + 6
|
||||
}
|
||||
|
||||
y = drawBullets("Condiciones", []string{
|
||||
"Esta cotización tiene una vigencia de 15 días hábiles.",
|
||||
"Cualquier ajuste al proyecto después de la aprobación del contenido afectará la fecha de entrega y por consiguiente el costo.",
|
||||
"El cliente deberá proporcionar la información solicitada por Uriel Jareth Consulting en tiempo y forma.",
|
||||
"Si la falta de información provoca un excedente en los plazos de entrega del proyecto, las horas adicionales de servicio se cotizarán por separado.",
|
||||
"Los pagos correspondientes a los servicios mensuales deberán realizarse en los primeros 5 días del mes.",
|
||||
"Todo el material e información necesarios para la realización del sitio web deberán ser entregados en un plazo máximo de 40 días naturales a partir del arranque del proyecto.",
|
||||
}, y)
|
||||
|
||||
y = drawBullets("¿Qué no incluye el proyecto?", []string{
|
||||
"Generación de diseños, videos, traducciones, cambios de divisas y unidades, o cualquier servicio externo a lo cotizado.",
|
||||
"Redacción de entradas de Blog.",
|
||||
"Integración de Servicios de terceros ajenos a los cotizados.",
|
||||
"Servicio de Recuperación de Accesos de: Google Analytics, Google Tag Manager, Google Search Console, Google Ads, y Meta Ads.",
|
||||
"Creación de Redes Sociales (En caso de requerir el servicio incluirá un costo adicional).",
|
||||
}, y)
|
||||
|
||||
y = drawBullets("Notas", []string{
|
||||
"El presente proyecto deberá tener un responsable oficial.",
|
||||
"La Hora Centinela tiene un precio de $700.00 MXN.",
|
||||
"Los archivos editables/fuente (AI, PSD) son propiedad intelectual de la agencia. Si requiere los archivos editables, estos pueden ser adquiridos abonando una tarifa de liberación (buy-out fee).",
|
||||
"Si el proyecto se pausa por razones ajenas a Uriel Jareth Consulting, esto generará costo extra del 15% al 30% para retomar el proyecto.",
|
||||
}, y)
|
||||
|
||||
y += 6
|
||||
y = c.need(120, y)
|
||||
y = sectionTitle("Datos Bancarios", y)
|
||||
|
||||
bank := extractBankInfo(data.ConfigBancaria)
|
||||
boxH := 48.0
|
||||
|
||||
c.rectFillStroke(c.L, y, c.W, boxH, colorLightBG, colorBorder, 0.5)
|
||||
c.drawSingleLine("Transferencia Nacional", c.L+8, y+4, c.W-16, "B", 7, dark, "L")
|
||||
if bank.CuentaNacional != "" {
|
||||
c.drawSingleLine("Cuenta: "+bank.CuentaNacional, c.L+8, y+15, c.W*0.43, "", 6.5, dark, "L")
|
||||
}
|
||||
if bank.ClabeNacional != "" {
|
||||
c.drawSingleLine("CLABE: "+bank.ClabeNacional, c.L+c.W*0.45, y+15, c.W*0.53, "", 6.5, dark, "L")
|
||||
}
|
||||
c.drawSingleLine("Razón Social: "+bank.RazonSocial, c.L+8, y+26, c.W*0.43, "", 6.5, dark, "L")
|
||||
c.drawSingleLine("RFC: "+bank.RFC, c.L+c.W*0.45, y+26, c.W*0.53, "", 6.5, dark, "L")
|
||||
if bank.BancoNacional != "" {
|
||||
c.drawSingleLine("Banco: "+bank.BancoNacional, c.L+8, y+37, c.W*0.43, "", 6.5, dark, "L")
|
||||
}
|
||||
y += boxH + 6
|
||||
|
||||
y = c.need(boxH+6, y)
|
||||
c.rectFillStroke(c.L, y, c.W, boxH, colorLightBG, colorBorder, 0.5)
|
||||
c.drawSingleLine("Transferencia Internacional", c.L+8, y+4, c.W-16, "B", 7, dark, "L")
|
||||
c.drawSingleLine("Beneficiario: "+bank.RazonSocial, c.L+8, y+15, c.W*0.43, "", 6.5, dark, "L")
|
||||
if bank.ClabeInternacional != "" {
|
||||
c.drawSingleLine("CLABE: "+bank.ClabeInternacional, c.L+c.W*0.45, y+15, c.W*0.53, "", 6.5, dark, "L")
|
||||
}
|
||||
c.drawSingleLine("Banco: BBVA México", c.L+8, y+26, c.W*0.43, "", 6.5, dark, "L")
|
||||
c.drawSingleLine("SWIFT: "+bank.Swift, c.L+c.W*0.45, y+26, c.W*0.53, "", 6.5, dark, "L")
|
||||
|
||||
return c.bytes()
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
package pdf
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"codeberg.org/go-pdf/fpdf"
|
||||
"golang.org/x/image/font/gofont/gobold"
|
||||
"golang.org/x/image/font/gofont/gobolditalic"
|
||||
"golang.org/x/image/font/gofont/goitalic"
|
||||
"golang.org/x/image/font/gofont/goregular"
|
||||
"golang.org/x/image/webp"
|
||||
|
||||
"cotizador/internal/domain"
|
||||
)
|
||||
|
||||
const (
|
||||
fontFamily = "Go"
|
||||
|
||||
defaultPrimary = "#0400C4"
|
||||
defaultDark = "#0F172A"
|
||||
colorMuted = "#64748b"
|
||||
colorBorder = "#cbd5e1"
|
||||
colorLightBG = "#f1f5f9"
|
||||
colorWhite = "#ffffff"
|
||||
colorSubtleSep = "#e5e7eb"
|
||||
)
|
||||
|
||||
var (
|
||||
hexColorRe = regexp.MustCompile(`^#[0-9a-fA-F]{6}$`)
|
||||
swiftRe = regexp.MustCompile(`(?i)SWIFT[^:]*:\s*(\S+)`)
|
||||
clabeRe = regexp.MustCompile(`(?i)CLABE[^:]*:\s*(\S+)`)
|
||||
)
|
||||
|
||||
func safeHex(v, fallback string) string {
|
||||
v = strings.TrimSpace(v)
|
||||
if hexColorRe.MatchString(v) {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func parseHexRGB(hexStr, fallback string) (int, int, int) {
|
||||
h := strings.TrimPrefix(safeHex(hexStr, fallback), "#")
|
||||
r, _ := strconv.ParseInt(h[0:2], 16, 64)
|
||||
g, _ := strconv.ParseInt(h[2:4], 16, 64)
|
||||
b, _ := strconv.ParseInt(h[4:6], 16, 64)
|
||||
return int(r), int(g), int(b)
|
||||
}
|
||||
|
||||
func capitalize(s string) string {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return ""
|
||||
}
|
||||
r := []rune(s)
|
||||
r[0] = unicode.ToUpper(r[0])
|
||||
return string(r)
|
||||
}
|
||||
|
||||
func formatMoney(amount float64, moneda string) string {
|
||||
if moneda == "" || strings.EqualFold(moneda, "MXN") {
|
||||
return domain.FormatCurrency(amount)
|
||||
}
|
||||
return domain.FormatMonto(amount, moneda)
|
||||
}
|
||||
|
||||
type bankInfo struct {
|
||||
RazonSocial string
|
||||
RFC string
|
||||
CuentaNacional string
|
||||
ClabeNacional string
|
||||
BancoNacional string
|
||||
ClabeInternacional string
|
||||
Swift string
|
||||
}
|
||||
|
||||
func extractBankInfo(cfg map[string]string) bankInfo {
|
||||
if cfg == nil {
|
||||
cfg = map[string]string{}
|
||||
}
|
||||
razon := strings.TrimSpace(cfg["razon_social"])
|
||||
if razon == "" {
|
||||
razon = "URIEL JARETH ALVARADO ORTIZ"
|
||||
}
|
||||
rfc := strings.TrimSpace(cfg["rfc"])
|
||||
if rfc == "" {
|
||||
rfc = "AAOU970201SU7"
|
||||
}
|
||||
cuentaNac := strings.TrimSpace(cfg["cuenta_nacional"])
|
||||
clabeNac := strings.TrimSpace(cfg["clabe_interbancaria"])
|
||||
if clabeNac == "" {
|
||||
clabeNac = cuentaNac
|
||||
}
|
||||
bancoNac := ""
|
||||
if cuentaNac != "" {
|
||||
bancoNac = "BBVA"
|
||||
}
|
||||
swift := "BCMRMXMMPYM"
|
||||
clabeInt := ""
|
||||
if intl := cfg["cuenta_internacional_swift"]; intl != "" {
|
||||
if m := swiftRe.FindStringSubmatch(intl); len(m) > 1 {
|
||||
swift = m[1]
|
||||
}
|
||||
if m := clabeRe.FindStringSubmatch(intl); len(m) > 1 {
|
||||
clabeInt = m[1]
|
||||
}
|
||||
}
|
||||
return bankInfo{
|
||||
RazonSocial: razon,
|
||||
RFC: rfc,
|
||||
CuentaNacional: cuentaNac,
|
||||
ClabeNacional: clabeNac,
|
||||
BancoNacional: bancoNac,
|
||||
ClabeInternacional: clabeInt,
|
||||
Swift: swift,
|
||||
}
|
||||
}
|
||||
|
||||
type logoAsset struct {
|
||||
name string
|
||||
w float64
|
||||
h float64
|
||||
ok bool
|
||||
}
|
||||
|
||||
// prepareLogoBytes decodes base64 and normalizes PNG/JPEG/WebP into a format fpdf safely accepts.
|
||||
// WebP (and non-standard PNGs) are decoded and re-encoded as standard 8-bit PNG.
|
||||
func prepareLogoBytes(b64, mime string) ([]byte, string, error) {
|
||||
b64 = strings.TrimSpace(b64)
|
||||
if b64 == "" {
|
||||
return nil, "", fmt.Errorf("empty logo")
|
||||
}
|
||||
// Strip optional data URI prefix.
|
||||
if idx := strings.Index(b64, ","); idx != -1 && strings.HasPrefix(b64[:idx], "data:") {
|
||||
if mime == "" {
|
||||
header := b64[len("data:"):idx]
|
||||
if semi := strings.Index(header, ";"); semi != -1 {
|
||||
mime = header[:semi]
|
||||
}
|
||||
}
|
||||
b64 = b64[idx+1:]
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(b64)
|
||||
if err != nil {
|
||||
raw, err = base64.RawStdEncoding.DecodeString(b64)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
}
|
||||
if len(raw) < 8 {
|
||||
return nil, "", fmt.Errorf("logo too short")
|
||||
}
|
||||
|
||||
m := strings.ToLower(strings.TrimSpace(mime))
|
||||
isWebP := m == "image/webp" || (len(raw) >= 12 && string(raw[0:4]) == "RIFF" && string(raw[8:12]) == "WEBP")
|
||||
if isWebP {
|
||||
img, err := webp.Decode(bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
var out bytes.Buffer
|
||||
if err := png.Encode(&out, img); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return out.Bytes(), "PNG", nil
|
||||
}
|
||||
|
||||
isJPEG := m == "image/jpeg" || m == "image/jpg" || (raw[0] == 0xFF && raw[1] == 0xD8)
|
||||
if isJPEG {
|
||||
if _, err := jpeg.DecodeConfig(bytes.NewReader(raw)); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return raw, "JPG", nil
|
||||
}
|
||||
|
||||
isPNG := m == "image/png" || bytes.Equal(raw[0:8], []byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'})
|
||||
if isPNG {
|
||||
// Re-encode through image/png so interlaced or 16-bit PNGs always work with fpdf.
|
||||
img, err := png.Decode(bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
var out bytes.Buffer
|
||||
if err := png.Encode(&out, img); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return out.Bytes(), "PNG", nil
|
||||
}
|
||||
|
||||
// Fallback: try generic image decode -> PNG.
|
||||
img, _, err := image.Decode(bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
var out bytes.Buffer
|
||||
if err := png.Encode(&out, img); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return out.Bytes(), "PNG", nil
|
||||
}
|
||||
|
||||
func registerLogo(doc *fpdf.Fpdf, name, b64, mime string) logoAsset {
|
||||
imgBytes, imgType, err := prepareLogoBytes(b64, mime)
|
||||
if err != nil {
|
||||
return logoAsset{}
|
||||
}
|
||||
opts := fpdf.ImageOptions{ImageType: imgType, ReadDpi: false}
|
||||
info := doc.RegisterImageOptionsReader(name, opts, bytes.NewReader(imgBytes))
|
||||
if info == nil || !doc.Ok() {
|
||||
doc.ClearError()
|
||||
return logoAsset{}
|
||||
}
|
||||
return logoAsset{
|
||||
name: name,
|
||||
w: info.Width(),
|
||||
h: info.Height(),
|
||||
ok: info.Width() > 0 && info.Height() > 0,
|
||||
}
|
||||
}
|
||||
|
||||
func (l logoAsset) drawByHeight(doc *fpdf.Fpdf, x, y, targetH float64) {
|
||||
if !l.ok {
|
||||
return
|
||||
}
|
||||
doc.ImageOptions(l.name, x, y, 0, targetH, false, fpdf.ImageOptions{}, 0, "")
|
||||
}
|
||||
|
||||
func (l logoAsset) drawRightAlignedByHeight(doc *fpdf.Fpdf, rightX, y, targetH float64) {
|
||||
if !l.ok {
|
||||
return
|
||||
}
|
||||
w := targetH * (l.w / l.h)
|
||||
if w > 90 {
|
||||
w = 90
|
||||
targetH = w * (l.h / l.w)
|
||||
}
|
||||
doc.ImageOptions(l.name, rightX-w, y, w, targetH, false, fpdf.ImageOptions{}, 0, "")
|
||||
}
|
||||
|
||||
func (l logoAsset) drawFit(doc *fpdf.Fpdf, x, y, maxW, maxH float64) (float64, float64) {
|
||||
if !l.ok {
|
||||
return 0, 0
|
||||
}
|
||||
scale := maxW / l.w
|
||||
if sh := maxH / l.h; sh < scale {
|
||||
scale = sh
|
||||
}
|
||||
w := l.w * scale
|
||||
h := l.h * scale
|
||||
doc.ImageOptions(l.name, x, y, w, h, false, fpdf.ImageOptions{}, 0, "")
|
||||
return w, h
|
||||
}
|
||||
|
||||
type canvas struct {
|
||||
doc *fpdf.Fpdf
|
||||
pw float64
|
||||
ph float64
|
||||
mTop float64
|
||||
mBottom float64
|
||||
mLeft float64
|
||||
mRight float64
|
||||
W float64
|
||||
L float64
|
||||
maxY float64
|
||||
}
|
||||
|
||||
func newCanvas(top, bottom, left, right float64) *canvas {
|
||||
doc := fpdf.New("P", "pt", "Letter", "")
|
||||
doc.AddUTF8FontFromBytes(fontFamily, "", goregular.TTF)
|
||||
doc.AddUTF8FontFromBytes(fontFamily, "B", gobold.TTF)
|
||||
doc.AddUTF8FontFromBytes(fontFamily, "I", goitalic.TTF)
|
||||
doc.AddUTF8FontFromBytes(fontFamily, "BI", gobolditalic.TTF)
|
||||
doc.SetMargins(left, top, right)
|
||||
doc.SetAutoPageBreak(false, 0)
|
||||
doc.SetCellMargin(0)
|
||||
doc.SetFont(fontFamily, "", 10)
|
||||
|
||||
pw, ph := doc.GetPageSize()
|
||||
return &canvas{
|
||||
doc: doc,
|
||||
pw: pw,
|
||||
ph: ph,
|
||||
mTop: top,
|
||||
mBottom: bottom,
|
||||
mLeft: left,
|
||||
mRight: right,
|
||||
W: pw - left - right,
|
||||
L: left,
|
||||
maxY: ph - bottom - 5,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *canvas) need(h, y float64) float64 {
|
||||
if y+h > c.maxY {
|
||||
c.doc.AddPage()
|
||||
return c.mTop
|
||||
}
|
||||
return y
|
||||
}
|
||||
|
||||
func (c *canvas) setFont(style string, size float64) {
|
||||
c.doc.SetFont(fontFamily, style, size)
|
||||
}
|
||||
|
||||
func (c *canvas) setTextColor(hex string) {
|
||||
r, g, b := parseHexRGB(hex, defaultDark)
|
||||
c.doc.SetTextColor(r, g, b)
|
||||
}
|
||||
|
||||
func (c *canvas) setFillColor(hex string) {
|
||||
r, g, b := parseHexRGB(hex, colorWhite)
|
||||
c.doc.SetFillColor(r, g, b)
|
||||
}
|
||||
|
||||
func (c *canvas) setDrawColor(hex string) {
|
||||
r, g, b := parseHexRGB(hex, colorBorder)
|
||||
c.doc.SetDrawColor(r, g, b)
|
||||
}
|
||||
|
||||
func lineHeight(size float64) float64 {
|
||||
return size * 1.25
|
||||
}
|
||||
|
||||
func (c *canvas) splitLines(txt string, width float64, style string, size float64) []string {
|
||||
c.setFont(style, size)
|
||||
if width <= 1 {
|
||||
return []string{txt}
|
||||
}
|
||||
rawLines := strings.Split(strings.ReplaceAll(txt, "\r\n", "\n"), "\n")
|
||||
var out []string
|
||||
for _, rl := range rawLines {
|
||||
if rl == "" {
|
||||
out = append(out, "")
|
||||
continue
|
||||
}
|
||||
parts := c.doc.SplitText(rl, width)
|
||||
if len(parts) == 0 {
|
||||
out = append(out, rl)
|
||||
} else {
|
||||
out = append(out, parts...)
|
||||
}
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return []string{""}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (c *canvas) textHeight(txt string, width float64, style string, size float64) float64 {
|
||||
lines := c.splitLines(txt, width, style, size)
|
||||
return float64(len(lines)) * lineHeight(size)
|
||||
}
|
||||
|
||||
// drawText writes multi-line wrapped text starting at (x, y) and returns total height drawn.
|
||||
func (c *canvas) drawText(txt string, x, y, width float64, style string, size float64, color, align string) float64 {
|
||||
if align == "" {
|
||||
align = "L"
|
||||
}
|
||||
lines := c.splitLines(txt, width, style, size)
|
||||
lh := lineHeight(size)
|
||||
c.setFont(style, size)
|
||||
c.setTextColor(color)
|
||||
curY := y
|
||||
for _, ln := range lines {
|
||||
c.doc.SetXY(x, curY)
|
||||
c.doc.CellFormat(width, lh, ln, "", 0, align, false, 0, "")
|
||||
curY += lh
|
||||
}
|
||||
return float64(len(lines)) * lh
|
||||
}
|
||||
|
||||
// drawSingleLine writes text on one line without wrapping.
|
||||
func (c *canvas) drawSingleLine(txt string, x, y, width float64, style string, size float64, color, align string) {
|
||||
if align == "" {
|
||||
align = "L"
|
||||
}
|
||||
c.setFont(style, size)
|
||||
c.setTextColor(color)
|
||||
c.doc.SetXY(x, y)
|
||||
if width <= 0 {
|
||||
width = c.doc.GetStringWidth(txt) + 2
|
||||
}
|
||||
c.doc.CellFormat(width, lineHeight(size), txt, "", 0, align, false, 0, "")
|
||||
}
|
||||
|
||||
func (c *canvas) rectFill(x, y, w, h float64, fillHex string) {
|
||||
c.setFillColor(fillHex)
|
||||
c.doc.Rect(x, y, w, h, "F")
|
||||
}
|
||||
|
||||
func (c *canvas) rectFillStroke(x, y, w, h float64, fillHex, strokeHex string, lw float64) {
|
||||
c.setFillColor(fillHex)
|
||||
c.setDrawColor(strokeHex)
|
||||
c.doc.SetLineWidth(lw)
|
||||
c.doc.Rect(x, y, w, h, "DF")
|
||||
}
|
||||
|
||||
func (c *canvas) hLine(x1, x2, y float64, strokeHex string, lw float64) {
|
||||
c.setDrawColor(strokeHex)
|
||||
c.doc.SetLineWidth(lw)
|
||||
c.doc.Line(x1, y, x2, y)
|
||||
}
|
||||
|
||||
func (c *canvas) circleFill(cx, cy, r float64, fillHex string) {
|
||||
c.setFillColor(fillHex)
|
||||
c.doc.Circle(cx, cy, r, "F")
|
||||
}
|
||||
|
||||
func (c *canvas) rowBg(y, h float64, bgHex string) {
|
||||
c.rectFill(c.L, y, c.W, h, bgHex)
|
||||
c.hLine(c.L, c.L+c.W, y+h, colorBorder, 0.3)
|
||||
}
|
||||
|
||||
func (c *canvas) bytes() ([]byte, error) {
|
||||
var buf bytes.Buffer
|
||||
if err := c.doc.Output(&buf); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,394 @@
|
||||
package pdf
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/domain"
|
||||
)
|
||||
|
||||
type RegistroHoraPDF struct {
|
||||
Fecha time.Time
|
||||
HoraInicio string
|
||||
HoraFin string
|
||||
Horas float64
|
||||
TarifaHora float64
|
||||
Descripcion string
|
||||
EstadoPago string
|
||||
}
|
||||
|
||||
type NotaHorasPDFData struct {
|
||||
Titulo string
|
||||
Numero string
|
||||
ClienteNombre string
|
||||
ClienteEmpresa string
|
||||
Proyecto string
|
||||
AsesorNombre string
|
||||
Moneda string
|
||||
IncluirIVA bool
|
||||
Modo string
|
||||
MostrarEstado bool
|
||||
MostrarBancarios bool
|
||||
Registros []RegistroHoraPDF
|
||||
ConfigBancaria map[string]string
|
||||
ColorPrimario string
|
||||
ColorSecundario string
|
||||
LogoBase64 string
|
||||
LogoMime string
|
||||
FechaEmision time.Time
|
||||
}
|
||||
|
||||
type notaHorasGrupo struct {
|
||||
Clave string
|
||||
Etiqueta string
|
||||
Count int
|
||||
Horas float64
|
||||
Importe float64
|
||||
}
|
||||
|
||||
func modoAgrupacionLabel(modo string) string {
|
||||
switch modo {
|
||||
case "dia":
|
||||
return "Por día"
|
||||
case "semana":
|
||||
return "Por semana"
|
||||
case "mes":
|
||||
return "Por mes"
|
||||
default:
|
||||
return "Detalle"
|
||||
}
|
||||
}
|
||||
|
||||
func etiquetaTotalNota(titulo string) string {
|
||||
low := strings.ToLower(titulo)
|
||||
switch {
|
||||
case strings.Contains(low, "pagadas"):
|
||||
return "Total pagado"
|
||||
case strings.Contains(low, "por pagar"):
|
||||
return "Total a pagar"
|
||||
default:
|
||||
return "Total"
|
||||
}
|
||||
}
|
||||
|
||||
func GenerateNotaHorasPDF(data NotaHorasPDFData) ([]byte, error) {
|
||||
primary := safeHex(data.ColorPrimario, defaultPrimary)
|
||||
dark := safeHex(data.ColorSecundario, defaultDark)
|
||||
muted := "#6b7280"
|
||||
border := "#d1d5db"
|
||||
headBG := "#f3f4f6"
|
||||
|
||||
titulo := strings.TrimSpace(data.Titulo)
|
||||
if titulo == "" {
|
||||
titulo = "Nota de horas por pagar"
|
||||
}
|
||||
modo := strings.ToLower(strings.TrimSpace(data.Modo))
|
||||
if modo != "detalle" && modo != "dia" && modo != "semana" && modo != "mes" {
|
||||
modo = "detalle"
|
||||
}
|
||||
modoLabel := modoAgrupacionLabel(modo)
|
||||
|
||||
emitida := data.FechaEmision
|
||||
if emitida.IsZero() {
|
||||
emitida = time.Now()
|
||||
}
|
||||
|
||||
// Copy and sort records chronologically.
|
||||
regs := make([]RegistroHoraPDF, len(data.Registros))
|
||||
copy(regs, data.Registros)
|
||||
sort.Slice(regs, func(i, j int) bool {
|
||||
if regs[i].Fecha.Equal(regs[j].Fecha) {
|
||||
return regs[i].HoraInicio < regs[j].HoraInicio
|
||||
}
|
||||
return regs[i].Fecha.Before(regs[j].Fecha)
|
||||
})
|
||||
|
||||
// Totals.
|
||||
var totalHoras, subtotal float64
|
||||
for _, r := range regs {
|
||||
totalHoras += r.Horas
|
||||
subtotal += r.Horas * r.TarifaHora
|
||||
}
|
||||
totalHoras = domain.Round2(totalHoras)
|
||||
subtotal = domain.Round2(subtotal)
|
||||
iva := 0.0
|
||||
if data.IncluirIVA {
|
||||
iva = domain.Round2(subtotal * domain.IVARate)
|
||||
}
|
||||
total := domain.Round2(subtotal + iva)
|
||||
|
||||
// Periodo text.
|
||||
periodoTexto := "Periodo: todos los registros"
|
||||
if len(regs) > 0 {
|
||||
minF := domain.FormatFechaRegistro(regs[0].Fecha)
|
||||
maxF := domain.FormatFechaRegistro(regs[len(regs)-1].Fecha)
|
||||
if minF == maxF {
|
||||
periodoTexto = "Periodo: " + minF
|
||||
} else {
|
||||
periodoTexto = fmt.Sprintf("Periodo: %s al %s", minF, maxF)
|
||||
}
|
||||
}
|
||||
|
||||
// Grouping if not detalle.
|
||||
var grupos []notaHorasGrupo
|
||||
if modo != "detalle" {
|
||||
m := make(map[string]*notaHorasGrupo)
|
||||
for _, r := range regs {
|
||||
per := domain.PeriodoAgrupacionDe(r.Fecha, modo)
|
||||
g, ok := m[per.Clave]
|
||||
if !ok {
|
||||
g = ¬aHorasGrupo{Clave: per.Clave, Etiqueta: per.Etiqueta}
|
||||
m[per.Clave] = g
|
||||
}
|
||||
g.Count++
|
||||
g.Horas += r.Horas
|
||||
g.Importe += r.Horas * r.TarifaHora
|
||||
}
|
||||
for _, g := range m {
|
||||
g.Horas = domain.Round2(g.Horas)
|
||||
g.Importe = domain.Round2(g.Importe)
|
||||
grupos = append(grupos, *g)
|
||||
}
|
||||
sort.Slice(grupos, func(i, j int) bool {
|
||||
return grupos[i].Clave < grupos[j].Clave
|
||||
})
|
||||
}
|
||||
|
||||
fmtMoney := func(n float64) string {
|
||||
return formatMoney(n, data.Moneda)
|
||||
}
|
||||
|
||||
c := newCanvas(45, 55, 50, 50)
|
||||
c.maxY = c.ph - c.mBottom
|
||||
logo := registerLogo(c.doc, "nota_logo", data.LogoBase64, data.LogoMime)
|
||||
|
||||
c.doc.AddPage()
|
||||
y := c.mTop
|
||||
|
||||
// ── ENCABEZADO ────────────────────────────────
|
||||
logoBottom := y
|
||||
if logo.ok {
|
||||
_, lh := logo.drawFit(c.doc, c.L, y, 46, 46)
|
||||
logoBottom = y + lh
|
||||
}
|
||||
txtX := c.L
|
||||
if logo.ok {
|
||||
txtX = c.L + 58
|
||||
}
|
||||
titleW := c.W - 170
|
||||
if logo.ok {
|
||||
titleW = c.W - 58 - 115
|
||||
}
|
||||
hTit := c.drawText(titulo, txtX, y+2, titleW, "B", 18, dark, "L")
|
||||
sub := fmt.Sprintf("Cotización %s · %s", data.Numero, data.Proyecto)
|
||||
hSub := c.drawText(sub, txtX, y+2+hTit+1, titleW, "", 9, muted, "L")
|
||||
c.drawSingleLine("Emitida: "+domain.FormatFechaRegistro(emitida), c.L, y+2, c.W, "", 9, muted, "R")
|
||||
|
||||
yTextEnd := y + 2 + hTit + 1 + hSub + 6
|
||||
y = y + 50
|
||||
if logoBottom+6 > y {
|
||||
y = logoBottom + 6
|
||||
}
|
||||
if yTextEnd > y {
|
||||
y = yTextEnd
|
||||
}
|
||||
c.hLine(c.L, c.L+c.W, y, primary, 2.5)
|
||||
y += 14
|
||||
|
||||
// ── META ──────────────────────────────────────
|
||||
cliente := data.ClienteEmpresa
|
||||
if strings.TrimSpace(cliente) == "" {
|
||||
cliente = data.ClienteNombre
|
||||
}
|
||||
drawMetaLine := func(label, val string) {
|
||||
c.setFont("B", 9.5)
|
||||
lw := c.doc.GetStringWidth(label) + 2
|
||||
c.drawSingleLine(label, c.L, y, lw, "B", 9.5, dark, "L")
|
||||
h := c.drawText(val, c.L+lw, y, c.W-lw, "", 9.5, dark, "L")
|
||||
y += h + 2
|
||||
}
|
||||
drawMetaLine("Cliente: ", cliente)
|
||||
if strings.TrimSpace(data.ClienteEmpresa) != "" && strings.TrimSpace(data.ClienteNombre) != "" {
|
||||
drawMetaLine("Contacto: ", data.ClienteNombre)
|
||||
}
|
||||
if strings.TrimSpace(data.AsesorNombre) != "" {
|
||||
drawMetaLine("Asesor: ", data.AsesorNombre)
|
||||
}
|
||||
hPer := c.drawText(fmt.Sprintf("%s · Desglose %s", periodoTexto, strings.ToLower(modoLabel)), c.L, y, c.W, "", 8.5, muted, "L")
|
||||
y += hPer + 12
|
||||
|
||||
// ── TABLA ─────────────────────────────────────
|
||||
if modo == "detalle" {
|
||||
wEstado := 0.0
|
||||
if data.MostrarEstado {
|
||||
wEstado = 58.0
|
||||
}
|
||||
cFecha := c.L
|
||||
wFecha, wHorario, wHoras, wTarifa, wImporte := 62.0, 72.0, 42.0, 52.0, 58.0
|
||||
cHorario := cFecha + wFecha
|
||||
cHoras := cHorario + wHorario
|
||||
cTarifa := cHoras + wHoras
|
||||
cImporte := cTarifa + wTarifa
|
||||
cDesc := cImporte + wImporte + 6
|
||||
estadoPad := 0.0
|
||||
if wEstado > 0 {
|
||||
estadoPad = 6.0
|
||||
}
|
||||
wDesc := c.L + c.W - cDesc - wEstado - estadoPad
|
||||
cEstado := c.L + c.W - wEstado
|
||||
|
||||
drawHeader := func(yy float64) float64 {
|
||||
c.rectFill(c.L, yy, c.W, 16, headBG)
|
||||
c.drawSingleLine("FECHA", cFecha+4, yy+4, wFecha-4, "B", 7, dark, "L")
|
||||
c.drawSingleLine("HORARIO", cHorario+4, yy+4, wHorario-4, "B", 7, dark, "L")
|
||||
c.drawSingleLine("HORAS", cHoras, yy+4, wHoras-2, "B", 7, dark, "R")
|
||||
c.drawSingleLine("TARIFA", cTarifa, yy+4, wTarifa-2, "B", 7, dark, "R")
|
||||
c.drawSingleLine("IMPORTE", cImporte, yy+4, wImporte-2, "B", 7, dark, "R")
|
||||
c.drawSingleLine("DESCRIPCIÓN", cDesc, yy+4, wDesc, "B", 7, dark, "L")
|
||||
if wEstado > 0 {
|
||||
c.drawSingleLine("ESTADO", cEstado, yy+4, wEstado, "B", 7, dark, "L")
|
||||
}
|
||||
return yy + 16
|
||||
}
|
||||
|
||||
y = drawHeader(y)
|
||||
for _, r := range regs {
|
||||
descH := c.textHeight(r.Descripcion, wDesc, "", 8)
|
||||
rowH := descH + 8
|
||||
if rowH < 16 {
|
||||
rowH = 16
|
||||
}
|
||||
if y+rowH > c.maxY {
|
||||
y = drawHeader(c.need(rowH+16, y))
|
||||
}
|
||||
c.drawSingleLine(domain.FormatFechaRegistro(r.Fecha), cFecha+4, y+4, wFecha-4, "", 8, dark, "L")
|
||||
c.drawSingleLine(fmt.Sprintf("%s-%s", r.HoraInicio, r.HoraFin), cHorario+4, y+4, wHorario-4, "", 8, dark, "L")
|
||||
c.drawSingleLine(fmt.Sprintf("%.2f", r.Horas), cHoras, y+4, wHoras-2, "", 8, dark, "R")
|
||||
c.drawSingleLine(fmtMoney(r.TarifaHora), cTarifa, y+4, wTarifa-2, "", 8, dark, "R")
|
||||
c.drawSingleLine(fmtMoney(r.Horas*r.TarifaHora), cImporte, y+4, wImporte-2, "", 8, dark, "R")
|
||||
c.drawText(r.Descripcion, cDesc, y+4, wDesc, "", 8, dark, "L")
|
||||
if wEstado > 0 {
|
||||
est := "Por pagar"
|
||||
if domain.EsPagada(r.EstadoPago) {
|
||||
est = "Pagada"
|
||||
}
|
||||
c.drawSingleLine(est, cEstado, y+4, wEstado, "", 8, dark, "L")
|
||||
}
|
||||
c.hLine(c.L, c.L+c.W, y+rowH, border, 0.3)
|
||||
y += rowH
|
||||
}
|
||||
} else {
|
||||
wReg, wHor, wImp := 90.0, 90.0, 90.0
|
||||
cPer := c.L
|
||||
wPer := c.W - wReg - wHor - wImp
|
||||
cReg := cPer + wPer
|
||||
cHor := cReg + wReg
|
||||
cImp := cHor + wHor
|
||||
|
||||
drawHeader := func(yy float64) float64 {
|
||||
c.rectFill(c.L, yy, c.W, 16, headBG)
|
||||
c.drawSingleLine(strings.ToUpper(modoLabel), cPer+4, yy+4, wPer-6, "B", 7, dark, "L")
|
||||
c.drawSingleLine("REGISTROS", cReg, yy+4, wReg-2, "B", 7, dark, "R")
|
||||
c.drawSingleLine("HORAS", cHor, yy+4, wHor-2, "B", 7, dark, "R")
|
||||
c.drawSingleLine("IMPORTE", cImp, yy+4, wImp-2, "B", 7, dark, "R")
|
||||
return yy + 16
|
||||
}
|
||||
|
||||
y = drawHeader(y)
|
||||
for _, g := range grupos {
|
||||
rowH := 16.0
|
||||
if y+rowH > c.maxY {
|
||||
y = drawHeader(c.need(rowH+16, y))
|
||||
}
|
||||
c.drawSingleLine(g.Etiqueta, cPer+4, y+4, wPer-6, "", 8, dark, "L")
|
||||
c.drawSingleLine(fmt.Sprintf("%d", g.Count), cReg, y+4, wReg-2, "", 8, dark, "R")
|
||||
c.drawSingleLine(fmt.Sprintf("%.2f", g.Horas), cHor, y+4, wHor-2, "", 8, dark, "R")
|
||||
c.drawSingleLine(fmtMoney(g.Importe), cImp, y+4, wImp-2, "", 8, dark, "R")
|
||||
c.hLine(c.L, c.L+c.W, y+rowH, border, 0.3)
|
||||
y += rowH
|
||||
}
|
||||
}
|
||||
|
||||
// ── TOTALES ───────────────────────────────────
|
||||
y += 12
|
||||
totW := 240.0
|
||||
totX := c.L + c.W - totW
|
||||
drawTotalLine := func(label, val string, bold, topLine bool) {
|
||||
y = c.need(20, y)
|
||||
if topLine {
|
||||
c.hLine(totX, totX+totW, y, primary, 1.2)
|
||||
y += 5
|
||||
}
|
||||
style := ""
|
||||
size := 9.0
|
||||
lblColor := muted
|
||||
step := 15.0
|
||||
if bold {
|
||||
style = "B"
|
||||
size = 12.0
|
||||
lblColor = dark
|
||||
step = 18.0
|
||||
}
|
||||
c.drawSingleLine(label, totX, y, totW-95, style, size, lblColor, "L")
|
||||
c.drawSingleLine(val, totX+totW-95, y, 95, style, size, dark, "R")
|
||||
y += step
|
||||
}
|
||||
|
||||
drawTotalLine("Total de horas", fmt.Sprintf("%.2f h", totalHoras), false, false)
|
||||
drawTotalLine("Subtotal", fmtMoney(subtotal), false, false)
|
||||
if data.IncluirIVA {
|
||||
drawTotalLine("IVA (16%)", fmtMoney(iva), false, false)
|
||||
}
|
||||
drawTotalLine(etiquetaTotalNota(titulo), fmtMoney(total), true, true)
|
||||
|
||||
// ── DATOS PARA EL PAGO ────────────────────────
|
||||
if data.MostrarBancarios {
|
||||
dp := extractBankInfo(data.ConfigBancaria)
|
||||
boxH := 52.0
|
||||
y = c.need(boxH+34, y) + 16
|
||||
c.rectFill(c.L, y+1, 3, 10, primary)
|
||||
c.drawSingleLine("Datos para el pago", c.L+10, y, c.W-10, "B", 10, dark, "L")
|
||||
y += 16
|
||||
|
||||
c.rectFillStroke(c.L, y, c.W, boxH, headBG, border, 0.5)
|
||||
c.drawSingleLine("Transferencia Nacional", c.L+8, y+5, c.W-16, "B", 8, dark, "L")
|
||||
if dp.CuentaNacional != "" {
|
||||
c.drawSingleLine("Cuenta: "+dp.CuentaNacional, c.L+8, y+18, c.W*0.48, "", 8.5, dark, "L")
|
||||
}
|
||||
if dp.ClabeNacional != "" {
|
||||
c.drawSingleLine("CLABE: "+dp.ClabeNacional, c.L+c.W*0.5, y+18, c.W*0.48, "", 8.5, dark, "L")
|
||||
}
|
||||
c.drawSingleLine("Beneficiario: "+dp.RazonSocial, c.L+8, y+30, c.W*0.48, "", 8.5, dark, "L")
|
||||
c.drawSingleLine("RFC: "+dp.RFC, c.L+c.W*0.5, y+30, c.W*0.48, "", 8.5, dark, "L")
|
||||
if dp.BancoNacional != "" {
|
||||
c.drawSingleLine("Banco: "+dp.BancoNacional, c.L+8, y+42, c.W*0.48, "", 8.5, dark, "L")
|
||||
}
|
||||
y += boxH + 8
|
||||
|
||||
if dp.ClabeInternacional != "" || dp.Swift != "" {
|
||||
y = c.need(boxH, y)
|
||||
c.rectFillStroke(c.L, y, c.W, boxH, headBG, border, 0.5)
|
||||
c.drawSingleLine("Transferencia Internacional", c.L+8, y+5, c.W-16, "B", 8, dark, "L")
|
||||
c.drawSingleLine("Beneficiario: "+dp.RazonSocial, c.L+8, y+18, c.W*0.48, "", 8.5, dark, "L")
|
||||
if dp.ClabeInternacional != "" {
|
||||
c.drawSingleLine("CLABE: "+dp.ClabeInternacional, c.L+c.W*0.5, y+18, c.W*0.48, "", 8.5, dark, "L")
|
||||
}
|
||||
c.drawSingleLine("Banco: BBVA México", c.L+8, y+30, c.W*0.48, "", 8.5, dark, "L")
|
||||
if dp.Swift != "" {
|
||||
c.drawSingleLine("SWIFT: "+dp.Swift, c.L+c.W*0.5, y+30, c.W*0.48, "", 8.5, dark, "L")
|
||||
}
|
||||
y += boxH + 8
|
||||
}
|
||||
}
|
||||
|
||||
// ── PIE ───────────────────────────────────────
|
||||
y = c.need(30, y) + 14
|
||||
c.drawText(
|
||||
"Documento generado desde el Cotizador. Conteo de horas trabajadas para cobro del proyecto.",
|
||||
c.L, y, c.W, "", 8, muted, "C",
|
||||
)
|
||||
|
||||
return c.bytes()
|
||||
}
|
||||
@@ -0,0 +1,454 @@
|
||||
package pdf
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/HugoSmits86/nativewebp"
|
||||
"golang.org/x/image/font/gofont/goregular"
|
||||
"golang.org/x/image/font/sfnt"
|
||||
|
||||
"cotizador/internal/domain"
|
||||
)
|
||||
|
||||
func f64(v float64) *float64 { return &v }
|
||||
func str(v string) *string { return &v }
|
||||
|
||||
func makeTestImage() image.Image {
|
||||
img := image.NewNRGBA(image.Rect(0, 0, 32, 16))
|
||||
for y := 0; y < 16; y++ {
|
||||
for x := 0; x < 32; x++ {
|
||||
img.Set(x, y, color.NRGBA{R: 4, G: 0, B: 196, A: 255})
|
||||
}
|
||||
}
|
||||
return img
|
||||
}
|
||||
|
||||
func makePNGLogoB64(t *testing.T) string {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, makeTestImage()); err != nil {
|
||||
t.Fatalf("png encode: %v", err)
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(buf.Bytes())
|
||||
}
|
||||
|
||||
func makeJPEGLogoB64(t *testing.T) string {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
if err := jpeg.Encode(&buf, makeTestImage(), &jpeg.Options{Quality: 85}); err != nil {
|
||||
t.Fatalf("jpeg encode: %v", err)
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(buf.Bytes())
|
||||
}
|
||||
|
||||
func makeWebPLogoB64(t *testing.T) string {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
if err := nativewebp.Encode(&buf, makeTestImage(), nil); err != nil {
|
||||
t.Fatalf("webp encode: %v", err)
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(buf.Bytes())
|
||||
}
|
||||
|
||||
func assertValidPDF(t *testing.T, b []byte, minPages int) {
|
||||
t.Helper()
|
||||
if len(b) < 500 {
|
||||
t.Fatalf("PDF too small: %d bytes", len(b))
|
||||
}
|
||||
if !bytes.HasPrefix(b, []byte("%PDF-")) {
|
||||
t.Fatalf("missing %%PDF- header: %q", b[:min(20, len(b))])
|
||||
}
|
||||
if !bytes.Contains(b, []byte("%%EOF")) {
|
||||
t.Fatalf("missing %%%%EOF trailer")
|
||||
}
|
||||
pages := bytes.Count(b, []byte("/Type /Page\n")) + bytes.Count(b, []byte("/Type /Page ")) + bytes.Count(b, []byte("/Type /Page/"))
|
||||
if pages < minPages {
|
||||
t.Fatalf("expected at least %d pages, counted %d", minPages, pages)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoFontGlyphCoverage(t *testing.T) {
|
||||
f, err := sfnt.Parse(goregular.TTF)
|
||||
if err != nil {
|
||||
t.Fatalf("parse goregular: %v", err)
|
||||
}
|
||||
var buf sfnt.Buffer
|
||||
const chars = "áéíóúüñÁÉÍÓÚÜÑ¿¡•·—×○$€%"
|
||||
for _, r := range chars {
|
||||
idx, err := f.GlyphIndex(&buf, r)
|
||||
if err != nil || idx == 0 {
|
||||
t.Errorf("goregular missing glyph for %q (U+%04X)", r, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCotizacionPDFDataHasNoObservacionesInternas(t *testing.T) {
|
||||
rt := reflect.TypeOf(CotizacionPDFData{})
|
||||
for i := 0; i < rt.NumField(); i++ {
|
||||
name := strings.ToLower(rt.Field(i).Name)
|
||||
if strings.Contains(name, "interna") {
|
||||
t.Fatalf("CotizacionPDFData must never declare internal observations field, found %q", rt.Field(i).Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateCotizacionPDFSingleAndLogos(t *testing.T) {
|
||||
fecha := time.Date(2026, 5, 10, 12, 0, 0, 0, time.UTC)
|
||||
vigencia := domain.CalcularVigencia(fecha)
|
||||
obs := "Primer párrafo con acentos: diseño, campaña y año.\n\n" + strings.Repeat("Observación extendida para probar el salto de línea automático en el PDF. ", 15)
|
||||
|
||||
baseData := CotizacionPDFData{
|
||||
Numero: "UJ2605UR001",
|
||||
ClienteNombre: "María José Peña",
|
||||
ClienteEmpresa: "Industrias del Bajío S.A.",
|
||||
AsesorNombre: "Uriel Jareth",
|
||||
Fecha: fecha,
|
||||
Vigencia: vigencia,
|
||||
Moneda: "MXN",
|
||||
TipoCambio: "N/A",
|
||||
Proyecto: "Rediseño Web y Campaña de Adquisición",
|
||||
EsquemaPago: "50% anticipo, 50% entrega",
|
||||
Servicios: []ServicioPDF{
|
||||
{
|
||||
Nombre: "Auditoría SEO y Técnica",
|
||||
Fase: 0,
|
||||
TipoPago: "unico",
|
||||
Precio: 8500,
|
||||
TiempoEntrega: "7 días",
|
||||
Entregables: []string{"Reporte técnico", "Mapa de palabras clave", "Plan de acción"},
|
||||
ModeloCobro: "fijo",
|
||||
},
|
||||
{
|
||||
Nombre: "Desarrollo a la medida",
|
||||
Fase: 1,
|
||||
TipoPago: "unico",
|
||||
Precio: 14000,
|
||||
TiempoEntrega: "15 días",
|
||||
Entregables: []string{"Arquitectura", "Implementación", "Pruebas QA"},
|
||||
ModeloCobro: "horas",
|
||||
EsPersonalizado: true,
|
||||
Horas: f64(20),
|
||||
TarifaHora: f64(700),
|
||||
},
|
||||
{
|
||||
Nombre: "Soporte Mensual Retainer",
|
||||
Fase: 2,
|
||||
TipoPago: "mensual",
|
||||
Precio: 7500,
|
||||
TiempoEntrega: "Mensual",
|
||||
Entregables: []string{"Monitoreo continuo", "Actualizaciones de seguridad"},
|
||||
ModeloCobro: "retainer",
|
||||
MontoMinimo: f64(7500),
|
||||
HorasIncluidas: f64(10),
|
||||
TarifaHora: f64(700),
|
||||
},
|
||||
{
|
||||
Nombre: "Horas Centinela bajo demanda",
|
||||
Fase: 3,
|
||||
TipoPago: "mensual",
|
||||
Precio: 0,
|
||||
TiempoEntrega: "Según consumo",
|
||||
ModeloCobro: "demanda",
|
||||
TarifaHora: f64(700),
|
||||
},
|
||||
},
|
||||
PlanBucefaloNivel: str("estandar"),
|
||||
PlanBucefaloPrecio: 3500,
|
||||
IncluirBonos: true,
|
||||
Bonos: []BonoPDF{
|
||||
{Numero: 1, Descripcion: "Workshop estratégico de diseño"},
|
||||
{Numero: 2, Descripcion: "Un mes gratis de Bucéfalo CRM"},
|
||||
},
|
||||
IncluirIVA: true,
|
||||
Observaciones: &obs,
|
||||
ConfigBancaria: map[string]string{
|
||||
"razon_social": "URIEL JARETH ALVARADO ORTIZ",
|
||||
"rfc": "AAOU970201SU7",
|
||||
"cuenta_nacional": "0123456789",
|
||||
"clabe_interbancaria": "012180001234567890",
|
||||
"cuenta_internacional_swift": "CLABE: 012180001234567890 SWIFT: BCMRMXMMPYM",
|
||||
},
|
||||
ColorPrimario: "#0400C4",
|
||||
ColorSecundario: "#0F172A",
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
b64 string
|
||||
mime string
|
||||
}{
|
||||
{"no_logo", "", ""},
|
||||
{"png_logo", makePNGLogoB64(t), "image/png"},
|
||||
{"jpeg_logo", makeJPEGLogoB64(t), "image/jpeg"},
|
||||
{"webp_logo", makeWebPLogoB64(t), "image/webp"},
|
||||
{"data_uri_png", "data:image/png;base64," + makePNGLogoB64(t), ""},
|
||||
{"corrupt_logo_fallback", "not-valid-base64!!!", "image/png"},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
d := baseData
|
||||
d.LogoBase64 = tc.b64
|
||||
d.LogoMime = tc.mime
|
||||
out, err := GenerateCotizacionPDF(d)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateCotizacionPDF(%s) error: %v", tc.name, err)
|
||||
}
|
||||
// Cover + Resumen + T&C = at least 3 pages
|
||||
assertValidPDF(t, out, 3)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateCotizacionPDFDoblePropuesta(t *testing.T) {
|
||||
fecha := time.Date(2026, 6, 1, 12, 0, 0, 0, time.UTC)
|
||||
d := CotizacionPDFData{
|
||||
Numero: "UJ2606UR002",
|
||||
ClienteNombre: "Carlos Núñez",
|
||||
ClienteEmpresa: "Núñez Logistics",
|
||||
AsesorNombre: "Uriel Jareth",
|
||||
Fecha: fecha,
|
||||
Vigencia: domain.CalcularVigencia(fecha),
|
||||
Moneda: "MXN",
|
||||
Proyecto: "Transformación Digital",
|
||||
EsquemaPago: "Mensual",
|
||||
EsDoble: true,
|
||||
IncluirIVA: true,
|
||||
IncluirBonos: true, // exercises fallback bonos
|
||||
OpcionesMetadata: map[string]domain.MetaOpcion{
|
||||
"1": {Titulo: "Esencial", Descripcion: "Arranque rápido con foco en captación.", NoIncluye: "Producción de video"},
|
||||
"2": {Titulo: "Crecimiento", Descripcion: "Estrategia integral con automatización.", NoIncluye: "Pauta publicitaria"},
|
||||
},
|
||||
Servicios: []ServicioPDF{
|
||||
{Nombre: "Auditoría inicial", Fase: 0, TipoPago: "unico", Precio: 5000, TiempoEntrega: "5 días", Opcion: str("ambas"), Horas: f64(6)},
|
||||
{Nombre: "Landing Page", Fase: 1, TipoPago: "unico", Precio: 12000, TiempoEntrega: "15 días", Opcion: str("1"), Horas: f64(15)},
|
||||
{Nombre: "Sitio Web Completo", Fase: 1, TipoPago: "unico", Precio: 28000, TiempoEntrega: "30 días", Opcion: str("2"), Horas: f64(35)},
|
||||
{Nombre: "Gestión Ads", Fase: 2, TipoPago: "mensual", Precio: 8000, TiempoEntrega: "Mensual", Opcion: str("ambas")},
|
||||
},
|
||||
ColorPrimario: "not-a-hex",
|
||||
ColorSecundario: "",
|
||||
}
|
||||
|
||||
out, err := GenerateCotizacionPDF(d)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateCotizacionPDF doble error: %v", err)
|
||||
}
|
||||
assertValidPDF(t, out, 3)
|
||||
}
|
||||
|
||||
func TestGenerateNotaHorasPDFAllModes(t *testing.T) {
|
||||
base := time.Date(2026, 5, 1, 12, 0, 0, 0, time.UTC)
|
||||
var regs []RegistroHoraPDF
|
||||
for i := 0; i < 35; i++ {
|
||||
estado := "por_pagar"
|
||||
if i%3 == 0 {
|
||||
estado = "pagada"
|
||||
}
|
||||
regs = append(regs, RegistroHoraPDF{
|
||||
Fecha: base.AddDate(0, 0, i*2),
|
||||
HoraInicio: "09:00",
|
||||
HoraFin: "11:30",
|
||||
Horas: 2.5,
|
||||
TarifaHora: 700,
|
||||
Descripcion: "Optimización de campaña y diseño de pruebas A/B con revisión de métricas",
|
||||
EstadoPago: estado,
|
||||
})
|
||||
}
|
||||
|
||||
for _, modo := range []string{"detalle", "dia", "semana", "mes"} {
|
||||
t.Run(modo, func(t *testing.T) {
|
||||
out, err := GenerateNotaHorasPDF(NotaHorasPDFData{
|
||||
Titulo: "Nota de horas por pagar",
|
||||
Numero: "UJ2605UR001",
|
||||
ClienteNombre: "Ana Gómez",
|
||||
ClienteEmpresa: "Gómez Tech",
|
||||
Proyecto: "Soporte Continuo",
|
||||
AsesorNombre: "Uriel Jareth",
|
||||
Moneda: "MXN",
|
||||
IncluirIVA: true,
|
||||
Modo: modo,
|
||||
MostrarEstado: modo == "detalle",
|
||||
MostrarBancarios: true,
|
||||
Registros: regs,
|
||||
ConfigBancaria: map[string]string{
|
||||
"cuenta_nacional": "0123456789",
|
||||
"clabe_interbancaria": "012180001234567890",
|
||||
"cuenta_internacional_swift": "CLABE: 012180001234567890 SWIFT: BCMRMXMMPYM",
|
||||
},
|
||||
LogoBase64: makeWebPLogoB64(t),
|
||||
LogoMime: "image/webp",
|
||||
FechaEmision: time.Date(2026, 7, 15, 12, 0, 0, 0, time.UTC),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateNotaHorasPDF(%s) error: %v", modo, err)
|
||||
}
|
||||
minPages := 1
|
||||
if modo == "detalle" {
|
||||
minPages = 2
|
||||
}
|
||||
assertValidPDF(t, out, minPages)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerarPropuestaYAnexoInternoPDF(t *testing.T) {
|
||||
contenido := map[string]any{
|
||||
"hechos": map[string]any{
|
||||
"citas": []map[string]any{
|
||||
{"id": "C01", "textoLiteral": "Perdemos cotizaciones porque tardamos días en responder por WhatsApp.", "quienLoDijo": "el director comercial"},
|
||||
},
|
||||
"materialesPendientes": []map[string]any{
|
||||
{"texto": "Accesos a Google Ads y Meta Business", "bloqueaEntrega": true},
|
||||
},
|
||||
"decisionesPendientes": []map[string]any{
|
||||
{"texto": "Definir presupuesto mensual de pauta", "quienDecide": "Dirección General"},
|
||||
},
|
||||
"mencionesFueraDeAlcance": []string{"Producción de video corporativo"},
|
||||
"redFlags": []map[string]any{
|
||||
{"senal": "El cliente espera resultados en 48 horas", "severidad": "alta"},
|
||||
},
|
||||
},
|
||||
"diagnostico": map[string]any{
|
||||
"hallazgos": []map[string]any{
|
||||
{"id": "D01", "urgencia": "rojo", "titulo": "Fuga de leads", "descripcion": "No hay seguimiento estructurado en CRM.", "confianza": "confirmado"},
|
||||
{"id": "D02", "urgencia": "ambar", "titulo": "Sitio lento", "descripcion": "Tiempo de carga superior a 6 segundos.", "confianza": "estimado"},
|
||||
{"id": "D03", "urgencia": "verde", "titulo": "Buena reputación", "descripcion": "Reseñas de 4.9 estrellas en Google.", "confianza": "confirmado"},
|
||||
},
|
||||
"valorProblema": map[string]any{
|
||||
"dimensiones": []map[string]any{
|
||||
{
|
||||
"tipo": "dinero",
|
||||
"descripcion": "Leads perdidos por falta de seguimiento oportuno",
|
||||
"montoAnualMXN": 480000.0,
|
||||
"confianza": "estimado",
|
||||
"factores": []map[string]any{
|
||||
{"nombre": "leads_perdidos_mes", "valor": 8.0, "confianza": "estimado"},
|
||||
{"nombre": "ticket_promedio", "valor": 5000.0, "confianza": "estimado"},
|
||||
},
|
||||
},
|
||||
},
|
||||
"notaMetodologia": "Cálculo conservador basado en promedio de los últimos 6 meses.",
|
||||
},
|
||||
"resultados": []map[string]any{
|
||||
{"enunciado": "Responder a cada prospecto en menos de 5 minutos", "metrica": "Tiempo de primera respuesta", "periodoMedicion": "60 días"},
|
||||
},
|
||||
},
|
||||
"redaccion": map[string]any{
|
||||
"hero": map[string]any{
|
||||
"titulo": "Sistema de Captación y Seguimiento Comercial",
|
||||
"subtitulo": "Propuesta diseñada para eliminar fugas de prospectos y multiplicar conversiones.",
|
||||
},
|
||||
"citaDestacadaId": "C01",
|
||||
"alcance": []map[string]any{
|
||||
{"refPartida": "P01", "descripcionResultado": "Diagnóstico completo para detectar cuellos de botella en captación."},
|
||||
},
|
||||
"beneficios": []map[string]any{
|
||||
{"etiqueta": "Cero leads perdidos", "texto": "Cada consulta entra automáticamente al embudo con recordatorios.", "hallazgoId": "D01"},
|
||||
},
|
||||
"exclusiones": []map[string]any{
|
||||
{"texto": "No incluye inversión en pauta publicitaria de Meta o Google.", "razon": "El cliente paga directo a la plataforma"},
|
||||
},
|
||||
"backlogEvolucion": []map[string]any{
|
||||
{"problema": "Integración con ERP contable", "momentoSugerido": "Trimestre 2"},
|
||||
},
|
||||
"notasInternas": []string{"NO_ENVIAR_SECRETO_ASESOR: negociar alcance antes de dar descuento"},
|
||||
},
|
||||
}
|
||||
|
||||
economia := map[string]any{
|
||||
"partidas": []map[string]any{
|
||||
{"refPartida": "P01", "nombre": "Auditoría Comercial", "fase": 0, "tipoPago": "unico", "precio": 8000.0, "tiempoEntrega": "7 días", "entregables": []string{"Mapa de embudo"}},
|
||||
{"refPartida": "P02", "nombre": "Implementación CRM", "fase": 1, "tipoPago": "unico", "precio": 22000.0, "tiempoEntrega": "15 días", "entregables": []string{"Flujos", "Capacitación"}},
|
||||
},
|
||||
"planBucefalo": map[string]any{"nivel": "estandar", "precio": 3500.0},
|
||||
"totales": map[string]any{
|
||||
"subtotalUnico": 30000.0,
|
||||
"subtotalMensual": 3500.0,
|
||||
"ivaUnico": 4800.0,
|
||||
"ivaMensual": 560.0,
|
||||
"totalUnico": 34800.0,
|
||||
"totalMensual": 4060.0,
|
||||
"totalPrimerAnio": 83520.0,
|
||||
"incluyeIva": true,
|
||||
},
|
||||
"moneda": "MXN",
|
||||
"asesor": "Uriel Jareth",
|
||||
}
|
||||
|
||||
in := PropuestaPDFInput{
|
||||
CotizacionNumero: "UJ2606UR010",
|
||||
ClienteNombre: "Roberto Peña",
|
||||
ClienteEmpresa: "Peña Industrial",
|
||||
Proyecto: "CRM y Captación",
|
||||
Moneda: "MXN",
|
||||
Fecha: time.Date(2026, 6, 10, 12, 0, 0, 0, time.UTC),
|
||||
Contenido: contenido,
|
||||
Economia: economia,
|
||||
ColorPrimario: "#0400C4",
|
||||
ColorSecundario: "#0F172A",
|
||||
LogoBase64: makePNGLogoB64(t),
|
||||
LogoMime: "image/png",
|
||||
}
|
||||
|
||||
propPDF, err := GenerarPropuestaPDF(in)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerarPropuestaPDF error: %v", err)
|
||||
}
|
||||
assertValidPDF(t, propPDF, 1)
|
||||
|
||||
anexoPDF, err := GenerarAnexoInternoPDF(in)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerarAnexoInternoPDF error: %v", err)
|
||||
}
|
||||
assertValidPDF(t, anexoPDF, 1)
|
||||
|
||||
// Empty maps should also succeed safely.
|
||||
emptyIn := PropuestaPDFInput{
|
||||
CotizacionNumero: "UJ2606UR011",
|
||||
ClienteNombre: "Cliente Vacío",
|
||||
Proyecto: "Proyecto Mínimo",
|
||||
}
|
||||
if out, err := GenerarPropuestaPDF(emptyIn); err != nil {
|
||||
t.Fatalf("empty GenerarPropuestaPDF error: %v", err)
|
||||
} else {
|
||||
assertValidPDF(t, out, 1)
|
||||
}
|
||||
if out, err := GenerarAnexoInternoPDF(emptyIn); err != nil {
|
||||
t.Fatalf("empty GenerarAnexoInternoPDF error: %v", err)
|
||||
} else {
|
||||
assertValidPDF(t, out, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCalcularRatioPropuesta(t *testing.T) {
|
||||
if r := calcularRatioPropuesta(10000, nil); r != nil {
|
||||
t.Fatalf("expected nil for nil valorAnual")
|
||||
}
|
||||
if r := calcularRatioPropuesta(10000, f64(0)); r != nil {
|
||||
t.Fatalf("expected nil for zero valorAnual")
|
||||
}
|
||||
cases := []struct {
|
||||
total, valor float64
|
||||
want string
|
||||
}{
|
||||
{5000, 100000, "subcotizado"},
|
||||
{20000, 100000, "en_rango"},
|
||||
{35000, 100000, "alto"},
|
||||
{50000, 100000, "objecion_probable"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
r := calcularRatioPropuesta(tc.total, f64(tc.valor))
|
||||
if r == nil || r.Lectura != tc.want {
|
||||
t.Fatalf("calcularRatioPropuesta(%v,%v) = %+v, want %q", tc.total, tc.valor, r, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,739 @@
|
||||
package pdf
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/domain"
|
||||
)
|
||||
|
||||
type PropuestaPDFInput struct {
|
||||
CotizacionNumero string
|
||||
ClienteNombre string
|
||||
ClienteEmpresa string
|
||||
Proyecto string
|
||||
Moneda string
|
||||
Fecha time.Time
|
||||
Contenido map[string]any
|
||||
Economia map[string]any
|
||||
ColorPrimario string
|
||||
ColorSecundario string
|
||||
LogoBase64 string
|
||||
LogoMime string
|
||||
}
|
||||
|
||||
// Internal typed shapes mirroring src/lib/propuesta/schemas.ts and economia.ts.
|
||||
type propuestaContenido struct {
|
||||
Hechos struct {
|
||||
Citas []struct {
|
||||
ID string `json:"id"`
|
||||
TextoLiteral string `json:"textoLiteral"`
|
||||
QuienLoDijo string `json:"quienLoDijo"`
|
||||
} `json:"citas"`
|
||||
MaterialesPendientes []struct {
|
||||
Texto string `json:"texto"`
|
||||
BloqueaEntrega bool `json:"bloqueaEntrega"`
|
||||
} `json:"materialesPendientes"`
|
||||
DecisionesPendientes []struct {
|
||||
Texto string `json:"texto"`
|
||||
QuienDecide string `json:"quienDecide"`
|
||||
} `json:"decisionesPendientes"`
|
||||
MencionesFueraDeAlcance []string `json:"mencionesFueraDeAlcance"`
|
||||
RedFlags []struct {
|
||||
Senal string `json:"senal"`
|
||||
Severidad string `json:"severidad"`
|
||||
} `json:"redFlags"`
|
||||
} `json:"hechos"`
|
||||
Diagnostico struct {
|
||||
Hallazgos []struct {
|
||||
ID string `json:"id"`
|
||||
Urgencia string `json:"urgencia"`
|
||||
Titulo string `json:"titulo"`
|
||||
Descripcion string `json:"descripcion"`
|
||||
Confianza string `json:"confianza"`
|
||||
} `json:"hallazgos"`
|
||||
ValorProblema struct {
|
||||
Dimensiones []struct {
|
||||
Tipo string `json:"tipo"`
|
||||
Descripcion string `json:"descripcion"`
|
||||
Factores []struct {
|
||||
Nombre string `json:"nombre"`
|
||||
Valor float64 `json:"valor"`
|
||||
Confianza string `json:"confianza"`
|
||||
} `json:"factores"`
|
||||
MontoAnualMXN *float64 `json:"montoAnualMXN"`
|
||||
Confianza string `json:"confianza"`
|
||||
} `json:"dimensiones"`
|
||||
NotaMetodologia string `json:"notaMetodologia"`
|
||||
} `json:"valorProblema"`
|
||||
Resultados []struct {
|
||||
Enunciado string `json:"enunciado"`
|
||||
Metrica string `json:"metrica"`
|
||||
LineaBase *string `json:"lineaBase"`
|
||||
PeriodoMedicion string `json:"periodoMedicion"`
|
||||
} `json:"resultados"`
|
||||
} `json:"diagnostico"`
|
||||
Redaccion struct {
|
||||
Hero struct {
|
||||
Titulo string `json:"titulo"`
|
||||
Subtitulo string `json:"subtitulo"`
|
||||
} `json:"hero"`
|
||||
CitaDestacadaID string `json:"citaDestacadaId"`
|
||||
Alcance []struct {
|
||||
RefPartida string `json:"refPartida"`
|
||||
DescripcionResultado string `json:"descripcionResultado"`
|
||||
} `json:"alcance"`
|
||||
Beneficios []struct {
|
||||
Etiqueta string `json:"etiqueta"`
|
||||
Texto string `json:"texto"`
|
||||
HallazgoID string `json:"hallazgoId"`
|
||||
} `json:"beneficios"`
|
||||
Exclusiones []struct {
|
||||
Texto string `json:"texto"`
|
||||
Razon string `json:"razon"`
|
||||
} `json:"exclusiones"`
|
||||
BacklogEvolucion []struct {
|
||||
Problema string `json:"problema"`
|
||||
MomentoSugerido string `json:"momentoSugerido"`
|
||||
} `json:"backlogEvolucion"`
|
||||
NotasInternas []string `json:"notasInternas"`
|
||||
} `json:"redaccion"`
|
||||
}
|
||||
|
||||
type propuestaPartida struct {
|
||||
RefPartida string `json:"refPartida"`
|
||||
Nombre string `json:"nombre"`
|
||||
Fase int `json:"fase"`
|
||||
TipoPago string `json:"tipoPago"`
|
||||
Precio float64 `json:"precio"`
|
||||
TiempoEntrega string `json:"tiempoEntrega"`
|
||||
ModeloCobro string `json:"modeloCobro"`
|
||||
Entregables []string `json:"entregables"`
|
||||
}
|
||||
|
||||
type propuestaEconomia struct {
|
||||
Partidas []propuestaPartida `json:"partidas"`
|
||||
Totales 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"`
|
||||
} `json:"totales"`
|
||||
Moneda string `json:"moneda"`
|
||||
Asesor string `json:"asesor"`
|
||||
PlanBucefalo *struct {
|
||||
Nivel string `json:"nivel"`
|
||||
Precio float64 `json:"precio"`
|
||||
} `json:"planBucefalo"`
|
||||
}
|
||||
|
||||
func decodeMapInto[T any](src map[string]any) T {
|
||||
var out T
|
||||
if len(src) == 0 {
|
||||
return out
|
||||
}
|
||||
b, err := json.Marshal(src)
|
||||
if err != nil {
|
||||
return out
|
||||
}
|
||||
_ = json.Unmarshal(b, &out)
|
||||
return out
|
||||
}
|
||||
|
||||
var (
|
||||
colorSemaforo = map[string]string{
|
||||
"rojo": "#dc2626",
|
||||
"ambar": "#d97706",
|
||||
"azul": "#0400C4",
|
||||
"verde": "#16a34a",
|
||||
}
|
||||
etiquetaSemaforo = map[string]string{
|
||||
"rojo": "Problema crítico",
|
||||
"ambar": "Área de mejora",
|
||||
"azul": "Oportunidad",
|
||||
"verde": "Ventaja existente",
|
||||
}
|
||||
etiquetaConfianza = map[string]string{
|
||||
"confirmado": "Confirmado",
|
||||
"estimado": "Estimado",
|
||||
"por_validar": "Por validar",
|
||||
}
|
||||
)
|
||||
|
||||
func detalleDePartida(p propuestaPartida) string {
|
||||
var trozos []string
|
||||
if len(p.Entregables) > 0 {
|
||||
limit := len(p.Entregables)
|
||||
if limit > 4 {
|
||||
limit = 4
|
||||
}
|
||||
trozos = append(trozos, strings.Join(p.Entregables[:limit], " · "))
|
||||
}
|
||||
if strings.TrimSpace(p.TiempoEntrega) != "" {
|
||||
trozos = append(trozos, "Entrega: "+p.TiempoEntrega)
|
||||
}
|
||||
if p.TipoPago == "mensual" {
|
||||
trozos = append(trozos, "Servicio mensual")
|
||||
}
|
||||
return strings.Join(trozos, " | ")
|
||||
}
|
||||
|
||||
type ratioResult struct {
|
||||
Ratio float64
|
||||
Lectura string
|
||||
}
|
||||
|
||||
func calcularRatioPropuesta(totalPrimerAnio float64, valorAnual *float64) *ratioResult {
|
||||
if valorAnual == nil || *valorAnual <= 0 {
|
||||
return nil
|
||||
}
|
||||
ratio := totalPrimerAnio / *valorAnual
|
||||
lectura := "objecion_probable"
|
||||
switch {
|
||||
case ratio < 0.1:
|
||||
lectura = "subcotizado"
|
||||
case ratio <= 0.25:
|
||||
lectura = "en_rango"
|
||||
case ratio <= 0.4:
|
||||
lectura = "alto"
|
||||
}
|
||||
return &ratioResult{
|
||||
Ratio: math.Round(ratio*1000) / 1000,
|
||||
Lectura: lectura,
|
||||
}
|
||||
}
|
||||
|
||||
func GenerarPropuestaPDF(in PropuestaPDFInput) ([]byte, error) {
|
||||
primary := safeHex(in.ColorPrimario, defaultPrimary)
|
||||
dark := safeHex(in.ColorSecundario, defaultDark)
|
||||
muted := colorMuted
|
||||
border := "#e2e8f0"
|
||||
|
||||
prop := decodeMapInto[propuestaContenido](in.Contenido)
|
||||
econ := decodeMapInto[propuestaEconomia](in.Economia)
|
||||
|
||||
moneda := in.Moneda
|
||||
if moneda == "" {
|
||||
moneda = econ.Moneda
|
||||
}
|
||||
fmtMoney := func(n float64) string {
|
||||
return formatMoney(n, moneda)
|
||||
}
|
||||
|
||||
fecha := in.Fecha
|
||||
if fecha.IsZero() {
|
||||
fecha = time.Now()
|
||||
}
|
||||
vigencia := domain.CalcularVigencia(fecha)
|
||||
clienteDisplay := in.ClienteEmpresa
|
||||
if strings.TrimSpace(clienteDisplay) == "" {
|
||||
clienteDisplay = in.ClienteNombre
|
||||
}
|
||||
|
||||
c := newCanvas(50, 55, 50, 50)
|
||||
c.doc.AliasNbPages("{nb}")
|
||||
logo := registerLogo(c.doc, "prop_logo", in.LogoBase64, in.LogoMime)
|
||||
|
||||
c.doc.SetFooterFunc(func() {
|
||||
c.hLine(c.L, c.L+c.W, c.ph-42, border, 0.5)
|
||||
leftTxt := fmt.Sprintf("%s · Propuesta consultiva · %s", in.CotizacionNumero, clienteDisplay)
|
||||
c.drawSingleLine(leftTxt, c.L, c.ph-35, c.W-60, "", 7, muted, "L")
|
||||
rightTxt := fmt.Sprintf("%d / {nb}", c.doc.PageNo())
|
||||
c.drawSingleLine(rightTxt, c.L, c.ph-35, c.W, "", 7, muted, "R")
|
||||
})
|
||||
|
||||
c.doc.AddPage()
|
||||
y := c.mTop
|
||||
|
||||
titulo := func(t string) {
|
||||
y = c.need(26, y)
|
||||
c.rectFill(c.L, y+1, 3, 10, primary)
|
||||
c.drawSingleLine(strings.ToUpper(t), c.L+10, y, c.W-10, "B", 10, dark, "L")
|
||||
y += 20
|
||||
}
|
||||
parrafo := func(t string, size float64, color string) {
|
||||
raw := strings.ReplaceAll(t, "\r\n", "\n")
|
||||
for _, p := range strings.Split(raw, "\n") {
|
||||
p = strings.TrimSpace(p)
|
||||
if p == "" {
|
||||
continue
|
||||
}
|
||||
h := c.textHeight(p, c.W, "", size)
|
||||
y = c.need(h+4, y)
|
||||
c.drawText(p, c.L, y, c.W, "", size, color, "L")
|
||||
y += h + 4
|
||||
}
|
||||
}
|
||||
|
||||
// ── HERO ──
|
||||
if logo.ok {
|
||||
logo.drawByHeight(c.doc, c.L, y, 26)
|
||||
y += 34
|
||||
}
|
||||
c.drawSingleLine("PROPUESTA CONSULTIVA", c.L, y, c.W, "B", 8.5, primary, "L")
|
||||
y += 16
|
||||
|
||||
heroTit := strings.TrimSpace(prop.Redaccion.Hero.Titulo)
|
||||
if heroTit == "" {
|
||||
heroTit = in.Proyecto
|
||||
}
|
||||
if heroTit != "" {
|
||||
hTit := c.drawText(heroTit, c.L, y, c.W, "B", 20, dark, "L")
|
||||
y += hTit + 8
|
||||
}
|
||||
if strings.TrimSpace(prop.Redaccion.Hero.Subtitulo) != "" {
|
||||
parrafo(prop.Redaccion.Hero.Subtitulo, 10, muted)
|
||||
y += 8
|
||||
}
|
||||
|
||||
metaParts := []string{
|
||||
clienteDisplay,
|
||||
in.CotizacionNumero,
|
||||
domain.FormatDateShort(fecha),
|
||||
"Vigencia " + domain.FormatDateShort(vigencia),
|
||||
}
|
||||
if strings.TrimSpace(econ.Asesor) != "" {
|
||||
metaParts = append(metaParts, econ.Asesor)
|
||||
}
|
||||
meta := strings.Join(metaParts, " · ")
|
||||
hMeta := c.drawText(meta, c.L, y, c.W, "", 8, muted, "L")
|
||||
y += hMeta + 12
|
||||
c.hLine(c.L, c.L+c.W, y, border, 0.5)
|
||||
y += 18
|
||||
|
||||
// ── DIAGNÓSTICO ──
|
||||
if len(prop.Diagnostico.Hallazgos) > 0 || prop.Redaccion.CitaDestacadaID != "" {
|
||||
titulo("Diagnóstico")
|
||||
for _, cita := range prop.Hechos.Citas {
|
||||
if cita.ID != "" && cita.ID == prop.Redaccion.CitaDestacadaID {
|
||||
texto := fmt.Sprintf("\"%s\"", cita.TextoLiteral)
|
||||
h := c.textHeight(texto, c.W-22, "I", 11)
|
||||
y = c.need(h+22, y)
|
||||
c.rectFill(c.L, y-3, 2.5, h+10, primary)
|
||||
c.drawText(texto, c.L+12, y, c.W-22, "I", 11, dark, "L")
|
||||
y += h + 4
|
||||
c.drawSingleLine("— "+cita.QuienLoDijo, c.L+12, y, c.W-22, "", 7.5, muted, "L")
|
||||
y += 18
|
||||
break
|
||||
}
|
||||
}
|
||||
for _, hal := range prop.Diagnostico.Hallazgos {
|
||||
cuerpo := fmt.Sprintf("%s — %s", hal.Titulo, hal.Descripcion)
|
||||
h := c.textHeight(cuerpo, c.W-24, "", 9)
|
||||
y = c.need(h+16, y)
|
||||
dotColor := colorSemaforo[hal.Urgencia]
|
||||
if dotColor == "" {
|
||||
dotColor = muted
|
||||
}
|
||||
c.circleFill(c.L+4.5, y+5, 3.2, dotColor)
|
||||
c.drawText(cuerpo, c.L+16, y, c.W-24, "", 9, dark, "L")
|
||||
y += h + 1
|
||||
subLbl := fmt.Sprintf("%s · %s", etiquetaSemaforo[hal.Urgencia], etiquetaConfianza[hal.Confianza])
|
||||
c.drawSingleLine(subLbl, c.L+16, y, c.W-24, "", 7, muted, "L")
|
||||
y += 13
|
||||
}
|
||||
y += 8
|
||||
}
|
||||
|
||||
// ── VALOR DEL PROBLEMA ──
|
||||
dims := prop.Diagnostico.ValorProblema.Dimensiones
|
||||
if len(dims) > 0 {
|
||||
titulo("Lo que cuesta no resolverlo")
|
||||
for _, dim := range dims {
|
||||
montoTxt := "sin cuantificar"
|
||||
if dim.MontoAnualMXN != nil {
|
||||
montoTxt = fmt.Sprintf("%s al año", fmtMoney(*dim.MontoAnualMXN))
|
||||
}
|
||||
linea := fmt.Sprintf("%s — %s", dim.Descripcion, montoTxt)
|
||||
h := c.textHeight(linea, c.W-14, "", 9)
|
||||
y = c.need(h+14, y)
|
||||
c.drawText(linea, c.L+6, y, c.W-14, "", 9, dark, "L")
|
||||
y += h + 1
|
||||
c.drawSingleLine(etiquetaConfianza[dim.Confianza], c.L+6, y, c.W-14, "", 7, muted, "L")
|
||||
y += 13
|
||||
}
|
||||
if strings.TrimSpace(prop.Diagnostico.ValorProblema.NotaMetodologia) != "" {
|
||||
y += 2
|
||||
parrafo(prop.Diagnostico.ValorProblema.NotaMetodologia, 8, muted)
|
||||
}
|
||||
y += 8
|
||||
}
|
||||
|
||||
// ── RESULTADOS ──
|
||||
if len(prop.Diagnostico.Resultados) > 0 {
|
||||
titulo("Resultados a lograr")
|
||||
for _, r := range prop.Diagnostico.Resultados {
|
||||
t := fmt.Sprintf("• %s (%s, %s)", r.Enunciado, r.Metrica, r.PeriodoMedicion)
|
||||
h := c.textHeight(t, c.W-8, "", 9)
|
||||
y = c.need(h+6, y)
|
||||
c.drawText(t, c.L+4, y, c.W-8, "", 9, dark, "L")
|
||||
y += h + 6
|
||||
}
|
||||
y += 8
|
||||
}
|
||||
|
||||
// ── ALCANCE ──
|
||||
titulo("Alcance de la inversión")
|
||||
descPorRef := make(map[string]string, len(prop.Redaccion.Alcance))
|
||||
for _, a := range prop.Redaccion.Alcance {
|
||||
descPorRef[a.RefPartida] = a.DescripcionResultado
|
||||
}
|
||||
for _, p := range econ.Partidas {
|
||||
descripcion := descPorRef[p.RefPartida]
|
||||
respaldo := ""
|
||||
if descripcion == "" {
|
||||
respaldo = detalleDePartida(p)
|
||||
}
|
||||
hNombre := c.textHeight(p.Nombre, c.W*0.68, "B", 9.5)
|
||||
subTxt := descripcion
|
||||
if subTxt == "" {
|
||||
subTxt = respaldo
|
||||
}
|
||||
hDesc := 0.0
|
||||
if subTxt != "" {
|
||||
hDesc = c.textHeight(subTxt, c.W*0.68, "", 8)
|
||||
}
|
||||
y = c.need(hNombre+hDesc+14, y)
|
||||
c.drawText(p.Nombre, c.L, y, c.W*0.68, "B", 9.5, dark, "L")
|
||||
c.drawSingleLine(fmtMoney(p.Precio), c.L+c.W*0.7, y, c.W*0.3, "B", 9.5, primary, "R")
|
||||
y += hNombre + 2
|
||||
if subTxt != "" {
|
||||
c.drawText(subTxt, c.L, y, c.W*0.68, "", 8, muted, "L")
|
||||
y += hDesc + 10
|
||||
} else {
|
||||
y += 8
|
||||
}
|
||||
}
|
||||
|
||||
if econ.PlanBucefalo != nil && strings.TrimSpace(econ.PlanBucefalo.Nivel) != "" {
|
||||
etiqueta := "CRM Bucéfalo — plan " + capitalize(econ.PlanBucefalo.Nivel)
|
||||
hE := c.textHeight(etiqueta, c.W*0.68, "B", 9.5)
|
||||
y = c.need(hE+22, y)
|
||||
c.drawText(etiqueta, c.L, y, c.W*0.68, "B", 9.5, dark, "L")
|
||||
c.drawSingleLine(fmtMoney(econ.PlanBucefalo.Precio)+" / mes", c.L+c.W*0.7, y, c.W*0.3, "B", 9.5, primary, "R")
|
||||
y += hE + 2
|
||||
c.drawSingleLine("Servicio mensual", c.L, y, c.W*0.68, "", 8, muted, "L")
|
||||
y += 20
|
||||
}
|
||||
|
||||
y = c.need(58, y)
|
||||
c.hLine(c.L, c.L+c.W, y, border, 0.5)
|
||||
y += 10
|
||||
|
||||
// ── CAJA DE TOTALES ──
|
||||
tot := econ.Totales
|
||||
fila := func(etiqueta, valor string, fuerte bool) {
|
||||
step := 15.0
|
||||
size := 9.0
|
||||
lblStyle := ""
|
||||
lblColor := muted
|
||||
valColor := dark
|
||||
if fuerte {
|
||||
step = 18.0
|
||||
size = 10.5
|
||||
lblStyle = "B"
|
||||
lblColor = dark
|
||||
valColor = primary
|
||||
}
|
||||
y = c.need(step, y)
|
||||
c.drawSingleLine(etiqueta, c.L, y, c.W*0.6, lblStyle, size, lblColor, "L")
|
||||
c.drawSingleLine(valor, c.L+c.W*0.6, y, c.W*0.4, "B", size, valColor, "R")
|
||||
y += step
|
||||
}
|
||||
|
||||
if tot.SubtotalUnico > 0 {
|
||||
fila("Subtotal pago único", fmtMoney(tot.SubtotalUnico), false)
|
||||
if tot.IncluyeIVA {
|
||||
fila("IVA 16%", fmtMoney(tot.IVAUnico), false)
|
||||
fila("Total pago único", fmtMoney(tot.TotalUnico), true)
|
||||
} else {
|
||||
fila("Total pago único (sin IVA)", fmtMoney(tot.TotalUnico), true)
|
||||
}
|
||||
}
|
||||
if tot.SubtotalMensual > 0 {
|
||||
if tot.SubtotalUnico > 0 {
|
||||
y += 4
|
||||
}
|
||||
fila("Subtotal mensual", fmtMoney(tot.SubtotalMensual), false)
|
||||
if tot.IncluyeIVA {
|
||||
fila("IVA 16%", fmtMoney(tot.IVAMensual), false)
|
||||
fila("Total mensual", fmtMoney(tot.TotalMensual), true)
|
||||
} else {
|
||||
fila("Total mensual (sin IVA)", fmtMoney(tot.TotalMensual), true)
|
||||
}
|
||||
}
|
||||
|
||||
y = c.need(20, y)
|
||||
notaIVA := "Los precios son en Moneda Nacional (MXN) y no incluyen IVA. Facturación CFDI."
|
||||
if tot.IncluyeIVA {
|
||||
notaIVA = "Los precios por partida son en Moneda Nacional (MXN) y no incluyen IVA; el IVA se desglosa arriba. Facturación CFDI."
|
||||
}
|
||||
hNota := c.drawText(notaIVA, c.L, y, c.W, "", 7.5, muted, "L")
|
||||
y += hNota + 16
|
||||
|
||||
// ── BENEFICIOS ──
|
||||
if len(prop.Redaccion.Beneficios) > 0 {
|
||||
titulo("Por qué tiene sentido")
|
||||
for _, b := range prop.Redaccion.Beneficios {
|
||||
hEt := c.textHeight(b.Etiqueta, c.W*0.24, "B", 9)
|
||||
hTx := c.textHeight(b.Texto, c.W*0.72, "", 8.5)
|
||||
h := hEt
|
||||
if hTx > h {
|
||||
h = hTx
|
||||
}
|
||||
y = c.need(h+9, y)
|
||||
c.drawText(b.Etiqueta, c.L, y, c.W*0.24, "B", 9, dark, "L")
|
||||
c.drawText(b.Texto, c.L+c.W*0.27, y, c.W*0.72, "", 8.5, muted, "L")
|
||||
y += h + 9
|
||||
}
|
||||
y += 8
|
||||
}
|
||||
|
||||
// ── EXCLUSIONES ──
|
||||
if len(prop.Redaccion.Exclusiones) > 0 {
|
||||
titulo("Qué no incluye esta propuesta")
|
||||
for _, e := range prop.Redaccion.Exclusiones {
|
||||
t2 := "× " + e.Texto
|
||||
h := c.textHeight(t2, c.W-8, "", 8.5)
|
||||
y = c.need(h+6, y)
|
||||
c.drawText(t2, c.L+4, y, c.W-8, "", 8.5, dark, "L")
|
||||
y += h + 6
|
||||
}
|
||||
y += 10
|
||||
}
|
||||
|
||||
// ── PENDIENTES ──
|
||||
mats := prop.Hechos.MaterialesPendientes
|
||||
decs := prop.Hechos.DecisionesPendientes
|
||||
if len(mats) > 0 || len(decs) > 0 {
|
||||
titulo("Qué necesitamos de ustedes")
|
||||
for _, mm := range mats {
|
||||
suffix := ""
|
||||
if mm.BloqueaEntrega {
|
||||
suffix = " (el avance queda condicionado a esto)"
|
||||
}
|
||||
t2 := "○ " + mm.Texto + suffix
|
||||
h := c.textHeight(t2, c.W-8, "", 8.5)
|
||||
y = c.need(h+6, y)
|
||||
c.drawText(t2, c.L+4, y, c.W-8, "", 8.5, dark, "L")
|
||||
y += h + 6
|
||||
}
|
||||
for _, dd := range decs {
|
||||
t2 := fmt.Sprintf("· %s (decide: %s)", dd.Texto, dd.QuienDecide)
|
||||
h := c.textHeight(t2, c.W-8, "", 8.5)
|
||||
y = c.need(h+6, y)
|
||||
c.drawText(t2, c.L+4, y, c.W-8, "", 8.5, muted, "L")
|
||||
y += h + 6
|
||||
}
|
||||
y += 10
|
||||
}
|
||||
|
||||
// ── BACKLOG ──
|
||||
if len(prop.Redaccion.BacklogEvolucion) > 0 {
|
||||
titulo("Registrado para más adelante")
|
||||
y = c.need(14, y)
|
||||
c.drawSingleLine("No comprometido en esta propuesta.", c.L, y, c.W, "I", 7.5, muted, "L")
|
||||
y += 14
|
||||
for _, b := range prop.Redaccion.BacklogEvolucion {
|
||||
t2 := fmt.Sprintf("· %s (%s)", b.Problema, b.MomentoSugerido)
|
||||
h := c.textHeight(t2, c.W-8, "", 8.5)
|
||||
y = c.need(h+6, y)
|
||||
c.drawText(t2, c.L+4, y, c.W-8, "", 8.5, dark, "L")
|
||||
y += h + 6
|
||||
}
|
||||
}
|
||||
|
||||
return c.bytes()
|
||||
}
|
||||
|
||||
// GenerarAnexoInternoPDF renders the internal-only advisor annex as a separate document
|
||||
// with an unmistakable red banner so it can never be confused with the client proposal.
|
||||
func GenerarAnexoInternoPDF(in PropuestaPDFInput) ([]byte, error) {
|
||||
prop := decodeMapInto[propuestaContenido](in.Contenido)
|
||||
econ := decodeMapInto[propuestaEconomia](in.Economia)
|
||||
|
||||
moneda := in.Moneda
|
||||
if moneda == "" {
|
||||
moneda = econ.Moneda
|
||||
}
|
||||
fmtMoney := func(n float64) string {
|
||||
return formatMoney(n, moneda)
|
||||
}
|
||||
|
||||
dark := defaultDark
|
||||
muted := colorMuted
|
||||
redBanner := "#b91c1c"
|
||||
|
||||
c := newCanvas(50, 55, 50, 50)
|
||||
c.doc.AddPage()
|
||||
|
||||
c.rectFill(0, 0, c.pw, 36, redBanner)
|
||||
c.drawSingleLine("USO INTERNO — NO ENVIAR AL CLIENTE", c.L, 11, c.W, "B", 13, colorWhite, "L")
|
||||
y := 56.0
|
||||
|
||||
clienteDisplay := in.ClienteEmpresa
|
||||
if strings.TrimSpace(clienteDisplay) == "" {
|
||||
clienteDisplay = in.ClienteNombre
|
||||
}
|
||||
metaParts := []string{in.CotizacionNumero, clienteDisplay}
|
||||
if strings.TrimSpace(econ.Asesor) != "" {
|
||||
metaParts = append(metaParts, econ.Asesor)
|
||||
}
|
||||
c.drawSingleLine(strings.Join(metaParts, " · "), c.L, y, c.W, "", 9, muted, "L")
|
||||
y += 24
|
||||
|
||||
var valorAnualSum float64
|
||||
for _, dim := range prop.Diagnostico.ValorProblema.Dimensiones {
|
||||
if dim.MontoAnualMXN != nil {
|
||||
valorAnualSum += *dim.MontoAnualMXN
|
||||
}
|
||||
}
|
||||
var valorAnual *float64
|
||||
if valorAnualSum > 0 {
|
||||
v := valorAnualSum
|
||||
valorAnual = &v
|
||||
}
|
||||
r := calcularRatioPropuesta(econ.Totales.TotalPrimerAnio, valorAnual)
|
||||
|
||||
seccion := func(t string) {
|
||||
y = c.need(24, y)
|
||||
c.drawSingleLine(t, c.L, y, c.W, "B", 11, dark, "L")
|
||||
y += 18
|
||||
}
|
||||
linea := func(k, v string) {
|
||||
y = c.need(15, y)
|
||||
c.drawSingleLine(k, c.L, y, c.W*0.5, "", 9, muted, "L")
|
||||
c.drawSingleLine(v, c.L+c.W*0.5, y, c.W*0.5, "B", 9, dark, "R")
|
||||
y += 15
|
||||
}
|
||||
|
||||
confirmados := 0
|
||||
for _, h := range prop.Diagnostico.Hallazgos {
|
||||
if h.Confianza == "confirmado" {
|
||||
confirmados++
|
||||
}
|
||||
}
|
||||
|
||||
valorAnualTxt := "sin cuantificar"
|
||||
if valorAnual != nil {
|
||||
valorAnualTxt = fmtMoney(*valorAnual)
|
||||
}
|
||||
ratioTxt := "no calculable"
|
||||
if r != nil {
|
||||
ratioTxt = fmt.Sprintf("%.1f%% — %s", r.Ratio*100, strings.ReplaceAll(r.Lectura, "_", " "))
|
||||
}
|
||||
|
||||
seccion("Ponderación de la cotización")
|
||||
linea("Inversión del primer año", fmtMoney(econ.Totales.TotalPrimerAnio))
|
||||
linea("Valor anual del problema", valorAnualTxt)
|
||||
linea("Ratio precio / valor", ratioTxt)
|
||||
linea("Hallazgos en el diagnóstico", fmt.Sprintf("%d", len(prop.Diagnostico.Hallazgos)))
|
||||
linea("Cifras confirmadas", fmt.Sprintf("%d", confirmados))
|
||||
linea("Exclusiones definidas", fmt.Sprintf("%d", len(prop.Redaccion.Exclusiones)))
|
||||
linea("Materiales pendientes", fmt.Sprintf("%d", len(prop.Hechos.MaterialesPendientes)))
|
||||
linea("Decisiones pendientes", fmt.Sprintf("%d", len(prop.Hechos.DecisionesPendientes)))
|
||||
linea("Red flags detectadas", fmt.Sprintf("%d", len(prop.Hechos.RedFlags)))
|
||||
y += 6
|
||||
|
||||
if len(prop.Diagnostico.ValorProblema.Dimensiones) > 0 {
|
||||
seccion("De dónde sale el valor anual")
|
||||
sinConfirmar := false
|
||||
for _, dim := range prop.Diagnostico.ValorProblema.Dimensiones {
|
||||
montoTxt := "sin cifra"
|
||||
if dim.MontoAnualMXN != nil {
|
||||
montoTxt = fmtMoney(*dim.MontoAnualMXN)
|
||||
}
|
||||
y = c.need(14, y)
|
||||
c.drawSingleLine(fmt.Sprintf("%s: %s", dim.Tipo, montoTxt), c.L, y, c.W, "B", 9, dark, "L")
|
||||
y += 13
|
||||
hasConfirmed := false
|
||||
if len(dim.Factores) > 0 {
|
||||
partes := make([]string, 0, len(dim.Factores))
|
||||
for _, f := range dim.Factores {
|
||||
if f.Confianza == "confirmado" {
|
||||
hasConfirmed = true
|
||||
}
|
||||
partes = append(partes, fmt.Sprintf("%s = %g (%s)", f.Nombre, f.Valor, f.Confianza))
|
||||
}
|
||||
desglose := strings.Join(partes, " x ")
|
||||
h := c.textHeight(desglose, c.W-10, "", 8)
|
||||
y = c.need(h+8, y)
|
||||
c.drawText(desglose, c.L+6, y, c.W-10, "", 8, muted, "L")
|
||||
y += h + 8
|
||||
}
|
||||
if dim.MontoAnualMXN != nil && !hasConfirmed {
|
||||
sinConfirmar = true
|
||||
}
|
||||
}
|
||||
if sinConfirmar {
|
||||
alerta := "Ojo: hay una cifra que descansa entera en factores estimados. Antes de fiarte del ratio, revisa que no falte un factor — la aritmética puede cuadrar y aun así estar inflada."
|
||||
h := c.textHeight(alerta, c.W, "B", 8.5)
|
||||
y = c.need(h+12, y)
|
||||
c.drawText(alerta, c.L, y, c.W, "B", 8.5, redBanner, "L")
|
||||
y += h + 14
|
||||
}
|
||||
y += 4
|
||||
}
|
||||
|
||||
if r != nil {
|
||||
var nota string
|
||||
switch r.Lectura {
|
||||
case "subcotizado":
|
||||
nota = "La inversión es menos del 10% de lo que el problema le cuesta al cliente cada año. Probablemente subcotizaste."
|
||||
case "objecion_probable":
|
||||
nota = "La inversión supera el 40% del valor anual del problema. Prepara la conversación de precio: se responde con alcance, no con descuento."
|
||||
case "alto":
|
||||
nota = "La inversión está en la banda alta. Justificable, pero conviene anclar bien el valor antes de dar el número."
|
||||
default:
|
||||
nota = "La inversión cae en el rango de referencia (15-25% del valor anual)."
|
||||
}
|
||||
h := c.textHeight(nota, c.W, "I", 8.5)
|
||||
y = c.need(h+12, y)
|
||||
c.drawText(nota, c.L, y, c.W, "I", 8.5, muted, "L")
|
||||
y += h + 16
|
||||
}
|
||||
|
||||
if len(prop.Hechos.RedFlags) > 0 {
|
||||
seccion("Red flags")
|
||||
for _, rf := range prop.Hechos.RedFlags {
|
||||
t := fmt.Sprintf("· [%s] %s", rf.Severidad, rf.Senal)
|
||||
h := c.textHeight(t, c.W-8, "", 9)
|
||||
y = c.need(h+6, y)
|
||||
c.drawText(t, c.L+4, y, c.W-8, "", 9, dark, "L")
|
||||
y += h + 6
|
||||
}
|
||||
y += 10
|
||||
}
|
||||
|
||||
if len(prop.Redaccion.NotasInternas) > 0 {
|
||||
seccion("Notas para el asesor")
|
||||
for _, n := range prop.Redaccion.NotasInternas {
|
||||
t := "· " + n
|
||||
h := c.textHeight(t, c.W-8, "", 9)
|
||||
y = c.need(h+6, y)
|
||||
c.drawText(t, c.L+4, y, c.W-8, "", 9, dark, "L")
|
||||
y += h + 6
|
||||
}
|
||||
y += 10
|
||||
}
|
||||
|
||||
if len(prop.Hechos.MencionesFueraDeAlcance) > 0 {
|
||||
seccion("Se mencionó y quedó fuera")
|
||||
for _, m := range prop.Hechos.MencionesFueraDeAlcance {
|
||||
t := "· " + m
|
||||
h := c.textHeight(t, c.W-8, "", 9)
|
||||
y = c.need(h+6, y)
|
||||
c.drawText(t, c.L+4, y, c.W-8, "", 9, dark, "L")
|
||||
y += h + 6
|
||||
}
|
||||
}
|
||||
|
||||
return c.bytes()
|
||||
}
|
||||
@@ -0,0 +1,476 @@
|
||||
package propuesta
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/config"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultMinimaxBaseURL = "https://api.minimax.io/anthropic"
|
||||
DefaultMinimaxModel = "MiniMax-M3"
|
||||
anthropicVersion = "2023-06-01"
|
||||
maxTransitoriosDef = 3
|
||||
)
|
||||
|
||||
// UsoTokens acumula el consumo de tokens reportado por el endpoint de mensajes.
|
||||
type UsoTokens struct {
|
||||
Entrada int `json:"entrada"`
|
||||
Salida int `json:"salida"`
|
||||
CacheLectura int `json:"cacheLectura"`
|
||||
CacheEscritura int `json:"cacheEscritura"`
|
||||
}
|
||||
|
||||
// BloqueSystem representa un bloque del prompt de sistema con cache opcional.
|
||||
type BloqueSystem struct {
|
||||
Texto string
|
||||
Cachear bool
|
||||
}
|
||||
|
||||
// Herramienta define la herramienta de salida estructurada para tool-calling.
|
||||
type Herramienta struct {
|
||||
Nombre string
|
||||
Descripcion string
|
||||
InputSchema map[string]any
|
||||
Validar func(datos map[string]any) []string
|
||||
}
|
||||
|
||||
// OpcionesLlamada configura una invocacion con tool-calling y bucle de validacion.
|
||||
type OpcionesLlamada struct {
|
||||
System []BloqueSystem
|
||||
MensajeUsuario string
|
||||
Herramienta Herramienta
|
||||
MaxIntentos int
|
||||
MaxTokens int
|
||||
}
|
||||
|
||||
// ResultadoLlamada contiene la salida validada, el uso acumulado y los intentos.
|
||||
type ResultadoLlamada struct {
|
||||
Datos map[string]any
|
||||
Uso UsoTokens
|
||||
Intentos int
|
||||
}
|
||||
|
||||
// ClienteIA habla con el endpoint compatible con Anthropic Messages de MiniMax
|
||||
// usando net/http puro (sin SDK externo).
|
||||
type ClienteIA struct {
|
||||
APIKey string
|
||||
BaseURL string
|
||||
Model string
|
||||
HTTPClient *http.Client
|
||||
Sleep func(ctx context.Context, d time.Duration) error
|
||||
}
|
||||
|
||||
// NuevoClienteIA construye el cliente de MiniMax leyendo MINIMAX_API_KEY,
|
||||
// MINIMAX_BASE_URL y MINIMAX_MODEL (desde cfg si se pasa, o desde el entorno).
|
||||
// Rechaza explicitamente una clave vacia y advierte cuando solo ANTHROPIC_API_KEY
|
||||
// esta presente para evitar enviar credenciales al proveedor equivocado.
|
||||
func NuevoClienteIA(cfg *config.Config) (*ClienteIA, error) {
|
||||
var apiKey, baseURL, model string
|
||||
if cfg != nil {
|
||||
apiKey = strings.TrimSpace(cfg.MinimaxAPIKey)
|
||||
baseURL = strings.TrimSpace(cfg.MinimaxBaseURL)
|
||||
model = strings.TrimSpace(cfg.MinimaxModel)
|
||||
} else {
|
||||
apiKey = strings.TrimSpace(os.Getenv("MINIMAX_API_KEY"))
|
||||
baseURL = strings.TrimSpace(os.Getenv("MINIMAX_BASE_URL"))
|
||||
model = strings.TrimSpace(os.Getenv("MINIMAX_MODEL"))
|
||||
}
|
||||
|
||||
if apiKey == "" {
|
||||
if strings.TrimSpace(os.Getenv("ANTHROPIC_API_KEY")) != "" {
|
||||
return nil, errors.New(
|
||||
"Falta MINIMAX_API_KEY (se detecto ANTHROPIC_API_KEY en el entorno, pero NO se usa para evitar mandar credenciales al proveedor equivocado). Define MINIMAX_API_KEY en .env.",
|
||||
)
|
||||
}
|
||||
return nil, errors.New(
|
||||
"Falta MINIMAX_API_KEY. Definela en .env. No uses ANTHROPIC_API_KEY: la clave de MiniMax nunca debe enviarse a api.anthropic.com.",
|
||||
)
|
||||
}
|
||||
|
||||
if baseURL == "" {
|
||||
baseURL = DefaultMinimaxBaseURL
|
||||
}
|
||||
baseURL = strings.TrimRight(baseURL, "/")
|
||||
|
||||
if model == "" {
|
||||
model = DefaultMinimaxModel
|
||||
}
|
||||
|
||||
return &ClienteIA{
|
||||
APIKey: apiKey,
|
||||
BaseURL: baseURL,
|
||||
Model: model,
|
||||
HTTPClient: &http.Client{
|
||||
Timeout: 120 * time.Second,
|
||||
},
|
||||
Sleep: sleepContext,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// NormalizarRespuesta corrige rarezas observadas en las respuestas de MiniMax
|
||||
// antes de validar: a veces envuelve elementos de arrays en `{item: {...}}`.
|
||||
// Solo desenvuelve cuando "item" es la UNICA clave del objeto.
|
||||
func NormalizarRespuesta(v any) any {
|
||||
switch val := v.(type) {
|
||||
case []any:
|
||||
out := make([]any, len(val))
|
||||
for i, elem := range val {
|
||||
out[i] = NormalizarRespuesta(elem)
|
||||
}
|
||||
return out
|
||||
case map[string]any:
|
||||
if len(val) == 1 {
|
||||
if inner, ok := val["item"]; ok {
|
||||
return NormalizarRespuesta(inner)
|
||||
}
|
||||
}
|
||||
out := make(map[string]any, len(val))
|
||||
for k, elem := range val {
|
||||
out[k] = NormalizarRespuesta(elem)
|
||||
}
|
||||
return out
|
||||
default:
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
type apiCacheControl struct {
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
type apiSystemBlock struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
CacheControl *apiCacheControl `json:"cache_control,omitempty"`
|
||||
}
|
||||
|
||||
type apiTool struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
InputSchema map[string]any `json:"input_schema"`
|
||||
}
|
||||
|
||||
type apiToolChoice struct {
|
||||
Type string `json:"type"`
|
||||
Name string `json:"name,omitempty"`
|
||||
}
|
||||
|
||||
type apiMessage struct {
|
||||
Role string `json:"role"`
|
||||
Content any `json:"content"`
|
||||
}
|
||||
|
||||
type apiRequest struct {
|
||||
Model string `json:"model"`
|
||||
MaxTokens int `json:"max_tokens"`
|
||||
System []apiSystemBlock `json:"system,omitempty"`
|
||||
Tools []apiTool `json:"tools,omitempty"`
|
||||
ToolChoice *apiToolChoice `json:"tool_choice,omitempty"`
|
||||
Messages []apiMessage `json:"messages"`
|
||||
}
|
||||
|
||||
type apiContentBlock struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text,omitempty"`
|
||||
ID string `json:"id,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Input any `json:"input,omitempty"`
|
||||
}
|
||||
|
||||
type apiUsage struct {
|
||||
InputTokens int `json:"input_tokens"`
|
||||
OutputTokens int `json:"output_tokens"`
|
||||
CacheReadInputTokens int `json:"cache_read_input_tokens"`
|
||||
CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
|
||||
}
|
||||
|
||||
type apiResponse struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Role string `json:"role"`
|
||||
Content []apiContentBlock `json:"content"`
|
||||
StopReason string `json:"stop_reason"`
|
||||
Usage apiUsage `json:"usage"`
|
||||
}
|
||||
|
||||
type apiHTTPError struct {
|
||||
Status int
|
||||
Body string
|
||||
}
|
||||
|
||||
func (e *apiHTTPError) Error() string {
|
||||
return fmt.Sprintf("error HTTP %d del proveedor IA: %s", e.Status, e.Body)
|
||||
}
|
||||
|
||||
var (
|
||||
reTransitorio400 = regexp.MustCompile(`(?i)unexpected|internal|parse|unknown`)
|
||||
reTransitorioRed = regexp.MustCompile(`(?i)ECONN|ETIMEDOUT|socket|network|connection reset|EOF|timeout`)
|
||||
)
|
||||
|
||||
func esTransitorio(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return false
|
||||
}
|
||||
var httpErr *apiHTTPError
|
||||
if errors.As(err, &httpErr) {
|
||||
switch httpErr.Status {
|
||||
case http.StatusRequestTimeout, http.StatusConflict, http.StatusTooManyRequests:
|
||||
return true
|
||||
}
|
||||
if httpErr.Status >= 500 {
|
||||
return true
|
||||
}
|
||||
if httpErr.Status == http.StatusBadRequest && reTransitorio400.MatchString(httpErr.Body) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
var netErr net.Error
|
||||
if errors.As(err, &netErr) {
|
||||
return true
|
||||
}
|
||||
return reTransitorioRed.MatchString(err.Error())
|
||||
}
|
||||
|
||||
func sleepContext(ctx context.Context, d time.Duration) error {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-t.C:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *ClienteIA) crearMensaje(ctx context.Context, reqBody apiRequest) (*apiResponse, error) {
|
||||
payload, err := json.Marshal(reqBody)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error serializando solicitud IA: %w", err)
|
||||
}
|
||||
|
||||
endpoint := strings.TrimRight(c.BaseURL, "/") + "/v1/messages"
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error creando solicitud HTTP: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("x-api-key", c.APIKey)
|
||||
req.Header.Set("anthropic-version", anthropicVersion)
|
||||
|
||||
httpClient := c.HTTPClient
|
||||
if httpClient == nil {
|
||||
httpClient = &http.Client{Timeout: 120 * time.Second}
|
||||
}
|
||||
|
||||
resp, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, 10<<20))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
bodyStr := strings.TrimSpace(string(raw))
|
||||
if len(bodyStr) > 1000 {
|
||||
bodyStr = bodyStr[:1000]
|
||||
}
|
||||
return nil, &apiHTTPError{Status: resp.StatusCode, Body: bodyStr}
|
||||
}
|
||||
|
||||
var parsed apiResponse
|
||||
if err := json.Unmarshal(raw, &parsed); err != nil {
|
||||
return nil, fmt.Errorf("error decodificando respuesta IA: %w", err)
|
||||
}
|
||||
return &parsed, nil
|
||||
}
|
||||
|
||||
func (c *ClienteIA) crearMensajeConReintentos(ctx context.Context, reqBody apiRequest, maxTransitorios int) (*apiResponse, error) {
|
||||
if maxTransitorios <= 0 {
|
||||
maxTransitorios = maxTransitoriosDef
|
||||
}
|
||||
sleepFn := c.Sleep
|
||||
if sleepFn == nil {
|
||||
sleepFn = sleepContext
|
||||
}
|
||||
|
||||
var ultimo error
|
||||
for i := 1; i <= maxTransitorios; i++ {
|
||||
res, err := c.crearMensaje(ctx, reqBody)
|
||||
if err == nil {
|
||||
return res, nil
|
||||
}
|
||||
ultimo = err
|
||||
if !esTransitorio(err) || i == maxTransitorios {
|
||||
return nil, err
|
||||
}
|
||||
backoff := time.Duration(1<<(i-1)) * time.Second // 1s, 2s
|
||||
if sleepErr := sleepFn(ctx, backoff); sleepErr != nil {
|
||||
return nil, sleepErr
|
||||
}
|
||||
}
|
||||
return nil, ultimo
|
||||
}
|
||||
|
||||
// LlamarConHerramienta invoca al modelo exigiendo una llamada a opts.Herramienta,
|
||||
// normaliza rarezas de MiniMax, valida contra el contrato y reintenta devolviendo
|
||||
// los errores exactos de validacion hasta opts.MaxIntentos.
|
||||
func (c *ClienteIA) LlamarConHerramienta(ctx context.Context, opts OpcionesLlamada) (*ResultadoLlamada, error) {
|
||||
maxIntentos := opts.MaxIntentos
|
||||
if maxIntentos <= 0 {
|
||||
maxIntentos = 3
|
||||
}
|
||||
maxTokens := opts.MaxTokens
|
||||
if maxTokens <= 0 {
|
||||
maxTokens = 8000
|
||||
}
|
||||
|
||||
systemBlocks := make([]apiSystemBlock, 0, len(opts.System))
|
||||
for _, b := range opts.System {
|
||||
blk := apiSystemBlock{
|
||||
Type: "text",
|
||||
Text: b.Texto,
|
||||
}
|
||||
if b.Cachear {
|
||||
blk.CacheControl = &apiCacheControl{Type: "ephemeral"}
|
||||
}
|
||||
systemBlocks = append(systemBlocks, blk)
|
||||
}
|
||||
|
||||
tools := []apiTool{
|
||||
{
|
||||
Name: opts.Herramienta.Nombre,
|
||||
Description: opts.Herramienta.Descripcion,
|
||||
InputSchema: opts.Herramienta.InputSchema,
|
||||
},
|
||||
}
|
||||
|
||||
toolChoice := &apiToolChoice{
|
||||
Type: "tool",
|
||||
Name: opts.Herramienta.Nombre,
|
||||
}
|
||||
|
||||
mensajes := []apiMessage{
|
||||
{Role: "user", Content: opts.MensajeUsuario},
|
||||
}
|
||||
|
||||
var uso UsoTokens
|
||||
var ultimoError string
|
||||
|
||||
for intento := 1; intento <= maxIntentos; intento++ {
|
||||
res, err := c.crearMensajeConReintentos(ctx, apiRequest{
|
||||
Model: c.Model,
|
||||
MaxTokens: maxTokens,
|
||||
System: systemBlocks,
|
||||
Tools: tools,
|
||||
ToolChoice: toolChoice,
|
||||
Messages: mensajes,
|
||||
}, maxTransitoriosDef)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
uso.Entrada += res.Usage.InputTokens
|
||||
uso.Salida += res.Usage.OutputTokens
|
||||
uso.CacheLectura += res.Usage.CacheReadInputTokens
|
||||
uso.CacheEscritura += res.Usage.CacheCreationInputTokens
|
||||
|
||||
var bloquesTool []apiContentBlock
|
||||
var candidatos []apiContentBlock
|
||||
for _, blk := range res.Content {
|
||||
if blk.Type == "tool_use" {
|
||||
bloquesTool = append(bloquesTool, blk)
|
||||
if blk.Name == opts.Herramienta.Nombre {
|
||||
candidatos = append(candidatos, blk)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var primerFallo *apiContentBlock
|
||||
for i := range candidatos {
|
||||
cand := candidatos[i]
|
||||
norm := NormalizarRespuesta(cand.Input)
|
||||
datos, ok := norm.(map[string]any)
|
||||
var errs []string
|
||||
if !ok {
|
||||
errs = []string{"La entrada de la herramienta debe ser un objeto JSON."}
|
||||
} else if opts.Herramienta.Validar != nil {
|
||||
errs = opts.Herramienta.Validar(datos)
|
||||
}
|
||||
if len(errs) == 0 {
|
||||
return &ResultadoLlamada{
|
||||
Datos: datos,
|
||||
Uso: uso,
|
||||
Intentos: intento,
|
||||
}, nil
|
||||
}
|
||||
if primerFallo == nil {
|
||||
cp := cand
|
||||
primerFallo = &cp
|
||||
ultimoError = strings.Join(errs, "\n")
|
||||
}
|
||||
}
|
||||
|
||||
if len(bloquesTool) > 0 {
|
||||
if primerFallo == nil {
|
||||
ultimoError = fmt.Sprintf("El modelo llamo a una herramienta inesperada. Usa %s.", opts.Herramienta.Nombre)
|
||||
}
|
||||
userBlocks := make([]any, 0, len(bloquesTool)+1)
|
||||
for _, b := range bloquesTool {
|
||||
content := fmt.Sprintf("Herramienta inesperada. Usa %s.", opts.Herramienta.Nombre)
|
||||
if primerFallo != nil && b.ID == primerFallo.ID {
|
||||
content = ultimoError
|
||||
}
|
||||
userBlocks = append(userBlocks, map[string]any{
|
||||
"type": "tool_result",
|
||||
"tool_use_id": b.ID,
|
||||
"is_error": true,
|
||||
"content": content,
|
||||
})
|
||||
}
|
||||
userBlocks = append(userBlocks, map[string]any{
|
||||
"type": "text",
|
||||
"text": fmt.Sprintf(
|
||||
"La llamada no cumple el schema. Corrige EXACTAMENTE estos errores y vuelve a llamar a %s:\n\n%s\n\nRevisa que cada objeto este en el array que le corresponde y que no falte ningun campo obligatorio. No agregues campos que el schema no declara.",
|
||||
opts.Herramienta.Nombre,
|
||||
ultimoError,
|
||||
),
|
||||
})
|
||||
mensajes = append(mensajes,
|
||||
apiMessage{Role: "assistant", Content: res.Content},
|
||||
apiMessage{Role: "user", Content: userBlocks},
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
ultimoError = "El modelo respondio con prosa en vez de llamar a la herramienta."
|
||||
mensajes = append(mensajes,
|
||||
apiMessage{Role: "assistant", Content: res.Content},
|
||||
apiMessage{
|
||||
Role: "user",
|
||||
Content: fmt.Sprintf("Debes responder llamando a la herramienta %s. No escribas prosa suelta.", opts.Herramienta.Nombre),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("El paso %q agoto %d intentos.\nUltimo error:\n%s", opts.Herramienta.Nombre, maxIntentos, ultimoError)
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
package propuesta
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"cotizador/internal/domain"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// PartidaEconomia representa una linea cotizada canonica.
|
||||
// Ref (P01, P02...) es lo unico que identifica la partida ante el modelo de IA;
|
||||
// los precios e importes nunca viajan al prompt y solo los usa el renderizador
|
||||
// o los calculos internos.
|
||||
type PartidaEconomia struct {
|
||||
Ref string `json:"refPartida"`
|
||||
Nombre string `json:"nombre"`
|
||||
Fase int `json:"fase"`
|
||||
TipoPago string `json:"tipoPago"`
|
||||
Precio float64 `json:"precio"`
|
||||
TiempoEntrega string `json:"tiempoEntrega"`
|
||||
Entregables []string `json:"entregables"`
|
||||
ModeloCobro string `json:"modeloCobro"`
|
||||
Horas *float64 `json:"horas"`
|
||||
TarifaHora *float64 `json:"tarifaHora"`
|
||||
MontoMinimo *float64 `json:"montoMinimo"`
|
||||
HorasIncluidas *float64 `json:"horasIncluidas"`
|
||||
}
|
||||
|
||||
// RatioValor resume la lectura precio/valor del anexo interno.
|
||||
type RatioValor struct {
|
||||
Ratio float64 `json:"ratio"`
|
||||
Etiqueta string `json:"etiqueta"`
|
||||
Nota string `json:"nota"`
|
||||
}
|
||||
|
||||
// EconomiaCotizacion agrupa las partidas seleccionadas, el plan Bucefalo
|
||||
// (si fue contratado) y los totales canonicos de la cotizacion.
|
||||
type EconomiaCotizacion struct {
|
||||
Partidas []PartidaEconomia `json:"partidas"`
|
||||
PlanBucefalo *struct {
|
||||
Nivel string `json:"nivel"`
|
||||
Precio float64 `json:"precio"`
|
||||
} `json:"planBucefalo"`
|
||||
Totales domain.TotalesCotizacion `json:"totales"`
|
||||
Moneda string `json:"moneda"`
|
||||
}
|
||||
|
||||
// CalcularRatio calcula el ratio precio/valor para el anexo interno comparando
|
||||
// el desembolso total del primer ano contra el costo anual del problema del cliente.
|
||||
//
|
||||
// Cortes:
|
||||
// - < 0.10: subcotizado
|
||||
// - <= 0.25: en_rango
|
||||
// - <= 0.40: alto
|
||||
// - > 0.40: objecion_probable
|
||||
func CalcularRatio(totalPrimerAnio, valorAnual float64) RatioValor {
|
||||
if valorAnual <= 0 {
|
||||
return RatioValor{
|
||||
Ratio: 0,
|
||||
Etiqueta: "",
|
||||
Nota: "Sin valor anual cuantificado del problema.",
|
||||
}
|
||||
}
|
||||
|
||||
ratio := totalPrimerAnio / valorAnual
|
||||
var etiqueta, nota string
|
||||
switch {
|
||||
case ratio < 0.10:
|
||||
etiqueta = "subcotizado"
|
||||
nota = "La inversion es menos del 10% de lo que el problema le cuesta al cliente cada ano. Probablemente subcotizaste."
|
||||
case ratio <= 0.25:
|
||||
etiqueta = "en_rango"
|
||||
nota = "La inversion cae en el rango de referencia (15-25% del valor anual)."
|
||||
case ratio <= 0.40:
|
||||
etiqueta = "alto"
|
||||
nota = "La inversion esta en la banda alta. Justificable, pero conviene anclar bien el valor antes de dar el numero."
|
||||
default:
|
||||
etiqueta = "objecion_probable"
|
||||
nota = "La inversion supera el 40% del valor anual del problema. Prepara la conversacion de precio: se responde con alcance, no con descuento."
|
||||
}
|
||||
|
||||
return RatioValor{
|
||||
Ratio: math.Round(ratio*1000) / 1000,
|
||||
Etiqueta: etiqueta,
|
||||
Nota: nota,
|
||||
}
|
||||
}
|
||||
|
||||
// CargarEconomiaCotizacion carga desde PostgreSQL las partidas seleccionadas,
|
||||
// el plan Bucefalo (si aplica) y los totales canonicos de una cotizacion.
|
||||
func CargarEconomiaCotizacion(ctx context.Context, pool *pgxpool.Pool, cotizacionID string) (*EconomiaCotizacion, error) {
|
||||
if pool == nil {
|
||||
return nil, errors.New("pool de base de datos no inicializado")
|
||||
}
|
||||
|
||||
var moneda string
|
||||
var incluirIVA bool
|
||||
err := pool.QueryRow(ctx, `
|
||||
SELECT "moneda", "incluirIva"
|
||||
FROM "Cotizacion"
|
||||
WHERE "id" = $1
|
||||
`, cotizacionID).Scan(&moneda, &incluirIVA)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, fmt.Errorf("Cotizacion %s no encontrada", cotizacionID)
|
||||
}
|
||||
return nil, fmt.Errorf("error consultando cotizacion %s: %w", cotizacionID, err)
|
||||
}
|
||||
|
||||
rows, err := pool.Query(ctx, `
|
||||
SELECT
|
||||
COALESCE(NULLIF(cat."nombre", ''), NULLIF(sc."nombre", ''), 'Servicio') AS nombre,
|
||||
sc."fase",
|
||||
sc."tipoPago",
|
||||
sc."precio",
|
||||
sc."tiempoEntrega",
|
||||
sc."entregables",
|
||||
sc."modeloCobro",
|
||||
sc."horas",
|
||||
sc."tarifaHora",
|
||||
sc."montoMinimo",
|
||||
sc."horasIncluidas"
|
||||
FROM "ServicioCotizado" sc
|
||||
LEFT JOIN "ServicioCatalogo" cat ON cat."id" = sc."servicioCatalogoId"
|
||||
WHERE sc."cotizacionId" = $1 AND sc."seleccionado" = true
|
||||
ORDER BY sc."fase" ASC, sc."createdAt" ASC
|
||||
`, cotizacionID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error consultando servicios de cotizacion %s: %w", cotizacionID, err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
partidas := make([]PartidaEconomia, 0)
|
||||
paraTotales := make([]domain.ServicioCalc, 0)
|
||||
idx := 0
|
||||
|
||||
for rows.Next() {
|
||||
var p PartidaEconomia
|
||||
var entregablesRaw []byte
|
||||
if err := rows.Scan(
|
||||
&p.Nombre,
|
||||
&p.Fase,
|
||||
&p.TipoPago,
|
||||
&p.Precio,
|
||||
&p.TiempoEntrega,
|
||||
&entregablesRaw,
|
||||
&p.ModeloCobro,
|
||||
&p.Horas,
|
||||
&p.TarifaHora,
|
||||
&p.MontoMinimo,
|
||||
&p.HorasIncluidas,
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("error leyendo servicio cotizado: %w", err)
|
||||
}
|
||||
idx++
|
||||
p.Ref = fmt.Sprintf("P%02d", idx)
|
||||
p.Entregables = parseStringSliceJSON(entregablesRaw)
|
||||
partidas = append(partidas, p)
|
||||
paraTotales = append(paraTotales, domain.ServicioCalc{
|
||||
Nombre: p.Nombre,
|
||||
ModeloCobro: p.ModeloCobro,
|
||||
TipoPago: p.TipoPago,
|
||||
Precio: p.Precio,
|
||||
Seleccionado: true,
|
||||
})
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("error iterando servicios cotizados: %w", err)
|
||||
}
|
||||
|
||||
var plan *struct {
|
||||
Nivel string `json:"nivel"`
|
||||
Precio float64 `json:"precio"`
|
||||
}
|
||||
var nivelPlan string
|
||||
var precioPlan float64
|
||||
err = pool.QueryRow(ctx, `
|
||||
SELECT "nivel", "precio"
|
||||
FROM "PlanBucefaloCotizacion"
|
||||
WHERE "cotizacionId" = $1 AND "seleccionado" = true
|
||||
LIMIT 1
|
||||
`, cotizacionID).Scan(&nivelPlan, &precioPlan)
|
||||
if err == nil {
|
||||
plan = &struct {
|
||||
Nivel string `json:"nivel"`
|
||||
Precio float64 `json:"precio"`
|
||||
}{
|
||||
Nivel: nivelPlan,
|
||||
Precio: precioPlan,
|
||||
}
|
||||
// El plan Bucefalo se cobra mensual y entra a los totales igual que en el PDF economico.
|
||||
paraTotales = append(paraTotales, domain.ServicioCalc{
|
||||
TipoPago: "mensual",
|
||||
Precio: precioPlan,
|
||||
Seleccionado: true,
|
||||
})
|
||||
} else if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, fmt.Errorf("error consultando plan Bucefalo de %s: %w", cotizacionID, err)
|
||||
}
|
||||
|
||||
return &EconomiaCotizacion{
|
||||
Partidas: partidas,
|
||||
PlanBucefalo: plan,
|
||||
Totales: domain.CalcularTotalesCotizacion(paraTotales, incluirIVA),
|
||||
Moneda: moneda,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func parseStringSliceJSON(raw []byte) []string {
|
||||
if len(raw) == 0 {
|
||||
return []string{}
|
||||
}
|
||||
var out []string
|
||||
if err := json.Unmarshal(raw, &out); err != nil || out == nil {
|
||||
return []string{}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package propuesta
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"cotizador/internal/config"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// GenerarInput encapsula los datos de entrada para generar una propuesta consultiva.
|
||||
type GenerarInput struct {
|
||||
CotizacionID string
|
||||
Transcripcion string
|
||||
NotasAdicionales string
|
||||
}
|
||||
|
||||
// GenerarResult devuelve el contenido estructurado de la propuesta, la traza
|
||||
// de consumo/intentos, los avisos de validacion y el modelo usado.
|
||||
type GenerarResult struct {
|
||||
Contenido map[string]any
|
||||
Traza map[string]any
|
||||
Avisos []Aviso
|
||||
Modelo string
|
||||
}
|
||||
|
||||
type pasoTraza struct {
|
||||
Paso string `json:"paso"`
|
||||
Intentos int `json:"intentos"`
|
||||
Uso UsoTokens `json:"uso"`
|
||||
}
|
||||
|
||||
// GenerarPropuesta ejecuta el pipeline consultivo de tres pasos (extraccion,
|
||||
// diagnostico, redaccion) contra MiniMax y valida la salida contra las reglas
|
||||
// de negocio y la economia canonica de la cotizacion.
|
||||
func GenerarPropuesta(ctx context.Context, cfg *config.Config, pool *pgxpool.Pool, in GenerarInput) (*GenerarResult, error) {
|
||||
if pool == nil {
|
||||
return nil, errors.New("pool de base de datos no inicializado")
|
||||
}
|
||||
if strings.TrimSpace(in.CotizacionID) == "" {
|
||||
return nil, errors.New("CotizacionID es obligatorio")
|
||||
}
|
||||
|
||||
var proyecto, observaciones, observacionesInternas, clienteNombre, clienteEmpresa string
|
||||
var esDoble bool
|
||||
err := pool.QueryRow(ctx, `
|
||||
SELECT
|
||||
c."proyecto",
|
||||
c."esDoble",
|
||||
COALESCE(c."observaciones", ''),
|
||||
COALESCE(c."observacionesInternas", ''),
|
||||
cl."nombre",
|
||||
COALESCE(cl."empresa", '')
|
||||
FROM "Cotizacion" c
|
||||
JOIN "Cliente" cl ON cl."id" = c."clienteId"
|
||||
WHERE c."id" = $1
|
||||
`, in.CotizacionID).Scan(
|
||||
&proyecto,
|
||||
&esDoble,
|
||||
&observaciones,
|
||||
&observacionesInternas,
|
||||
&clienteNombre,
|
||||
&clienteEmpresa,
|
||||
)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, fmt.Errorf("Cotizacion %s no encontrada", in.CotizacionID)
|
||||
}
|
||||
return nil, fmt.Errorf("error cargando contexto de cotizacion %s: %w", in.CotizacionID, err)
|
||||
}
|
||||
|
||||
if esDoble {
|
||||
return nil, errors.New(
|
||||
"Esta cotizacion es de doble propuesta y el documento consultivo todavia no las soporta: sumaria las dos opciones como si fueran una sola. Genera la propuesta desde una cotizacion de opcion unica.",
|
||||
)
|
||||
}
|
||||
|
||||
rows, err := pool.Query(ctx, `
|
||||
SELECT "notas"
|
||||
FROM "ServicioCotizado"
|
||||
WHERE "cotizacionId" = $1 AND "notas" IS NOT NULL AND BTRIM("notas") <> ''
|
||||
ORDER BY "fase" ASC, "createdAt" ASC
|
||||
`, in.CotizacionID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error consultando notas de partidas: %w", err)
|
||||
}
|
||||
var notasLista []string
|
||||
for rows.Next() {
|
||||
var n string
|
||||
if err := rows.Scan(&n); err != nil {
|
||||
rows.Close()
|
||||
return nil, fmt.Errorf("error leyendo nota de partida: %w", err)
|
||||
}
|
||||
if trimmed := strings.TrimSpace(n); trimmed != "" {
|
||||
notasLista = append(notasLista, trimmed)
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
return nil, fmt.Errorf("error iterando notas de partidas: %w", err)
|
||||
}
|
||||
rows.Close()
|
||||
|
||||
if extra := strings.TrimSpace(in.NotasAdicionales); extra != "" {
|
||||
notasLista = append(notasLista, extra)
|
||||
}
|
||||
notasCombinadas := strings.Join(notasLista, "\n")
|
||||
|
||||
economia, err := CargarEconomiaCotizacion(ctx, pool, in.CotizacionID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(economia.Partidas) == 0 {
|
||||
return nil, errors.New("La cotizacion no tiene partidas seleccionadas. Agrega servicios antes de generar la propuesta.")
|
||||
}
|
||||
|
||||
cliente, err := NuevoClienteIA(cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
entrada := ContextoEntrada{
|
||||
Transcripcion: in.Transcripcion,
|
||||
Notas: notasCombinadas,
|
||||
Observaciones: observaciones,
|
||||
Cliente: clienteNombre,
|
||||
Empresa: clienteEmpresa,
|
||||
Proyecto: proyecto,
|
||||
}
|
||||
|
||||
return ejecutarPipeline(ctx, cliente, entrada, economia, observacionesInternas)
|
||||
}
|
||||
|
||||
func ejecutarPipeline(
|
||||
ctx context.Context,
|
||||
cliente *ClienteIA,
|
||||
entrada ContextoEntrada,
|
||||
economia *EconomiaCotizacion,
|
||||
notasInternas string,
|
||||
) (*GenerarResult, error) {
|
||||
system := []BloqueSystem{{Texto: SystemBase, Cachear: true}}
|
||||
pasos := make([]pasoTraza, 0, 3)
|
||||
var totalUso UsoTokens
|
||||
acumular := func(u UsoTokens) {
|
||||
totalUso.Entrada += u.Entrada
|
||||
totalUso.Salida += u.Salida
|
||||
totalUso.CacheLectura += u.CacheLectura
|
||||
totalUso.CacheEscritura += u.CacheEscritura
|
||||
}
|
||||
|
||||
r1, err := cliente.LlamarConHerramienta(ctx, OpcionesLlamada{
|
||||
System: system,
|
||||
MensajeUsuario: MensajePaso1(entrada),
|
||||
Herramienta: Herramienta{
|
||||
Nombre: "registrar_hechos",
|
||||
Descripcion: "Registra las citas literales, los hechos, los pendientes y las red flags extraidos del material de la reunion.",
|
||||
InputSchema: SchemaHechos(),
|
||||
Validar: ValidarHechos,
|
||||
},
|
||||
MaxIntentos: 5,
|
||||
MaxTokens: 8000,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pasos = append(pasos, pasoTraza{Paso: "extraccion", Intentos: r1.Intentos, Uso: r1.Uso})
|
||||
acumular(r1.Uso)
|
||||
|
||||
r2, err := cliente.LlamarConHerramienta(ctx, OpcionesLlamada{
|
||||
System: system,
|
||||
MensajeUsuario: MensajePaso2(entrada, r1.Datos, economia),
|
||||
Herramienta: Herramienta{
|
||||
Nombre: "registrar_diagnostico",
|
||||
Descripcion: "Registra los hallazgos con su semaforo de urgencia, el valor anual del problema y los resultados de negocio a lograr.",
|
||||
InputSchema: SchemaDiagnostico(),
|
||||
Validar: ValidarDiagnostico,
|
||||
},
|
||||
MaxIntentos: 4,
|
||||
MaxTokens: 8000,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pasos = append(pasos, pasoTraza{Paso: "diagnostico", Intentos: r2.Intentos, Uso: r2.Uso})
|
||||
acumular(r2.Uso)
|
||||
|
||||
r3, err := cliente.LlamarConHerramienta(ctx, OpcionesLlamada{
|
||||
System: system,
|
||||
MensajeUsuario: MensajePaso3(entrada, r1.Datos, r2.Datos, economia),
|
||||
Herramienta: Herramienta{
|
||||
Nombre: "registrar_propuesta",
|
||||
Descripcion: "Registra la redaccion final de la propuesta consultiva para el cliente.",
|
||||
InputSchema: SchemaRedaccion(),
|
||||
Validar: ValidarRedaccion,
|
||||
},
|
||||
MaxIntentos: 4,
|
||||
MaxTokens: 12000,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pasos = append(pasos, pasoTraza{Paso: "redaccion", Intentos: r3.Intentos, Uso: r3.Uso})
|
||||
acumular(r3.Uso)
|
||||
|
||||
contenido := map[string]any{
|
||||
"hechos": r1.Datos,
|
||||
"diagnostico": r2.Datos,
|
||||
"redaccion": r3.Datos,
|
||||
}
|
||||
|
||||
fuentesCliente := strings.Join([]string{entrada.Transcripcion, entrada.Observaciones, entrada.Notas}, "\n")
|
||||
avisos := ValidarPropuesta(contenido, economia, fuentesCliente, notasInternas)
|
||||
|
||||
traza := map[string]any{
|
||||
"modelo": cliente.Model,
|
||||
"pasos": pasos,
|
||||
"totalUso": totalUso,
|
||||
}
|
||||
|
||||
return &GenerarResult{
|
||||
Contenido: contenido,
|
||||
Traza: traza,
|
||||
Avisos: avisos,
|
||||
Modelo: cliente.Model,
|
||||
}, nil
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,876 @@
|
||||
package propuesta
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/config"
|
||||
"cotizador/internal/domain"
|
||||
)
|
||||
|
||||
// ─────────────────────────── economia.go ───────────────────────────
|
||||
|
||||
func TestCalcularRatio(t *testing.T) {
|
||||
// Sin valor anual / cero / negativo -> sin etiqueta ni division entre cero
|
||||
for _, val := range []float64{0, -5, -1000} {
|
||||
r := CalcularRatio(100000, val)
|
||||
if r.Ratio != 0 || r.Etiqueta != "" {
|
||||
t.Fatalf("valorAnual=%v: esperado Ratio=0 Etiqueta=\"\", obtuve %+v", val, r)
|
||||
}
|
||||
if r.Nota == "" {
|
||||
t.Fatalf("valorAnual=%v: esperaba Nota explicativa", val)
|
||||
}
|
||||
}
|
||||
|
||||
casos := []struct {
|
||||
nombre string
|
||||
total float64
|
||||
valor float64
|
||||
etiqueta string
|
||||
ratio float64
|
||||
}{
|
||||
{"5% subcotizado", 50000, 1000000, "subcotizado", 0.05},
|
||||
{"corte exacto 10% en_rango", 100000, 1000000, "en_rango", 0.1},
|
||||
{"20% en_rango", 200000, 1000000, "en_rango", 0.2},
|
||||
{"corte exacto 25% en_rango", 250000, 1000000, "en_rango", 0.25},
|
||||
{"35% alto", 350000, 1000000, "alto", 0.35},
|
||||
{"corte exacto 40% alto", 400000, 1000000, "alto", 0.4},
|
||||
{"60% objecion_probable", 600000, 1000000, "objecion_probable", 0.6},
|
||||
{"redondeo a 3 decimales", 123456, 1000000, "en_rango", 0.123},
|
||||
}
|
||||
|
||||
for _, tc := range casos {
|
||||
t.Run(tc.nombre, func(t *testing.T) {
|
||||
got := CalcularRatio(tc.total, tc.valor)
|
||||
if got.Etiqueta != tc.etiqueta {
|
||||
t.Fatalf("etiqueta: esperado %q, obtuve %q (ratio=%v)", tc.etiqueta, got.Etiqueta, got.Ratio)
|
||||
}
|
||||
if got.Ratio != tc.ratio {
|
||||
t.Fatalf("ratio: esperado %v, obtuve %v", tc.ratio, got.Ratio)
|
||||
}
|
||||
if got.Nota == "" {
|
||||
t.Fatalf("se esperaba Nota no vacia para %q", tc.etiqueta)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────── cliente_ia.go ───────────────────────────
|
||||
|
||||
func TestNuevoClienteIA(t *testing.T) {
|
||||
t.Run("rechaza clave faltante nombrando MINIMAX_API_KEY y ANTHROPIC_API_KEY", func(t *testing.T) {
|
||||
t.Setenv("MINIMAX_API_KEY", "")
|
||||
t.Setenv("ANTHROPIC_API_KEY", "")
|
||||
_, err := NuevoClienteIA(&config.Config{})
|
||||
if err == nil {
|
||||
t.Fatal("esperaba error sin MINIMAX_API_KEY")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "MINIMAX_API_KEY") || !strings.Contains(err.Error(), "ANTHROPIC_API_KEY") {
|
||||
t.Fatalf("mensaje debe mencionar MINIMAX_API_KEY y ANTHROPIC_API_KEY: %q", err.Error())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("advierte explicitamente si solo ANTHROPIC_API_KEY esta definida", func(t *testing.T) {
|
||||
t.Setenv("MINIMAX_API_KEY", "")
|
||||
t.Setenv("ANTHROPIC_API_KEY", "sk-ant-solo-prueba")
|
||||
_, err := NuevoClienteIA(&config.Config{})
|
||||
if err == nil {
|
||||
t.Fatal("esperaba error cuando solo ANTHROPIC_API_KEY esta definida")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "ANTHROPIC_API_KEY") || !strings.Contains(err.Error(), "MINIMAX_API_KEY") {
|
||||
t.Fatalf("error debe advertir sobre ANTHROPIC_API_KEY: %q", err.Error())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("defaults e ignorar ANTHROPIC_BASE_URL", func(t *testing.T) {
|
||||
t.Setenv("ANTHROPIC_BASE_URL", "https://api.anthropic.com")
|
||||
c, err := NuevoClienteIA(&config.Config{MinimaxAPIKey: "clave-prueba"})
|
||||
if err != nil {
|
||||
t.Fatalf("error inesperado: %v", err)
|
||||
}
|
||||
if !strings.Contains(c.BaseURL, "api.minimax.io") {
|
||||
t.Fatalf("BaseURL esperado de MiniMax, obtuve %q", c.BaseURL)
|
||||
}
|
||||
if strings.Contains(c.BaseURL, "api.anthropic.com") {
|
||||
t.Fatalf("ANTHROPIC_BASE_URL no debe secuestrar BaseURL: %q", c.BaseURL)
|
||||
}
|
||||
if c.Model != "MiniMax-M3" {
|
||||
t.Fatalf("Model por defecto esperado MiniMax-M3, obtuve %q", c.Model)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("respeta MINIMAX_BASE_URL y MINIMAX_MODEL", func(t *testing.T) {
|
||||
c, err := NuevoClienteIA(&config.Config{
|
||||
MinimaxAPIKey: "clave-prueba",
|
||||
MinimaxBaseURL: "https://ejemplo.local/anthropic/",
|
||||
MinimaxModel: "MiniMax-M2",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("error inesperado: %v", err)
|
||||
}
|
||||
if c.BaseURL != "https://ejemplo.local/anthropic" {
|
||||
t.Fatalf("BaseURL inesperado: %q", c.BaseURL)
|
||||
}
|
||||
if c.Model != "MiniMax-M2" {
|
||||
t.Fatalf("Model inesperado: %q", c.Model)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestNormalizarRespuesta(t *testing.T) {
|
||||
casos := []struct {
|
||||
nombre string
|
||||
in any
|
||||
want any
|
||||
}{
|
||||
{
|
||||
"desenvuelve {item: X} cuando item es la unica clave",
|
||||
map[string]any{"item": map[string]any{"a": 1}},
|
||||
map[string]any{"a": 1},
|
||||
},
|
||||
{
|
||||
"desenvuelve dentro de arrays",
|
||||
[]any{map[string]any{"item": map[string]any{"a": 1}}, map[string]any{"item": map[string]any{"a": 2}}},
|
||||
[]any{map[string]any{"a": 1}, map[string]any{"a": 2}},
|
||||
},
|
||||
{
|
||||
"desenvuelve en profundidad",
|
||||
map[string]any{"lista": []any{map[string]any{"item": map[string]any{"x": []any{map[string]any{"item": 5}}}}}},
|
||||
map[string]any{"lista": []any{map[string]any{"x": []any{5}}}},
|
||||
},
|
||||
{
|
||||
"NO toca un objeto con item junto a otras claves",
|
||||
map[string]any{"item": 1, "otro": 2},
|
||||
map[string]any{"item": 1, "otro": 2},
|
||||
},
|
||||
{
|
||||
"deja intactos valores simples",
|
||||
"texto",
|
||||
"texto",
|
||||
},
|
||||
{
|
||||
"deja intacto nil",
|
||||
nil,
|
||||
nil,
|
||||
},
|
||||
{
|
||||
"no altera un objeto normal",
|
||||
map[string]any{"a": 1, "b": []any{1, 2}},
|
||||
map[string]any{"a": 1, "b": []any{1, 2}},
|
||||
},
|
||||
{
|
||||
"caso real: alcance envuelto",
|
||||
map[string]any{"alcance": []any{map[string]any{"item": map[string]any{"refPartida": "P01", "descripcionResultado": "x"}}}},
|
||||
map[string]any{"alcance": []any{map[string]any{"refPartida": "P01", "descripcionResultado": "x"}}},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range casos {
|
||||
t.Run(tc.nombre, func(t *testing.T) {
|
||||
got := NormalizarRespuesta(tc.in)
|
||||
if !reflect.DeepEqual(got, tc.want) {
|
||||
t.Fatalf("esperado %#v, obtuve %#v", tc.want, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClienteIAToolCallingRetryYFeedback(t *testing.T) {
|
||||
var calls int32
|
||||
var sawToolChoice, sawCacheControl, sawToolResultError bool
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
n := atomic.AddInt32(&calls, 1)
|
||||
if r.URL.Path != "/v1/messages" {
|
||||
t.Errorf("path inesperado: %s", r.URL.Path)
|
||||
}
|
||||
if r.Header.Get("x-api-key") != "test-key" {
|
||||
t.Errorf("x-api-key faltante o invalido: %q", r.Header.Get("x-api-key"))
|
||||
}
|
||||
|
||||
var body map[string]any
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Fatalf("body JSON invalido: %v", err)
|
||||
}
|
||||
if tc, ok := body["tool_choice"].(map[string]any); ok && tc["type"] == "tool" && tc["name"] == "registrar_hechos" {
|
||||
sawToolChoice = true
|
||||
}
|
||||
if sys, ok := body["system"].([]any); ok && len(sys) > 0 {
|
||||
if s0, ok := sys[0].(map[string]any); ok {
|
||||
if cc, ok := s0["cache_control"].(map[string]any); ok && cc["type"] == "ephemeral" {
|
||||
sawCacheControl = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Llamada 1: fallo transitorio 429
|
||||
if n == 1 {
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
_, _ = w.Write([]byte(`{"error":"rate_limit"}`))
|
||||
return
|
||||
}
|
||||
// Llamada 2: devuelve tool_use invalido (cita muy corta -> dispara feedback loop)
|
||||
if n == 2 {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"id": "msg_1",
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"content": []any{
|
||||
map[string]any{
|
||||
"type": "tool_use",
|
||||
"id": "tu_1",
|
||||
"name": "registrar_hechos",
|
||||
"input": map[string]any{
|
||||
"citas": []any{map[string]any{"id": "C01", "textoLiteral": "corta", "quienLoDijo": "socio"}},
|
||||
"hechos": []any{}, "materialesPendientes": []any{},
|
||||
"decisionesPendientes": []any{}, "mencionesFueraDeAlcance": []any{}, "redFlags": []any{},
|
||||
},
|
||||
},
|
||||
},
|
||||
"usage": map[string]any{"input_tokens": 100, "output_tokens": 50, "cache_creation_input_tokens": 80},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Llamada 3: verificar que llego tool_result con is_error=true y responder valido envuelto en {item:...}
|
||||
if msgs, ok := body["messages"].([]any); ok && len(msgs) >= 3 {
|
||||
if last, ok := msgs[len(msgs)-1].(map[string]any); ok {
|
||||
if blocks, ok := last["content"].([]any); ok {
|
||||
for _, b := range blocks {
|
||||
if bm, ok := b.(map[string]any); ok && bm["type"] == "tool_result" && bm["is_error"] == true {
|
||||
sawToolResultError = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"id": "msg_2",
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"content": []any{
|
||||
map[string]any{
|
||||
"type": "tool_use",
|
||||
"id": "tu_2",
|
||||
"name": "registrar_hechos",
|
||||
"input": map[string]any{
|
||||
"citas": []any{map[string]any{"item": map[string]any{
|
||||
"id": "C01",
|
||||
"textoLiteral": "no llevamos control de quien contesta el whatsapp el fin de semana",
|
||||
"quienLoDijo": "el socio",
|
||||
}}},
|
||||
"hechos": []any{}, "materialesPendientes": []any{},
|
||||
"decisionesPendientes": []any{}, "mencionesFueraDeAlcance": []any{}, "redFlags": []any{},
|
||||
},
|
||||
},
|
||||
},
|
||||
"usage": map[string]any{"input_tokens": 120, "output_tokens": 60, "cache_read_input_tokens": 80},
|
||||
})
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
cliente := &ClienteIA{
|
||||
APIKey: "test-key",
|
||||
BaseURL: srv.URL,
|
||||
Model: "MiniMax-M3",
|
||||
HTTPClient: srv.Client(),
|
||||
Sleep: func(context.Context, time.Duration) error { return nil },
|
||||
}
|
||||
|
||||
res, err := cliente.LlamarConHerramienta(context.Background(), OpcionesLlamada{
|
||||
System: []BloqueSystem{{Texto: SystemBase, Cachear: true}},
|
||||
MensajeUsuario: "extrae hechos",
|
||||
Herramienta: Herramienta{
|
||||
Nombre: "registrar_hechos",
|
||||
Descripcion: "test",
|
||||
InputSchema: SchemaHechos(),
|
||||
Validar: ValidarHechos,
|
||||
},
|
||||
MaxIntentos: 3,
|
||||
MaxTokens: 1000,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("error inesperado: %v", err)
|
||||
}
|
||||
if !sawToolChoice {
|
||||
t.Fatal("esperaba tool_choice: {type: tool, name: registrar_hechos}")
|
||||
}
|
||||
if !sawCacheControl {
|
||||
t.Fatal("esperaba cache_control: {type: ephemeral}")
|
||||
}
|
||||
if !sawToolResultError {
|
||||
t.Fatal("esperaba feedback loop con tool_result is_error=true")
|
||||
}
|
||||
if res.Intentos != 2 {
|
||||
t.Fatalf("esperaba 2 intentos de validacion (mas 1 reintento HTTP 429), obtuve %d", res.Intentos)
|
||||
}
|
||||
if res.Uso.Entrada != 220 || res.Uso.Salida != 110 || res.Uso.CacheEscritura != 80 || res.Uso.CacheLectura != 80 {
|
||||
t.Fatalf("acumulacion de uso incorrecta: %+v", res.Uso)
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────── prompts.go & schemas ───────────────────────────
|
||||
|
||||
func TestSystemBaseCacheInvariants(t *testing.T) {
|
||||
anioActual := strconv.Itoa(time.Now().Year())
|
||||
if strings.Contains(SystemBase, anioActual) {
|
||||
t.Fatalf("SystemBase no debe contener el anio actual (%s)", anioActual)
|
||||
}
|
||||
if regexp.MustCompile(`\d{4}-\d{2}-\d{2}`).MatchString(SystemBase) {
|
||||
t.Fatal("SystemBase no debe contener fechas ISO")
|
||||
}
|
||||
if regexp.MustCompile(`UJ\d{4}`).MatchString(SystemBase) {
|
||||
t.Fatal("SystemBase no debe contener folios de cotizacion")
|
||||
}
|
||||
if len(SystemBase) <= 2500 {
|
||||
t.Fatalf("SystemBase debe superar el minimo cacheable (>2500 chars), tiene %d", len(SystemBase))
|
||||
}
|
||||
|
||||
for _, p := range []string{"P1.", "P2.", "P3.", "P4.", "P5.", "P6.", "P7.", "P8."} {
|
||||
if !strings.Contains(SystemBase, p) {
|
||||
t.Fatalf("SystemBase debe declarar principio %s", p)
|
||||
}
|
||||
}
|
||||
for _, s := range []string{
|
||||
"rojo:", "ambar:", "azul:", "verde:", "entre pares",
|
||||
"Bucefalo", "ningun otro CRM", "USD", "garantizado",
|
||||
"sinergias", "UNICAMENTE servicios digitales",
|
||||
"nombres de empleados", "MATERIAL ES POBRE", "contenido de valor",
|
||||
} {
|
||||
if !strings.Contains(SystemBase, s) {
|
||||
t.Fatalf("SystemBase debe contener %q", s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBloqueContextoYMensajesSinPrecios(t *testing.T) {
|
||||
sinNada := BloqueContexto(ContextoEntrada{Cliente: "Ana", Proyecto: "P"})
|
||||
if !strings.Contains(sinNada, "No se entrego transcripcion") {
|
||||
t.Fatal("sin transcripcion debe declararlo explicitamente")
|
||||
}
|
||||
if strings.Contains(sinNada, "()") {
|
||||
t.Fatal("sin empresa no debe imprimir parentesis vacios")
|
||||
}
|
||||
|
||||
conTodo := BloqueContexto(ContextoEntrada{
|
||||
Transcripcion: "TRANS", Notas: "NOTAS", Observaciones: "OBS",
|
||||
Cliente: "Ana", Empresa: "ACME", Proyecto: "P",
|
||||
})
|
||||
for _, needle := range []string{"TRANS", "NOTAS", "OBS", "(ACME)"} {
|
||||
if !strings.Contains(conTodo, needle) {
|
||||
t.Fatalf("BloqueContexto debe incluir %q", needle)
|
||||
}
|
||||
}
|
||||
|
||||
econ := &EconomiaCotizacion{
|
||||
Partidas: []PartidaEconomia{
|
||||
{Ref: "P01", Nombre: "Sitio web", Fase: 1, TipoPago: "unico", Precio: 12345, TiempoEntrega: "2 semanas", ModeloCobro: "fijo"},
|
||||
},
|
||||
Totales: domain.TotalesCotizacion{
|
||||
SubtotalUnico: 12345, IVAUnico: 1975.2, TotalUnico: 14320.2, TotalPrimerAnio: 14320.2, IncluyeIVA: true,
|
||||
},
|
||||
Moneda: "MXN",
|
||||
}
|
||||
ctx := ContextoEntrada{Transcripcion: "t", Cliente: "Ana", Empresa: "ACME", Proyecto: "P"}
|
||||
hechos := map[string]any{"citas": []any{}, "hechos": []any{}}
|
||||
diag := map[string]any{"hallazgos": []any{}, "valorProblema": map[string]any{"dimensiones": []any{}, "notaMetodologia": ""}}
|
||||
|
||||
m1 := MensajePaso1(ctx)
|
||||
m2 := MensajePaso2(ctx, hechos, econ)
|
||||
m3 := MensajePaso3(ctx, hechos, diag, econ)
|
||||
|
||||
if !strings.Contains(m1, "registrar_hechos") || !strings.Contains(m1, "TEXTUALES") {
|
||||
t.Fatal("MensajePaso1 debe pedir registrar_hechos y citas TEXTUALES")
|
||||
}
|
||||
if !strings.Contains(m2, "registrar_diagnostico") {
|
||||
t.Fatal("MensajePaso2 debe pedir registrar_diagnostico")
|
||||
}
|
||||
if !strings.Contains(m3, "registrar_propuesta") {
|
||||
t.Fatal("MensajePaso3 debe pedir registrar_propuesta")
|
||||
}
|
||||
|
||||
for nombre, msg := range map[string]string{"paso 2": m2, "paso 3": m3} {
|
||||
if strings.Contains(msg, "12345") || strings.Contains(msg, "14320") {
|
||||
t.Fatalf("%s NO puede filtrar precios o totales", nombre)
|
||||
}
|
||||
if !strings.Contains(msg, "P01") {
|
||||
t.Fatalf("%s SI debe incluir refPartida P01", nombre)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolSchemasZeroUJCPriceKeys(t *testing.T) {
|
||||
schemas := []map[string]any{SchemaHechos(), SchemaDiagnostico(), SchemaRedaccion()}
|
||||
rawBytes, err := json.Marshal(schemas)
|
||||
if err != nil {
|
||||
t.Fatalf("error serializando schemas: %v", err)
|
||||
}
|
||||
todos := string(rawBytes)
|
||||
|
||||
prohibidos := []string{"precio", "total", "subtotal", "iva", "montoMinimo", "tarifaHora", "descuento"}
|
||||
for _, p := range prohibidos {
|
||||
if strings.Contains(todos, `"`+p+`"`) {
|
||||
t.Fatalf("ningun tool schema puede declarar propiedad de dinero UJC %q", p)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(todos, `"montoAnualMXN"`) {
|
||||
t.Fatal("SchemaDiagnostico debe incluir montoAnualMXN (costo del problema del cliente)")
|
||||
}
|
||||
if strings.Contains(todos, `"$schema"`) {
|
||||
t.Fatal("los tool schemas no deben llevar $schema")
|
||||
}
|
||||
if strings.Contains(todos, `"calculo"`) {
|
||||
t.Fatal("la dimension de valorProblema debe ser plana, sin objeto calculo")
|
||||
}
|
||||
if !strings.Contains(todos, `"additionalProperties"`) || !strings.Contains(todos, `"description"`) {
|
||||
t.Fatal("los tool schemas deben conservar additionalProperties y description")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidadoresSchemaPasos(t *testing.T) {
|
||||
// Hechos vacios validos (material pobre)
|
||||
if errs := ValidarHechos(map[string]any{
|
||||
"citas": []any{}, "hechos": []any{}, "materialesPendientes": []any{},
|
||||
"decisionesPendientes": []any{}, "mencionesFueraDeAlcance": []any{}, "redFlags": []any{},
|
||||
}); len(errs) != 0 {
|
||||
t.Fatalf("hechos vacios deben ser validos: %v", errs)
|
||||
}
|
||||
|
||||
// Diagnostico: omitir montoAnualMXN se tolera y rellena nil; con monto y <2 factores se rechaza
|
||||
dimSinMonto := map[string]any{
|
||||
"tipo": "tiempo", "descripcion": "Horas perdidas en atencion",
|
||||
"factores": []any{}, "confianza": "por_validar", "hechos": []any{},
|
||||
}
|
||||
diag := map[string]any{
|
||||
"hallazgos": []any{map[string]any{
|
||||
"id": "D01", "urgencia": "rojo", "titulo": "Titulo valido",
|
||||
"descripcion": strings.Repeat("x", 25), "confianza": "confirmado",
|
||||
"citas": []any{}, "hechos": []any{},
|
||||
}},
|
||||
"valorProblema": map[string]any{
|
||||
"dimensiones": []any{dimSinMonto},
|
||||
"notaMetodologia": "sin cifras",
|
||||
},
|
||||
"resultados": []any{},
|
||||
}
|
||||
if errs := ValidarDiagnostico(diag); len(errs) != 0 {
|
||||
t.Fatalf("diagnostico omitiendo montoAnualMXN debe validar: %v", errs)
|
||||
}
|
||||
if val, exists := dimSinMonto["montoAnualMXN"]; !exists || val != nil {
|
||||
t.Fatalf("omitir montoAnualMXN debe rellenar nil, obtuve exists=%v val=%v", exists, val)
|
||||
}
|
||||
|
||||
// Con montoAnualMXN y solo 1 factor -> error
|
||||
dimUnFactor := map[string]any{
|
||||
"tipo": "tiempo", "descripcion": "Horas perdidas en atencion",
|
||||
"factores": []any{map[string]any{"nombre": "a", "valor": 1.0, "confianza": "estimado"}},
|
||||
"montoAnualMXN": 1.0, "confianza": "estimado", "hechos": []any{},
|
||||
}
|
||||
diag["valorProblema"].(map[string]any)["dimensiones"] = []any{dimUnFactor}
|
||||
if errs := ValidarDiagnostico(diag); len(errs) == 0 {
|
||||
t.Fatal("esperaba rechazo al declarar montoAnualMXN con menos de 2 factores")
|
||||
}
|
||||
|
||||
// Redaccion estricta rechaza propiedad desconocida `precioTotal`
|
||||
red := map[string]any{
|
||||
"hero": map[string]any{"titulo": "Titulo valido", "subtitulo": strings.Repeat("x", 25)},
|
||||
"citaDestacadaId": "C01",
|
||||
"alcance": []any{map[string]any{"refPartida": "P01", "descripcionResultado": strings.Repeat("x", 25)}},
|
||||
"beneficios": []any{},
|
||||
"exclusiones": []any{map[string]any{"texto": strings.Repeat("x", 20), "razon": "porque si"}},
|
||||
"backlogEvolucion": []any{},
|
||||
"notasInternas": []any{},
|
||||
"precioTotal": 99999,
|
||||
}
|
||||
if errs := ValidarRedaccion(red); len(errs) == 0 {
|
||||
t.Fatal("ValidarRedaccion debe rechazar propiedades desconocidas")
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────── validacion.go ───────────────────────────
|
||||
|
||||
const citaPrueba = "no llevamos control de quien contesta el whatsapp el fin de semana"
|
||||
|
||||
func econPrueba() *EconomiaCotizacion {
|
||||
return &EconomiaCotizacion{
|
||||
Partidas: []PartidaEconomia{
|
||||
{Ref: "P01", Nombre: "Sitio web", Fase: 1, TipoPago: "unico", Precio: 12000, TiempoEntrega: "2 semanas", ModeloCobro: "fijo"},
|
||||
},
|
||||
Totales: domain.TotalesCotizacion{
|
||||
SubtotalUnico: 12000, IVAUnico: 1920, TotalUnico: 13920, TotalPrimerAnio: 13920, IncluyeIVA: true,
|
||||
},
|
||||
Moneda: "MXN",
|
||||
}
|
||||
}
|
||||
|
||||
func propuestaBase() map[string]any {
|
||||
return map[string]any{
|
||||
"hechos": map[string]any{
|
||||
"citas": []any{
|
||||
map[string]any{"id": "C01", "textoLiteral": citaPrueba, "quienLoDijo": "el socio"},
|
||||
},
|
||||
"hechos": []any{
|
||||
map[string]any{"id": "H01", "enunciado": "No hay control de la atencion", "confianza": "confirmado", "citas": []any{"C01"}},
|
||||
},
|
||||
"materialesPendientes": []any{map[string]any{"texto": "Accesos al dominio", "bloqueaEntrega": true}},
|
||||
"decisionesPendientes": []any{map[string]any{"texto": "Definir responsable de atencion", "quienDecide": "el socio"}},
|
||||
"mencionesFueraDeAlcance": []any{},
|
||||
"redFlags": []any{},
|
||||
},
|
||||
"diagnostico": map[string]any{
|
||||
"hallazgos": []any{
|
||||
map[string]any{
|
||||
"id": "D01", "urgencia": "rojo", "titulo": "Prospectos sin seguimiento",
|
||||
"descripcion": "Los mensajes del fin de semana se pierden.",
|
||||
"confianza": "confirmado", "citas": []any{"C01"}, "hechos": []any{"H01"},
|
||||
},
|
||||
},
|
||||
"valorProblema": map[string]any{
|
||||
"dimensiones": []any{
|
||||
map[string]any{
|
||||
"tipo": "tiempo", "descripcion": "Horas perdidas de atencion",
|
||||
"factores": []any{
|
||||
map[string]any{"nombre": "horas por semana", "valor": 8.0, "confianza": "confirmado"},
|
||||
map[string]any{"nombre": "semanas", "valor": 52.0, "confianza": "confirmado"},
|
||||
map[string]any{"nombre": "costo por hora", "valor": 400.0, "confianza": "estimado"},
|
||||
},
|
||||
"montoAnualMXN": 166400.0, "confianza": "estimado", "hechos": []any{"H01"},
|
||||
},
|
||||
},
|
||||
"notaMetodologia": "Ocho horas por semana a costo cargado.",
|
||||
},
|
||||
"resultados": []any{
|
||||
map[string]any{
|
||||
"enunciado": "Ningun mensaje sin respuesta en mas de 24 horas",
|
||||
"metrica": "tiempo de respuesta", "lineaBase": nil, "periodoMedicion": "mensual",
|
||||
},
|
||||
},
|
||||
},
|
||||
"redaccion": map[string]any{
|
||||
"hero": map[string]any{
|
||||
"titulo": "Propuesta de digitalizacion",
|
||||
"subtitulo": "Ordenar la atencion para dejar de perder prospectos.",
|
||||
},
|
||||
"citaDestacadaId": "C01",
|
||||
"alcance": []any{
|
||||
map[string]any{"refPartida": "P01", "descripcionResultado": "Un lugar a donde mandar a los prospectos que llegan de los anuncios."},
|
||||
},
|
||||
"beneficios": []any{
|
||||
map[string]any{"etiqueta": "Respuesta", "texto": "Cada mensaje queda registrado y con responsable.", "hallazgoId": "D01"},
|
||||
},
|
||||
"exclusiones": []any{
|
||||
map[string]any{"texto": "No incluye migrar el historico de pedidos de los ultimos 4 anos.", "razon": "Se evalua en fase 2."},
|
||||
},
|
||||
"backlogEvolucion": []any{},
|
||||
"notasInternas": []any{"El socio es quien decide."},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func tieneRegla(avisos []Aviso, regla string) bool {
|
||||
for _, a := range avisos {
|
||||
if a.Regla == regla {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func severidadRegla(avisos []Aviso, regla string) string {
|
||||
for _, a := range avisos {
|
||||
if a.Regla == regla {
|
||||
return a.Severidad
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func TestNormalizarTexto(t *testing.T) {
|
||||
if got := NormalizarTexto("¿Cómo estás, Juan?"); got != "como estas juan" {
|
||||
t.Fatalf("esperado %q, obtuve %q", "como estas juan", got)
|
||||
}
|
||||
if got := NormalizarTexto(" a b "); got != "a b" {
|
||||
t.Fatalf("esperado %q, obtuve %q", "a b", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidarPropuestaTodasLasReglas(t *testing.T) {
|
||||
econ := econPrueba()
|
||||
fuentes := "El socio dijo: " + citaPrueba + ". Nada mas."
|
||||
|
||||
t.Run("propuesta limpia sin bloqueantes", func(t *testing.T) {
|
||||
avisos := ValidarPropuesta(propuestaBase(), econ, fuentes, "")
|
||||
if HayBloqueantes(avisos) {
|
||||
t.Fatalf("propuesta limpia no debe producir bloqueantes: %+v", avisos)
|
||||
}
|
||||
if len(avisos) != 0 {
|
||||
t.Fatalf("propuesta limpia no debe producir avisos: %+v", avisos)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("R0 fuga de notas internas 7-gramas", func(t *testing.T) {
|
||||
interno := "el socio pidio descuento antes de entender el alcance del proyecto completo"
|
||||
|
||||
// Fuga en hero
|
||||
p := propuestaBase()
|
||||
p["redaccion"].(map[string]any)["hero"].(map[string]any)["subtitulo"] = "Contexto del proyecto: " + interno + "."
|
||||
av := ValidarPropuesta(p, econ, fuentes, interno)
|
||||
if !tieneRegla(av, "R0") || severidadRegla(av, "R0") != "bloqueante" {
|
||||
t.Fatalf("R0 debe bloquear fuga en hero: %+v", av)
|
||||
}
|
||||
|
||||
// Fuga en hallazgo
|
||||
p = propuestaBase()
|
||||
p["diagnostico"].(map[string]any)["hallazgos"].([]any)[0].(map[string]any)["descripcion"] = "Observado: " + interno + "."
|
||||
av = ValidarPropuesta(p, econ, fuentes, interno)
|
||||
if !tieneRegla(av, "R0") {
|
||||
t.Fatalf("R0 debe revisar todos los campos visibles (hallazgo): %+v", av)
|
||||
}
|
||||
|
||||
// Sin fuga -> ok
|
||||
if tieneRegla(ValidarPropuesta(propuestaBase(), econ, fuentes, interno), "R0") {
|
||||
t.Fatal("R0 no debe disparar si no hay fuga")
|
||||
}
|
||||
|
||||
// En notasInternas del propio resultado -> NO se imprime, NO dispara R0
|
||||
p = propuestaBase()
|
||||
p["redaccion"].(map[string]any)["notasInternas"] = []any{interno}
|
||||
if tieneRegla(ValidarPropuesta(p, econ, fuentes, interno), "R0") {
|
||||
t.Fatal("R0 no debe quejarse de notasInternas (no se imprimen)")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("R2 y R2b referencias de partidas", func(t *testing.T) {
|
||||
p := propuestaBase()
|
||||
p["redaccion"].(map[string]any)["alcance"].([]any)[0].(map[string]any)["refPartida"] = "P99"
|
||||
av := ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "R2") || severidadRegla(av, "R2") != "bloqueante" {
|
||||
t.Fatalf("R2 debe bloquear partida inventada P99: %+v", av)
|
||||
}
|
||||
|
||||
p = propuestaBase()
|
||||
p["redaccion"].(map[string]any)["alcance"] = []any{}
|
||||
av = ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "R2b") || severidadRegla(av, "R2b") != "advertencia" {
|
||||
t.Fatalf("R2b debe advertir partida cotizada no descrita: %+v", av)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("R3 cita destacada existe y es literal", func(t *testing.T) {
|
||||
p := propuestaBase()
|
||||
p["redaccion"].(map[string]any)["citaDestacadaId"] = "C09"
|
||||
av := ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "R3") || severidadRegla(av, "R3") != "bloqueante" {
|
||||
t.Fatalf("R3 debe bloquear cita inexistente: %+v", av)
|
||||
}
|
||||
|
||||
p = propuestaBase()
|
||||
p["hechos"].(map[string]any)["citas"].([]any)[0].(map[string]any)["textoLiteral"] = "esto nunca lo dijo nadie en la reunion"
|
||||
av = ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "R3") {
|
||||
t.Fatalf("R3 debe bloquear cita no literal: %+v", av)
|
||||
}
|
||||
|
||||
// Tolera acentos, mayusculas y puntuacion
|
||||
p = propuestaBase()
|
||||
p["hechos"].(map[string]any)["citas"].([]any)[0].(map[string]any)["textoLiteral"] = "NO LLEVAMOS CONTROL, de quién contesta... el WhatsApp el fin de semana!"
|
||||
if tieneRegla(ValidarPropuesta(p, econ, fuentes, ""), "R3") {
|
||||
t.Fatal("R3 debe tolerar acentos, mayusculas y puntuacion")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("R4 confirmado sin evidencia", func(t *testing.T) {
|
||||
p := propuestaBase()
|
||||
h0 := p["diagnostico"].(map[string]any)["hallazgos"].([]any)[0].(map[string]any)
|
||||
h0["citas"] = []any{}
|
||||
h0["hechos"] = []any{}
|
||||
av := ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "R4") || severidadRegla(av, "R4") != "advertencia" {
|
||||
t.Fatalf("R4 debe advertir hallazgo confirmado sin citas ni hechos: %+v", av)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("R5 aritmetica dentro de 2% y R5b sin factores confirmados", func(t *testing.T) {
|
||||
// No cuadra -> R5 bloqueante
|
||||
p := propuestaBase()
|
||||
dim := p["diagnostico"].(map[string]any)["valorProblema"].(map[string]any)["dimensiones"].([]any)[0].(map[string]any)
|
||||
dim["montoAnualMXN"] = 999999.0
|
||||
av := ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "R5") || severidadRegla(av, "R5") != "bloqueante" {
|
||||
t.Fatalf("R5 debe bloquear aritmetica inconsistente: %+v", av)
|
||||
}
|
||||
|
||||
// Cuadra por suma dentro de 2% -> sin R5
|
||||
p = propuestaBase()
|
||||
dim = p["diagnostico"].(map[string]any)["valorProblema"].(map[string]any)["dimensiones"].([]any)[0].(map[string]any)
|
||||
dim["factores"] = []any{
|
||||
map[string]any{"nombre": "a", "valor": 10000.0, "confianza": "confirmado"},
|
||||
map[string]any{"nombre": "b", "valor": 5000.0, "confianza": "estimado"},
|
||||
}
|
||||
dim["montoAnualMXN"] = 15100.0 // diferencia < 1%
|
||||
if tieneRegla(ValidarPropuesta(p, econ, fuentes, ""), "R5") {
|
||||
t.Fatal("R5 debe aceptar suma dentro del margen de 2%")
|
||||
}
|
||||
|
||||
// Sin cifra (nil) -> sin R5 ni R5b
|
||||
p = propuestaBase()
|
||||
dim = p["diagnostico"].(map[string]any)["valorProblema"].(map[string]any)["dimensiones"].([]any)[0].(map[string]any)
|
||||
dim["montoAnualMXN"] = nil
|
||||
dim["factores"] = []any{}
|
||||
av = ValidarPropuesta(p, econ, fuentes, "")
|
||||
if tieneRegla(av, "R5") || tieneRegla(av, "R5b") {
|
||||
t.Fatalf("sin montoAnualMXN no debe disparar R5 ni R5b: %+v", av)
|
||||
}
|
||||
|
||||
// Solo estimados -> R5b advertencia
|
||||
p = propuestaBase()
|
||||
dim = p["diagnostico"].(map[string]any)["valorProblema"].(map[string]any)["dimensiones"].([]any)[0].(map[string]any)
|
||||
for _, f := range dim["factores"].([]any) {
|
||||
f.(map[string]any)["confianza"] = "estimado"
|
||||
}
|
||||
av = ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "R5b") || severidadRegla(av, "R5b") != "advertencia" {
|
||||
t.Fatalf("R5b debe advertir cuando ningun factor es confirmado: %+v", av)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("R6 hallazgoId colgante", func(t *testing.T) {
|
||||
p := propuestaBase()
|
||||
p["redaccion"].(map[string]any)["beneficios"].([]any)[0].(map[string]any)["hallazgoId"] = "D99"
|
||||
av := ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "R6") || severidadRegla(av, "R6") != "advertencia" {
|
||||
t.Fatalf("R6 debe advertir beneficio colgante: %+v", av)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("MARCA MONEDA GARANTIA PII", func(t *testing.T) {
|
||||
// MARCA
|
||||
p := propuestaBase()
|
||||
p["redaccion"].(map[string]any)["beneficios"].([]any)[0].(map[string]any)["texto"] = "Lo integramos con HubSpot sin problema alguno."
|
||||
av := ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "MARCA") || severidadRegla(av, "MARCA") != "bloqueante" {
|
||||
t.Fatalf("MARCA debe bloquear otro CRM: %+v", av)
|
||||
}
|
||||
|
||||
// MONEDA
|
||||
p = propuestaBase()
|
||||
p["redaccion"].(map[string]any)["hero"].(map[string]any)["subtitulo"] = "Una inversion de 1,800 USD al mes para tu negocio."
|
||||
av = ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "MONEDA") || severidadRegla(av, "MONEDA") != "bloqueante" {
|
||||
t.Fatalf("MONEDA debe bloquear USD: %+v", av)
|
||||
}
|
||||
|
||||
// GARANTIA
|
||||
p = propuestaBase()
|
||||
p["redaccion"].(map[string]any)["beneficios"].([]any)[0].(map[string]any)["texto"] = "Te garantizamos la posicion numero uno en Google."
|
||||
av = ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "GARANTIA") || severidadRegla(av, "GARANTIA") != "bloqueante" {
|
||||
t.Fatalf("GARANTIA debe bloquear promesa garantizada: %+v", av)
|
||||
}
|
||||
|
||||
// PII (advertencia, no bloqueante)
|
||||
p = propuestaBase()
|
||||
p["redaccion"].(map[string]any)["hero"].(map[string]any)["subtitulo"] = "El sueldo de quien atiende sale muy caro hoy en dia."
|
||||
av = ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "PII") || severidadRegla(av, "PII") != "advertencia" || HayBloqueantes(av) {
|
||||
t.Fatalf("PII debe ser advertencia no bloqueante: %+v", av)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ─────────────────────────── pipeline.go ───────────────────────────
|
||||
|
||||
func TestEjecutarPipelineTresPasos(t *testing.T) {
|
||||
base := propuestaBase()
|
||||
var step int32
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
n := atomic.AddInt32(&step, 1)
|
||||
var toolName string
|
||||
var payload any
|
||||
switch n {
|
||||
case 1:
|
||||
toolName = "registrar_hechos"
|
||||
payload = base["hechos"]
|
||||
case 2:
|
||||
toolName = "registrar_diagnostico"
|
||||
payload = base["diagnostico"]
|
||||
case 3:
|
||||
toolName = "registrar_propuesta"
|
||||
payload = base["redaccion"]
|
||||
default:
|
||||
t.Fatalf("llamada inesperada #%d", n)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"id": "msg_" + strconv.Itoa(int(n)),
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"content": []any{
|
||||
map[string]any{
|
||||
"type": "tool_use",
|
||||
"id": "tu_" + strconv.Itoa(int(n)),
|
||||
"name": toolName,
|
||||
"input": payload,
|
||||
},
|
||||
},
|
||||
"usage": map[string]any{
|
||||
"input_tokens": 100 * int(n),
|
||||
"output_tokens": 50 * int(n),
|
||||
"cache_read_input_tokens": 40,
|
||||
"cache_creation_input_tokens": 10,
|
||||
},
|
||||
})
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
cliente := &ClienteIA{
|
||||
APIKey: "test-key",
|
||||
BaseURL: srv.URL,
|
||||
Model: "MiniMax-M3",
|
||||
HTTPClient: srv.Client(),
|
||||
Sleep: func(context.Context, time.Duration) error { return nil },
|
||||
}
|
||||
|
||||
res, err := ejecutarPipeline(
|
||||
context.Background(),
|
||||
cliente,
|
||||
ContextoEntrada{
|
||||
Transcripcion: "El socio dijo: " + citaPrueba + ".",
|
||||
Cliente: "Juan Perez",
|
||||
Empresa: "ACME",
|
||||
Proyecto: "MKT Digital",
|
||||
},
|
||||
econPrueba(),
|
||||
"nota confidencial que no debe aparecer en la propuesta final jamas",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("error en pipeline: %v", err)
|
||||
}
|
||||
if res.Modelo != "MiniMax-M3" {
|
||||
t.Fatalf("Modelo esperado MiniMax-M3, obtuve %q", res.Modelo)
|
||||
}
|
||||
if HayBloqueantes(res.Avisos) {
|
||||
t.Fatalf("no esperaba bloqueantes en pipeline limpio: %+v", res.Avisos)
|
||||
}
|
||||
if res.Contenido["hechos"] == nil || res.Contenido["diagnostico"] == nil || res.Contenido["redaccion"] == nil {
|
||||
t.Fatalf("Contenido incompleto: %+v", res.Contenido)
|
||||
}
|
||||
totalUso, ok := res.Traza["totalUso"].(UsoTokens)
|
||||
if !ok || totalUso.Entrada != 600 || totalUso.Salida != 300 || totalUso.CacheLectura != 120 || totalUso.CacheEscritura != 30 {
|
||||
t.Fatalf("Traza totalUso incorrecta: %#v", res.Traza["totalUso"])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,476 @@
|
||||
package propuesta
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"golang.org/x/text/unicode/norm"
|
||||
)
|
||||
|
||||
// Aviso describe un hallazgo de validacion post-generacion.
|
||||
// Severidad: "bloqueante" | "advertencia".
|
||||
type Aviso struct {
|
||||
Regla string `json:"regla"`
|
||||
Severidad string `json:"severidad"`
|
||||
Mensaje string `json:"mensaje"`
|
||||
Campo string `json:"campo,omitempty"`
|
||||
}
|
||||
|
||||
// NormalizarTexto quita acentos, pasa a minusculas, elimina puntuacion y
|
||||
// colapsa espacios. Laxa a proposito para sobrevivir al ruido de transcripcion.
|
||||
func NormalizarTexto(s string) string {
|
||||
decomposed := norm.NFD.String(s)
|
||||
var b strings.Builder
|
||||
b.Grow(len(decomposed))
|
||||
for _, r := range decomposed {
|
||||
if unicode.Is(unicode.Mn, r) {
|
||||
continue
|
||||
}
|
||||
r = unicode.ToLower(r)
|
||||
if unicode.IsLetter(r) || unicode.IsNumber(r) {
|
||||
b.WriteRune(r)
|
||||
} else {
|
||||
b.WriteByte(' ')
|
||||
}
|
||||
}
|
||||
return strings.Join(strings.Fields(b.String()), " ")
|
||||
}
|
||||
|
||||
var (
|
||||
reOtroCRM = regexp.MustCompile(`(?i)\b(hubspot|salesforce|pipedrive|zoho|go\s*high\s*level|gohighlevel|clientify|kommo|monday\s*crm)\b`)
|
||||
rePromesaGarantia = regexp.MustCompile(`(?i)\bgarantiza(mos|do|da|r|remos)?\b|\baseguramos\s+(ventas|resultados|posici)`)
|
||||
reMontoUSD = regexp.MustCompile(`(?i)\b(usd|d[oóÓ]lares|dlls?)\b|\$\s*[\d,.]+\s*(usd|dls)\b`)
|
||||
reTemaSensible = regexp.MustCompile(`(?i)\b(sueldo|salario|n[oóÓ]mina|despido|demanda laboral|incapacidad|embarazo|enfermedad)\b`)
|
||||
)
|
||||
|
||||
type campoVisible struct {
|
||||
campo string
|
||||
texto string
|
||||
}
|
||||
|
||||
func getMap(m map[string]any, key string) map[string]any {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
if sub, ok := m[key].(map[string]any); ok {
|
||||
return sub
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func getSlice(m map[string]any, key string) []any {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
if arr, ok := m[key].([]any); ok {
|
||||
return arr
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func getString(m map[string]any, key string) string {
|
||||
if m == nil {
|
||||
return ""
|
||||
}
|
||||
if s, ok := m[key].(string); ok {
|
||||
return s
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// textoVisible recopila TODOS los campos de texto que terminan impresos en el
|
||||
// documento del cliente (excluyendo notasInternas, redFlags y razon de exclusiones).
|
||||
func textoVisible(contenido map[string]any) []campoVisible {
|
||||
hechos := getMap(contenido, "hechos")
|
||||
diag := getMap(contenido, "diagnostico")
|
||||
red := getMap(contenido, "redaccion")
|
||||
hero := getMap(red, "hero")
|
||||
vp := getMap(diag, "valorProblema")
|
||||
|
||||
out := []campoVisible{
|
||||
{campo: "hero.titulo", texto: getString(hero, "titulo")},
|
||||
{campo: "hero.subtitulo", texto: getString(hero, "subtitulo")},
|
||||
{campo: "valorProblema.notaMetodologia", texto: getString(vp, "notaMetodologia")},
|
||||
}
|
||||
|
||||
citaDestID := getString(red, "citaDestacadaId")
|
||||
for _, raw := range getSlice(hechos, "citas") {
|
||||
c, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
id := getString(c, "id")
|
||||
if id != "" && id == citaDestID {
|
||||
out = append(out,
|
||||
campoVisible{campo: fmt.Sprintf("citas.%s.textoLiteral", id), texto: getString(c, "textoLiteral")},
|
||||
campoVisible{campo: fmt.Sprintf("citas.%s.quienLoDijo", id), texto: getString(c, "quienLoDijo")},
|
||||
)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
for i, raw := range getSlice(diag, "hallazgos") {
|
||||
h, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
out = append(out,
|
||||
campoVisible{campo: fmt.Sprintf("hallazgos[%d].titulo", i), texto: getString(h, "titulo")},
|
||||
campoVisible{campo: fmt.Sprintf("hallazgos[%d].descripcion", i), texto: getString(h, "descripcion")},
|
||||
)
|
||||
}
|
||||
|
||||
for i, raw := range getSlice(vp, "dimensiones") {
|
||||
d, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
out = append(out, campoVisible{
|
||||
campo: fmt.Sprintf("valorProblema.dimensiones[%d]", i),
|
||||
texto: getString(d, "descripcion"),
|
||||
})
|
||||
}
|
||||
|
||||
for i, raw := range getSlice(diag, "resultados") {
|
||||
r, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
out = append(out,
|
||||
campoVisible{campo: fmt.Sprintf("resultados[%d].enunciado", i), texto: getString(r, "enunciado")},
|
||||
campoVisible{campo: fmt.Sprintf("resultados[%d].metrica", i), texto: getString(r, "metrica")},
|
||||
campoVisible{campo: fmt.Sprintf("resultados[%d].periodoMedicion", i), texto: getString(r, "periodoMedicion")},
|
||||
)
|
||||
}
|
||||
|
||||
for i, raw := range getSlice(red, "alcance") {
|
||||
a, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
out = append(out, campoVisible{
|
||||
campo: fmt.Sprintf("alcance[%d]", i),
|
||||
texto: getString(a, "descripcionResultado"),
|
||||
})
|
||||
}
|
||||
|
||||
for i, raw := range getSlice(red, "beneficios") {
|
||||
b, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
out = append(out, campoVisible{
|
||||
campo: fmt.Sprintf("beneficios[%d]", i),
|
||||
texto: getString(b, "etiqueta") + " " + getString(b, "texto"),
|
||||
})
|
||||
}
|
||||
|
||||
for i, raw := range getSlice(red, "exclusiones") {
|
||||
e, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
out = append(out, campoVisible{
|
||||
campo: fmt.Sprintf("exclusiones[%d]", i),
|
||||
texto: getString(e, "texto"),
|
||||
})
|
||||
}
|
||||
|
||||
for i, raw := range getSlice(red, "backlogEvolucion") {
|
||||
b, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
out = append(out,
|
||||
campoVisible{campo: fmt.Sprintf("backlog[%d].problema", i), texto: getString(b, "problema")},
|
||||
campoVisible{campo: fmt.Sprintf("backlog[%d].momentoSugerido", i), texto: getString(b, "momentoSugerido")},
|
||||
)
|
||||
}
|
||||
|
||||
for i, raw := range getSlice(hechos, "materialesPendientes") {
|
||||
m, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
out = append(out, campoVisible{
|
||||
campo: fmt.Sprintf("materiales[%d]", i),
|
||||
texto: getString(m, "texto"),
|
||||
})
|
||||
}
|
||||
|
||||
for i, raw := range getSlice(hechos, "decisionesPendientes") {
|
||||
d, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
out = append(out,
|
||||
campoVisible{campo: fmt.Sprintf("decisiones[%d].texto", i), texto: getString(d, "texto")},
|
||||
campoVisible{campo: fmt.Sprintf("decisiones[%d].quienDecide", i), texto: getString(d, "quienDecide")},
|
||||
)
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
func ngramas(texto string, n int) map[string]struct{} {
|
||||
palabras := strings.Fields(NormalizarTexto(texto))
|
||||
out := make(map[string]struct{})
|
||||
if n <= 0 || len(palabras) < n {
|
||||
return out
|
||||
}
|
||||
for i := 0; i+n <= len(palabras); i++ {
|
||||
out[strings.Join(palabras[i:i+n], " ")] = struct{}{}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func truncar(s string, max int) string {
|
||||
r := []rune(s)
|
||||
if len(r) <= max {
|
||||
return s
|
||||
}
|
||||
return string(r[:max])
|
||||
}
|
||||
|
||||
// ValidarPropuesta ejecuta las reglas deterministicas post-generacion:
|
||||
// R0, R2, R2b, R3, R4, R5, R5b, R6, MARCA, MONEDA, GARANTIA y PII.
|
||||
func ValidarPropuesta(contenido map[string]any, economia *EconomiaCotizacion, fuentesCliente string, notasInternas string) []Aviso {
|
||||
avisos := make([]Aviso, 0)
|
||||
visible := textoVisible(contenido)
|
||||
|
||||
hechos := getMap(contenido, "hechos")
|
||||
diag := getMap(contenido, "diagnostico")
|
||||
red := getMap(contenido, "redaccion")
|
||||
vp := getMap(diag, "valorProblema")
|
||||
|
||||
// ── R0 (bloqueante): fuga de notas internas del asesor (7-gramas) ──
|
||||
if strings.TrimSpace(notasInternas) != "" {
|
||||
internos := ngramas(notasInternas, 7)
|
||||
if len(internos) > 0 {
|
||||
for _, v := range visible {
|
||||
palabras := strings.Fields(NormalizarTexto(v.texto))
|
||||
for i := 0; i+7 <= len(palabras); i++ {
|
||||
g := strings.Join(palabras[i:i+7], " ")
|
||||
if _, leaked := internos[g]; leaked {
|
||||
avisos = append(avisos, Aviso{
|
||||
Regla: "R0",
|
||||
Severidad: "bloqueante",
|
||||
Campo: v.campo,
|
||||
Mensaje: fmt.Sprintf("Texto de las notas internas aparece en el documento del cliente: %q", g),
|
||||
})
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── R2 (bloqueante) / R2b (advertencia): correspondencia de partidas ──
|
||||
refsReales := make(map[string]bool)
|
||||
if economia != nil {
|
||||
for _, p := range economia.Partidas {
|
||||
refsReales[p.Ref] = true
|
||||
}
|
||||
}
|
||||
refsUsadas := make(map[string]bool)
|
||||
for _, raw := range getSlice(red, "alcance") {
|
||||
a, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
ref := getString(a, "refPartida")
|
||||
refsUsadas[ref] = true
|
||||
if !refsReales[ref] {
|
||||
avisos = append(avisos, Aviso{
|
||||
Regla: "R2",
|
||||
Severidad: "bloqueante",
|
||||
Campo: "alcance " + ref,
|
||||
Mensaje: fmt.Sprintf("La partida %s no existe en la cotizacion.", ref),
|
||||
})
|
||||
}
|
||||
}
|
||||
if economia != nil {
|
||||
for _, real := range economia.Partidas {
|
||||
if !refsUsadas[real.Ref] {
|
||||
avisos = append(avisos, Aviso{
|
||||
Regla: "R2b",
|
||||
Severidad: "advertencia",
|
||||
Campo: real.Ref,
|
||||
Mensaje: fmt.Sprintf("La partida %q (%s) esta cotizada pero no aparece descrita.", real.Nombre, real.Ref),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── R3 (bloqueante): cita destacada existe y aparece literal en fuentesCliente ──
|
||||
citaID := getString(red, "citaDestacadaId")
|
||||
var citaEncontrada map[string]any
|
||||
for _, raw := range getSlice(hechos, "citas") {
|
||||
c, ok := raw.(map[string]any)
|
||||
if ok && getString(c, "id") == citaID && citaID != "" {
|
||||
citaEncontrada = c
|
||||
break
|
||||
}
|
||||
}
|
||||
if citaEncontrada == nil {
|
||||
avisos = append(avisos, Aviso{
|
||||
Regla: "R3",
|
||||
Severidad: "bloqueante",
|
||||
Campo: "citaDestacadaId",
|
||||
Mensaje: fmt.Sprintf("citaDestacadaId %s no corresponde a ninguna cita extraida.", citaID),
|
||||
})
|
||||
} else if strings.TrimSpace(fuentesCliente) != "" {
|
||||
textoLiteral := getString(citaEncontrada, "textoLiteral")
|
||||
if !strings.Contains(NormalizarTexto(fuentesCliente), NormalizarTexto(textoLiteral)) {
|
||||
avisos = append(avisos, Aviso{
|
||||
Regla: "R3",
|
||||
Severidad: "bloqueante",
|
||||
Campo: citaID,
|
||||
Mensaje: fmt.Sprintf("La cita destacada no aparece literal en las fuentes: \"%s...\"", truncar(textoLiteral, 70)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ── R4 (advertencia): hallazgo confirmado sin citas ni hechos ──
|
||||
idsHallazgo := make(map[string]bool)
|
||||
for i, raw := range getSlice(diag, "hallazgos") {
|
||||
h, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if id := getString(h, "id"); id != "" {
|
||||
idsHallazgo[id] = true
|
||||
}
|
||||
if getString(h, "confianza") == "confirmado" && len(getSlice(h, "citas"))+len(getSlice(h, "hechos")) == 0 {
|
||||
avisos = append(avisos, Aviso{
|
||||
Regla: "R4",
|
||||
Severidad: "advertencia",
|
||||
Campo: fmt.Sprintf("hallazgos[%d]", i),
|
||||
Mensaje: fmt.Sprintf("%q se declara confirmado sin citas ni hechos. Deberia ser por_validar.", getString(h, "titulo")),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ── R5 (bloqueante) y R5b (advertencia): aritmetica y evidencia del valor anual ──
|
||||
for i, raw := range getSlice(vp, "dimensiones") {
|
||||
d, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
rawMonto, exists := d["montoAnualMXN"]
|
||||
if !exists || rawMonto == nil {
|
||||
continue
|
||||
}
|
||||
m, ok := asNumber(rawMonto)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
factores := getSlice(d, "factores")
|
||||
producto := 1.0
|
||||
suma := 0.0
|
||||
confirmados := 0
|
||||
for _, fRaw := range factores {
|
||||
f, ok := fRaw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
val, _ := asNumber(f["valor"])
|
||||
producto *= val
|
||||
suma += val
|
||||
if getString(f, "confianza") == "confirmado" {
|
||||
confirmados++
|
||||
}
|
||||
}
|
||||
|
||||
base := math.Max(math.Abs(m), 1.0)
|
||||
cuadra := math.Abs(producto-m)/base < 0.02 || math.Abs(suma-m)/base < 0.02
|
||||
if !cuadra {
|
||||
avisos = append(avisos, Aviso{
|
||||
Regla: "R5",
|
||||
Severidad: "bloqueante",
|
||||
Campo: fmt.Sprintf("valorProblema.dimensiones[%d]", i),
|
||||
Mensaje: fmt.Sprintf("montoAnualMXN %v no cuadra con sus factores (producto %v, suma %v).", m, producto, suma),
|
||||
})
|
||||
}
|
||||
if confirmados == 0 {
|
||||
avisos = append(avisos, Aviso{
|
||||
Regla: "R5b",
|
||||
Severidad: "advertencia",
|
||||
Campo: fmt.Sprintf("valorProblema.dimensiones[%d]", i),
|
||||
Mensaje: fmt.Sprintf(
|
||||
"La cifra de %v no tiene ni un factor confirmado: descansa entera en estimaciones. Revisa el desglose antes de fiarte del ratio precio/valor.",
|
||||
m,
|
||||
),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ── R6 (advertencia): referencias colgantes de hallazgoId en beneficios ──
|
||||
for i, raw := range getSlice(red, "beneficios") {
|
||||
b, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
hid := getString(b, "hallazgoId")
|
||||
if !idsHallazgo[hid] {
|
||||
avisos = append(avisos, Aviso{
|
||||
Regla: "R6",
|
||||
Severidad: "advertencia",
|
||||
Campo: fmt.Sprintf("beneficios[%d]", i),
|
||||
Mensaje: fmt.Sprintf("El beneficio apunta al hallazgo %s, que no existe.", hid),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ── Filtros de contenido sobre lo visible al cliente ──
|
||||
for _, v := range visible {
|
||||
if reOtroCRM.MatchString(v.texto) {
|
||||
avisos = append(avisos, Aviso{
|
||||
Regla: "MARCA",
|
||||
Severidad: "bloqueante",
|
||||
Campo: v.campo,
|
||||
Mensaje: "Menciona un CRM que no es Bucefalo.",
|
||||
})
|
||||
}
|
||||
if reMontoUSD.MatchString(v.texto) {
|
||||
avisos = append(avisos, Aviso{
|
||||
Regla: "MONEDA",
|
||||
Severidad: "bloqueante",
|
||||
Campo: v.campo,
|
||||
Mensaje: "Contiene un monto o referencia en USD.",
|
||||
})
|
||||
}
|
||||
if rePromesaGarantia.MatchString(v.texto) {
|
||||
avisos = append(avisos, Aviso{
|
||||
Regla: "GARANTIA",
|
||||
Severidad: "bloqueante",
|
||||
Campo: v.campo,
|
||||
Mensaje: "Promete un resultado garantizado.",
|
||||
})
|
||||
}
|
||||
if reTemaSensible.MatchString(v.texto) {
|
||||
avisos = append(avisos, Aviso{
|
||||
Regla: "PII",
|
||||
Severidad: "advertencia",
|
||||
Campo: v.campo,
|
||||
Mensaje: "Menciona un tema laboral, salarial o de salud. Revisalo antes de enviar.",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return avisos
|
||||
}
|
||||
|
||||
// HayBloqueantes devuelve true si algun aviso tiene severidad "bloqueante".
|
||||
func HayBloqueantes(avisos []Aviso) bool {
|
||||
for _, a := range avisos {
|
||||
if a.Severidad == "bloqueante" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
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()
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,376 @@
|
||||
package seed
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/auth"
|
||||
"cotizador/internal/db"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// AgentKeyPreset defines a named agent API key preset.
|
||||
type AgentKeyPreset struct {
|
||||
Nombre string
|
||||
Scopes []string
|
||||
RateLimitPerMin int
|
||||
}
|
||||
|
||||
// DefaultAgentPresets returns the 5 standard agent API key presets matching scripts/provision-agent-keys.ts.
|
||||
func DefaultAgentPresets() []AgentKeyPreset {
|
||||
return []AgentKeyPreset{
|
||||
{
|
||||
Nombre: "sales-agent",
|
||||
Scopes: []string{
|
||||
"catalogo:leer",
|
||||
"clientes:leer",
|
||||
"clientes:escribir",
|
||||
"cotizaciones:leer",
|
||||
"cotizaciones:borrador",
|
||||
"cotizaciones:enviar",
|
||||
},
|
||||
RateLimitPerMin: 60,
|
||||
},
|
||||
{
|
||||
Nombre: "jefe-operaciones",
|
||||
Scopes: []string{
|
||||
"catalogo:leer",
|
||||
"clientes:leer",
|
||||
"cotizaciones:leer",
|
||||
"cobros:leer",
|
||||
},
|
||||
RateLimitPerMin: 120,
|
||||
},
|
||||
{
|
||||
Nombre: "cobranza",
|
||||
Scopes: []string{
|
||||
"clientes:leer",
|
||||
"cobros:leer",
|
||||
},
|
||||
RateLimitPerMin: 60,
|
||||
},
|
||||
{
|
||||
Nombre: "entrega",
|
||||
Scopes: []string{
|
||||
"clientes:leer",
|
||||
"cotizaciones:leer_aceptadas",
|
||||
},
|
||||
RateLimitPerMin: 60,
|
||||
},
|
||||
{
|
||||
Nombre: "n8n-ecosystem",
|
||||
Scopes: []string{
|
||||
"catalogo:leer",
|
||||
"clientes:leer",
|
||||
"cotizaciones:leer",
|
||||
"cotizaciones:enviar",
|
||||
"cobros:leer",
|
||||
},
|
||||
RateLimitPerMin: 180,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type provisionOpts struct {
|
||||
List bool
|
||||
Preset bool
|
||||
Rotate bool
|
||||
Nombre string
|
||||
Scopes []string
|
||||
RateLimitPerMin int
|
||||
HasRateLimit bool
|
||||
}
|
||||
|
||||
func parseProvisionArgs(args []string) (provisionOpts, error) {
|
||||
opts := provisionOpts{RateLimitPerMin: 60}
|
||||
for i := 0; i < len(args); i++ {
|
||||
tok := args[i]
|
||||
if !strings.HasPrefix(tok, "--") {
|
||||
continue
|
||||
}
|
||||
key := tok[2:]
|
||||
var val string
|
||||
hasEq := false
|
||||
if eq := strings.IndexByte(key, '='); eq >= 0 {
|
||||
val = key[eq+1:]
|
||||
key = key[:eq]
|
||||
hasEq = true
|
||||
}
|
||||
|
||||
nextVal := func() string {
|
||||
if hasEq {
|
||||
return val
|
||||
}
|
||||
if i+1 < len(args) && !strings.HasPrefix(args[i+1], "--") {
|
||||
i++
|
||||
return args[i]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
switch key {
|
||||
case "list":
|
||||
opts.List = true
|
||||
case "preset":
|
||||
opts.Preset = true
|
||||
case "rotate":
|
||||
opts.Rotate = true
|
||||
case "nombre":
|
||||
opts.Nombre = strings.TrimSpace(nextVal())
|
||||
case "scopes":
|
||||
raw := nextVal()
|
||||
for _, part := range strings.Split(raw, ",") {
|
||||
s := strings.TrimSpace(part)
|
||||
if s != "" {
|
||||
opts.Scopes = append(opts.Scopes, s)
|
||||
}
|
||||
}
|
||||
case "rate-limit":
|
||||
raw := strings.TrimSpace(nextVal())
|
||||
if raw != "" {
|
||||
n, err := strconv.Atoi(raw)
|
||||
if err == nil && n > 0 {
|
||||
opts.RateLimitPerMin = n
|
||||
opts.HasRateLimit = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !opts.List && !opts.Preset && opts.Nombre == "" {
|
||||
return opts, errors.New("Uso: provision-keys --list | --preset [--rotate] | --nombre <nombre> --scopes <a,b> [--rate-limit 60] [--rotate]")
|
||||
}
|
||||
|
||||
if !opts.List && !opts.Preset {
|
||||
for _, sc := range opts.Scopes {
|
||||
if !auth.IsValidScope(sc) {
|
||||
return opts, fmt.Errorf("Scope invalido: %q. Validos: %s", sc, strings.Join(auth.AgentScopes, ", "))
|
||||
}
|
||||
}
|
||||
}
|
||||
return opts, nil
|
||||
}
|
||||
|
||||
func dedupeStrings(in []string) []string {
|
||||
seen := make(map[string]struct{}, len(in))
|
||||
out := make([]string, 0, len(in))
|
||||
for _, s := range in {
|
||||
if _, ok := seen[s]; ok {
|
||||
continue
|
||||
}
|
||||
seen[s] = struct{}{}
|
||||
out = append(out, s)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
type listedKey struct {
|
||||
ID string `json:"id"`
|
||||
Nombre string `json:"nombre"`
|
||||
Prefijo string `json:"prefijo"`
|
||||
Scopes []string `json:"scopes"`
|
||||
RateLimitPerMin int `json:"rateLimitPerMin"`
|
||||
Activo bool `json:"activo"`
|
||||
RevokedAt *time.Time `json:"revokedAt"`
|
||||
LastUsedAt *time.Time `json:"lastUsedAt"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type provisionResult struct {
|
||||
Nombre string `json:"nombre"`
|
||||
Action string `json:"action"`
|
||||
ID string `json:"id"`
|
||||
Prefijo string `json:"prefijo"`
|
||||
Scopes []string `json:"scopes"`
|
||||
RateLimitPerMin int `json:"rateLimitPerMin"`
|
||||
Activo *bool `json:"activo,omitempty"`
|
||||
RawKey string `json:"rawKey,omitempty"`
|
||||
}
|
||||
|
||||
// RunProvisionKeys ports scripts/provision-agent-keys.ts to Go.
|
||||
func RunProvisionKeys(ctx context.Context, pool *pgxpool.Pool, args []string) error {
|
||||
return runProvisionKeysWithWriter(ctx, pool, args, os.Stdout)
|
||||
}
|
||||
|
||||
func runProvisionKeysWithWriter(ctx context.Context, pool *pgxpool.Pool, args []string, out io.Writer) error {
|
||||
opts, err := parseProvisionArgs(args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if opts.List {
|
||||
rows, err := pool.Query(ctx, `
|
||||
SELECT "id", "nombre", "prefijo", "scopes", "rateLimitPerMin", "activo", "revokedAt", "lastUsedAt", "createdAt"
|
||||
FROM "AgentApiKey"
|
||||
ORDER BY "createdAt" ASC
|
||||
`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("list agent keys: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
keys := make([]listedKey, 0)
|
||||
for rows.Next() {
|
||||
var k listedKey
|
||||
if err := rows.Scan(&k.ID, &k.Nombre, &k.Prefijo, &k.Scopes, &k.RateLimitPerMin, &k.Activo, &k.RevokedAt, &k.LastUsedAt, &k.CreatedAt); err != nil {
|
||||
return fmt.Errorf("scan agent key: %w", err)
|
||||
}
|
||||
if k.Scopes == nil {
|
||||
k.Scopes = []string{}
|
||||
}
|
||||
keys = append(keys, k)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return writeIndentedJSON(out, map[string]any{
|
||||
"ok": true,
|
||||
"keys": keys,
|
||||
})
|
||||
}
|
||||
|
||||
var targets []AgentKeyPreset
|
||||
if opts.Preset {
|
||||
targets = DefaultAgentPresets()
|
||||
} else {
|
||||
targets = []AgentKeyPreset{
|
||||
{
|
||||
Nombre: opts.Nombre,
|
||||
Scopes: opts.Scopes,
|
||||
RateLimitPerMin: opts.RateLimitPerMin,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
results := make([]provisionResult, 0, len(targets))
|
||||
for _, target := range targets {
|
||||
var existingID, existingNombre, existingPrefijo string
|
||||
var existingScopes []string
|
||||
var existingRateLimit int
|
||||
var existingActivo bool
|
||||
|
||||
err := pool.QueryRow(ctx, `
|
||||
SELECT "id", "nombre", "prefijo", "scopes", "rateLimitPerMin", "activo"
|
||||
FROM "AgentApiKey"
|
||||
WHERE "nombre" = $1
|
||||
`, target.Nombre).Scan(&existingID, &existingNombre, &existingPrefijo, &existingScopes, &existingRateLimit, &existingActivo)
|
||||
|
||||
exists := true
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
exists = false
|
||||
} else if err != nil {
|
||||
return fmt.Errorf("lookup agent key %s: %w", target.Nombre, err)
|
||||
}
|
||||
|
||||
if exists && !opts.Rotate {
|
||||
activo := existingActivo
|
||||
if existingScopes == nil {
|
||||
existingScopes = []string{}
|
||||
}
|
||||
results = append(results, provisionResult{
|
||||
Nombre: existingNombre,
|
||||
Action: "exists",
|
||||
ID: existingID,
|
||||
Prefijo: existingPrefijo,
|
||||
Scopes: existingScopes,
|
||||
RateLimitPerMin: existingRateLimit,
|
||||
Activo: &activo,
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
var scopesFinal []string
|
||||
if len(target.Scopes) > 0 {
|
||||
scopesFinal = dedupeStrings(target.Scopes)
|
||||
} else if exists {
|
||||
scopesFinal = existingScopes
|
||||
}
|
||||
if len(scopesFinal) == 0 {
|
||||
return fmt.Errorf("Debes indicar --scopes al crear la clave %q", target.Nombre)
|
||||
}
|
||||
|
||||
rawKey, prefijo, keyHash := auth.GenerateAPIKey()
|
||||
|
||||
if exists {
|
||||
rateLimit := target.RateLimitPerMin
|
||||
if !opts.Preset && !opts.HasRateLimit && existingRateLimit > 0 {
|
||||
rateLimit = existingRateLimit
|
||||
}
|
||||
if rateLimit <= 0 {
|
||||
rateLimit = existingRateLimit
|
||||
}
|
||||
if rateLimit <= 0 {
|
||||
rateLimit = 60
|
||||
}
|
||||
_, err := pool.Exec(ctx, `
|
||||
UPDATE "AgentApiKey"
|
||||
SET "prefijo" = $1,
|
||||
"keyHash" = $2,
|
||||
"scopes" = $3,
|
||||
"rateLimitPerMin" = $4,
|
||||
"activo" = true,
|
||||
"revokedAt" = NULL,
|
||||
"updatedAt" = NOW()
|
||||
WHERE "id" = $5
|
||||
`, prefijo, keyHash, scopesFinal, rateLimit, existingID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("rotate agent key %s: %w", target.Nombre, err)
|
||||
}
|
||||
results = append(results, provisionResult{
|
||||
Nombre: existingNombre,
|
||||
Action: "rotated",
|
||||
ID: existingID,
|
||||
Prefijo: prefijo,
|
||||
Scopes: scopesFinal,
|
||||
RateLimitPerMin: rateLimit,
|
||||
RawKey: rawKey,
|
||||
})
|
||||
} else {
|
||||
newID := db.NewID()
|
||||
rateLimit := target.RateLimitPerMin
|
||||
if rateLimit <= 0 {
|
||||
rateLimit = 60
|
||||
}
|
||||
_, err := pool.Exec(ctx, `
|
||||
INSERT INTO "AgentApiKey" ("id", "nombre", "prefijo", "keyHash", "scopes", "rateLimitPerMin", "activo", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, $5, $6, true, NOW(), NOW())
|
||||
`, newID, target.Nombre, prefijo, keyHash, scopesFinal, rateLimit)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create agent key %s: %w", target.Nombre, err)
|
||||
}
|
||||
results = append(results, provisionResult{
|
||||
Nombre: target.Nombre,
|
||||
Action: "created",
|
||||
ID: newID,
|
||||
Prefijo: prefijo,
|
||||
Scopes: scopesFinal,
|
||||
RateLimitPerMin: rateLimit,
|
||||
RawKey: rawKey,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return writeIndentedJSON(out, map[string]any{
|
||||
"ok": true,
|
||||
"results": results,
|
||||
})
|
||||
}
|
||||
|
||||
func writeIndentedJSON(w io.Writer, v any) error {
|
||||
b, err := json.MarshalIndent(v, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = fmt.Fprintln(w, string(b))
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
package seed
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
|
||||
"cotizador/internal/auth"
|
||||
"cotizador/internal/config"
|
||||
"cotizador/internal/db"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type servicioRow struct {
|
||||
ID string
|
||||
Nombre string
|
||||
Fase int
|
||||
Nivel *string
|
||||
}
|
||||
|
||||
// Run executes the idempotent database seed matching prisma/seed.ts.
|
||||
func Run(ctx context.Context, pool *pgxpool.Pool, cfg *config.Config) error {
|
||||
if cfg == nil {
|
||||
cfg = &config.Config{}
|
||||
}
|
||||
|
||||
log.Println("Seeding database...")
|
||||
|
||||
// ── USERS ──
|
||||
adminEmail := strings.TrimSpace(cfg.SeedAdminEmail)
|
||||
if adminEmail == "" {
|
||||
adminEmail = "[email protected]"
|
||||
}
|
||||
adminName := strings.TrimSpace(cfg.SeedAdminName)
|
||||
if adminName == "" {
|
||||
adminName = "Administrador"
|
||||
}
|
||||
adminPassword := cfg.SeedAdminPassword
|
||||
if adminPassword == "" {
|
||||
log.Printf(` AVISO: SEED_ADMIN_PASSWORD no definida. Si el usuario %s no existe, se creara con password "admin123" — cambiala de inmediato.`, adminEmail)
|
||||
}
|
||||
rawAdminPass := adminPassword
|
||||
if rawAdminPass == "" {
|
||||
rawAdminPass = "admin123"
|
||||
}
|
||||
adminHash, err := auth.HashPassword(rawAdminPass)
|
||||
if err != nil {
|
||||
return fmt.Errorf("hash password admin: %w", err)
|
||||
}
|
||||
|
||||
if adminPassword != "" {
|
||||
_, err = pool.Exec(ctx, `
|
||||
INSERT INTO "User" ("id", "email", "password", "name", "role", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, 'admin', NOW(), NOW())
|
||||
ON CONFLICT ("email") DO UPDATE SET
|
||||
"password" = EXCLUDED."password",
|
||||
"updatedAt" = NOW()
|
||||
`, db.NewID(), adminEmail, adminHash, adminName)
|
||||
} else {
|
||||
_, err = pool.Exec(ctx, `
|
||||
INSERT INTO "User" ("id", "email", "password", "name", "role", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, 'admin', NOW(), NOW())
|
||||
ON CONFLICT ("email") DO NOTHING
|
||||
`, db.NewID(), adminEmail, adminHash, adminName)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("upsert admin user: %w", err)
|
||||
}
|
||||
|
||||
asesorEmail := strings.TrimSpace(cfg.SeedAsesorEmail)
|
||||
if asesorEmail != "" {
|
||||
asesorName := strings.TrimSpace(cfg.SeedAsesorName)
|
||||
if asesorName == "" {
|
||||
asesorName = "Asesor"
|
||||
}
|
||||
asesorPassword := cfg.SeedAsesorPass
|
||||
rawAsesorPass := asesorPassword
|
||||
if rawAsesorPass == "" {
|
||||
rawAsesorPass = "asesor123"
|
||||
}
|
||||
asesorHash, err := auth.HashPassword(rawAsesorPass)
|
||||
if err != nil {
|
||||
return fmt.Errorf("hash password asesor: %w", err)
|
||||
}
|
||||
if asesorPassword != "" {
|
||||
_, err = pool.Exec(ctx, `
|
||||
INSERT INTO "User" ("id", "email", "password", "name", "role", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, 'asesor', NOW(), NOW())
|
||||
ON CONFLICT ("email") DO UPDATE SET
|
||||
"password" = EXCLUDED."password",
|
||||
"updatedAt" = NOW()
|
||||
`, db.NewID(), asesorEmail, asesorHash, asesorName)
|
||||
} else {
|
||||
_, err = pool.Exec(ctx, `
|
||||
INSERT INTO "User" ("id", "email", "password", "name", "role", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, 'asesor', NOW(), NOW())
|
||||
ON CONFLICT ("email") DO NOTHING
|
||||
`, db.NewID(), asesorEmail, asesorHash, asesorName)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("upsert asesor user: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// ── CATEGORIAS (must be created BEFORE servicios for FK) ──
|
||||
categorias := DefaultCategorias()
|
||||
catMap := make(map[string]string, len(categorias))
|
||||
for _, cat := range categorias {
|
||||
var catID string
|
||||
err := pool.QueryRow(ctx, `
|
||||
INSERT INTO "Categoria" ("id", "nombre", "descripcion", "color", "activo", "orden", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, true, $5, NOW(), NOW())
|
||||
ON CONFLICT ("nombre") DO UPDATE SET
|
||||
"color" = EXCLUDED."color",
|
||||
"orden" = EXCLUDED."orden",
|
||||
"updatedAt" = NOW()
|
||||
RETURNING "id"
|
||||
`, db.NewID(), cat.Nombre, cat.Descripcion, cat.Color, cat.Orden).Scan(&catID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("upsert categoria %s: %w", cat.Nombre, err)
|
||||
}
|
||||
catMap[cat.Nombre] = catID
|
||||
}
|
||||
|
||||
// ── SERVICIOS CATALOGO ──
|
||||
catAlias := DefaultCatAlias()
|
||||
servicios := DefaultServicios()
|
||||
for _, s := range servicios {
|
||||
catNombre, ok := catAlias[s.Categoria]
|
||||
if !ok {
|
||||
catNombre = "Desarrollo Personalizado"
|
||||
}
|
||||
var catID *string
|
||||
if id, exists := catMap[catNombre]; exists {
|
||||
idCopy := id
|
||||
catID = &idCopy
|
||||
}
|
||||
var variante *string
|
||||
if s.Variante != "" {
|
||||
v := s.Variante
|
||||
variante = &v
|
||||
}
|
||||
var nivel *string
|
||||
if s.Nivel != "" {
|
||||
n := s.Nivel
|
||||
nivel = &n
|
||||
}
|
||||
entregablesJSON, err := json.Marshal(s.EntregablesDefault)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal entregables %s: %w", s.Nombre, err)
|
||||
}
|
||||
servicioID := ServicioID(s.Nombre, s.Orden)
|
||||
soloAdmin := IsSoloAdmin(servicioID, s.Nombre, s.SoloAdmin)
|
||||
|
||||
_, err = pool.Exec(ctx, `
|
||||
INSERT INTO "ServicioCatalogo" (
|
||||
"id", "nombre", "descripcion", "fase", "tipoPago", "precioBase",
|
||||
"tiempoEntrega", "entregablesDefault", "categoriaId", "variante",
|
||||
"nivel", "activo", "soloAdmin", "orden", "createdAt", "updatedAt"
|
||||
) VALUES (
|
||||
$1, $2, $3, $4, $5, $6,
|
||||
$7, $8::jsonb, $9, $10,
|
||||
$11, true, $12, $13, NOW(), NOW()
|
||||
)
|
||||
ON CONFLICT ("id") DO UPDATE SET
|
||||
"soloAdmin" = CASE WHEN EXCLUDED."soloAdmin" THEN true ELSE "ServicioCatalogo"."soloAdmin" END
|
||||
`,
|
||||
servicioID, s.Nombre, s.Descripcion, s.Fase, s.TipoPago, s.PrecioBase,
|
||||
s.TiempoEntrega, string(entregablesJSON), catID, variante,
|
||||
nivel, soloAdmin, s.Orden,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("upsert servicio %s: %w", servicioID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Load all services currently in DB for package mapping (mirrors prisma.servicioCatalogo.findMany()).
|
||||
rows, err := pool.Query(ctx, `SELECT "id", "nombre", "fase", "nivel" FROM "ServicioCatalogo"`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("query servicios: %w", err)
|
||||
}
|
||||
var allServicios []servicioRow
|
||||
for rows.Next() {
|
||||
var r servicioRow
|
||||
if err := rows.Scan(&r.ID, &r.Nombre, &r.Fase, &r.Nivel); err != nil {
|
||||
rows.Close()
|
||||
return fmt.Errorf("scan servicio: %w", err)
|
||||
}
|
||||
allServicios = append(allServicios, r)
|
||||
}
|
||||
rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return fmt.Errorf("iterate servicios: %w", err)
|
||||
}
|
||||
|
||||
// ── PAQUETE GENERAL ──
|
||||
_, err = pool.Exec(ctx, `
|
||||
INSERT INTO "Paquete" ("id", "nombre", "descripcion", "activo", "createdAt", "updatedAt")
|
||||
VALUES ('paquete-general', 'General', 'Paquete completo de servicios de marketing digital', true, NOW(), NOW())
|
||||
ON CONFLICT ("id") DO NOTHING
|
||||
`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("upsert paquete-general: %w", err)
|
||||
}
|
||||
|
||||
fasesGeneral := DefaultFasesGeneral()
|
||||
faseMap := make(map[int]string, len(fasesGeneral))
|
||||
for _, fg := range fasesGeneral {
|
||||
faseID := fmt.Sprintf("fase-general-%d", fg.Orden)
|
||||
_, err := pool.Exec(ctx, `
|
||||
INSERT INTO "FasePaquete" ("id", "paqueteId", "nombre", "orden", "createdAt", "updatedAt")
|
||||
VALUES ($1, 'paquete-general', $2, $3, NOW(), NOW())
|
||||
ON CONFLICT ("id") DO UPDATE SET
|
||||
"nombre" = EXCLUDED."nombre",
|
||||
"orden" = EXCLUDED."orden",
|
||||
"updatedAt" = NOW()
|
||||
`, faseID, fg.Nombre, fg.Orden)
|
||||
if err != nil {
|
||||
return fmt.Errorf("upsert fase %s: %w", faseID, err)
|
||||
}
|
||||
faseMap[fg.Orden] = faseID
|
||||
}
|
||||
|
||||
for _, s := range allServicios {
|
||||
fasePaqueteID, ok := faseMap[s.Fase]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
_, err := pool.Exec(ctx, `
|
||||
INSERT INTO "ServicioPaquete" ("id", "servicioCatalogoId", "fasePaqueteId", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, NOW(), NOW())
|
||||
ON CONFLICT ("servicioCatalogoId", "fasePaqueteId") DO NOTHING
|
||||
`, db.NewID(), s.ID, fasePaqueteID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("upsert servicioPaquete general (%s -> %s): %w", s.ID, fasePaqueteID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// ── PAQUETES RECOMENDADOS PYME ──
|
||||
for _, pq := range DefaultPaquetesPyme() {
|
||||
_, err := pool.Exec(ctx, `
|
||||
INSERT INTO "Paquete" ("id", "nombre", "descripcion", "activo", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, true, NOW(), NOW())
|
||||
ON CONFLICT ("id") DO UPDATE SET
|
||||
"nombre" = EXCLUDED."nombre",
|
||||
"descripcion" = EXCLUDED."descripcion",
|
||||
"activo" = true,
|
||||
"updatedAt" = NOW()
|
||||
`, pq.ID, pq.Nombre, pq.Descripcion)
|
||||
if err != nil {
|
||||
return fmt.Errorf("upsert paquete %s: %w", pq.ID, err)
|
||||
}
|
||||
|
||||
for _, fase := range pq.Fases {
|
||||
faseID := fmt.Sprintf("fase-%s-%d", pq.ID, fase.Orden)
|
||||
_, err := pool.Exec(ctx, `
|
||||
INSERT INTO "FasePaquete" ("id", "paqueteId", "nombre", "orden", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, NOW(), NOW())
|
||||
ON CONFLICT ("id") DO UPDATE SET
|
||||
"nombre" = EXCLUDED."nombre",
|
||||
"orden" = EXCLUDED."orden",
|
||||
"updatedAt" = NOW()
|
||||
`, faseID, pq.ID, fase.Nombre, fase.Orden)
|
||||
if err != nil {
|
||||
return fmt.Errorf("upsert fase %s: %w", faseID, err)
|
||||
}
|
||||
|
||||
for _, ref := range fase.Servicios {
|
||||
servicioCatalogoID, err := findServicioID(allServicios, ref.Nombre, ref.Nivel)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = pool.Exec(ctx, `
|
||||
INSERT INTO "ServicioPaquete" ("id", "servicioCatalogoId", "fasePaqueteId", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, NOW(), NOW())
|
||||
ON CONFLICT ("servicioCatalogoId", "fasePaqueteId") DO NOTHING
|
||||
`, db.NewID(), servicioCatalogoID, faseID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("upsert servicioPaquete (%s -> %s): %w", servicioCatalogoID, faseID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── BONOS (only insert when table is empty) ──
|
||||
var bonoCount int
|
||||
if err := pool.QueryRow(ctx, `SELECT COUNT(*) FROM "Bono"`).Scan(&bonoCount); err != nil {
|
||||
return fmt.Errorf("count bonos: %w", err)
|
||||
}
|
||||
if bonoCount == 0 {
|
||||
for _, bono := range DefaultBonos() {
|
||||
_, err := pool.Exec(ctx, `
|
||||
INSERT INTO "Bono" ("id", "numero", "titulo", "descripcion", "activo")
|
||||
VALUES ($1, $2, $3, $4, true)
|
||||
`, db.NewID(), bono.Numero, bono.Titulo, bono.Descripcion)
|
||||
if err != nil {
|
||||
return fmt.Errorf("insert bono %d: %w", bono.Numero, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── FINANCIAMIENTO PLANES ──
|
||||
for _, plan := range DefaultFinanciamientoPlanes() {
|
||||
_, err := pool.Exec(ctx, `
|
||||
INSERT INTO "FinanciamientoPlan" ("id", "meses", "tasa", "comision", "montoMinimo", "iva")
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
ON CONFLICT ("meses") DO NOTHING
|
||||
`, db.NewID(), plan.Meses, plan.Tasa, plan.Comision, plan.MontoMinimo, plan.IVA)
|
||||
if err != nil {
|
||||
return fmt.Errorf("upsert financiamiento %d meses: %w", plan.Meses, err)
|
||||
}
|
||||
}
|
||||
|
||||
// ── CONFIGURACION (ON CONFLICT DO NOTHING to preserve production branding/bank settings) ──
|
||||
for _, c := range DefaultConfigs() {
|
||||
_, err := pool.Exec(ctx, `
|
||||
INSERT INTO "Configuracion" ("id", "clave", "valor", "updatedAt")
|
||||
VALUES ($1, $2, $3, NOW())
|
||||
ON CONFLICT ("clave") DO NOTHING
|
||||
`, db.NewID(), c.Clave, c.Valor)
|
||||
if err != nil {
|
||||
return fmt.Errorf("upsert configuracion %s: %w", c.Clave, err)
|
||||
}
|
||||
}
|
||||
|
||||
log.Println("Seed completed successfully!")
|
||||
return nil
|
||||
}
|
||||
|
||||
func findServicioID(all []servicioRow, nombre, nivel string) (string, error) {
|
||||
var matches []string
|
||||
for _, s := range all {
|
||||
sNivel := ""
|
||||
if s.Nivel != nil {
|
||||
sNivel = *s.Nivel
|
||||
}
|
||||
if s.Nombre == nombre && sNivel == nivel {
|
||||
matches = append(matches, s.ID)
|
||||
}
|
||||
}
|
||||
if len(matches) != 1 {
|
||||
return "", fmt.Errorf("Paquete PyME: '%s' (nivel=%q) resolvio %d servicios", nombre, nivel, len(matches))
|
||||
}
|
||||
return matches[0], nil
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package seed
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"cotizador/internal/auth"
|
||||
)
|
||||
|
||||
func TestSeedDataCounts(t *testing.T) {
|
||||
categorias := DefaultCategorias()
|
||||
if len(categorias) != 7 {
|
||||
t.Fatalf("expected 7 categorias, got %d", len(categorias))
|
||||
}
|
||||
|
||||
servicios := DefaultServicios()
|
||||
if len(servicios) != 58 {
|
||||
t.Fatalf("expected 58 servicios (exact count in prisma/seed.ts), got %d", len(servicios))
|
||||
}
|
||||
|
||||
// 1 paquete-general + 6 paquetes PyME = 7 paquetes total
|
||||
paquetesPyme := DefaultPaquetesPyme()
|
||||
if len(paquetesPyme) != 6 {
|
||||
t.Fatalf("expected 6 paquetes PyME (7 total with paquete-general), got %d", len(paquetesPyme))
|
||||
}
|
||||
if len(DefaultFasesGeneral()) != 4 {
|
||||
t.Fatalf("expected 4 fases in paquete-general, got %d", len(DefaultFasesGeneral()))
|
||||
}
|
||||
|
||||
bonos := DefaultBonos()
|
||||
if len(bonos) != 6 {
|
||||
t.Fatalf("expected 6 bonos, got %d", len(bonos))
|
||||
}
|
||||
|
||||
planes := DefaultFinanciamientoPlanes()
|
||||
if len(planes) != 4 {
|
||||
t.Fatalf("expected 4 financiamiento planes, got %d", len(planes))
|
||||
}
|
||||
expectedMeses := []int{3, 6, 9, 12}
|
||||
for i, m := range expectedMeses {
|
||||
if planes[i].Meses != m {
|
||||
t.Errorf("plan[%d].Meses = %d, want %d", i, planes[i].Meses, m)
|
||||
}
|
||||
}
|
||||
|
||||
configs := DefaultConfigs()
|
||||
if len(configs) != 16 {
|
||||
t.Fatalf("expected 16 config keys, got %d", len(configs))
|
||||
}
|
||||
}
|
||||
|
||||
func TestServicioIDsAndSoloAdmin(t *testing.T) {
|
||||
servicios := DefaultServicios()
|
||||
seen := make(map[string]bool, len(servicios))
|
||||
soloAdminIDs := make(map[string]bool)
|
||||
|
||||
for _, s := range servicios {
|
||||
id := ServicioID(s.Nombre, s.Orden)
|
||||
if seen[id] {
|
||||
t.Fatalf("duplicate servicio ID: %s", id)
|
||||
}
|
||||
seen[id] = true
|
||||
|
||||
if IsSoloAdmin(id, s.Nombre, s.SoloAdmin) {
|
||||
soloAdminIDs[id] = true
|
||||
}
|
||||
}
|
||||
|
||||
// Verify exact known slug IDs from prisma/seed.ts
|
||||
for _, want := range []string{
|
||||
"auditoria-en-sitio-web-2",
|
||||
"configuracion-y-puesta-en-marc-12",
|
||||
"plan-mensual-crm-bucefalo-18",
|
||||
"logo-e-identidad-101",
|
||||
"estrategia-empresarial-en-ecom-100",
|
||||
} {
|
||||
if !seen[want] {
|
||||
t.Errorf("expected slug ID %q not found in DefaultServicios", want)
|
||||
}
|
||||
}
|
||||
|
||||
// Verify soloAdmin flags on Bucefalo CRM items
|
||||
if len(soloAdminIDs) != 2 {
|
||||
t.Fatalf("expected exactly 2 soloAdmin servicios, got %d: %v", len(soloAdminIDs), soloAdminIDs)
|
||||
}
|
||||
if !soloAdminIDs["configuracion-y-puesta-en-marc-12"] {
|
||||
t.Errorf("expected configuracion-y-puesta-en-marc-12 to be soloAdmin")
|
||||
}
|
||||
if !soloAdminIDs["plan-mensual-crm-bucefalo-18"] {
|
||||
t.Errorf("expected plan-mensual-crm-bucefalo-18 to be soloAdmin")
|
||||
}
|
||||
|
||||
// Accented/case-insensitive Bucefalo detection
|
||||
if !IsSoloAdmin("otro-1", "Servicio Bucéfalo Extra", false) {
|
||||
t.Errorf("expected accented Bucéfalo name to trigger soloAdmin")
|
||||
}
|
||||
if IsSoloAdmin("auditoria-en-sitio-web-2", "Auditoria en Sitio Web", false) {
|
||||
t.Errorf("expected normal service NOT to trigger soloAdmin")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCategoriasAndPaqueteReferences(t *testing.T) {
|
||||
catSet := make(map[string]bool)
|
||||
for _, c := range DefaultCategorias() {
|
||||
catSet[c.Nombre] = true
|
||||
}
|
||||
|
||||
catAlias := DefaultCatAlias()
|
||||
var rows []servicioRow
|
||||
for _, s := range DefaultServicios() {
|
||||
catNombre, ok := catAlias[s.Categoria]
|
||||
if !ok {
|
||||
t.Errorf("servicio %q has unknown categoria alias %q", s.Nombre, s.Categoria)
|
||||
}
|
||||
if !catSet[catNombre] {
|
||||
t.Errorf("catAlias %q -> %q not found in DefaultCategorias", s.Categoria, catNombre)
|
||||
}
|
||||
var nivelPtr *string
|
||||
if s.Nivel != "" {
|
||||
n := s.Nivel
|
||||
nivelPtr = &n
|
||||
}
|
||||
rows = append(rows, servicioRow{
|
||||
ID: ServicioID(s.Nombre, s.Orden),
|
||||
Nombre: s.Nombre,
|
||||
Fase: s.Fase,
|
||||
Nivel: nivelPtr,
|
||||
})
|
||||
}
|
||||
|
||||
// Every service referenced in all 6 PyME packages must resolve uniquely
|
||||
for _, pq := range DefaultPaquetesPyme() {
|
||||
if !strings.HasPrefix(pq.ID, "paquete-") {
|
||||
t.Errorf("unexpected paquete ID %q", pq.ID)
|
||||
}
|
||||
for _, f := range pq.Fases {
|
||||
for _, ref := range f.Servicios {
|
||||
id, err := findServicioID(rows, ref.Nombre, ref.Nivel)
|
||||
if err != nil {
|
||||
t.Errorf("paquete %s fase %d: %v", pq.ID, f.Orden, err)
|
||||
}
|
||||
if id == "" {
|
||||
t.Errorf("paquete %s fase %d: empty id for %s", pq.ID, f.Orden, ref.Nombre)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigKeysUnique(t *testing.T) {
|
||||
seen := make(map[string]bool)
|
||||
for _, c := range DefaultConfigs() {
|
||||
if seen[c.Clave] {
|
||||
t.Fatalf("duplicate config clave: %s", c.Clave)
|
||||
}
|
||||
seen[c.Clave] = true
|
||||
}
|
||||
for _, required := range []string{"razon_social", "rfc", "clabe_interbancaria", "color_primario", "color_secundario", "logo_base64", "iva"} {
|
||||
if !seen[required] {
|
||||
t.Errorf("missing required config key %q", required)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProvisionArgsAndPresets(t *testing.T) {
|
||||
// Presets sanity
|
||||
presets := DefaultAgentPresets()
|
||||
if len(presets) != 5 {
|
||||
t.Fatalf("expected 5 agent presets, got %d", len(presets))
|
||||
}
|
||||
for _, p := range presets {
|
||||
for _, sc := range p.Scopes {
|
||||
if !auth.IsValidScope(sc) {
|
||||
t.Errorf("preset %s has invalid scope %q", p.Nombre, sc)
|
||||
}
|
||||
if strings.Contains(sc, "aprobar") {
|
||||
t.Errorf("preset %s must NEVER contain an approval scope: %q", p.Nombre, sc)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --list
|
||||
opts, err := parseProvisionArgs([]string{"--list"})
|
||||
if err != nil || !opts.List {
|
||||
t.Fatalf("expected --list to parse cleanly, got opts=%+v err=%v", opts, err)
|
||||
}
|
||||
|
||||
// --preset --rotate
|
||||
opts, err = parseProvisionArgs([]string{"--preset", "--rotate"})
|
||||
if err != nil || !opts.Preset || !opts.Rotate {
|
||||
t.Fatalf("expected --preset --rotate to parse cleanly, got opts=%+v err=%v", opts, err)
|
||||
}
|
||||
|
||||
// --nombre with valid scopes and rate limit
|
||||
opts, err = parseProvisionArgs([]string{
|
||||
"--nombre", "custom-agent",
|
||||
"--scopes", "catalogo:leer,clientes:leer",
|
||||
"--rate-limit", "90",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if opts.Nombre != "custom-agent" || len(opts.Scopes) != 2 || opts.RateLimitPerMin != 90 || !opts.HasRateLimit {
|
||||
t.Fatalf("unexpected parsed opts: %+v", opts)
|
||||
}
|
||||
|
||||
// invalid scope rejected
|
||||
_, err = parseProvisionArgs([]string{"--nombre", "bad", "--scopes", "cotizaciones:aprobar"})
|
||||
if err == nil {
|
||||
t.Fatalf("expected error for invalid approval scope")
|
||||
}
|
||||
|
||||
// missing action rejected
|
||||
_, err = parseProvisionArgs([]string{})
|
||||
if err == nil {
|
||||
t.Fatalf("expected usage error when no flags given")
|
||||
}
|
||||
}
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
<!doctype html><html lang="es"><head><meta charset="UTF-8"><title>Cotizador — Uriel Jareth Consulting</title></head><body><div id="root"></div></body></html>
|
||||
@@ -0,0 +1,55 @@
|
||||
package spa
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"path"
|
||||
"strings"
|
||||
)
|
||||
|
||||
//go:embed all:dist
|
||||
var distFS embed.FS
|
||||
|
||||
// Handler serves the embedded Vite React SPA with client-side routing fallback,
|
||||
// immutable caching for /assets/*, and no-cache for index.html and /sw.js.
|
||||
func Handler() http.Handler {
|
||||
sub, err := fs.Sub(distFS, "dist")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fileServer := http.FileServer(http.FS(sub))
|
||||
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
p := strings.TrimPrefix(path.Clean("/"+r.URL.Path), "/")
|
||||
if p == "" {
|
||||
p = "index.html"
|
||||
}
|
||||
|
||||
// Try exact static file first
|
||||
if f, err := sub.Open(p); err == nil {
|
||||
stat, statErr := f.Stat()
|
||||
_ = f.Close()
|
||||
if statErr == nil && !stat.IsDir() {
|
||||
if strings.HasPrefix(p, "assets/") {
|
||||
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
|
||||
} else if p == "sw.js" || p == "index.html" {
|
||||
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
|
||||
}
|
||||
fileServer.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// SPA fallback to index.html for client routes
|
||||
indexBytes, err := fs.ReadFile(sub, "index.html")
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(indexBytes)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
package webhooks
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/config"
|
||||
"cotizador/internal/db"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
var EventosOficiales = []string{
|
||||
"cotizacion.creada",
|
||||
"cotizacion.aprobada",
|
||||
"cotizacion.enviada",
|
||||
"cotizacion.aceptada",
|
||||
"cotizacion.rechazada",
|
||||
"cotizacion.vencida",
|
||||
"pago.registrado",
|
||||
"pago.vencido",
|
||||
}
|
||||
|
||||
func EsEventoValido(evento string) bool {
|
||||
return evento == "*" || slices.Contains(EventosOficiales, evento)
|
||||
}
|
||||
|
||||
// FirmarPayload returns "sha256=<64-hex>" HMAC-SHA256 signature.
|
||||
func FirmarPayload(rawPayload []byte, secret string) string {
|
||||
mac := hmac.New(sha256.New, []byte(secret))
|
||||
mac.Write(rawPayload)
|
||||
return "sha256=" + hex.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
|
||||
// VerificarFirma performs constant-time HMAC-SHA256 verification.
|
||||
func VerificarFirma(rawPayload []byte, signatureHeader, secret string) bool {
|
||||
if secret == "" || !strings.HasPrefix(signatureHeader, "sha256=") {
|
||||
return false
|
||||
}
|
||||
expected := FirmarPayload(rawPayload, secret)
|
||||
return hmac.Equal([]byte(expected), []byte(signatureHeader))
|
||||
}
|
||||
|
||||
type Dispatcher struct {
|
||||
pool *pgxpool.Pool
|
||||
cfg *config.Config
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func NewDispatcher(pool *pgxpool.Pool, cfg *config.Config) *Dispatcher {
|
||||
return &Dispatcher{
|
||||
pool: pool,
|
||||
cfg: cfg,
|
||||
client: &http.Client{Timeout: 8 * time.Second},
|
||||
}
|
||||
}
|
||||
|
||||
type target struct {
|
||||
EndpointID *string
|
||||
URL string
|
||||
Secret string
|
||||
}
|
||||
|
||||
func (d *Dispatcher) Emitir(ctx context.Context, evento string, data map[string]any) {
|
||||
if d == nil || d.pool == nil {
|
||||
return
|
||||
}
|
||||
|
||||
var targets []target
|
||||
seenURL := map[string]bool{}
|
||||
|
||||
rows, err := d.pool.Query(ctx, `
|
||||
SELECT "id", "url", "secret", "eventos"
|
||||
FROM "WebhookEndpoint"
|
||||
WHERE "activo" = true
|
||||
`)
|
||||
if err == nil {
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var id, urlStr, secret string
|
||||
var eventos []string
|
||||
if err := rows.Scan(&id, &urlStr, &secret, &eventos); err != nil {
|
||||
continue
|
||||
}
|
||||
if slices.Contains(eventos, "*") || slices.Contains(eventos, evento) {
|
||||
eid := id
|
||||
targets = append(targets, target{EndpointID: &eid, URL: urlStr, Secret: secret})
|
||||
seenURL[urlStr] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if d.cfg != nil && d.cfg.WebhookN8NURL != "" && !seenURL[d.cfg.WebhookN8NURL] {
|
||||
targets = append(targets, target{
|
||||
EndpointID: nil,
|
||||
URL: d.cfg.WebhookN8NURL,
|
||||
Secret: d.cfg.WebhookN8NSecret,
|
||||
})
|
||||
}
|
||||
|
||||
if len(targets) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
envelope := map[string]any{
|
||||
"event": evento,
|
||||
"timestamp": time.Now().UTC().Format(time.RFC3339),
|
||||
"data": data,
|
||||
}
|
||||
rawPayload, err := json.Marshal(envelope)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
for _, t := range targets {
|
||||
d.deliverWithRetry(ctx, t, evento, rawPayload)
|
||||
}
|
||||
}
|
||||
|
||||
func (d *Dispatcher) deliverWithRetry(ctx context.Context, t target, evento string, rawPayload []byte) {
|
||||
deliveryID := uuid.NewString()
|
||||
ts := strconv.FormatInt(time.Now().Unix(), 10)
|
||||
sig := ""
|
||||
if t.Secret != "" {
|
||||
sig = FirmarPayload(rawPayload, t.Secret)
|
||||
}
|
||||
|
||||
var statusCode *int
|
||||
var lastErr string
|
||||
exito := false
|
||||
intentos := 0
|
||||
|
||||
for attempt := 1; attempt <= 3; attempt++ {
|
||||
intentos = attempt
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, t.URL, bytes.NewReader(rawPayload))
|
||||
if err != nil {
|
||||
lastErr = err.Error()
|
||||
break
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-Cotizador-Event", evento)
|
||||
req.Header.Set("X-Cotizador-Timestamp", ts)
|
||||
req.Header.Set("X-Cotizador-Delivery-Id", deliveryID)
|
||||
if sig != "" {
|
||||
req.Header.Set("X-Cotizador-Signature", sig)
|
||||
}
|
||||
|
||||
resp, err := d.client.Do(req)
|
||||
if err != nil {
|
||||
lastErr = err.Error()
|
||||
} else {
|
||||
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
|
||||
_ = resp.Body.Close()
|
||||
sc := resp.StatusCode
|
||||
statusCode = &sc
|
||||
if sc >= 200 && sc < 300 {
|
||||
exito = true
|
||||
lastErr = ""
|
||||
break
|
||||
}
|
||||
lastErr = fmt.Sprintf("HTTP %d", sc)
|
||||
if sc < 500 {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if attempt < 3 {
|
||||
time.Sleep(time.Duration(attempt) * 500 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
var errPtr *string
|
||||
if lastErr != "" {
|
||||
errPtr = &lastErr
|
||||
}
|
||||
_, err := d.pool.Exec(ctx, `
|
||||
INSERT INTO "WebhookDelivery" ("id", "endpointId", "url", "evento", "payload", "statusCode", "exito", "intentos", "error")
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
||||
`, db.NewID(), t.EndpointID, t.URL, evento, rawPayload, statusCode, exito, intentos, errPtr)
|
||||
if err != nil {
|
||||
log.Printf("[webhooks] error guardando WebhookDelivery (%s -> %s): %v", evento, t.URL, err)
|
||||
}
|
||||
}
|
||||
|
||||
type WhatsAppSendResult struct {
|
||||
OK bool
|
||||
Outside24h bool
|
||||
StatusCode int
|
||||
ErrorMessage string
|
||||
ResponsePayload map[string]any
|
||||
}
|
||||
|
||||
// InvocarEnvioWhatsAppN8n sends cotizacion.enviar_whatsapp to WEBHOOK_WHATSAPP_SEND_URL (15s timeout, no retries).
|
||||
func (d *Dispatcher) InvocarEnvioWhatsAppN8n(ctx context.Context, payload map[string]any) WhatsAppSendResult {
|
||||
if d == nil || d.cfg == nil || d.cfg.WebhookWhatsAppSendURL == "" {
|
||||
return WhatsAppSendResult{
|
||||
OK: false,
|
||||
ErrorMessage: "WEBHOOK_WHATSAPP_SEND_URL no esta configurado",
|
||||
}
|
||||
}
|
||||
|
||||
raw, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return WhatsAppSendResult{OK: false, ErrorMessage: err.Error()}
|
||||
}
|
||||
|
||||
client := &http.Client{Timeout: 15 * time.Second}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, d.cfg.WebhookWhatsAppSendURL, bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return WhatsAppSendResult{OK: false, ErrorMessage: err.Error()}
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-Cotizador-Event", "cotizacion.enviar_whatsapp")
|
||||
req.Header.Set("X-Cotizador-Timestamp", strconv.FormatInt(time.Now().Unix(), 10))
|
||||
req.Header.Set("X-Cotizador-Delivery-Id", uuid.NewString())
|
||||
if d.cfg.WebhookN8NSecret != "" {
|
||||
req.Header.Set("X-Cotizador-Signature", FirmarPayload(raw, d.cfg.WebhookN8NSecret))
|
||||
}
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return WhatsAppSendResult{OK: false, ErrorMessage: err.Error()}
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
bodyBytes, _ := io.ReadAll(io.LimitReader(resp.Body, 64*1024))
|
||||
|
||||
var parsed map[string]any
|
||||
_ = json.Unmarshal(bodyBytes, &parsed)
|
||||
|
||||
outside := false
|
||||
if parsed != nil {
|
||||
if v, ok := parsed["outside_24h_window"].(bool); ok && v {
|
||||
outside = true
|
||||
}
|
||||
if code, ok := parsed["code"].(string); ok && code == "outside_24h_window" {
|
||||
outside = true
|
||||
}
|
||||
if errStr, ok := parsed["error"].(string); ok && strings.Contains(strings.ToLower(errStr), "outside_24h") {
|
||||
outside = true
|
||||
}
|
||||
}
|
||||
|
||||
if resp.StatusCode >= 200 && resp.StatusCode < 300 && !outside {
|
||||
return WhatsAppSendResult{
|
||||
OK: true,
|
||||
StatusCode: resp.StatusCode,
|
||||
ResponsePayload: parsed,
|
||||
}
|
||||
}
|
||||
|
||||
errMsg := fmt.Sprintf("HTTP %d", resp.StatusCode)
|
||||
if parsed != nil {
|
||||
if m, ok := parsed["error"].(string); ok && m != "" {
|
||||
errMsg = m
|
||||
} else if m, ok := parsed["message"].(string); ok && m != "" {
|
||||
errMsg = m
|
||||
}
|
||||
}
|
||||
return WhatsAppSendResult{
|
||||
OK: false,
|
||||
Outside24h: outside,
|
||||
StatusCode: resp.StatusCode,
|
||||
ErrorMessage: errMsg,
|
||||
ResponsePayload: parsed,
|
||||
}
|
||||
}
|
||||
|
||||
type PagoVencidoItem struct {
|
||||
PagoID string
|
||||
ProgramaID string
|
||||
ClienteID string
|
||||
ClienteNombre string
|
||||
ClienteEmpresa string
|
||||
ClienteEmail string
|
||||
ClienteTelefono string
|
||||
Concepto string
|
||||
Monto float64
|
||||
Moneda string
|
||||
Fecha string
|
||||
DiasAtraso int
|
||||
}
|
||||
|
||||
// PagoVencidoStore abstracts atomic claim for testability.
|
||||
type PagoVencidoStore interface {
|
||||
ClaimVencido(ctx context.Context, pagoID string) (bool, error)
|
||||
}
|
||||
|
||||
type pgPagoVencidoStore struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func (s pgPagoVencidoStore) ClaimVencido(ctx context.Context, pagoID string) (bool, error) {
|
||||
tag, err := s.pool.Exec(ctx, `
|
||||
UPDATE "PagoRecurrente"
|
||||
SET "vencidoNotificadoAt" = NOW(), "updatedAt" = NOW()
|
||||
WHERE "id" = $1 AND "vencidoNotificadoAt" IS NULL
|
||||
`, pagoID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return tag.RowsAffected() == 1, nil
|
||||
}
|
||||
|
||||
// EmitirPagosVencidosIdempotente atomically stamps vencidoNotificadoAt and emits pago.vencido once per charge.
|
||||
func EmitirPagosVencidosIdempotente(ctx context.Context, store PagoVencidoStore, items []PagoVencidoItem, emit func(ctx context.Context, evento string, data map[string]any)) int {
|
||||
emitted := 0
|
||||
for _, it := range items {
|
||||
claimed, err := store.ClaimVencido(ctx, it.PagoID)
|
||||
if err != nil || !claimed {
|
||||
continue
|
||||
}
|
||||
emit(ctx, "pago.vencido", map[string]any{
|
||||
"pagoId": it.PagoID,
|
||||
"programaId": it.ProgramaID,
|
||||
"clienteId": it.ClienteID,
|
||||
"clienteNombre": it.ClienteNombre,
|
||||
"clienteEmpresa": it.ClienteEmpresa,
|
||||
"clienteEmail": it.ClienteEmail,
|
||||
"clienteTelefono": it.ClienteTelefono,
|
||||
"concepto": it.Concepto,
|
||||
"monto": it.Monto,
|
||||
"moneda": it.Moneda,
|
||||
"fecha": it.Fecha,
|
||||
"diasAtraso": it.DiasAtraso,
|
||||
})
|
||||
emitted++
|
||||
}
|
||||
return emitted
|
||||
}
|
||||
|
||||
func (d *Dispatcher) EmitirPagosVencidos(ctx context.Context, items []PagoVencidoItem) int {
|
||||
if d == nil || d.pool == nil {
|
||||
return 0
|
||||
}
|
||||
return EmitirPagosVencidosIdempotente(ctx, pgPagoVencidoStore{pool: d.pool}, items, d.Emitir)
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package webhooks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHMACSigningAndEvents(t *testing.T) {
|
||||
if len(EventosOficiales) != 8 {
|
||||
t.Fatalf("expected 8 official events, got %d", len(EventosOficiales))
|
||||
}
|
||||
payload := []byte(`{"event":"cotizacion.aprobada","data":{"id":"c1"}}`)
|
||||
secret := "whsec_test_123"
|
||||
sig := FirmarPayload(payload, secret)
|
||||
if !strings.HasPrefix(sig, "sha256=") || len(sig) != 7+64 {
|
||||
t.Fatalf("invalid signature format: %s", sig)
|
||||
}
|
||||
if !VerificarFirma(payload, sig, secret) {
|
||||
t.Fatal("valid signature rejected")
|
||||
}
|
||||
if VerificarFirma([]byte(`{"tampered":true}`), sig, secret) {
|
||||
t.Fatal("tampered payload accepted")
|
||||
}
|
||||
if VerificarFirma(payload, sig, "wrong-secret") {
|
||||
t.Fatal("wrong secret accepted")
|
||||
}
|
||||
if VerificarFirma(payload, "invalid", secret) {
|
||||
t.Fatal("malformed header accepted")
|
||||
}
|
||||
}
|
||||
|
||||
type memClaimStore struct {
|
||||
mu sync.Mutex
|
||||
claimed map[string]bool
|
||||
}
|
||||
|
||||
func (m *memClaimStore) ClaimVencido(_ context.Context, pagoID string) (bool, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.claimed[pagoID] {
|
||||
return false, nil
|
||||
}
|
||||
m.claimed[pagoID] = true
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func TestPagoVencidoIdempotencyConcurrency(t *testing.T) {
|
||||
store := &memClaimStore{claimed: map[string]bool{}}
|
||||
items := []PagoVencidoItem{{PagoID: "p1", ClienteID: "c1", Monto: 750, Moneda: "MXN", DiasAtraso: 3}}
|
||||
|
||||
var mu sync.Mutex
|
||||
totalEmitted := 0
|
||||
emit := func(_ context.Context, _ string, _ map[string]any) {
|
||||
mu.Lock()
|
||||
totalEmitted++
|
||||
mu.Unlock()
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 10; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
EmitirPagosVencidosIdempotente(context.Background(), store, items, emit)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
if totalEmitted != 1 {
|
||||
t.Fatalf("expected exactly 1 emission under concurrency, got %d", totalEmitted)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user