feat: migrar backend unificado a Go 1.27 + SPA Vite embebido

This commit is contained in:
urieljareth
2026-11-28 09:20:55 -06:00
parent 4f64487b88
commit b5ebcd0b86
332 changed files with 29135 additions and 37275 deletions
+497
View File
@@ -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()))
}
+540
View File
@@ -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
}
+979
View File
@@ -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{}
}
}
+438
View File
@@ -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})
}
+418
View File
@@ -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)
}
+701
View File
@@ -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, &nota, &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)
}
+266
View File
@@ -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")
}
}
+343
View File
@@ -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 ""
}