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 }