package excel import ( "fmt" "math" "regexp" "strconv" "strings" "time" "unicode" "unicode/utf8" "github.com/xuri/excelize/v2" "cotizador/internal/domain" ) type ServicioExcel 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 } // CotizacionExcelData holds client-facing quotation data for Excel export. // ObservacionesInternas is intentionally NOT declared here so internal notes // can never leak into a client workbook. type CotizacionExcelData struct { RazonSocial string DomicilioFiscal string Numero string ClienteNombre string ClienteEmpresa string AsesorNombre string Fecha time.Time Vigencia time.Time Moneda string TipoCambio string Proyecto string EsquemaPago string Servicios []ServicioExcel EsDoble bool OpcionesMetadata map[string]domain.MetaOpcion PlanBucefaloNivel *string PlanBucefaloPrecio *float64 ColorPrimario string ColorSecundario string IncluirIVA bool Observaciones *string } var ( hexRe = regexp.MustCompile(`^#?[0-9a-fA-F]{6}$`) invalidTabRe = regexp.MustCompile(`[/\\*?\[\]:]`) fasesExcelMap = map[int]string{ 0: "FASE 0", 1: "FASE 1", 2: "FASE 2", 3: "FASE 3", } ) func cleanHex(v, fallback string) string { v = strings.TrimSpace(v) if !hexRe.MatchString(v) { v = fallback } return strings.ToUpper(strings.TrimPrefix(v, "#")) } // tintLight blends ~10% of hex color onto white (#FFFFFF) for crisp light fills in Excel. func tintLight(hex6 string) string { r, _ := strconv.ParseInt(hex6[0:2], 16, 64) g, _ := strconv.ParseInt(hex6[2:4], 16, 64) b, _ := strconv.ParseInt(hex6[4:6], 16, 64) blend := func(c int64) int64 { return int64(math.Round(float64(c)*0.10 + 255.0*0.90)) } return fmt.Sprintf("%02X%02X%02X", blend(r), blend(g), blend(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 servicioExcelToCalc(s ServicioExcel) 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 serviciosExcelToCalc(list []ServicioExcel) []domain.ServicioCalc { out := make([]domain.ServicioCalc, len(list)) for i, s := range list { out[i] = servicioExcelToCalc(s) } return out } func estimateRowHeight(text string, widthChars float64, fontSize float64) float64 { cpl := int(math.Floor(widthChars)) if cpl < 8 { cpl = 8 } lineH := 14.0 switch { case fontSize <= 10: lineH = 14 case fontSize <= 11: lineH = 15.5 case fontSize <= 12: lineH = 17 default: lineH = 20 } lines := 0 for _, seg := range strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n") { n := utf8.RuneCountInString(seg) l := int(math.Ceil(float64(n) / float64(cpl))) if l < 1 { l = 1 } lines += l } h := math.Round(float64(lines)*lineH + 4) if h < 16 { return 16 } return h } func sanitizeSheetName(name string, used map[string]bool) string { cleaned := strings.TrimSpace(invalidTabRe.ReplaceAllString(name, "")) cleaned = strings.Trim(cleaned, "'") if cleaned == "" { cleaned = "Servicio" } runes := []rune(cleaned) if len(runes) > 31 { runes = runes[:31] } base := string(runes) candidate := base n := 2 for used[strings.ToLower(candidate)] { suffix := fmt.Sprintf(" (%d)", n) maxBase := 31 - utf8.RuneCountInString(suffix) br := []rune(base) if len(br) > maxBase { br = br[:maxBase] } candidate = string(br) + suffix n++ } used[strings.ToLower(candidate)] = true return candidate } type styleSpec struct { bold bool italic bool size float64 fontColor string fillColor string borderClr string horiz string vert string wrap bool numFmt string } type wbHelper struct { f *excelize.File styles map[styleSpec]int } func newWBHelper() *wbHelper { return &wbHelper{ f: excelize.NewFile(), styles: make(map[styleSpec]int), } } func (h *wbHelper) styleID(s styleSpec) int { if id, ok := h.styles[s]; ok { return id } size := s.size if size <= 0 { size = 10 } st := &excelize.Style{ Font: &excelize.Font{ Family: "Calibri", Size: size, Bold: s.bold, Italic: s.italic, Color: s.fontColor, }, Alignment: &excelize.Alignment{ Horizontal: s.horiz, Vertical: s.vert, WrapText: s.wrap, }, } if s.fillColor != "" { st.Fill = excelize.Fill{ Type: "pattern", Pattern: 1, Color: []string{s.fillColor}, } } if s.borderClr != "" { st.Border = []excelize.Border{ {Type: "top", Color: s.borderClr, Style: 1}, {Type: "bottom", Color: s.borderClr, Style: 1}, {Type: "left", Color: s.borderClr, Style: 1}, {Type: "right", Color: s.borderClr, Style: 1}, } } if s.numFmt != "" { nf := s.numFmt st.CustomNumFmt = &nf } id, err := h.f.NewStyle(st) if err != nil { return 0 } h.styles[s] = id return id } func (h *wbHelper) hideGrid(sheet string) { show := false _ = h.f.SetSheetView(sheet, 0, &excelize.ViewOptions{ShowGridLines: &show}) } func (h *wbHelper) setColWidths(sheet string, widths map[string]float64) { for col, w := range widths { _ = h.f.SetColWidth(sheet, col, col, w) } } func (h *wbHelper) ensureRowHeight(sheet string, row int, minH float64) { cur, _ := h.f.GetRowHeight(sheet, row) if cur < minH { _ = h.f.SetRowHeight(sheet, row, minH) } } func sumWidths(widths map[string]float64, cols ...string) float64 { total := 0.0 for _, c := range cols { if w, ok := widths[c]; ok { total += w } else { total += 8 } } return total } func BuildCotizacionExcel(data CotizacionExcelData) ([]byte, error) { primary := cleanHex(data.ColorPrimario, "0400C4") primaryLight := tintLight(primary) secondary := cleanHex(data.ColorSecundario, "0F172A") white := "FFFFFF" lightBG := "F8FAFC" muted := "64748B" borderColor := "E2E8F0" wb := newWBHelper() defer wb.f.Close() _ = wb.f.SetDocProps(&excelize.DocProperties{ Creator: "Cotizador — Uriel Jareth Consulting", Created: time.Now().UTC().Format(time.RFC3339), }) const resumenSheet = "HOJA RESUMEN" _ = wb.f.SetSheetName("Sheet1", resumenSheet) resumenWidths := map[string]float64{ "A": 3, "B": 18, "C": 26, "D": 13, "E": 16, "F": 22, "G": 6, "H": 6, "I": 6, "J": 6, "K": 16, } wb.setColWidths(resumenSheet, resumenWidths) wb.hideGrid(resumenSheet) // Common styles. stBanner1 := wb.styleID(styleSpec{bold: true, size: 16, fontColor: white, fillColor: primary, vert: "center"}) stBanner2 := wb.styleID(styleSpec{bold: true, size: 11, fontColor: white, fillColor: secondary, vert: "center"}) stLabel := wb.styleID(styleSpec{bold: true, size: 10, fontColor: muted, vert: "top"}) stValueWrap := wb.styleID(styleSpec{size: 10, vert: "top", wrap: true}) stDate := wb.styleID(styleSpec{size: 10, vert: "top", numFmt: "DD/MM/YYYY"}) stHeaderL := wb.styleID(styleSpec{bold: true, size: 10, fontColor: white, fillColor: primary, borderClr: primary, horiz: "left", vert: "center"}) stHeaderR := wb.styleID(styleSpec{bold: true, size: 10, fontColor: white, fillColor: primary, borderClr: primary, horiz: "right", vert: "center"}) stFase := wb.styleID(styleSpec{bold: true, size: 11, fontColor: primary, fillColor: primaryLight, vert: "center"}) stSmall := wb.styleID(styleSpec{italic: true, size: 9, fontColor: muted, vert: "top", wrap: true}) stIvaNote := wb.styleID(styleSpec{size: 9, fontColor: muted}) stObsTitle := wb.styleID(styleSpec{bold: true, size: 10, fontColor: primary}) stOpBanner := wb.styleID(styleSpec{bold: true, size: 12, fontColor: white, fillColor: secondary, vert: "center"}) stCompBanner := wb.styleID(styleSpec{bold: true, size: 12, fontColor: white, fillColor: primary, vert: "center"}) // ── Banner ── _ = wb.f.MergeCell(resumenSheet, "B2", "K2") _ = wb.f.SetCellValue(resumenSheet, "B2", data.RazonSocial) _ = wb.f.SetCellStyle(resumenSheet, "A2", "K2", stBanner1) _ = wb.f.SetRowHeight(resumenSheet, 2, 28) _ = wb.f.MergeCell(resumenSheet, "B3", "K3") _ = wb.f.SetCellValue(resumenSheet, "B3", data.Numero) _ = wb.f.SetCellStyle(resumenSheet, "A3", "K3", stBanner2) _ = wb.f.SetRowHeight(resumenSheet, 3, 20) // ── Info cliente / proyecto ── infoStart := 5 empresa := data.ClienteEmpresa if strings.TrimSpace(empresa) == "" { empresa = "—" } type infoPair struct{ l1, v1, l2, v2 string } infoRows := []infoPair{ {"En atención a:", data.ClienteNombre, "Empresa:", empresa}, {"Proyecto:", data.Proyecto, "Moneda:", data.Moneda}, {"Asesor:", data.AsesorNombre, "Tipo de Cambio:", data.TipoCambio}, {"Fecha:", "", "Esquema de Pago:", data.EsquemaPago}, } for i, ip := range infoRows { r := infoStart + i _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", r), ip.l1) _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", r), fmt.Sprintf("B%d", r), stLabel) if ip.v1 != "" { _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("C%d", r), ip.v1) _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("C%d", r), fmt.Sprintf("C%d", r), stValueWrap) wb.ensureRowHeight(resumenSheet, r, estimateRowHeight(ip.v1, resumenWidths["C"], 10)) } _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("E%d", r), ip.l2) _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("E%d", r), fmt.Sprintf("E%d", r), stLabel) if ip.v2 != "" { _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("F%d", r), ip.v2) _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("F%d", r), fmt.Sprintf("F%d", r), stValueWrap) wb.ensureRowHeight(resumenSheet, r, estimateRowHeight(ip.v2, resumenWidths["F"], 10)) } } if !data.Fecha.IsZero() { fUTC := time.Date(data.Fecha.Year(), data.Fecha.Month(), data.Fecha.Day(), 0, 0, 0, 0, time.UTC) _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("C%d", infoStart+3), fUTC) _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("C%d", infoStart+3), fmt.Sprintf("C%d", infoStart+3), stDate) } vigRow := infoStart + 4 _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", vigRow), "Vigencia:") _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", vigRow), fmt.Sprintf("B%d", vigRow), stLabel) if !data.Vigencia.IsZero() { vUTC := time.Date(data.Vigencia.Year(), data.Vigencia.Month(), data.Vigencia.Day(), 0, 0, 0, 0, time.UTC) _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("C%d", vigRow), vUTC) _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("C%d", vigRow), fmt.Sprintf("C%d", vigRow), stDate) } // ── Tabla de servicios ── tableStart := infoStart + 6 _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("D%d", tableStart), fmt.Sprintf("J%d", tableStart)) _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", tableStart), fmt.Sprintf("J%d", tableStart), stHeaderL) _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("K%d", tableStart), fmt.Sprintf("K%d", tableStart), stHeaderR) _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", tableStart), "Fase") _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("C%d", tableStart), "Tipo de Pago") _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("D%d", tableStart), "Servicio") _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("K%d", tableStart), "Precio") _ = wb.f.SetRowHeight(resumenSheet, tableStart, 24) var unicos, mensuales []ServicioExcel for _, s := range data.Servicios { if s.TipoPago == "mensual" { mensuales = append(mensuales, s) } else { unicos = append(unicos, s) } } servWidth := sumWidths(resumenWidths, "D", "E", "F", "G", "H", "I", "J") fullWidth := sumWidths(resumenWidths, "B", "C", "D", "E", "F", "G", "H", "I", "J", "K") row := tableStart + 1 writeTotalRow := func(label string, amount float64, fontSize float64) { stLbl := wb.styleID(styleSpec{bold: true, size: fontSize, fillColor: primaryLight, borderClr: primary, horiz: "left", vert: "center"}) stAmt := wb.styleID(styleSpec{bold: true, size: fontSize, fillColor: primaryLight, borderClr: primary, horiz: "right", vert: "center", numFmt: "$#,##0.00"}) _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("J%d", row)) _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), label) _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("J%d", row), stLbl) _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("K%d", row), amount) _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("K%d", row), fmt.Sprintf("K%d", row), stAmt) _ = wb.f.SetRowHeight(resumenSheet, row, 20) row++ } writeIvaNote := func() { _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("J%d", row)) _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), "(+ IVA)") _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("J%d", row), stIvaNote) row++ } drawServiceRows := func(servs []ServicioExcel) { currentFase := -1 for _, serv := range servs { if serv.Fase != currentFase { currentFase = serv.Fase _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row)) fLbl := fasesExcelMap[serv.Fase] if fLbl == "" { fLbl = fmt.Sprintf("FASE %d", serv.Fase) } _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), fLbl) _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stFase) _ = wb.f.SetRowHeight(resumenSheet, row, 20) row++ } bg := white if row%2 == 0 { bg = lightBG } stCell := wb.styleID(styleSpec{size: 10, fillColor: bg, borderClr: borderColor, horiz: "left", vert: "top"}) stCellWrap := wb.styleID(styleSpec{size: 10, fillColor: bg, borderClr: borderColor, horiz: "left", vert: "top", wrap: true}) stPrice := wb.styleID(styleSpec{size: 10, fillColor: bg, borderClr: borderColor, horiz: "right", vert: "top", numFmt: "$#,##0.00"}) _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("D%d", row), fmt.Sprintf("J%d", row)) _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("C%d", row), stCell) _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("D%d", row), fmt.Sprintf("J%d", row), stCellWrap) _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("K%d", row), fmt.Sprintf("K%d", row), stPrice) tipo := "Único" if serv.TipoPago == "mensual" { tipo = "Mensual" } _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("C%d", row), tipo) detalle := domain.DetalleModelo(servicioExcelToCalc(serv)) servText := serv.Nombre if detalle != "" { servText = fmt.Sprintf("%s — %s", serv.Nombre, detalle) } _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("D%d", row), servText) _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("K%d", row), serv.Precio) wb.ensureRowHeight(resumenSheet, row, estimateRowHeight(servText, servWidth, 10)) row++ } } writeOpcionBanner := func(op string) { meta := data.OpcionesMetadata[op] _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row)) tit := "OPCIÓN " + op if strings.TrimSpace(meta.Titulo) != "" { tit += ": " + meta.Titulo } _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), tit) _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stOpBanner) _ = wb.f.SetRowHeight(resumenSheet, row, 22) row++ if strings.TrimSpace(meta.Descripcion) != "" { _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row)) _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), meta.Descripcion) _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stValueWrap) wb.ensureRowHeight(resumenSheet, row, estimateRowHeight(meta.Descripcion, fullWidth, 10)) row++ } if strings.TrimSpace(meta.NoIncluye) != "" { _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row)) txt := "No incluye: " + meta.NoIncluye _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), txt) _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stSmall) wb.ensureRowHeight(resumenSheet, row, estimateRowHeight(txt, fullWidth, 9)) row++ } } sumPrices := func(list []ServicioExcel) float64 { tot := 0.0 for _, s := range list { tot += s.Precio } return domain.Round2(tot) } if data.EsDoble { filterOp := func(list []ServicioExcel, op string) []ServicioExcel { var out []ServicioExcel for _, s := range list { if s.Opcion != nil && (*s.Opcion == op || *s.Opcion == "ambas") { out = append(out, s) } } return out } for _, op := range []string{"1", "2"} { u := filterOp(unicos, op) me := filterOp(mensuales, op) writeOpcionBanner(op) combined := make([]ServicioExcel, 0, len(u)+len(me)) combined = append(combined, u...) combined = append(combined, me...) drawServiceRows(combined) row++ writeTotalRow(fmt.Sprintf("Total Pago Único - Opción %s", op), sumPrices(u), 11) writeIvaNote() writeTotalRow(fmt.Sprintf("Total Pago Mensual - Opción %s", op), sumPrices(me), 11) writeIvaNote() row++ } calcs := serviciosExcelToCalc(data.Servicios) t1 := domain.CalcularTotalesOpcion(calcs, "1") t2 := domain.CalcularTotalesOpcion(calcs, "2") _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row)) _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), "COMPARATIVA DE OPCIONES") _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stCompBanner) _ = wb.f.SetRowHeight(resumenSheet, row, 22) row++ compRow := func(lab, v1, v2 string, bold bool) { stL := wb.styleID(styleSpec{bold: bold, size: 10, borderClr: borderColor, horiz: "left", vert: "center"}) stR := wb.styleID(styleSpec{bold: bold, size: 10, borderClr: borderColor, horiz: "right", vert: "center"}) _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("F%d", row)) _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), lab) _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("F%d", row), stL) _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("G%d", row), fmt.Sprintf("H%d", row)) _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("G%d", row), v1) _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("G%d", row), fmt.Sprintf("H%d", row), stR) _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("I%d", row), fmt.Sprintf("K%d", row)) _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("I%d", row), v2) _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("I%d", row), fmt.Sprintf("K%d", row), stR) row++ } 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 } compRow("Concepto", op1Lbl, op2Lbl, true) ivaLbl := "" if data.IncluirIVA { ivaLbl = " (c/IVA)" } compRow("Total único"+ivaLbl, domain.FormatCurrency(domain.ConIVA(t1.TotalUnico, data.IncluirIVA)), domain.FormatCurrency(domain.ConIVA(t2.TotalUnico, data.IncluirIVA)), false) compRow("Total mensual"+ivaLbl, domain.FormatCurrency(domain.ConIVA(t1.TotalMensual, data.IncluirIVA)), domain.FormatCurrency(domain.ConIVA(t2.TotalMensual, data.IncluirIVA)), false) compRow("Horas estimadas", fmt.Sprintf("%g h", t1.Horas), fmt.Sprintf("%g h", t2.Horas), false) row++ } else { combined := make([]ServicioExcel, 0, len(unicos)+len(mensuales)) combined = append(combined, unicos...) combined = append(combined, mensuales...) drawServiceRows(combined) row++ writeTotalRow("Total Pago Único", sumPrices(unicos), 11) writeIvaNote() writeTotalRow("Total Pago Mensual", sumPrices(mensuales), 11) writeIvaNote() row++ } if data.PlanBucefaloNivel != nil && strings.TrimSpace(*data.PlanBucefaloNivel) != "" { nivel := strings.TrimSpace(*data.PlanBucefaloNivel) precio := domain.BucefaloPrecio(strings.ToLower(nivel)) if data.PlanBucefaloPrecio != nil { precio = *data.PlanBucefaloPrecio } writeTotalRow("CRM Bucéfalo - "+capitalize(nivel), precio, 10) row++ } notaResumen := "Todos los precios son en Moneda Nacional (MX), los precios no incluyen IVA. Vigencia de 15 días hábiles." _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row)) _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), notaResumen) _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stSmall) wb.ensureRowHeight(resumenSheet, row, estimateRowHeight(notaResumen, fullWidth, 9)) // Observaciones del cliente (solo cliente, nunca observaciones internas). if data.Observaciones != nil && strings.TrimSpace(*data.Observaciones) != "" { row += 2 _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row)) _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), "OBSERVACIONES") _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stObsTitle) row++ texto := strings.TrimSpace(*data.Observaciones) _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row)) _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), texto) _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stSmall) wb.ensureRowHeight(resumenSheet, row, estimateRowHeight(texto, fullWidth, 9)) } // ═══════════════════════════════════════════════════════════════════════════ // HOJAS DETALLADAS POR SERVICIO // ═══════════════════════════════════════════════════════════════════════════ usedNames := map[string]bool{ strings.ToLower(resumenSheet): true, } detailWidths := map[string]float64{ "A": 3, "B": 16, "C": 30, "D": 8, "E": 4, "F": 18, "G": 22, "H": 6, "I": 6, "J": 16, } stDetBanner := wb.styleID(styleSpec{bold: true, size: 14, fontColor: white, fillColor: primary, vert: "center", wrap: true}) stBoldWrap := wb.styleID(styleSpec{bold: true, size: 10, vert: "top", wrap: true}) stServTit := wb.styleID(styleSpec{bold: true, size: 12, fontColor: primary, vert: "top", wrap: true}) stEntHead := wb.styleID(styleSpec{bold: true, size: 10, fontColor: white, fillColor: primary, vert: "center"}) stTotLbl := wb.styleID(styleSpec{bold: true, size: 11, fillColor: primaryLight, borderClr: primary, horiz: "left", vert: "center"}) stTotVal := wb.styleID(styleSpec{bold: true, size: 11, fillColor: primaryLight, borderClr: primary, horiz: "right", vert: "center", numFmt: "$#,##0.00"}) stRazon := wb.styleID(styleSpec{bold: true, size: 10, fontColor: primary}) for _, serv := range data.Servicios { tabName := sanitizeSheetName(serv.Nombre, usedNames) _, _ = wb.f.NewSheet(tabName) wb.setColWidths(tabName, detailWidths) wb.hideGrid(tabName) fLbl := fasesExcelMap[serv.Fase] if fLbl == "" { fLbl = fmt.Sprintf("FASE %d", serv.Fase) } bannerText := fmt.Sprintf("%s — %s", fLbl, serv.Nombre) _ = wb.f.MergeCell(tabName, "B1", "J1") _ = wb.f.SetCellValue(tabName, "B1", bannerText) _ = wb.f.SetCellStyle(tabName, "A1", "J1", stDetBanner) bh := estimateRowHeight(bannerText, sumWidths(detailWidths, "B", "C", "D", "E", "F", "G", "H", "I", "J"), 14) if bh < 30 { bh = 30 } _ = wb.f.SetRowHeight(tabName, 1, bh) cValW := sumWidths(detailWidths, "C", "D") gValW := sumWidths(detailWidths, "G", "H") entW := sumWidths(detailWidths, "B", "C", "D", "E", "F", "G", "H", "I", "J") r := 3 clienteDisp := data.ClienteEmpresa if strings.TrimSpace(clienteDisp) == "" { clienteDisp = data.ClienteNombre } _ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), "Cliente:") _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("B%d", r), stLabel) _ = wb.f.MergeCell(tabName, fmt.Sprintf("C%d", r), fmt.Sprintf("D%d", r)) _ = wb.f.SetCellValue(tabName, fmt.Sprintf("C%d", r), clienteDisp) _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("C%d", r), fmt.Sprintf("D%d", r), stBoldWrap) wb.ensureRowHeight(tabName, r, estimateRowHeight(clienteDisp, cValW, 10)) _ = wb.f.SetCellValue(tabName, fmt.Sprintf("F%d", r), "No. Cotización:") _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("F%d", r), fmt.Sprintf("F%d", r), stLabel) _ = wb.f.MergeCell(tabName, fmt.Sprintf("G%d", r), fmt.Sprintf("H%d", r)) _ = wb.f.SetCellValue(tabName, fmt.Sprintf("G%d", r), data.Numero) _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("G%d", r), fmt.Sprintf("H%d", r), stBoldWrap) r += 2 _ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), "Servicio:") _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("B%d", r), stLabel) _ = wb.f.MergeCell(tabName, fmt.Sprintf("C%d", r), fmt.Sprintf("D%d", r)) _ = wb.f.SetCellValue(tabName, fmt.Sprintf("C%d", r), serv.Nombre) _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("C%d", r), fmt.Sprintf("D%d", r), stServTit) wb.ensureRowHeight(tabName, r, estimateRowHeight(serv.Nombre, cValW, 12)) _ = wb.f.SetCellValue(tabName, fmt.Sprintf("F%d", r), "Tiempo de Entrega:") _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("F%d", r), fmt.Sprintf("F%d", r), stLabel) _ = wb.f.MergeCell(tabName, fmt.Sprintf("G%d", r), fmt.Sprintf("H%d", r)) _ = wb.f.SetCellValue(tabName, fmt.Sprintf("G%d", r), serv.TiempoEntrega) _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("G%d", r), fmt.Sprintf("H%d", r), stValueWrap) wb.ensureRowHeight(tabName, r, estimateRowHeight(serv.TiempoEntrega, gValW, 10)) r += 2 detalleServ := domain.DetalleModelo(servicioExcelToCalc(serv)) if detalleServ != "" { _ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), "Detalle:") _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("B%d", r), stLabel) _ = wb.f.MergeCell(tabName, fmt.Sprintf("C%d", r), fmt.Sprintf("J%d", r)) _ = wb.f.SetCellValue(tabName, fmt.Sprintf("C%d", r), detalleServ) _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("C%d", r), fmt.Sprintf("J%d", r), stValueWrap) wb.ensureRowHeight(tabName, r, estimateRowHeight(detalleServ, sumWidths(detailWidths, "C", "D", "E", "F", "G", "H", "I", "J"), 10)) r += 2 } // Entregables header _ = wb.f.MergeCell(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("J%d", r)) _ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), "Entregables") _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("J%d", r), stEntHead) _ = wb.f.SetRowHeight(tabName, r, 22) r++ for i, ent := range serv.Entregables { er := r + i bg := white if i%2 == 1 { bg = lightBG } stEnt := wb.styleID(styleSpec{size: 10, fillColor: bg, borderClr: borderColor, horiz: "left", vert: "top", wrap: true}) txt := fmt.Sprintf("%d. %s", i+1, ent) _ = wb.f.MergeCell(tabName, fmt.Sprintf("B%d", er), fmt.Sprintf("J%d", er)) _ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", er), txt) _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", er), fmt.Sprintf("J%d", er), stEnt) wb.ensureRowHeight(tabName, er, estimateRowHeight(txt, entW, 10)) } r += len(serv.Entregables) + 1 tipoTot := "Único" if serv.TipoPago == "mensual" { tipoTot = "Mensual" } _ = wb.f.MergeCell(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("H%d", r)) _ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), "Total Pago "+tipoTot) _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("H%d", r), stTotLbl) _ = wb.f.MergeCell(tabName, fmt.Sprintf("I%d", r), fmt.Sprintf("J%d", r)) _ = wb.f.SetCellValue(tabName, fmt.Sprintf("I%d", r), serv.Precio) _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("I%d", r), fmt.Sprintf("J%d", r), stTotVal) _ = wb.f.SetRowHeight(tabName, r, 20) r++ _ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), "(+ IVA)") _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("B%d", r), stIvaNote) r += 2 notaDetalle := "Esta cotización tiene una vigencia de 15 días hábiles. Todos los precios en MXN, precios + IVA." _ = wb.f.MergeCell(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("J%d", r)) _ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), notaDetalle) _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("J%d", r), stSmall) wb.ensureRowHeight(tabName, r, estimateRowHeight(notaDetalle, entW, 9)) r += 2 // Brand decision: never print domicilio fiscal in generated documents. _ = wb.f.MergeCell(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("J%d", r)) _ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), data.RazonSocial) _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("J%d", r), stRazon) } buf, err := wb.f.WriteToBuffer() if err != nil { return nil, err } return buf.Bytes(), nil }