feat: migrar backend unificado a Go 1.27 + SPA Vite embebido

This commit is contained in:
urieljareth
2026-11-28 09:20:55 -06:00
parent 4f64487b88
commit b5ebcd0b86
332 changed files with 29135 additions and 37275 deletions
+582
View File
@@ -0,0 +1,582 @@
package pdf
import (
"fmt"
"strings"
"time"
"cotizador/internal/domain"
)
type ServicioPDF struct {
Nombre string
Fase int
TipoPago string
Precio float64
TiempoEntrega string
Entregables []string
EsPersonalizado bool
Horas *float64
TarifaHora *float64
ModeloCobro string
MontoMinimo *float64
HorasIncluidas *float64
Opcion *string
}
type BonoPDF struct {
Numero int
Descripcion string
}
// CotizacionPDFData holds client-facing quotation data for PDF generation.
// ObservacionesInternas is intentionally NOT declared here so internal notes
// can never leak into a client document.
type CotizacionPDFData struct {
Numero string
ClienteNombre string
ClienteEmpresa string
AsesorNombre string
Fecha time.Time
Vigencia time.Time
Moneda string
TipoCambio string
Proyecto string
EsquemaPago string
Servicios []ServicioPDF
EsDoble bool
OpcionesMetadata map[string]domain.MetaOpcion
PlanBucefaloNivel *string
PlanBucefaloPrecio float64
IncluirBonos bool
Bonos []BonoPDF
IncluirIVA bool
Observaciones *string
ConfigBancaria map[string]string
ColorPrimario string
ColorSecundario string
LogoBase64 string
LogoMime string
}
func servicioPDFToCalc(s ServicioPDF) domain.ServicioCalc {
return domain.ServicioCalc{
Nombre: s.Nombre,
ModeloCobro: s.ModeloCobro,
EsPersonalizado: s.EsPersonalizado,
Horas: s.Horas,
TarifaHora: s.TarifaHora,
MontoMinimo: s.MontoMinimo,
HorasIncluidas: s.HorasIncluidas,
Opcion: s.Opcion,
TipoPago: s.TipoPago,
Precio: s.Precio,
Seleccionado: true,
}
}
func serviciosPDFToCalc(list []ServicioPDF) []domain.ServicioCalc {
out := make([]domain.ServicioCalc, len(list))
for i, s := range list {
out[i] = servicioPDFToCalc(s)
}
return out
}
func GenerateCotizacionPDF(data CotizacionPDFData) ([]byte, error) {
primary := safeHex(data.ColorPrimario, defaultPrimary)
dark := safeHex(data.ColorSecundario, defaultDark)
c := newCanvas(45, 55, 50, 50)
logo := registerLogo(c.doc, "cot_logo", data.LogoBase64, data.LogoMime)
// Footer on every page.
c.doc.SetFooterFunc(func() {
c.hLine(c.L, c.L+c.W, c.ph-42, colorBorder, 0.5)
c.drawSingleLine("Uriel Jareth Consulting", c.L, c.ph-35, c.W, "", 6.5, colorMuted, "C")
c.drawSingleLine("urieljareth.com | [email protected] | (445) 182 9943", c.L, c.ph-26, c.W, "", 6.5, colorMuted, "C")
})
fmtMoney := func(n float64) string {
return formatMoney(n, data.Moneda)
}
sectionTitle := func(title string, y float64) float64 {
y = c.need(20, y)
c.rectFill(c.L, y+1, 3, 9, primary)
c.drawSingleLine(title, c.L+10, y, c.W-10, "B", 9, dark, "L")
return y + 15
}
// ── PAGE 1: COVER ──────────────────────────────
c.doc.AddPage()
c.rectFill(0, 0, c.pw, c.ph, colorWhite)
if logo.ok {
logo.drawByHeight(c.doc, c.L, 55, 65)
} else {
c.drawSingleLine("UJ", c.L, 55, 48, "B", 28, primary, "L")
c.drawSingleLine("Uriel Jareth Consulting", c.L+48, 70, c.W-48, "", 9, colorMuted, "L")
}
barY := 130.0
if logo.ok {
barY = 145.0
}
c.rectFill(c.L, barY, c.W, 4, primary)
c.drawSingleLine("Cotización", c.L, barY+24, c.W, "B", 36, dark, "L")
c.drawSingleLine(data.Numero, c.L, barY+68, c.W, "", 18, primary, "L")
iy := barY + 110
cL := c.L
cR := c.L + c.W*0.52
colW := c.W * 0.46
type kv struct{ k, v string }
infoL := []kv{{"Cliente", data.ClienteNombre}}
if strings.TrimSpace(data.ClienteEmpresa) != "" {
infoL = append(infoL, kv{"Empresa", data.ClienteEmpresa})
}
infoL = append(infoL,
kv{"Proyecto", data.Proyecto},
kv{"Asesor", data.AsesorNombre},
)
infoR := []kv{
{"Fecha", domain.FormatDateLongMX(data.Fecha)},
{"Vigencia", domain.FormatDateLongMX(data.Vigencia)},
{"Moneda", data.Moneda},
{"Esquema", data.EsquemaPago},
}
maxRows := len(infoL)
if len(infoR) > maxRows {
maxRows = len(infoR)
}
for i := 0; i < maxRows; i++ {
hL, hR := 0.0, 0.0
if i < len(infoL) {
c.drawSingleLine(infoL[i].k, cL, iy, colW, "", 9, colorMuted, "L")
hL = c.drawText(infoL[i].v, cL, iy+12, colW, "", 11, dark, "L")
}
if i < len(infoR) {
c.drawSingleLine(infoR[i].k, cR, iy, colW, "", 9, colorMuted, "L")
hR = c.drawText(infoR[i].v, cR, iy+12, colW, "", 11, dark, "L")
}
step := hL
if hR > step {
step = hR
}
if step < 18 {
step = 18
}
iy += 14 + step
}
// ── PAGE 2+: HOJA RESUMEN ──────────────────────
c.doc.AddPage()
y := c.mTop
if logo.ok {
logo.drawRightAlignedByHeight(c.doc, c.L+c.W, c.mTop-5, 22)
}
c.rectFill(c.L, y, 4, 16, primary)
c.drawSingleLine("Hoja Resumen", c.L+12, y, c.W-90, "B", 15, dark, "L")
y += 26
enAtencion := data.ClienteEmpresa
if strings.TrimSpace(enAtencion) == "" {
enAtencion = data.ClienteNombre
}
c.drawSingleLine("En atención a: "+enAtencion, c.L, y, c.W*0.44, "", 8, colorMuted, "L")
c.drawSingleLine("No. Cotización: "+data.Numero, c.L+c.W*0.45, y, c.W*0.55, "", 8, colorMuted, "L")
y += 11
c.drawSingleLine("Asesor: "+data.AsesorNombre, c.L, y, c.W*0.44, "", 8, colorMuted, "L")
c.drawSingleLine(fmt.Sprintf("Fecha: %s | Moneda: %s", domain.FormatDateLongMX(data.Fecha), data.Moneda), c.L+c.W*0.45, y, c.W*0.55, "", 8, colorMuted, "L")
y += 16
colNombre := c.L
colTipo := c.L + c.W - 200
colTiempo := c.L + c.W - 120
colPrecio := c.L + c.W - 60
nombreW := colTipo - colNombre - 16
drawTableHeader := func() {
y = c.need(20, y)
c.rowBg(y, 16, colorLightBG)
c.drawSingleLine("Servicio", colNombre+6, y+4, nombreW, "B", 7, dark, "L")
c.drawSingleLine("Tipo", colTipo+4, y+4, 72, "B", 7, dark, "L")
c.drawSingleLine("Entrega", colTiempo+4, y+4, 56, "B", 7, dark, "L")
c.drawSingleLine("Precio", colPrecio, y+4, 60, "B", 7, dark, "R")
y += 18
}
var unicos, mensuales []ServicioPDF
for _, s := range data.Servicios {
if s.TipoPago == "mensual" {
mensuales = append(mensuales, s)
} else {
unicos = append(unicos, s)
}
}
drawSection := func(servicios []ServicioPDF, tipoLabel, tituloTotal string) {
if len(servicios) == 0 {
return
}
currentFase := -1
for _, serv := range servicios {
if serv.Fase != currentFase {
currentFase = serv.Fase
y = c.need(20, y)
c.rectFill(c.L, y, c.W, 14, colorLightBG)
faseLbl := domain.FasesShort[serv.Fase]
if faseLbl == "" {
faseLbl = fmt.Sprintf("FASE %d", serv.Fase)
}
c.drawSingleLine(faseLbl, c.L+6, y+3, c.W-12, "B", 7, primary, "L")
y += 16
}
detalle := domain.DetalleModelo(servicioPDFToCalc(serv))
hNombre := c.textHeight(serv.Nombre, nombreW, "", 8)
if hNombre < 11 {
hNombre = 11
}
hTiempo := c.textHeight(serv.TiempoEntrega, 56, "", 7)
rowTopH := hNombre
if hTiempo > rowTopH {
rowTopH = hTiempo
}
hDetalle := 0.0
if detalle != "" {
hDetalle = c.textHeight(detalle, nombreW-4, "I", 6.5) + 2
}
colW := c.W * 0.44
half := (len(serv.Entregables) + 1) / 2
entH := 0.0
for i := 0; i < half; i++ {
h1 := c.textHeight("• "+serv.Entregables[i], colW, "", 6.5)
h2 := 0.0
if i+half < len(serv.Entregables) {
h2 = c.textHeight("• "+serv.Entregables[i+half], colW, "", 6.5)
}
if h2 > h1 {
h1 = h2
}
entH += h1 + 1.5
}
totalServH := rowTopH + 2 + hDetalle + entH + 6
y = c.need(totalServH, y)
c.drawText(serv.Nombre, colNombre+6, y, nombreW, "", 8, dark, "L")
c.drawSingleLine(tipoLabel, colTipo+4, y, 72, "", 7, colorMuted, "L")
c.drawText(serv.TiempoEntrega, colTiempo+4, y, 56, "", 7, colorMuted, "L")
c.drawSingleLine(fmtMoney(serv.Precio), colPrecio, y, 60, "B", 8, dark, "R")
y += rowTopH + 2
if detalle != "" {
dh := c.drawText(detalle, colNombre+10, y, nombreW-4, "I", 6.5, colorMuted, "L")
y += dh + 2
}
if len(serv.Entregables) > 0 {
col1X := colNombre + 10
col2X := colNombre + c.W*0.48
for i := 0; i < half; i++ {
h1 := c.drawText("• "+serv.Entregables[i], col1X, y, colW, "", 6.5, colorMuted, "L")
h2 := 0.0
if i+half < len(serv.Entregables) {
h2 = c.drawText("• "+serv.Entregables[i+half], col2X, y, colW, "", 6.5, colorMuted, "L")
}
if h2 > h1 {
h1 = h2
}
y += h1 + 1.5
}
}
c.hLine(colNombre+6, c.L+c.W, y, colorSubtleSep, 0.2)
y += 4
}
y += 3
total := 0.0
for _, s := range servicios {
total += s.Precio
}
y = c.need(34, y)
c.rowBg(y, 18, "#f8fafc")
c.drawSingleLine(tituloTotal, colNombre+6, y+4, c.W-80, "B", 8.5, primary, "L")
c.drawSingleLine(fmtMoney(total), colPrecio-20, y+4, 80, "B", 8.5, primary, "R")
y += 22
c.drawSingleLine("(Precios en Moneda Nacional, no incluyen IVA)", colNombre+6, y, c.W-12, "", 6.5, colorMuted, "L")
y += 12
}
drawOpcionHeader := func(op string) {
meta := data.OpcionesMetadata[op]
y = c.need(30, y)
y += 4
c.rectFill(c.L, y, c.W, 18, primary)
title := "OPCIÓN " + op
if strings.TrimSpace(meta.Titulo) != "" {
title += ": " + meta.Titulo
}
c.drawSingleLine(title, c.L+8, y+3, c.W-16, "B", 10, colorWhite, "L")
y += 22
if strings.TrimSpace(meta.Descripcion) != "" {
h := c.textHeight(meta.Descripcion, c.W-12, "", 7.5)
y = c.need(h+4, y)
c.drawText(meta.Descripcion, c.L+6, y, c.W-12, "", 7.5, dark, "L")
y += h + 4
}
if strings.TrimSpace(meta.NoIncluye) != "" {
lbl := "No incluye: " + meta.NoIncluye
h := c.textHeight(lbl, c.W-12, "I", 7)
y = c.need(h+4, y)
c.drawText(lbl, c.L+6, y, c.W-12, "I", 7, colorMuted, "L")
y += h + 6
}
}
drawComparativa := func() {
calcs := serviciosPDFToCalc(data.Servicios)
t1 := domain.CalcularTotalesOpcion(calcs, "1")
t2 := domain.CalcularTotalesOpcion(calcs, "2")
y = c.need(90, y)
y += 6
c.rectFill(c.L, y+1, 3, 10, primary)
c.drawSingleLine("Comparativa de opciones", c.L+10, y, c.W-10, "B", 10, dark, "L")
y += 18
cLabel := c.L
cOp1 := c.L + c.W*0.45
cOp2 := c.L + c.W*0.72
wOp1 := c.W*0.27 - 4
wOp2 := c.W*0.28 - 4
t1Tit := data.OpcionesMetadata["1"].Titulo
t2Tit := data.OpcionesMetadata["2"].Titulo
op1Lbl := "Opción 1"
if t1Tit != "" {
op1Lbl += " - " + t1Tit
}
op2Lbl := "Opción 2"
if t2Tit != "" {
op2Lbl += " - " + t2Tit
}
c.rowBg(y, 16, colorLightBG)
c.drawSingleLine("Concepto", cLabel+6, y+4, c.W*0.43, "B", 7.5, dark, "L")
c.drawSingleLine(op1Lbl, cOp1, y+4, wOp1, "B", 7.5, dark, "L")
c.drawSingleLine(op2Lbl, cOp2, y+4, wOp2, "B", 7.5, dark, "L")
y += 18
ivaLbl := ""
if data.IncluirIVA {
ivaLbl = " (c/IVA)"
}
type compRow struct{ lab, v1, v2 string }
filas := []compRow{
{"Total único" + ivaLbl, fmtMoney(domain.ConIVA(t1.TotalUnico, data.IncluirIVA)), fmtMoney(domain.ConIVA(t2.TotalUnico, data.IncluirIVA))},
{"Total mensual" + ivaLbl, fmtMoney(domain.ConIVA(t1.TotalMensual, data.IncluirIVA)), fmtMoney(domain.ConIVA(t2.TotalMensual, data.IncluirIVA))},
{"Horas estimadas", fmt.Sprintf("%g h", t1.Horas), fmt.Sprintf("%g h", t2.Horas)},
}
for _, f := range filas {
y = c.need(14, y)
c.drawSingleLine(f.lab, cLabel+6, y, c.W*0.43, "", 8, dark, "L")
c.drawSingleLine(f.v1, cOp1, y, wOp1, "B", 8, dark, "L")
c.drawSingleLine(f.v2, cOp2, y, wOp2, "B", 8, dark, "L")
c.hLine(cLabel+6, c.L+c.W, y+12, colorSubtleSep, 0.2)
y += 14
}
y += 8
}
filterByOp := func(list []ServicioPDF, op string) []ServicioPDF {
var out []ServicioPDF
for _, s := range list {
if s.Opcion != nil && (*s.Opcion == op || *s.Opcion == "ambas") {
out = append(out, s)
}
}
return out
}
if data.EsDoble {
for _, op := range []string{"1", "2"} {
drawOpcionHeader(op)
drawTableHeader()
u := filterByOp(unicos, op)
me := filterByOp(mensuales, op)
if len(u) > 0 {
drawSection(u, "Único", fmt.Sprintf("Total Pago Único - Opción %s", op))
}
if len(me) > 0 {
drawSection(me, "Mensual", fmt.Sprintf("Total Pago Mensual - Opción %s", op))
}
}
drawComparativa()
} else {
drawTableHeader()
if len(unicos) > 0 {
drawSection(unicos, "Único", "Total Pago Único")
}
if len(mensuales) > 0 {
drawSection(mensuales, "Mensual", "Total Pago Mensual")
}
}
if data.PlanBucefaloNivel != nil && strings.TrimSpace(*data.PlanBucefaloNivel) != "" {
y = c.need(20, y)
nivel := strings.TrimSpace(*data.PlanBucefaloNivel)
precio := data.PlanBucefaloPrecio
if precio <= 0 {
precio = domain.BucefaloPrecio(strings.ToLower(nivel))
}
c.rowBg(y, 16, colorLightBG)
c.drawSingleLine("Plan Bucéfalo CRM - "+capitalize(nivel), colNombre+6, y+3, c.W-80, "B", 7.5, dark, "L")
c.drawSingleLine(fmtMoney(precio), colPrecio-20, y+3, 80, "B", 7.5, dark, "R")
y += 20
}
if data.IncluirBonos {
y = c.need(90, y)
y += 4
c.rectFill(c.L, y+1, 3, 10, primary)
c.drawSingleLine("Bonos (Pago en una exhibición)", c.L+10, y, c.W-10, "B", 9, dark, "L")
y += 16
respaldo := []string{
"Bono 1: 30 min mensuales en servicios Centinela (Sitio Web)",
"Bono 2: Workshop Estratégico de Buyer Persona",
"Bono 3: Workshop de Propuestas de Valor y Oferta Irresistible",
"Bono 4: 1 año de Membresía Premium",
"Bono 5: Un mes gratis de Bucéfalo CRM, Marketing y Ventas",
"Bono 6: Script de Ventas con más de 100 complementos",
}
var bonos []string
if len(data.Bonos) > 0 {
for _, b := range data.Bonos {
bonos = append(bonos, fmt.Sprintf("Bono %d: %s", b.Numero, b.Descripcion))
}
} else {
bonos = respaldo
}
for _, b := range bonos {
txt := "• " + b
h := c.textHeight(txt, c.W-16, "", 7.5)
y = c.need(h+3, y)
c.drawText(txt, c.L+8, y, c.W-16, "", 7.5, dark, "L")
y += h + 3
}
}
// ── OBSERVACIONES (solo cliente) ───────────────
if data.Observaciones != nil && strings.TrimSpace(*data.Observaciones) != "" {
y += 6
y = sectionTitle("Observaciones", y)
raw := strings.ReplaceAll(*data.Observaciones, "\r\n", "\n")
for _, p := range strings.Split(raw, "\n") {
p = strings.TrimSpace(p)
if p == "" {
continue
}
lines := c.splitLines(p, c.W-4, "", 7.5)
lh := lineHeight(7.5)
for _, ln := range lines {
y = c.need(lh+2, y)
c.drawSingleLine(ln, c.L+2, y, c.W-4, "", 7.5, dark, "L")
y += lh
}
y += 4
}
y += 4
}
// ── T&C PAGE ───────────────────────────────────
c.doc.AddPage()
y = c.mTop
if logo.ok {
logo.drawRightAlignedByHeight(c.doc, c.L+c.W, c.mTop-5, 22)
}
c.rectFill(c.L, y, 4, 16, primary)
c.drawSingleLine("Términos y Condiciones", c.L+12, y, c.W-90, "B", 15, dark, "L")
y += 28
drawBullets := func(title string, items []string, yStart float64) float64 {
yy := sectionTitle(title, yStart)
for _, item := range items {
txt := "• " + item
h := c.textHeight(txt, c.W-4, "", 7.5)
yy = c.need(h+4, yy)
c.drawText(txt, c.L+2, yy, c.W-4, "", 7.5, dark, "L")
yy += h + 4
}
return yy + 6
}
y = drawBullets("Condiciones", []string{
"Esta cotización tiene una vigencia de 15 días hábiles.",
"Cualquier ajuste al proyecto después de la aprobación del contenido afectará la fecha de entrega y por consiguiente el costo.",
"El cliente deberá proporcionar la información solicitada por Uriel Jareth Consulting en tiempo y forma.",
"Si la falta de información provoca un excedente en los plazos de entrega del proyecto, las horas adicionales de servicio se cotizarán por separado.",
"Los pagos correspondientes a los servicios mensuales deberán realizarse en los primeros 5 días del mes.",
"Todo el material e información necesarios para la realización del sitio web deberán ser entregados en un plazo máximo de 40 días naturales a partir del arranque del proyecto.",
}, y)
y = drawBullets("¿Qué no incluye el proyecto?", []string{
"Generación de diseños, videos, traducciones, cambios de divisas y unidades, o cualquier servicio externo a lo cotizado.",
"Redacción de entradas de Blog.",
"Integración de Servicios de terceros ajenos a los cotizados.",
"Servicio de Recuperación de Accesos de: Google Analytics, Google Tag Manager, Google Search Console, Google Ads, y Meta Ads.",
"Creación de Redes Sociales (En caso de requerir el servicio incluirá un costo adicional).",
}, y)
y = drawBullets("Notas", []string{
"El presente proyecto deberá tener un responsable oficial.",
"La Hora Centinela tiene un precio de $700.00 MXN.",
"Los archivos editables/fuente (AI, PSD) son propiedad intelectual de la agencia. Si requiere los archivos editables, estos pueden ser adquiridos abonando una tarifa de liberación (buy-out fee).",
"Si el proyecto se pausa por razones ajenas a Uriel Jareth Consulting, esto generará costo extra del 15% al 30% para retomar el proyecto.",
}, y)
y += 6
y = c.need(120, y)
y = sectionTitle("Datos Bancarios", y)
bank := extractBankInfo(data.ConfigBancaria)
boxH := 48.0
c.rectFillStroke(c.L, y, c.W, boxH, colorLightBG, colorBorder, 0.5)
c.drawSingleLine("Transferencia Nacional", c.L+8, y+4, c.W-16, "B", 7, dark, "L")
if bank.CuentaNacional != "" {
c.drawSingleLine("Cuenta: "+bank.CuentaNacional, c.L+8, y+15, c.W*0.43, "", 6.5, dark, "L")
}
if bank.ClabeNacional != "" {
c.drawSingleLine("CLABE: "+bank.ClabeNacional, c.L+c.W*0.45, y+15, c.W*0.53, "", 6.5, dark, "L")
}
c.drawSingleLine("Razón Social: "+bank.RazonSocial, c.L+8, y+26, c.W*0.43, "", 6.5, dark, "L")
c.drawSingleLine("RFC: "+bank.RFC, c.L+c.W*0.45, y+26, c.W*0.53, "", 6.5, dark, "L")
if bank.BancoNacional != "" {
c.drawSingleLine("Banco: "+bank.BancoNacional, c.L+8, y+37, c.W*0.43, "", 6.5, dark, "L")
}
y += boxH + 6
y = c.need(boxH+6, y)
c.rectFillStroke(c.L, y, c.W, boxH, colorLightBG, colorBorder, 0.5)
c.drawSingleLine("Transferencia Internacional", c.L+8, y+4, c.W-16, "B", 7, dark, "L")
c.drawSingleLine("Beneficiario: "+bank.RazonSocial, c.L+8, y+15, c.W*0.43, "", 6.5, dark, "L")
if bank.ClabeInternacional != "" {
c.drawSingleLine("CLABE: "+bank.ClabeInternacional, c.L+c.W*0.45, y+15, c.W*0.53, "", 6.5, dark, "L")
}
c.drawSingleLine("Banco: BBVA México", c.L+8, y+26, c.W*0.43, "", 6.5, dark, "L")
c.drawSingleLine("SWIFT: "+bank.Swift, c.L+c.W*0.45, y+26, c.W*0.53, "", 6.5, dark, "L")
return c.bytes()
}
+429
View File
@@ -0,0 +1,429 @@
package pdf
import (
"bytes"
"encoding/base64"
"fmt"
"image"
"image/jpeg"
"image/png"
"regexp"
"strconv"
"strings"
"unicode"
"codeberg.org/go-pdf/fpdf"
"golang.org/x/image/font/gofont/gobold"
"golang.org/x/image/font/gofont/gobolditalic"
"golang.org/x/image/font/gofont/goitalic"
"golang.org/x/image/font/gofont/goregular"
"golang.org/x/image/webp"
"cotizador/internal/domain"
)
const (
fontFamily = "Go"
defaultPrimary = "#0400C4"
defaultDark = "#0F172A"
colorMuted = "#64748b"
colorBorder = "#cbd5e1"
colorLightBG = "#f1f5f9"
colorWhite = "#ffffff"
colorSubtleSep = "#e5e7eb"
)
var (
hexColorRe = regexp.MustCompile(`^#[0-9a-fA-F]{6}$`)
swiftRe = regexp.MustCompile(`(?i)SWIFT[^:]*:\s*(\S+)`)
clabeRe = regexp.MustCompile(`(?i)CLABE[^:]*:\s*(\S+)`)
)
func safeHex(v, fallback string) string {
v = strings.TrimSpace(v)
if hexColorRe.MatchString(v) {
return v
}
return fallback
}
func parseHexRGB(hexStr, fallback string) (int, int, int) {
h := strings.TrimPrefix(safeHex(hexStr, fallback), "#")
r, _ := strconv.ParseInt(h[0:2], 16, 64)
g, _ := strconv.ParseInt(h[2:4], 16, 64)
b, _ := strconv.ParseInt(h[4:6], 16, 64)
return int(r), int(g), int(b)
}
func capitalize(s string) string {
s = strings.TrimSpace(s)
if s == "" {
return ""
}
r := []rune(s)
r[0] = unicode.ToUpper(r[0])
return string(r)
}
func formatMoney(amount float64, moneda string) string {
if moneda == "" || strings.EqualFold(moneda, "MXN") {
return domain.FormatCurrency(amount)
}
return domain.FormatMonto(amount, moneda)
}
type bankInfo struct {
RazonSocial string
RFC string
CuentaNacional string
ClabeNacional string
BancoNacional string
ClabeInternacional string
Swift string
}
func extractBankInfo(cfg map[string]string) bankInfo {
if cfg == nil {
cfg = map[string]string{}
}
razon := strings.TrimSpace(cfg["razon_social"])
if razon == "" {
razon = "URIEL JARETH ALVARADO ORTIZ"
}
rfc := strings.TrimSpace(cfg["rfc"])
if rfc == "" {
rfc = "AAOU970201SU7"
}
cuentaNac := strings.TrimSpace(cfg["cuenta_nacional"])
clabeNac := strings.TrimSpace(cfg["clabe_interbancaria"])
if clabeNac == "" {
clabeNac = cuentaNac
}
bancoNac := ""
if cuentaNac != "" {
bancoNac = "BBVA"
}
swift := "BCMRMXMMPYM"
clabeInt := ""
if intl := cfg["cuenta_internacional_swift"]; intl != "" {
if m := swiftRe.FindStringSubmatch(intl); len(m) > 1 {
swift = m[1]
}
if m := clabeRe.FindStringSubmatch(intl); len(m) > 1 {
clabeInt = m[1]
}
}
return bankInfo{
RazonSocial: razon,
RFC: rfc,
CuentaNacional: cuentaNac,
ClabeNacional: clabeNac,
BancoNacional: bancoNac,
ClabeInternacional: clabeInt,
Swift: swift,
}
}
type logoAsset struct {
name string
w float64
h float64
ok bool
}
// prepareLogoBytes decodes base64 and normalizes PNG/JPEG/WebP into a format fpdf safely accepts.
// WebP (and non-standard PNGs) are decoded and re-encoded as standard 8-bit PNG.
func prepareLogoBytes(b64, mime string) ([]byte, string, error) {
b64 = strings.TrimSpace(b64)
if b64 == "" {
return nil, "", fmt.Errorf("empty logo")
}
// Strip optional data URI prefix.
if idx := strings.Index(b64, ","); idx != -1 && strings.HasPrefix(b64[:idx], "data:") {
if mime == "" {
header := b64[len("data:"):idx]
if semi := strings.Index(header, ";"); semi != -1 {
mime = header[:semi]
}
}
b64 = b64[idx+1:]
}
raw, err := base64.StdEncoding.DecodeString(b64)
if err != nil {
raw, err = base64.RawStdEncoding.DecodeString(b64)
if err != nil {
return nil, "", err
}
}
if len(raw) < 8 {
return nil, "", fmt.Errorf("logo too short")
}
m := strings.ToLower(strings.TrimSpace(mime))
isWebP := m == "image/webp" || (len(raw) >= 12 && string(raw[0:4]) == "RIFF" && string(raw[8:12]) == "WEBP")
if isWebP {
img, err := webp.Decode(bytes.NewReader(raw))
if err != nil {
return nil, "", err
}
var out bytes.Buffer
if err := png.Encode(&out, img); err != nil {
return nil, "", err
}
return out.Bytes(), "PNG", nil
}
isJPEG := m == "image/jpeg" || m == "image/jpg" || (raw[0] == 0xFF && raw[1] == 0xD8)
if isJPEG {
if _, err := jpeg.DecodeConfig(bytes.NewReader(raw)); err != nil {
return nil, "", err
}
return raw, "JPG", nil
}
isPNG := m == "image/png" || bytes.Equal(raw[0:8], []byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'})
if isPNG {
// Re-encode through image/png so interlaced or 16-bit PNGs always work with fpdf.
img, err := png.Decode(bytes.NewReader(raw))
if err != nil {
return nil, "", err
}
var out bytes.Buffer
if err := png.Encode(&out, img); err != nil {
return nil, "", err
}
return out.Bytes(), "PNG", nil
}
// Fallback: try generic image decode -> PNG.
img, _, err := image.Decode(bytes.NewReader(raw))
if err != nil {
return nil, "", err
}
var out bytes.Buffer
if err := png.Encode(&out, img); err != nil {
return nil, "", err
}
return out.Bytes(), "PNG", nil
}
func registerLogo(doc *fpdf.Fpdf, name, b64, mime string) logoAsset {
imgBytes, imgType, err := prepareLogoBytes(b64, mime)
if err != nil {
return logoAsset{}
}
opts := fpdf.ImageOptions{ImageType: imgType, ReadDpi: false}
info := doc.RegisterImageOptionsReader(name, opts, bytes.NewReader(imgBytes))
if info == nil || !doc.Ok() {
doc.ClearError()
return logoAsset{}
}
return logoAsset{
name: name,
w: info.Width(),
h: info.Height(),
ok: info.Width() > 0 && info.Height() > 0,
}
}
func (l logoAsset) drawByHeight(doc *fpdf.Fpdf, x, y, targetH float64) {
if !l.ok {
return
}
doc.ImageOptions(l.name, x, y, 0, targetH, false, fpdf.ImageOptions{}, 0, "")
}
func (l logoAsset) drawRightAlignedByHeight(doc *fpdf.Fpdf, rightX, y, targetH float64) {
if !l.ok {
return
}
w := targetH * (l.w / l.h)
if w > 90 {
w = 90
targetH = w * (l.h / l.w)
}
doc.ImageOptions(l.name, rightX-w, y, w, targetH, false, fpdf.ImageOptions{}, 0, "")
}
func (l logoAsset) drawFit(doc *fpdf.Fpdf, x, y, maxW, maxH float64) (float64, float64) {
if !l.ok {
return 0, 0
}
scale := maxW / l.w
if sh := maxH / l.h; sh < scale {
scale = sh
}
w := l.w * scale
h := l.h * scale
doc.ImageOptions(l.name, x, y, w, h, false, fpdf.ImageOptions{}, 0, "")
return w, h
}
type canvas struct {
doc *fpdf.Fpdf
pw float64
ph float64
mTop float64
mBottom float64
mLeft float64
mRight float64
W float64
L float64
maxY float64
}
func newCanvas(top, bottom, left, right float64) *canvas {
doc := fpdf.New("P", "pt", "Letter", "")
doc.AddUTF8FontFromBytes(fontFamily, "", goregular.TTF)
doc.AddUTF8FontFromBytes(fontFamily, "B", gobold.TTF)
doc.AddUTF8FontFromBytes(fontFamily, "I", goitalic.TTF)
doc.AddUTF8FontFromBytes(fontFamily, "BI", gobolditalic.TTF)
doc.SetMargins(left, top, right)
doc.SetAutoPageBreak(false, 0)
doc.SetCellMargin(0)
doc.SetFont(fontFamily, "", 10)
pw, ph := doc.GetPageSize()
return &canvas{
doc: doc,
pw: pw,
ph: ph,
mTop: top,
mBottom: bottom,
mLeft: left,
mRight: right,
W: pw - left - right,
L: left,
maxY: ph - bottom - 5,
}
}
func (c *canvas) need(h, y float64) float64 {
if y+h > c.maxY {
c.doc.AddPage()
return c.mTop
}
return y
}
func (c *canvas) setFont(style string, size float64) {
c.doc.SetFont(fontFamily, style, size)
}
func (c *canvas) setTextColor(hex string) {
r, g, b := parseHexRGB(hex, defaultDark)
c.doc.SetTextColor(r, g, b)
}
func (c *canvas) setFillColor(hex string) {
r, g, b := parseHexRGB(hex, colorWhite)
c.doc.SetFillColor(r, g, b)
}
func (c *canvas) setDrawColor(hex string) {
r, g, b := parseHexRGB(hex, colorBorder)
c.doc.SetDrawColor(r, g, b)
}
func lineHeight(size float64) float64 {
return size * 1.25
}
func (c *canvas) splitLines(txt string, width float64, style string, size float64) []string {
c.setFont(style, size)
if width <= 1 {
return []string{txt}
}
rawLines := strings.Split(strings.ReplaceAll(txt, "\r\n", "\n"), "\n")
var out []string
for _, rl := range rawLines {
if rl == "" {
out = append(out, "")
continue
}
parts := c.doc.SplitText(rl, width)
if len(parts) == 0 {
out = append(out, rl)
} else {
out = append(out, parts...)
}
}
if len(out) == 0 {
return []string{""}
}
return out
}
func (c *canvas) textHeight(txt string, width float64, style string, size float64) float64 {
lines := c.splitLines(txt, width, style, size)
return float64(len(lines)) * lineHeight(size)
}
// drawText writes multi-line wrapped text starting at (x, y) and returns total height drawn.
func (c *canvas) drawText(txt string, x, y, width float64, style string, size float64, color, align string) float64 {
if align == "" {
align = "L"
}
lines := c.splitLines(txt, width, style, size)
lh := lineHeight(size)
c.setFont(style, size)
c.setTextColor(color)
curY := y
for _, ln := range lines {
c.doc.SetXY(x, curY)
c.doc.CellFormat(width, lh, ln, "", 0, align, false, 0, "")
curY += lh
}
return float64(len(lines)) * lh
}
// drawSingleLine writes text on one line without wrapping.
func (c *canvas) drawSingleLine(txt string, x, y, width float64, style string, size float64, color, align string) {
if align == "" {
align = "L"
}
c.setFont(style, size)
c.setTextColor(color)
c.doc.SetXY(x, y)
if width <= 0 {
width = c.doc.GetStringWidth(txt) + 2
}
c.doc.CellFormat(width, lineHeight(size), txt, "", 0, align, false, 0, "")
}
func (c *canvas) rectFill(x, y, w, h float64, fillHex string) {
c.setFillColor(fillHex)
c.doc.Rect(x, y, w, h, "F")
}
func (c *canvas) rectFillStroke(x, y, w, h float64, fillHex, strokeHex string, lw float64) {
c.setFillColor(fillHex)
c.setDrawColor(strokeHex)
c.doc.SetLineWidth(lw)
c.doc.Rect(x, y, w, h, "DF")
}
func (c *canvas) hLine(x1, x2, y float64, strokeHex string, lw float64) {
c.setDrawColor(strokeHex)
c.doc.SetLineWidth(lw)
c.doc.Line(x1, y, x2, y)
}
func (c *canvas) circleFill(cx, cy, r float64, fillHex string) {
c.setFillColor(fillHex)
c.doc.Circle(cx, cy, r, "F")
}
func (c *canvas) rowBg(y, h float64, bgHex string) {
c.rectFill(c.L, y, c.W, h, bgHex)
c.hLine(c.L, c.L+c.W, y+h, colorBorder, 0.3)
}
func (c *canvas) bytes() ([]byte, error) {
var buf bytes.Buffer
if err := c.doc.Output(&buf); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
+394
View File
@@ -0,0 +1,394 @@
package pdf
import (
"fmt"
"sort"
"strings"
"time"
"cotizador/internal/domain"
)
type RegistroHoraPDF struct {
Fecha time.Time
HoraInicio string
HoraFin string
Horas float64
TarifaHora float64
Descripcion string
EstadoPago string
}
type NotaHorasPDFData struct {
Titulo string
Numero string
ClienteNombre string
ClienteEmpresa string
Proyecto string
AsesorNombre string
Moneda string
IncluirIVA bool
Modo string
MostrarEstado bool
MostrarBancarios bool
Registros []RegistroHoraPDF
ConfigBancaria map[string]string
ColorPrimario string
ColorSecundario string
LogoBase64 string
LogoMime string
FechaEmision time.Time
}
type notaHorasGrupo struct {
Clave string
Etiqueta string
Count int
Horas float64
Importe float64
}
func modoAgrupacionLabel(modo string) string {
switch modo {
case "dia":
return "Por día"
case "semana":
return "Por semana"
case "mes":
return "Por mes"
default:
return "Detalle"
}
}
func etiquetaTotalNota(titulo string) string {
low := strings.ToLower(titulo)
switch {
case strings.Contains(low, "pagadas"):
return "Total pagado"
case strings.Contains(low, "por pagar"):
return "Total a pagar"
default:
return "Total"
}
}
func GenerateNotaHorasPDF(data NotaHorasPDFData) ([]byte, error) {
primary := safeHex(data.ColorPrimario, defaultPrimary)
dark := safeHex(data.ColorSecundario, defaultDark)
muted := "#6b7280"
border := "#d1d5db"
headBG := "#f3f4f6"
titulo := strings.TrimSpace(data.Titulo)
if titulo == "" {
titulo = "Nota de horas por pagar"
}
modo := strings.ToLower(strings.TrimSpace(data.Modo))
if modo != "detalle" && modo != "dia" && modo != "semana" && modo != "mes" {
modo = "detalle"
}
modoLabel := modoAgrupacionLabel(modo)
emitida := data.FechaEmision
if emitida.IsZero() {
emitida = time.Now()
}
// Copy and sort records chronologically.
regs := make([]RegistroHoraPDF, len(data.Registros))
copy(regs, data.Registros)
sort.Slice(regs, func(i, j int) bool {
if regs[i].Fecha.Equal(regs[j].Fecha) {
return regs[i].HoraInicio < regs[j].HoraInicio
}
return regs[i].Fecha.Before(regs[j].Fecha)
})
// Totals.
var totalHoras, subtotal float64
for _, r := range regs {
totalHoras += r.Horas
subtotal += r.Horas * r.TarifaHora
}
totalHoras = domain.Round2(totalHoras)
subtotal = domain.Round2(subtotal)
iva := 0.0
if data.IncluirIVA {
iva = domain.Round2(subtotal * domain.IVARate)
}
total := domain.Round2(subtotal + iva)
// Periodo text.
periodoTexto := "Periodo: todos los registros"
if len(regs) > 0 {
minF := domain.FormatFechaRegistro(regs[0].Fecha)
maxF := domain.FormatFechaRegistro(regs[len(regs)-1].Fecha)
if minF == maxF {
periodoTexto = "Periodo: " + minF
} else {
periodoTexto = fmt.Sprintf("Periodo: %s al %s", minF, maxF)
}
}
// Grouping if not detalle.
var grupos []notaHorasGrupo
if modo != "detalle" {
m := make(map[string]*notaHorasGrupo)
for _, r := range regs {
per := domain.PeriodoAgrupacionDe(r.Fecha, modo)
g, ok := m[per.Clave]
if !ok {
g = &notaHorasGrupo{Clave: per.Clave, Etiqueta: per.Etiqueta}
m[per.Clave] = g
}
g.Count++
g.Horas += r.Horas
g.Importe += r.Horas * r.TarifaHora
}
for _, g := range m {
g.Horas = domain.Round2(g.Horas)
g.Importe = domain.Round2(g.Importe)
grupos = append(grupos, *g)
}
sort.Slice(grupos, func(i, j int) bool {
return grupos[i].Clave < grupos[j].Clave
})
}
fmtMoney := func(n float64) string {
return formatMoney(n, data.Moneda)
}
c := newCanvas(45, 55, 50, 50)
c.maxY = c.ph - c.mBottom
logo := registerLogo(c.doc, "nota_logo", data.LogoBase64, data.LogoMime)
c.doc.AddPage()
y := c.mTop
// ── ENCABEZADO ────────────────────────────────
logoBottom := y
if logo.ok {
_, lh := logo.drawFit(c.doc, c.L, y, 46, 46)
logoBottom = y + lh
}
txtX := c.L
if logo.ok {
txtX = c.L + 58
}
titleW := c.W - 170
if logo.ok {
titleW = c.W - 58 - 115
}
hTit := c.drawText(titulo, txtX, y+2, titleW, "B", 18, dark, "L")
sub := fmt.Sprintf("Cotización %s · %s", data.Numero, data.Proyecto)
hSub := c.drawText(sub, txtX, y+2+hTit+1, titleW, "", 9, muted, "L")
c.drawSingleLine("Emitida: "+domain.FormatFechaRegistro(emitida), c.L, y+2, c.W, "", 9, muted, "R")
yTextEnd := y + 2 + hTit + 1 + hSub + 6
y = y + 50
if logoBottom+6 > y {
y = logoBottom + 6
}
if yTextEnd > y {
y = yTextEnd
}
c.hLine(c.L, c.L+c.W, y, primary, 2.5)
y += 14
// ── META ──────────────────────────────────────
cliente := data.ClienteEmpresa
if strings.TrimSpace(cliente) == "" {
cliente = data.ClienteNombre
}
drawMetaLine := func(label, val string) {
c.setFont("B", 9.5)
lw := c.doc.GetStringWidth(label) + 2
c.drawSingleLine(label, c.L, y, lw, "B", 9.5, dark, "L")
h := c.drawText(val, c.L+lw, y, c.W-lw, "", 9.5, dark, "L")
y += h + 2
}
drawMetaLine("Cliente: ", cliente)
if strings.TrimSpace(data.ClienteEmpresa) != "" && strings.TrimSpace(data.ClienteNombre) != "" {
drawMetaLine("Contacto: ", data.ClienteNombre)
}
if strings.TrimSpace(data.AsesorNombre) != "" {
drawMetaLine("Asesor: ", data.AsesorNombre)
}
hPer := c.drawText(fmt.Sprintf("%s · Desglose %s", periodoTexto, strings.ToLower(modoLabel)), c.L, y, c.W, "", 8.5, muted, "L")
y += hPer + 12
// ── TABLA ─────────────────────────────────────
if modo == "detalle" {
wEstado := 0.0
if data.MostrarEstado {
wEstado = 58.0
}
cFecha := c.L
wFecha, wHorario, wHoras, wTarifa, wImporte := 62.0, 72.0, 42.0, 52.0, 58.0
cHorario := cFecha + wFecha
cHoras := cHorario + wHorario
cTarifa := cHoras + wHoras
cImporte := cTarifa + wTarifa
cDesc := cImporte + wImporte + 6
estadoPad := 0.0
if wEstado > 0 {
estadoPad = 6.0
}
wDesc := c.L + c.W - cDesc - wEstado - estadoPad
cEstado := c.L + c.W - wEstado
drawHeader := func(yy float64) float64 {
c.rectFill(c.L, yy, c.W, 16, headBG)
c.drawSingleLine("FECHA", cFecha+4, yy+4, wFecha-4, "B", 7, dark, "L")
c.drawSingleLine("HORARIO", cHorario+4, yy+4, wHorario-4, "B", 7, dark, "L")
c.drawSingleLine("HORAS", cHoras, yy+4, wHoras-2, "B", 7, dark, "R")
c.drawSingleLine("TARIFA", cTarifa, yy+4, wTarifa-2, "B", 7, dark, "R")
c.drawSingleLine("IMPORTE", cImporte, yy+4, wImporte-2, "B", 7, dark, "R")
c.drawSingleLine("DESCRIPCIÓN", cDesc, yy+4, wDesc, "B", 7, dark, "L")
if wEstado > 0 {
c.drawSingleLine("ESTADO", cEstado, yy+4, wEstado, "B", 7, dark, "L")
}
return yy + 16
}
y = drawHeader(y)
for _, r := range regs {
descH := c.textHeight(r.Descripcion, wDesc, "", 8)
rowH := descH + 8
if rowH < 16 {
rowH = 16
}
if y+rowH > c.maxY {
y = drawHeader(c.need(rowH+16, y))
}
c.drawSingleLine(domain.FormatFechaRegistro(r.Fecha), cFecha+4, y+4, wFecha-4, "", 8, dark, "L")
c.drawSingleLine(fmt.Sprintf("%s-%s", r.HoraInicio, r.HoraFin), cHorario+4, y+4, wHorario-4, "", 8, dark, "L")
c.drawSingleLine(fmt.Sprintf("%.2f", r.Horas), cHoras, y+4, wHoras-2, "", 8, dark, "R")
c.drawSingleLine(fmtMoney(r.TarifaHora), cTarifa, y+4, wTarifa-2, "", 8, dark, "R")
c.drawSingleLine(fmtMoney(r.Horas*r.TarifaHora), cImporte, y+4, wImporte-2, "", 8, dark, "R")
c.drawText(r.Descripcion, cDesc, y+4, wDesc, "", 8, dark, "L")
if wEstado > 0 {
est := "Por pagar"
if domain.EsPagada(r.EstadoPago) {
est = "Pagada"
}
c.drawSingleLine(est, cEstado, y+4, wEstado, "", 8, dark, "L")
}
c.hLine(c.L, c.L+c.W, y+rowH, border, 0.3)
y += rowH
}
} else {
wReg, wHor, wImp := 90.0, 90.0, 90.0
cPer := c.L
wPer := c.W - wReg - wHor - wImp
cReg := cPer + wPer
cHor := cReg + wReg
cImp := cHor + wHor
drawHeader := func(yy float64) float64 {
c.rectFill(c.L, yy, c.W, 16, headBG)
c.drawSingleLine(strings.ToUpper(modoLabel), cPer+4, yy+4, wPer-6, "B", 7, dark, "L")
c.drawSingleLine("REGISTROS", cReg, yy+4, wReg-2, "B", 7, dark, "R")
c.drawSingleLine("HORAS", cHor, yy+4, wHor-2, "B", 7, dark, "R")
c.drawSingleLine("IMPORTE", cImp, yy+4, wImp-2, "B", 7, dark, "R")
return yy + 16
}
y = drawHeader(y)
for _, g := range grupos {
rowH := 16.0
if y+rowH > c.maxY {
y = drawHeader(c.need(rowH+16, y))
}
c.drawSingleLine(g.Etiqueta, cPer+4, y+4, wPer-6, "", 8, dark, "L")
c.drawSingleLine(fmt.Sprintf("%d", g.Count), cReg, y+4, wReg-2, "", 8, dark, "R")
c.drawSingleLine(fmt.Sprintf("%.2f", g.Horas), cHor, y+4, wHor-2, "", 8, dark, "R")
c.drawSingleLine(fmtMoney(g.Importe), cImp, y+4, wImp-2, "", 8, dark, "R")
c.hLine(c.L, c.L+c.W, y+rowH, border, 0.3)
y += rowH
}
}
// ── TOTALES ───────────────────────────────────
y += 12
totW := 240.0
totX := c.L + c.W - totW
drawTotalLine := func(label, val string, bold, topLine bool) {
y = c.need(20, y)
if topLine {
c.hLine(totX, totX+totW, y, primary, 1.2)
y += 5
}
style := ""
size := 9.0
lblColor := muted
step := 15.0
if bold {
style = "B"
size = 12.0
lblColor = dark
step = 18.0
}
c.drawSingleLine(label, totX, y, totW-95, style, size, lblColor, "L")
c.drawSingleLine(val, totX+totW-95, y, 95, style, size, dark, "R")
y += step
}
drawTotalLine("Total de horas", fmt.Sprintf("%.2f h", totalHoras), false, false)
drawTotalLine("Subtotal", fmtMoney(subtotal), false, false)
if data.IncluirIVA {
drawTotalLine("IVA (16%)", fmtMoney(iva), false, false)
}
drawTotalLine(etiquetaTotalNota(titulo), fmtMoney(total), true, true)
// ── DATOS PARA EL PAGO ────────────────────────
if data.MostrarBancarios {
dp := extractBankInfo(data.ConfigBancaria)
boxH := 52.0
y = c.need(boxH+34, y) + 16
c.rectFill(c.L, y+1, 3, 10, primary)
c.drawSingleLine("Datos para el pago", c.L+10, y, c.W-10, "B", 10, dark, "L")
y += 16
c.rectFillStroke(c.L, y, c.W, boxH, headBG, border, 0.5)
c.drawSingleLine("Transferencia Nacional", c.L+8, y+5, c.W-16, "B", 8, dark, "L")
if dp.CuentaNacional != "" {
c.drawSingleLine("Cuenta: "+dp.CuentaNacional, c.L+8, y+18, c.W*0.48, "", 8.5, dark, "L")
}
if dp.ClabeNacional != "" {
c.drawSingleLine("CLABE: "+dp.ClabeNacional, c.L+c.W*0.5, y+18, c.W*0.48, "", 8.5, dark, "L")
}
c.drawSingleLine("Beneficiario: "+dp.RazonSocial, c.L+8, y+30, c.W*0.48, "", 8.5, dark, "L")
c.drawSingleLine("RFC: "+dp.RFC, c.L+c.W*0.5, y+30, c.W*0.48, "", 8.5, dark, "L")
if dp.BancoNacional != "" {
c.drawSingleLine("Banco: "+dp.BancoNacional, c.L+8, y+42, c.W*0.48, "", 8.5, dark, "L")
}
y += boxH + 8
if dp.ClabeInternacional != "" || dp.Swift != "" {
y = c.need(boxH, y)
c.rectFillStroke(c.L, y, c.W, boxH, headBG, border, 0.5)
c.drawSingleLine("Transferencia Internacional", c.L+8, y+5, c.W-16, "B", 8, dark, "L")
c.drawSingleLine("Beneficiario: "+dp.RazonSocial, c.L+8, y+18, c.W*0.48, "", 8.5, dark, "L")
if dp.ClabeInternacional != "" {
c.drawSingleLine("CLABE: "+dp.ClabeInternacional, c.L+c.W*0.5, y+18, c.W*0.48, "", 8.5, dark, "L")
}
c.drawSingleLine("Banco: BBVA México", c.L+8, y+30, c.W*0.48, "", 8.5, dark, "L")
if dp.Swift != "" {
c.drawSingleLine("SWIFT: "+dp.Swift, c.L+c.W*0.5, y+30, c.W*0.48, "", 8.5, dark, "L")
}
y += boxH + 8
}
}
// ── PIE ───────────────────────────────────────
y = c.need(30, y) + 14
c.drawText(
"Documento generado desde el Cotizador. Conteo de horas trabajadas para cobro del proyecto.",
c.L, y, c.W, "", 8, muted, "C",
)
return c.bytes()
}
+454
View File
@@ -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)
}
}
}
+739
View File
@@ -0,0 +1,739 @@
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()
}