740 lines
21 KiB
Go
740 lines
21 KiB
Go
package pdf
|
||
|
||
import (
|
||
"encoding/json"
|
||
"fmt"
|
||
"math"
|
||
"strings"
|
||
"time"
|
||
|
||
"cotizador/internal/domain"
|
||
)
|
||
|
||
type PropuestaPDFInput struct {
|
||
CotizacionNumero string
|
||
ClienteNombre string
|
||
ClienteEmpresa string
|
||
Proyecto string
|
||
Moneda string
|
||
Fecha time.Time
|
||
Contenido map[string]any
|
||
Economia map[string]any
|
||
ColorPrimario string
|
||
ColorSecundario string
|
||
LogoBase64 string
|
||
LogoMime string
|
||
}
|
||
|
||
// Internal typed shapes mirroring src/lib/propuesta/schemas.ts and economia.ts.
|
||
type propuestaContenido struct {
|
||
Hechos struct {
|
||
Citas []struct {
|
||
ID string `json:"id"`
|
||
TextoLiteral string `json:"textoLiteral"`
|
||
QuienLoDijo string `json:"quienLoDijo"`
|
||
} `json:"citas"`
|
||
MaterialesPendientes []struct {
|
||
Texto string `json:"texto"`
|
||
BloqueaEntrega bool `json:"bloqueaEntrega"`
|
||
} `json:"materialesPendientes"`
|
||
DecisionesPendientes []struct {
|
||
Texto string `json:"texto"`
|
||
QuienDecide string `json:"quienDecide"`
|
||
} `json:"decisionesPendientes"`
|
||
MencionesFueraDeAlcance []string `json:"mencionesFueraDeAlcance"`
|
||
RedFlags []struct {
|
||
Senal string `json:"senal"`
|
||
Severidad string `json:"severidad"`
|
||
} `json:"redFlags"`
|
||
} `json:"hechos"`
|
||
Diagnostico struct {
|
||
Hallazgos []struct {
|
||
ID string `json:"id"`
|
||
Urgencia string `json:"urgencia"`
|
||
Titulo string `json:"titulo"`
|
||
Descripcion string `json:"descripcion"`
|
||
Confianza string `json:"confianza"`
|
||
} `json:"hallazgos"`
|
||
ValorProblema struct {
|
||
Dimensiones []struct {
|
||
Tipo string `json:"tipo"`
|
||
Descripcion string `json:"descripcion"`
|
||
Factores []struct {
|
||
Nombre string `json:"nombre"`
|
||
Valor float64 `json:"valor"`
|
||
Confianza string `json:"confianza"`
|
||
} `json:"factores"`
|
||
MontoAnualMXN *float64 `json:"montoAnualMXN"`
|
||
Confianza string `json:"confianza"`
|
||
} `json:"dimensiones"`
|
||
NotaMetodologia string `json:"notaMetodologia"`
|
||
} `json:"valorProblema"`
|
||
Resultados []struct {
|
||
Enunciado string `json:"enunciado"`
|
||
Metrica string `json:"metrica"`
|
||
LineaBase *string `json:"lineaBase"`
|
||
PeriodoMedicion string `json:"periodoMedicion"`
|
||
} `json:"resultados"`
|
||
} `json:"diagnostico"`
|
||
Redaccion struct {
|
||
Hero struct {
|
||
Titulo string `json:"titulo"`
|
||
Subtitulo string `json:"subtitulo"`
|
||
} `json:"hero"`
|
||
CitaDestacadaID string `json:"citaDestacadaId"`
|
||
Alcance []struct {
|
||
RefPartida string `json:"refPartida"`
|
||
DescripcionResultado string `json:"descripcionResultado"`
|
||
} `json:"alcance"`
|
||
Beneficios []struct {
|
||
Etiqueta string `json:"etiqueta"`
|
||
Texto string `json:"texto"`
|
||
HallazgoID string `json:"hallazgoId"`
|
||
} `json:"beneficios"`
|
||
Exclusiones []struct {
|
||
Texto string `json:"texto"`
|
||
Razon string `json:"razon"`
|
||
} `json:"exclusiones"`
|
||
BacklogEvolucion []struct {
|
||
Problema string `json:"problema"`
|
||
MomentoSugerido string `json:"momentoSugerido"`
|
||
} `json:"backlogEvolucion"`
|
||
NotasInternas []string `json:"notasInternas"`
|
||
} `json:"redaccion"`
|
||
}
|
||
|
||
type propuestaPartida struct {
|
||
RefPartida string `json:"refPartida"`
|
||
Nombre string `json:"nombre"`
|
||
Fase int `json:"fase"`
|
||
TipoPago string `json:"tipoPago"`
|
||
Precio float64 `json:"precio"`
|
||
TiempoEntrega string `json:"tiempoEntrega"`
|
||
ModeloCobro string `json:"modeloCobro"`
|
||
Entregables []string `json:"entregables"`
|
||
}
|
||
|
||
type propuestaEconomia struct {
|
||
Partidas []propuestaPartida `json:"partidas"`
|
||
Totales struct {
|
||
SubtotalUnico float64 `json:"subtotalUnico"`
|
||
SubtotalMensual float64 `json:"subtotalMensual"`
|
||
IVAUnico float64 `json:"ivaUnico"`
|
||
IVAMensual float64 `json:"ivaMensual"`
|
||
TotalUnico float64 `json:"totalUnico"`
|
||
TotalMensual float64 `json:"totalMensual"`
|
||
TotalPrimerAnio float64 `json:"totalPrimerAnio"`
|
||
IncluyeIVA bool `json:"incluyeIva"`
|
||
} `json:"totales"`
|
||
Moneda string `json:"moneda"`
|
||
Asesor string `json:"asesor"`
|
||
PlanBucefalo *struct {
|
||
Nivel string `json:"nivel"`
|
||
Precio float64 `json:"precio"`
|
||
} `json:"planBucefalo"`
|
||
}
|
||
|
||
func decodeMapInto[T any](src map[string]any) T {
|
||
var out T
|
||
if len(src) == 0 {
|
||
return out
|
||
}
|
||
b, err := json.Marshal(src)
|
||
if err != nil {
|
||
return out
|
||
}
|
||
_ = json.Unmarshal(b, &out)
|
||
return out
|
||
}
|
||
|
||
var (
|
||
colorSemaforo = map[string]string{
|
||
"rojo": "#dc2626",
|
||
"ambar": "#d97706",
|
||
"azul": "#0400C4",
|
||
"verde": "#16a34a",
|
||
}
|
||
etiquetaSemaforo = map[string]string{
|
||
"rojo": "Problema crítico",
|
||
"ambar": "Área de mejora",
|
||
"azul": "Oportunidad",
|
||
"verde": "Ventaja existente",
|
||
}
|
||
etiquetaConfianza = map[string]string{
|
||
"confirmado": "Confirmado",
|
||
"estimado": "Estimado",
|
||
"por_validar": "Por validar",
|
||
}
|
||
)
|
||
|
||
func detalleDePartida(p propuestaPartida) string {
|
||
var trozos []string
|
||
if len(p.Entregables) > 0 {
|
||
limit := len(p.Entregables)
|
||
if limit > 4 {
|
||
limit = 4
|
||
}
|
||
trozos = append(trozos, strings.Join(p.Entregables[:limit], " · "))
|
||
}
|
||
if strings.TrimSpace(p.TiempoEntrega) != "" {
|
||
trozos = append(trozos, "Entrega: "+p.TiempoEntrega)
|
||
}
|
||
if p.TipoPago == "mensual" {
|
||
trozos = append(trozos, "Servicio mensual")
|
||
}
|
||
return strings.Join(trozos, " | ")
|
||
}
|
||
|
||
type ratioResult struct {
|
||
Ratio float64
|
||
Lectura string
|
||
}
|
||
|
||
func calcularRatioPropuesta(totalPrimerAnio float64, valorAnual *float64) *ratioResult {
|
||
if valorAnual == nil || *valorAnual <= 0 {
|
||
return nil
|
||
}
|
||
ratio := totalPrimerAnio / *valorAnual
|
||
lectura := "objecion_probable"
|
||
switch {
|
||
case ratio < 0.1:
|
||
lectura = "subcotizado"
|
||
case ratio <= 0.25:
|
||
lectura = "en_rango"
|
||
case ratio <= 0.4:
|
||
lectura = "alto"
|
||
}
|
||
return &ratioResult{
|
||
Ratio: math.Round(ratio*1000) / 1000,
|
||
Lectura: lectura,
|
||
}
|
||
}
|
||
|
||
func GenerarPropuestaPDF(in PropuestaPDFInput) ([]byte, error) {
|
||
primary := safeHex(in.ColorPrimario, defaultPrimary)
|
||
dark := safeHex(in.ColorSecundario, defaultDark)
|
||
muted := colorMuted
|
||
border := "#e2e8f0"
|
||
|
||
prop := decodeMapInto[propuestaContenido](in.Contenido)
|
||
econ := decodeMapInto[propuestaEconomia](in.Economia)
|
||
|
||
moneda := in.Moneda
|
||
if moneda == "" {
|
||
moneda = econ.Moneda
|
||
}
|
||
fmtMoney := func(n float64) string {
|
||
return formatMoney(n, moneda)
|
||
}
|
||
|
||
fecha := in.Fecha
|
||
if fecha.IsZero() {
|
||
fecha = time.Now()
|
||
}
|
||
vigencia := domain.CalcularVigencia(fecha)
|
||
clienteDisplay := in.ClienteEmpresa
|
||
if strings.TrimSpace(clienteDisplay) == "" {
|
||
clienteDisplay = in.ClienteNombre
|
||
}
|
||
|
||
c := newCanvas(50, 55, 50, 50)
|
||
c.doc.AliasNbPages("{nb}")
|
||
logo := registerLogo(c.doc, "prop_logo", in.LogoBase64, in.LogoMime)
|
||
|
||
c.doc.SetFooterFunc(func() {
|
||
c.hLine(c.L, c.L+c.W, c.ph-42, border, 0.5)
|
||
leftTxt := fmt.Sprintf("%s · Propuesta consultiva · %s", in.CotizacionNumero, clienteDisplay)
|
||
c.drawSingleLine(leftTxt, c.L, c.ph-35, c.W-60, "", 7, muted, "L")
|
||
rightTxt := fmt.Sprintf("%d / {nb}", c.doc.PageNo())
|
||
c.drawSingleLine(rightTxt, c.L, c.ph-35, c.W, "", 7, muted, "R")
|
||
})
|
||
|
||
c.doc.AddPage()
|
||
y := c.mTop
|
||
|
||
titulo := func(t string) {
|
||
y = c.need(26, y)
|
||
c.rectFill(c.L, y+1, 3, 10, primary)
|
||
c.drawSingleLine(strings.ToUpper(t), c.L+10, y, c.W-10, "B", 10, dark, "L")
|
||
y += 20
|
||
}
|
||
parrafo := func(t string, size float64, color string) {
|
||
raw := strings.ReplaceAll(t, "\r\n", "\n")
|
||
for _, p := range strings.Split(raw, "\n") {
|
||
p = strings.TrimSpace(p)
|
||
if p == "" {
|
||
continue
|
||
}
|
||
h := c.textHeight(p, c.W, "", size)
|
||
y = c.need(h+4, y)
|
||
c.drawText(p, c.L, y, c.W, "", size, color, "L")
|
||
y += h + 4
|
||
}
|
||
}
|
||
|
||
// ── HERO ──
|
||
if logo.ok {
|
||
logo.drawByHeight(c.doc, c.L, y, 26)
|
||
y += 34
|
||
}
|
||
c.drawSingleLine("PROPUESTA CONSULTIVA", c.L, y, c.W, "B", 8.5, primary, "L")
|
||
y += 16
|
||
|
||
heroTit := strings.TrimSpace(prop.Redaccion.Hero.Titulo)
|
||
if heroTit == "" {
|
||
heroTit = in.Proyecto
|
||
}
|
||
if heroTit != "" {
|
||
hTit := c.drawText(heroTit, c.L, y, c.W, "B", 20, dark, "L")
|
||
y += hTit + 8
|
||
}
|
||
if strings.TrimSpace(prop.Redaccion.Hero.Subtitulo) != "" {
|
||
parrafo(prop.Redaccion.Hero.Subtitulo, 10, muted)
|
||
y += 8
|
||
}
|
||
|
||
metaParts := []string{
|
||
clienteDisplay,
|
||
in.CotizacionNumero,
|
||
domain.FormatDateShort(fecha),
|
||
"Vigencia " + domain.FormatDateShort(vigencia),
|
||
}
|
||
if strings.TrimSpace(econ.Asesor) != "" {
|
||
metaParts = append(metaParts, econ.Asesor)
|
||
}
|
||
meta := strings.Join(metaParts, " · ")
|
||
hMeta := c.drawText(meta, c.L, y, c.W, "", 8, muted, "L")
|
||
y += hMeta + 12
|
||
c.hLine(c.L, c.L+c.W, y, border, 0.5)
|
||
y += 18
|
||
|
||
// ── DIAGNÓSTICO ──
|
||
if len(prop.Diagnostico.Hallazgos) > 0 || prop.Redaccion.CitaDestacadaID != "" {
|
||
titulo("Diagnóstico")
|
||
for _, cita := range prop.Hechos.Citas {
|
||
if cita.ID != "" && cita.ID == prop.Redaccion.CitaDestacadaID {
|
||
texto := fmt.Sprintf("\"%s\"", cita.TextoLiteral)
|
||
h := c.textHeight(texto, c.W-22, "I", 11)
|
||
y = c.need(h+22, y)
|
||
c.rectFill(c.L, y-3, 2.5, h+10, primary)
|
||
c.drawText(texto, c.L+12, y, c.W-22, "I", 11, dark, "L")
|
||
y += h + 4
|
||
c.drawSingleLine("— "+cita.QuienLoDijo, c.L+12, y, c.W-22, "", 7.5, muted, "L")
|
||
y += 18
|
||
break
|
||
}
|
||
}
|
||
for _, hal := range prop.Diagnostico.Hallazgos {
|
||
cuerpo := fmt.Sprintf("%s — %s", hal.Titulo, hal.Descripcion)
|
||
h := c.textHeight(cuerpo, c.W-24, "", 9)
|
||
y = c.need(h+16, y)
|
||
dotColor := colorSemaforo[hal.Urgencia]
|
||
if dotColor == "" {
|
||
dotColor = muted
|
||
}
|
||
c.circleFill(c.L+4.5, y+5, 3.2, dotColor)
|
||
c.drawText(cuerpo, c.L+16, y, c.W-24, "", 9, dark, "L")
|
||
y += h + 1
|
||
subLbl := fmt.Sprintf("%s · %s", etiquetaSemaforo[hal.Urgencia], etiquetaConfianza[hal.Confianza])
|
||
c.drawSingleLine(subLbl, c.L+16, y, c.W-24, "", 7, muted, "L")
|
||
y += 13
|
||
}
|
||
y += 8
|
||
}
|
||
|
||
// ── VALOR DEL PROBLEMA ──
|
||
dims := prop.Diagnostico.ValorProblema.Dimensiones
|
||
if len(dims) > 0 {
|
||
titulo("Lo que cuesta no resolverlo")
|
||
for _, dim := range dims {
|
||
montoTxt := "sin cuantificar"
|
||
if dim.MontoAnualMXN != nil {
|
||
montoTxt = fmt.Sprintf("%s al año", fmtMoney(*dim.MontoAnualMXN))
|
||
}
|
||
linea := fmt.Sprintf("%s — %s", dim.Descripcion, montoTxt)
|
||
h := c.textHeight(linea, c.W-14, "", 9)
|
||
y = c.need(h+14, y)
|
||
c.drawText(linea, c.L+6, y, c.W-14, "", 9, dark, "L")
|
||
y += h + 1
|
||
c.drawSingleLine(etiquetaConfianza[dim.Confianza], c.L+6, y, c.W-14, "", 7, muted, "L")
|
||
y += 13
|
||
}
|
||
if strings.TrimSpace(prop.Diagnostico.ValorProblema.NotaMetodologia) != "" {
|
||
y += 2
|
||
parrafo(prop.Diagnostico.ValorProblema.NotaMetodologia, 8, muted)
|
||
}
|
||
y += 8
|
||
}
|
||
|
||
// ── RESULTADOS ──
|
||
if len(prop.Diagnostico.Resultados) > 0 {
|
||
titulo("Resultados a lograr")
|
||
for _, r := range prop.Diagnostico.Resultados {
|
||
t := fmt.Sprintf("• %s (%s, %s)", r.Enunciado, r.Metrica, r.PeriodoMedicion)
|
||
h := c.textHeight(t, c.W-8, "", 9)
|
||
y = c.need(h+6, y)
|
||
c.drawText(t, c.L+4, y, c.W-8, "", 9, dark, "L")
|
||
y += h + 6
|
||
}
|
||
y += 8
|
||
}
|
||
|
||
// ── ALCANCE ──
|
||
titulo("Alcance de la inversión")
|
||
descPorRef := make(map[string]string, len(prop.Redaccion.Alcance))
|
||
for _, a := range prop.Redaccion.Alcance {
|
||
descPorRef[a.RefPartida] = a.DescripcionResultado
|
||
}
|
||
for _, p := range econ.Partidas {
|
||
descripcion := descPorRef[p.RefPartida]
|
||
respaldo := ""
|
||
if descripcion == "" {
|
||
respaldo = detalleDePartida(p)
|
||
}
|
||
hNombre := c.textHeight(p.Nombre, c.W*0.68, "B", 9.5)
|
||
subTxt := descripcion
|
||
if subTxt == "" {
|
||
subTxt = respaldo
|
||
}
|
||
hDesc := 0.0
|
||
if subTxt != "" {
|
||
hDesc = c.textHeight(subTxt, c.W*0.68, "", 8)
|
||
}
|
||
y = c.need(hNombre+hDesc+14, y)
|
||
c.drawText(p.Nombre, c.L, y, c.W*0.68, "B", 9.5, dark, "L")
|
||
c.drawSingleLine(fmtMoney(p.Precio), c.L+c.W*0.7, y, c.W*0.3, "B", 9.5, primary, "R")
|
||
y += hNombre + 2
|
||
if subTxt != "" {
|
||
c.drawText(subTxt, c.L, y, c.W*0.68, "", 8, muted, "L")
|
||
y += hDesc + 10
|
||
} else {
|
||
y += 8
|
||
}
|
||
}
|
||
|
||
if econ.PlanBucefalo != nil && strings.TrimSpace(econ.PlanBucefalo.Nivel) != "" {
|
||
etiqueta := "CRM Bucéfalo — plan " + capitalize(econ.PlanBucefalo.Nivel)
|
||
hE := c.textHeight(etiqueta, c.W*0.68, "B", 9.5)
|
||
y = c.need(hE+22, y)
|
||
c.drawText(etiqueta, c.L, y, c.W*0.68, "B", 9.5, dark, "L")
|
||
c.drawSingleLine(fmtMoney(econ.PlanBucefalo.Precio)+" / mes", c.L+c.W*0.7, y, c.W*0.3, "B", 9.5, primary, "R")
|
||
y += hE + 2
|
||
c.drawSingleLine("Servicio mensual", c.L, y, c.W*0.68, "", 8, muted, "L")
|
||
y += 20
|
||
}
|
||
|
||
y = c.need(58, y)
|
||
c.hLine(c.L, c.L+c.W, y, border, 0.5)
|
||
y += 10
|
||
|
||
// ── CAJA DE TOTALES ──
|
||
tot := econ.Totales
|
||
fila := func(etiqueta, valor string, fuerte bool) {
|
||
step := 15.0
|
||
size := 9.0
|
||
lblStyle := ""
|
||
lblColor := muted
|
||
valColor := dark
|
||
if fuerte {
|
||
step = 18.0
|
||
size = 10.5
|
||
lblStyle = "B"
|
||
lblColor = dark
|
||
valColor = primary
|
||
}
|
||
y = c.need(step, y)
|
||
c.drawSingleLine(etiqueta, c.L, y, c.W*0.6, lblStyle, size, lblColor, "L")
|
||
c.drawSingleLine(valor, c.L+c.W*0.6, y, c.W*0.4, "B", size, valColor, "R")
|
||
y += step
|
||
}
|
||
|
||
if tot.SubtotalUnico > 0 {
|
||
fila("Subtotal pago único", fmtMoney(tot.SubtotalUnico), false)
|
||
if tot.IncluyeIVA {
|
||
fila("IVA 16%", fmtMoney(tot.IVAUnico), false)
|
||
fila("Total pago único", fmtMoney(tot.TotalUnico), true)
|
||
} else {
|
||
fila("Total pago único (sin IVA)", fmtMoney(tot.TotalUnico), true)
|
||
}
|
||
}
|
||
if tot.SubtotalMensual > 0 {
|
||
if tot.SubtotalUnico > 0 {
|
||
y += 4
|
||
}
|
||
fila("Subtotal mensual", fmtMoney(tot.SubtotalMensual), false)
|
||
if tot.IncluyeIVA {
|
||
fila("IVA 16%", fmtMoney(tot.IVAMensual), false)
|
||
fila("Total mensual", fmtMoney(tot.TotalMensual), true)
|
||
} else {
|
||
fila("Total mensual (sin IVA)", fmtMoney(tot.TotalMensual), true)
|
||
}
|
||
}
|
||
|
||
y = c.need(20, y)
|
||
notaIVA := "Los precios son en Moneda Nacional (MXN) y no incluyen IVA. Facturación CFDI."
|
||
if tot.IncluyeIVA {
|
||
notaIVA = "Los precios por partida son en Moneda Nacional (MXN) y no incluyen IVA; el IVA se desglosa arriba. Facturación CFDI."
|
||
}
|
||
hNota := c.drawText(notaIVA, c.L, y, c.W, "", 7.5, muted, "L")
|
||
y += hNota + 16
|
||
|
||
// ── BENEFICIOS ──
|
||
if len(prop.Redaccion.Beneficios) > 0 {
|
||
titulo("Por qué tiene sentido")
|
||
for _, b := range prop.Redaccion.Beneficios {
|
||
hEt := c.textHeight(b.Etiqueta, c.W*0.24, "B", 9)
|
||
hTx := c.textHeight(b.Texto, c.W*0.72, "", 8.5)
|
||
h := hEt
|
||
if hTx > h {
|
||
h = hTx
|
||
}
|
||
y = c.need(h+9, y)
|
||
c.drawText(b.Etiqueta, c.L, y, c.W*0.24, "B", 9, dark, "L")
|
||
c.drawText(b.Texto, c.L+c.W*0.27, y, c.W*0.72, "", 8.5, muted, "L")
|
||
y += h + 9
|
||
}
|
||
y += 8
|
||
}
|
||
|
||
// ── EXCLUSIONES ──
|
||
if len(prop.Redaccion.Exclusiones) > 0 {
|
||
titulo("Qué no incluye esta propuesta")
|
||
for _, e := range prop.Redaccion.Exclusiones {
|
||
t2 := "× " + e.Texto
|
||
h := c.textHeight(t2, c.W-8, "", 8.5)
|
||
y = c.need(h+6, y)
|
||
c.drawText(t2, c.L+4, y, c.W-8, "", 8.5, dark, "L")
|
||
y += h + 6
|
||
}
|
||
y += 10
|
||
}
|
||
|
||
// ── PENDIENTES ──
|
||
mats := prop.Hechos.MaterialesPendientes
|
||
decs := prop.Hechos.DecisionesPendientes
|
||
if len(mats) > 0 || len(decs) > 0 {
|
||
titulo("Qué necesitamos de ustedes")
|
||
for _, mm := range mats {
|
||
suffix := ""
|
||
if mm.BloqueaEntrega {
|
||
suffix = " (el avance queda condicionado a esto)"
|
||
}
|
||
t2 := "○ " + mm.Texto + suffix
|
||
h := c.textHeight(t2, c.W-8, "", 8.5)
|
||
y = c.need(h+6, y)
|
||
c.drawText(t2, c.L+4, y, c.W-8, "", 8.5, dark, "L")
|
||
y += h + 6
|
||
}
|
||
for _, dd := range decs {
|
||
t2 := fmt.Sprintf("· %s (decide: %s)", dd.Texto, dd.QuienDecide)
|
||
h := c.textHeight(t2, c.W-8, "", 8.5)
|
||
y = c.need(h+6, y)
|
||
c.drawText(t2, c.L+4, y, c.W-8, "", 8.5, muted, "L")
|
||
y += h + 6
|
||
}
|
||
y += 10
|
||
}
|
||
|
||
// ── BACKLOG ──
|
||
if len(prop.Redaccion.BacklogEvolucion) > 0 {
|
||
titulo("Registrado para más adelante")
|
||
y = c.need(14, y)
|
||
c.drawSingleLine("No comprometido en esta propuesta.", c.L, y, c.W, "I", 7.5, muted, "L")
|
||
y += 14
|
||
for _, b := range prop.Redaccion.BacklogEvolucion {
|
||
t2 := fmt.Sprintf("· %s (%s)", b.Problema, b.MomentoSugerido)
|
||
h := c.textHeight(t2, c.W-8, "", 8.5)
|
||
y = c.need(h+6, y)
|
||
c.drawText(t2, c.L+4, y, c.W-8, "", 8.5, dark, "L")
|
||
y += h + 6
|
||
}
|
||
}
|
||
|
||
return c.bytes()
|
||
}
|
||
|
||
// GenerarAnexoInternoPDF renders the internal-only advisor annex as a separate document
|
||
// with an unmistakable red banner so it can never be confused with the client proposal.
|
||
func GenerarAnexoInternoPDF(in PropuestaPDFInput) ([]byte, error) {
|
||
prop := decodeMapInto[propuestaContenido](in.Contenido)
|
||
econ := decodeMapInto[propuestaEconomia](in.Economia)
|
||
|
||
moneda := in.Moneda
|
||
if moneda == "" {
|
||
moneda = econ.Moneda
|
||
}
|
||
fmtMoney := func(n float64) string {
|
||
return formatMoney(n, moneda)
|
||
}
|
||
|
||
dark := defaultDark
|
||
muted := colorMuted
|
||
redBanner := "#b91c1c"
|
||
|
||
c := newCanvas(50, 55, 50, 50)
|
||
c.doc.AddPage()
|
||
|
||
c.rectFill(0, 0, c.pw, 36, redBanner)
|
||
c.drawSingleLine("USO INTERNO — NO ENVIAR AL CLIENTE", c.L, 11, c.W, "B", 13, colorWhite, "L")
|
||
y := 56.0
|
||
|
||
clienteDisplay := in.ClienteEmpresa
|
||
if strings.TrimSpace(clienteDisplay) == "" {
|
||
clienteDisplay = in.ClienteNombre
|
||
}
|
||
metaParts := []string{in.CotizacionNumero, clienteDisplay}
|
||
if strings.TrimSpace(econ.Asesor) != "" {
|
||
metaParts = append(metaParts, econ.Asesor)
|
||
}
|
||
c.drawSingleLine(strings.Join(metaParts, " · "), c.L, y, c.W, "", 9, muted, "L")
|
||
y += 24
|
||
|
||
var valorAnualSum float64
|
||
for _, dim := range prop.Diagnostico.ValorProblema.Dimensiones {
|
||
if dim.MontoAnualMXN != nil {
|
||
valorAnualSum += *dim.MontoAnualMXN
|
||
}
|
||
}
|
||
var valorAnual *float64
|
||
if valorAnualSum > 0 {
|
||
v := valorAnualSum
|
||
valorAnual = &v
|
||
}
|
||
r := calcularRatioPropuesta(econ.Totales.TotalPrimerAnio, valorAnual)
|
||
|
||
seccion := func(t string) {
|
||
y = c.need(24, y)
|
||
c.drawSingleLine(t, c.L, y, c.W, "B", 11, dark, "L")
|
||
y += 18
|
||
}
|
||
linea := func(k, v string) {
|
||
y = c.need(15, y)
|
||
c.drawSingleLine(k, c.L, y, c.W*0.5, "", 9, muted, "L")
|
||
c.drawSingleLine(v, c.L+c.W*0.5, y, c.W*0.5, "B", 9, dark, "R")
|
||
y += 15
|
||
}
|
||
|
||
confirmados := 0
|
||
for _, h := range prop.Diagnostico.Hallazgos {
|
||
if h.Confianza == "confirmado" {
|
||
confirmados++
|
||
}
|
||
}
|
||
|
||
valorAnualTxt := "sin cuantificar"
|
||
if valorAnual != nil {
|
||
valorAnualTxt = fmtMoney(*valorAnual)
|
||
}
|
||
ratioTxt := "no calculable"
|
||
if r != nil {
|
||
ratioTxt = fmt.Sprintf("%.1f%% — %s", r.Ratio*100, strings.ReplaceAll(r.Lectura, "_", " "))
|
||
}
|
||
|
||
seccion("Ponderación de la cotización")
|
||
linea("Inversión del primer año", fmtMoney(econ.Totales.TotalPrimerAnio))
|
||
linea("Valor anual del problema", valorAnualTxt)
|
||
linea("Ratio precio / valor", ratioTxt)
|
||
linea("Hallazgos en el diagnóstico", fmt.Sprintf("%d", len(prop.Diagnostico.Hallazgos)))
|
||
linea("Cifras confirmadas", fmt.Sprintf("%d", confirmados))
|
||
linea("Exclusiones definidas", fmt.Sprintf("%d", len(prop.Redaccion.Exclusiones)))
|
||
linea("Materiales pendientes", fmt.Sprintf("%d", len(prop.Hechos.MaterialesPendientes)))
|
||
linea("Decisiones pendientes", fmt.Sprintf("%d", len(prop.Hechos.DecisionesPendientes)))
|
||
linea("Red flags detectadas", fmt.Sprintf("%d", len(prop.Hechos.RedFlags)))
|
||
y += 6
|
||
|
||
if len(prop.Diagnostico.ValorProblema.Dimensiones) > 0 {
|
||
seccion("De dónde sale el valor anual")
|
||
sinConfirmar := false
|
||
for _, dim := range prop.Diagnostico.ValorProblema.Dimensiones {
|
||
montoTxt := "sin cifra"
|
||
if dim.MontoAnualMXN != nil {
|
||
montoTxt = fmtMoney(*dim.MontoAnualMXN)
|
||
}
|
||
y = c.need(14, y)
|
||
c.drawSingleLine(fmt.Sprintf("%s: %s", dim.Tipo, montoTxt), c.L, y, c.W, "B", 9, dark, "L")
|
||
y += 13
|
||
hasConfirmed := false
|
||
if len(dim.Factores) > 0 {
|
||
partes := make([]string, 0, len(dim.Factores))
|
||
for _, f := range dim.Factores {
|
||
if f.Confianza == "confirmado" {
|
||
hasConfirmed = true
|
||
}
|
||
partes = append(partes, fmt.Sprintf("%s = %g (%s)", f.Nombre, f.Valor, f.Confianza))
|
||
}
|
||
desglose := strings.Join(partes, " x ")
|
||
h := c.textHeight(desglose, c.W-10, "", 8)
|
||
y = c.need(h+8, y)
|
||
c.drawText(desglose, c.L+6, y, c.W-10, "", 8, muted, "L")
|
||
y += h + 8
|
||
}
|
||
if dim.MontoAnualMXN != nil && !hasConfirmed {
|
||
sinConfirmar = true
|
||
}
|
||
}
|
||
if sinConfirmar {
|
||
alerta := "Ojo: hay una cifra que descansa entera en factores estimados. Antes de fiarte del ratio, revisa que no falte un factor — la aritmética puede cuadrar y aun así estar inflada."
|
||
h := c.textHeight(alerta, c.W, "B", 8.5)
|
||
y = c.need(h+12, y)
|
||
c.drawText(alerta, c.L, y, c.W, "B", 8.5, redBanner, "L")
|
||
y += h + 14
|
||
}
|
||
y += 4
|
||
}
|
||
|
||
if r != nil {
|
||
var nota string
|
||
switch r.Lectura {
|
||
case "subcotizado":
|
||
nota = "La inversión es menos del 10% de lo que el problema le cuesta al cliente cada año. Probablemente subcotizaste."
|
||
case "objecion_probable":
|
||
nota = "La inversión supera el 40% del valor anual del problema. Prepara la conversación de precio: se responde con alcance, no con descuento."
|
||
case "alto":
|
||
nota = "La inversión está en la banda alta. Justificable, pero conviene anclar bien el valor antes de dar el número."
|
||
default:
|
||
nota = "La inversión cae en el rango de referencia (15-25% del valor anual)."
|
||
}
|
||
h := c.textHeight(nota, c.W, "I", 8.5)
|
||
y = c.need(h+12, y)
|
||
c.drawText(nota, c.L, y, c.W, "I", 8.5, muted, "L")
|
||
y += h + 16
|
||
}
|
||
|
||
if len(prop.Hechos.RedFlags) > 0 {
|
||
seccion("Red flags")
|
||
for _, rf := range prop.Hechos.RedFlags {
|
||
t := fmt.Sprintf("· [%s] %s", rf.Severidad, rf.Senal)
|
||
h := c.textHeight(t, c.W-8, "", 9)
|
||
y = c.need(h+6, y)
|
||
c.drawText(t, c.L+4, y, c.W-8, "", 9, dark, "L")
|
||
y += h + 6
|
||
}
|
||
y += 10
|
||
}
|
||
|
||
if len(prop.Redaccion.NotasInternas) > 0 {
|
||
seccion("Notas para el asesor")
|
||
for _, n := range prop.Redaccion.NotasInternas {
|
||
t := "· " + n
|
||
h := c.textHeight(t, c.W-8, "", 9)
|
||
y = c.need(h+6, y)
|
||
c.drawText(t, c.L+4, y, c.W-8, "", 9, dark, "L")
|
||
y += h + 6
|
||
}
|
||
y += 10
|
||
}
|
||
|
||
if len(prop.Hechos.MencionesFueraDeAlcance) > 0 {
|
||
seccion("Se mencionó y quedó fuera")
|
||
for _, m := range prop.Hechos.MencionesFueraDeAlcance {
|
||
t := "· " + m
|
||
h := c.textHeight(t, c.W-8, "", 9)
|
||
y = c.need(h+6, y)
|
||
c.drawText(t, c.L+4, y, c.W-8, "", 9, dark, "L")
|
||
y += h + 6
|
||
}
|
||
}
|
||
|
||
return c.bytes()
|
||
}
|