feat: migrar backend unificado a Go 1.27 + SPA Vite embebido
This commit is contained in:
@@ -0,0 +1,454 @@
|
||||
package pdf
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/HugoSmits86/nativewebp"
|
||||
"golang.org/x/image/font/gofont/goregular"
|
||||
"golang.org/x/image/font/sfnt"
|
||||
|
||||
"cotizador/internal/domain"
|
||||
)
|
||||
|
||||
func f64(v float64) *float64 { return &v }
|
||||
func str(v string) *string { return &v }
|
||||
|
||||
func makeTestImage() image.Image {
|
||||
img := image.NewNRGBA(image.Rect(0, 0, 32, 16))
|
||||
for y := 0; y < 16; y++ {
|
||||
for x := 0; x < 32; x++ {
|
||||
img.Set(x, y, color.NRGBA{R: 4, G: 0, B: 196, A: 255})
|
||||
}
|
||||
}
|
||||
return img
|
||||
}
|
||||
|
||||
func makePNGLogoB64(t *testing.T) string {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, makeTestImage()); err != nil {
|
||||
t.Fatalf("png encode: %v", err)
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(buf.Bytes())
|
||||
}
|
||||
|
||||
func makeJPEGLogoB64(t *testing.T) string {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
if err := jpeg.Encode(&buf, makeTestImage(), &jpeg.Options{Quality: 85}); err != nil {
|
||||
t.Fatalf("jpeg encode: %v", err)
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(buf.Bytes())
|
||||
}
|
||||
|
||||
func makeWebPLogoB64(t *testing.T) string {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
if err := nativewebp.Encode(&buf, makeTestImage(), nil); err != nil {
|
||||
t.Fatalf("webp encode: %v", err)
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(buf.Bytes())
|
||||
}
|
||||
|
||||
func assertValidPDF(t *testing.T, b []byte, minPages int) {
|
||||
t.Helper()
|
||||
if len(b) < 500 {
|
||||
t.Fatalf("PDF too small: %d bytes", len(b))
|
||||
}
|
||||
if !bytes.HasPrefix(b, []byte("%PDF-")) {
|
||||
t.Fatalf("missing %%PDF- header: %q", b[:min(20, len(b))])
|
||||
}
|
||||
if !bytes.Contains(b, []byte("%%EOF")) {
|
||||
t.Fatalf("missing %%%%EOF trailer")
|
||||
}
|
||||
pages := bytes.Count(b, []byte("/Type /Page\n")) + bytes.Count(b, []byte("/Type /Page ")) + bytes.Count(b, []byte("/Type /Page/"))
|
||||
if pages < minPages {
|
||||
t.Fatalf("expected at least %d pages, counted %d", minPages, pages)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoFontGlyphCoverage(t *testing.T) {
|
||||
f, err := sfnt.Parse(goregular.TTF)
|
||||
if err != nil {
|
||||
t.Fatalf("parse goregular: %v", err)
|
||||
}
|
||||
var buf sfnt.Buffer
|
||||
const chars = "áéíóúüñÁÉÍÓÚÜÑ¿¡•·—×○$€%"
|
||||
for _, r := range chars {
|
||||
idx, err := f.GlyphIndex(&buf, r)
|
||||
if err != nil || idx == 0 {
|
||||
t.Errorf("goregular missing glyph for %q (U+%04X)", r, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCotizacionPDFDataHasNoObservacionesInternas(t *testing.T) {
|
||||
rt := reflect.TypeOf(CotizacionPDFData{})
|
||||
for i := 0; i < rt.NumField(); i++ {
|
||||
name := strings.ToLower(rt.Field(i).Name)
|
||||
if strings.Contains(name, "interna") {
|
||||
t.Fatalf("CotizacionPDFData must never declare internal observations field, found %q", rt.Field(i).Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateCotizacionPDFSingleAndLogos(t *testing.T) {
|
||||
fecha := time.Date(2026, 5, 10, 12, 0, 0, 0, time.UTC)
|
||||
vigencia := domain.CalcularVigencia(fecha)
|
||||
obs := "Primer párrafo con acentos: diseño, campaña y año.\n\n" + strings.Repeat("Observación extendida para probar el salto de línea automático en el PDF. ", 15)
|
||||
|
||||
baseData := CotizacionPDFData{
|
||||
Numero: "UJ2605UR001",
|
||||
ClienteNombre: "María José Peña",
|
||||
ClienteEmpresa: "Industrias del Bajío S.A.",
|
||||
AsesorNombre: "Uriel Jareth",
|
||||
Fecha: fecha,
|
||||
Vigencia: vigencia,
|
||||
Moneda: "MXN",
|
||||
TipoCambio: "N/A",
|
||||
Proyecto: "Rediseño Web y Campaña de Adquisición",
|
||||
EsquemaPago: "50% anticipo, 50% entrega",
|
||||
Servicios: []ServicioPDF{
|
||||
{
|
||||
Nombre: "Auditoría SEO y Técnica",
|
||||
Fase: 0,
|
||||
TipoPago: "unico",
|
||||
Precio: 8500,
|
||||
TiempoEntrega: "7 días",
|
||||
Entregables: []string{"Reporte técnico", "Mapa de palabras clave", "Plan de acción"},
|
||||
ModeloCobro: "fijo",
|
||||
},
|
||||
{
|
||||
Nombre: "Desarrollo a la medida",
|
||||
Fase: 1,
|
||||
TipoPago: "unico",
|
||||
Precio: 14000,
|
||||
TiempoEntrega: "15 días",
|
||||
Entregables: []string{"Arquitectura", "Implementación", "Pruebas QA"},
|
||||
ModeloCobro: "horas",
|
||||
EsPersonalizado: true,
|
||||
Horas: f64(20),
|
||||
TarifaHora: f64(700),
|
||||
},
|
||||
{
|
||||
Nombre: "Soporte Mensual Retainer",
|
||||
Fase: 2,
|
||||
TipoPago: "mensual",
|
||||
Precio: 7500,
|
||||
TiempoEntrega: "Mensual",
|
||||
Entregables: []string{"Monitoreo continuo", "Actualizaciones de seguridad"},
|
||||
ModeloCobro: "retainer",
|
||||
MontoMinimo: f64(7500),
|
||||
HorasIncluidas: f64(10),
|
||||
TarifaHora: f64(700),
|
||||
},
|
||||
{
|
||||
Nombre: "Horas Centinela bajo demanda",
|
||||
Fase: 3,
|
||||
TipoPago: "mensual",
|
||||
Precio: 0,
|
||||
TiempoEntrega: "Según consumo",
|
||||
ModeloCobro: "demanda",
|
||||
TarifaHora: f64(700),
|
||||
},
|
||||
},
|
||||
PlanBucefaloNivel: str("estandar"),
|
||||
PlanBucefaloPrecio: 3500,
|
||||
IncluirBonos: true,
|
||||
Bonos: []BonoPDF{
|
||||
{Numero: 1, Descripcion: "Workshop estratégico de diseño"},
|
||||
{Numero: 2, Descripcion: "Un mes gratis de Bucéfalo CRM"},
|
||||
},
|
||||
IncluirIVA: true,
|
||||
Observaciones: &obs,
|
||||
ConfigBancaria: map[string]string{
|
||||
"razon_social": "URIEL JARETH ALVARADO ORTIZ",
|
||||
"rfc": "AAOU970201SU7",
|
||||
"cuenta_nacional": "0123456789",
|
||||
"clabe_interbancaria": "012180001234567890",
|
||||
"cuenta_internacional_swift": "CLABE: 012180001234567890 SWIFT: BCMRMXMMPYM",
|
||||
},
|
||||
ColorPrimario: "#0400C4",
|
||||
ColorSecundario: "#0F172A",
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
b64 string
|
||||
mime string
|
||||
}{
|
||||
{"no_logo", "", ""},
|
||||
{"png_logo", makePNGLogoB64(t), "image/png"},
|
||||
{"jpeg_logo", makeJPEGLogoB64(t), "image/jpeg"},
|
||||
{"webp_logo", makeWebPLogoB64(t), "image/webp"},
|
||||
{"data_uri_png", "data:image/png;base64," + makePNGLogoB64(t), ""},
|
||||
{"corrupt_logo_fallback", "not-valid-base64!!!", "image/png"},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
d := baseData
|
||||
d.LogoBase64 = tc.b64
|
||||
d.LogoMime = tc.mime
|
||||
out, err := GenerateCotizacionPDF(d)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateCotizacionPDF(%s) error: %v", tc.name, err)
|
||||
}
|
||||
// Cover + Resumen + T&C = at least 3 pages
|
||||
assertValidPDF(t, out, 3)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateCotizacionPDFDoblePropuesta(t *testing.T) {
|
||||
fecha := time.Date(2026, 6, 1, 12, 0, 0, 0, time.UTC)
|
||||
d := CotizacionPDFData{
|
||||
Numero: "UJ2606UR002",
|
||||
ClienteNombre: "Carlos Núñez",
|
||||
ClienteEmpresa: "Núñez Logistics",
|
||||
AsesorNombre: "Uriel Jareth",
|
||||
Fecha: fecha,
|
||||
Vigencia: domain.CalcularVigencia(fecha),
|
||||
Moneda: "MXN",
|
||||
Proyecto: "Transformación Digital",
|
||||
EsquemaPago: "Mensual",
|
||||
EsDoble: true,
|
||||
IncluirIVA: true,
|
||||
IncluirBonos: true, // exercises fallback bonos
|
||||
OpcionesMetadata: map[string]domain.MetaOpcion{
|
||||
"1": {Titulo: "Esencial", Descripcion: "Arranque rápido con foco en captación.", NoIncluye: "Producción de video"},
|
||||
"2": {Titulo: "Crecimiento", Descripcion: "Estrategia integral con automatización.", NoIncluye: "Pauta publicitaria"},
|
||||
},
|
||||
Servicios: []ServicioPDF{
|
||||
{Nombre: "Auditoría inicial", Fase: 0, TipoPago: "unico", Precio: 5000, TiempoEntrega: "5 días", Opcion: str("ambas"), Horas: f64(6)},
|
||||
{Nombre: "Landing Page", Fase: 1, TipoPago: "unico", Precio: 12000, TiempoEntrega: "15 días", Opcion: str("1"), Horas: f64(15)},
|
||||
{Nombre: "Sitio Web Completo", Fase: 1, TipoPago: "unico", Precio: 28000, TiempoEntrega: "30 días", Opcion: str("2"), Horas: f64(35)},
|
||||
{Nombre: "Gestión Ads", Fase: 2, TipoPago: "mensual", Precio: 8000, TiempoEntrega: "Mensual", Opcion: str("ambas")},
|
||||
},
|
||||
ColorPrimario: "not-a-hex",
|
||||
ColorSecundario: "",
|
||||
}
|
||||
|
||||
out, err := GenerateCotizacionPDF(d)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateCotizacionPDF doble error: %v", err)
|
||||
}
|
||||
assertValidPDF(t, out, 3)
|
||||
}
|
||||
|
||||
func TestGenerateNotaHorasPDFAllModes(t *testing.T) {
|
||||
base := time.Date(2026, 5, 1, 12, 0, 0, 0, time.UTC)
|
||||
var regs []RegistroHoraPDF
|
||||
for i := 0; i < 35; i++ {
|
||||
estado := "por_pagar"
|
||||
if i%3 == 0 {
|
||||
estado = "pagada"
|
||||
}
|
||||
regs = append(regs, RegistroHoraPDF{
|
||||
Fecha: base.AddDate(0, 0, i*2),
|
||||
HoraInicio: "09:00",
|
||||
HoraFin: "11:30",
|
||||
Horas: 2.5,
|
||||
TarifaHora: 700,
|
||||
Descripcion: "Optimización de campaña y diseño de pruebas A/B con revisión de métricas",
|
||||
EstadoPago: estado,
|
||||
})
|
||||
}
|
||||
|
||||
for _, modo := range []string{"detalle", "dia", "semana", "mes"} {
|
||||
t.Run(modo, func(t *testing.T) {
|
||||
out, err := GenerateNotaHorasPDF(NotaHorasPDFData{
|
||||
Titulo: "Nota de horas por pagar",
|
||||
Numero: "UJ2605UR001",
|
||||
ClienteNombre: "Ana Gómez",
|
||||
ClienteEmpresa: "Gómez Tech",
|
||||
Proyecto: "Soporte Continuo",
|
||||
AsesorNombre: "Uriel Jareth",
|
||||
Moneda: "MXN",
|
||||
IncluirIVA: true,
|
||||
Modo: modo,
|
||||
MostrarEstado: modo == "detalle",
|
||||
MostrarBancarios: true,
|
||||
Registros: regs,
|
||||
ConfigBancaria: map[string]string{
|
||||
"cuenta_nacional": "0123456789",
|
||||
"clabe_interbancaria": "012180001234567890",
|
||||
"cuenta_internacional_swift": "CLABE: 012180001234567890 SWIFT: BCMRMXMMPYM",
|
||||
},
|
||||
LogoBase64: makeWebPLogoB64(t),
|
||||
LogoMime: "image/webp",
|
||||
FechaEmision: time.Date(2026, 7, 15, 12, 0, 0, 0, time.UTC),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateNotaHorasPDF(%s) error: %v", modo, err)
|
||||
}
|
||||
minPages := 1
|
||||
if modo == "detalle" {
|
||||
minPages = 2
|
||||
}
|
||||
assertValidPDF(t, out, minPages)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerarPropuestaYAnexoInternoPDF(t *testing.T) {
|
||||
contenido := map[string]any{
|
||||
"hechos": map[string]any{
|
||||
"citas": []map[string]any{
|
||||
{"id": "C01", "textoLiteral": "Perdemos cotizaciones porque tardamos días en responder por WhatsApp.", "quienLoDijo": "el director comercial"},
|
||||
},
|
||||
"materialesPendientes": []map[string]any{
|
||||
{"texto": "Accesos a Google Ads y Meta Business", "bloqueaEntrega": true},
|
||||
},
|
||||
"decisionesPendientes": []map[string]any{
|
||||
{"texto": "Definir presupuesto mensual de pauta", "quienDecide": "Dirección General"},
|
||||
},
|
||||
"mencionesFueraDeAlcance": []string{"Producción de video corporativo"},
|
||||
"redFlags": []map[string]any{
|
||||
{"senal": "El cliente espera resultados en 48 horas", "severidad": "alta"},
|
||||
},
|
||||
},
|
||||
"diagnostico": map[string]any{
|
||||
"hallazgos": []map[string]any{
|
||||
{"id": "D01", "urgencia": "rojo", "titulo": "Fuga de leads", "descripcion": "No hay seguimiento estructurado en CRM.", "confianza": "confirmado"},
|
||||
{"id": "D02", "urgencia": "ambar", "titulo": "Sitio lento", "descripcion": "Tiempo de carga superior a 6 segundos.", "confianza": "estimado"},
|
||||
{"id": "D03", "urgencia": "verde", "titulo": "Buena reputación", "descripcion": "Reseñas de 4.9 estrellas en Google.", "confianza": "confirmado"},
|
||||
},
|
||||
"valorProblema": map[string]any{
|
||||
"dimensiones": []map[string]any{
|
||||
{
|
||||
"tipo": "dinero",
|
||||
"descripcion": "Leads perdidos por falta de seguimiento oportuno",
|
||||
"montoAnualMXN": 480000.0,
|
||||
"confianza": "estimado",
|
||||
"factores": []map[string]any{
|
||||
{"nombre": "leads_perdidos_mes", "valor": 8.0, "confianza": "estimado"},
|
||||
{"nombre": "ticket_promedio", "valor": 5000.0, "confianza": "estimado"},
|
||||
},
|
||||
},
|
||||
},
|
||||
"notaMetodologia": "Cálculo conservador basado en promedio de los últimos 6 meses.",
|
||||
},
|
||||
"resultados": []map[string]any{
|
||||
{"enunciado": "Responder a cada prospecto en menos de 5 minutos", "metrica": "Tiempo de primera respuesta", "periodoMedicion": "60 días"},
|
||||
},
|
||||
},
|
||||
"redaccion": map[string]any{
|
||||
"hero": map[string]any{
|
||||
"titulo": "Sistema de Captación y Seguimiento Comercial",
|
||||
"subtitulo": "Propuesta diseñada para eliminar fugas de prospectos y multiplicar conversiones.",
|
||||
},
|
||||
"citaDestacadaId": "C01",
|
||||
"alcance": []map[string]any{
|
||||
{"refPartida": "P01", "descripcionResultado": "Diagnóstico completo para detectar cuellos de botella en captación."},
|
||||
},
|
||||
"beneficios": []map[string]any{
|
||||
{"etiqueta": "Cero leads perdidos", "texto": "Cada consulta entra automáticamente al embudo con recordatorios.", "hallazgoId": "D01"},
|
||||
},
|
||||
"exclusiones": []map[string]any{
|
||||
{"texto": "No incluye inversión en pauta publicitaria de Meta o Google.", "razon": "El cliente paga directo a la plataforma"},
|
||||
},
|
||||
"backlogEvolucion": []map[string]any{
|
||||
{"problema": "Integración con ERP contable", "momentoSugerido": "Trimestre 2"},
|
||||
},
|
||||
"notasInternas": []string{"NO_ENVIAR_SECRETO_ASESOR: negociar alcance antes de dar descuento"},
|
||||
},
|
||||
}
|
||||
|
||||
economia := map[string]any{
|
||||
"partidas": []map[string]any{
|
||||
{"refPartida": "P01", "nombre": "Auditoría Comercial", "fase": 0, "tipoPago": "unico", "precio": 8000.0, "tiempoEntrega": "7 días", "entregables": []string{"Mapa de embudo"}},
|
||||
{"refPartida": "P02", "nombre": "Implementación CRM", "fase": 1, "tipoPago": "unico", "precio": 22000.0, "tiempoEntrega": "15 días", "entregables": []string{"Flujos", "Capacitación"}},
|
||||
},
|
||||
"planBucefalo": map[string]any{"nivel": "estandar", "precio": 3500.0},
|
||||
"totales": map[string]any{
|
||||
"subtotalUnico": 30000.0,
|
||||
"subtotalMensual": 3500.0,
|
||||
"ivaUnico": 4800.0,
|
||||
"ivaMensual": 560.0,
|
||||
"totalUnico": 34800.0,
|
||||
"totalMensual": 4060.0,
|
||||
"totalPrimerAnio": 83520.0,
|
||||
"incluyeIva": true,
|
||||
},
|
||||
"moneda": "MXN",
|
||||
"asesor": "Uriel Jareth",
|
||||
}
|
||||
|
||||
in := PropuestaPDFInput{
|
||||
CotizacionNumero: "UJ2606UR010",
|
||||
ClienteNombre: "Roberto Peña",
|
||||
ClienteEmpresa: "Peña Industrial",
|
||||
Proyecto: "CRM y Captación",
|
||||
Moneda: "MXN",
|
||||
Fecha: time.Date(2026, 6, 10, 12, 0, 0, 0, time.UTC),
|
||||
Contenido: contenido,
|
||||
Economia: economia,
|
||||
ColorPrimario: "#0400C4",
|
||||
ColorSecundario: "#0F172A",
|
||||
LogoBase64: makePNGLogoB64(t),
|
||||
LogoMime: "image/png",
|
||||
}
|
||||
|
||||
propPDF, err := GenerarPropuestaPDF(in)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerarPropuestaPDF error: %v", err)
|
||||
}
|
||||
assertValidPDF(t, propPDF, 1)
|
||||
|
||||
anexoPDF, err := GenerarAnexoInternoPDF(in)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerarAnexoInternoPDF error: %v", err)
|
||||
}
|
||||
assertValidPDF(t, anexoPDF, 1)
|
||||
|
||||
// Empty maps should also succeed safely.
|
||||
emptyIn := PropuestaPDFInput{
|
||||
CotizacionNumero: "UJ2606UR011",
|
||||
ClienteNombre: "Cliente Vacío",
|
||||
Proyecto: "Proyecto Mínimo",
|
||||
}
|
||||
if out, err := GenerarPropuestaPDF(emptyIn); err != nil {
|
||||
t.Fatalf("empty GenerarPropuestaPDF error: %v", err)
|
||||
} else {
|
||||
assertValidPDF(t, out, 1)
|
||||
}
|
||||
if out, err := GenerarAnexoInternoPDF(emptyIn); err != nil {
|
||||
t.Fatalf("empty GenerarAnexoInternoPDF error: %v", err)
|
||||
} else {
|
||||
assertValidPDF(t, out, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCalcularRatioPropuesta(t *testing.T) {
|
||||
if r := calcularRatioPropuesta(10000, nil); r != nil {
|
||||
t.Fatalf("expected nil for nil valorAnual")
|
||||
}
|
||||
if r := calcularRatioPropuesta(10000, f64(0)); r != nil {
|
||||
t.Fatalf("expected nil for zero valorAnual")
|
||||
}
|
||||
cases := []struct {
|
||||
total, valor float64
|
||||
want string
|
||||
}{
|
||||
{5000, 100000, "subcotizado"},
|
||||
{20000, 100000, "en_rango"},
|
||||
{35000, 100000, "alto"},
|
||||
{50000, 100000, "objecion_probable"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
r := calcularRatioPropuesta(tc.total, f64(tc.valor))
|
||||
if r == nil || r.Lectura != tc.want {
|
||||
t.Fatalf("calcularRatioPropuesta(%v,%v) = %+v, want %q", tc.total, tc.valor, r, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user