feat: migrar backend unificado a Go 1.27 + SPA Vite embebido
This commit is contained in:
@@ -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 ""
|
||||
}
|
||||
Reference in New Issue
Block a user