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) }