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 | contacto@urieljareth.com | (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() }