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
+253
View File
@@ -0,0 +1,253 @@
package excel
import (
"bytes"
"encoding/csv"
"errors"
"fmt"
"io"
"math"
"strconv"
"strings"
)
type CatalogoCSVRow struct {
Nombre string
Categoria string
Fase int
TipoPago string
PrecioBase float64
TiempoEntrega string
Entregables []string
Variante string
}
var fasesExportCSV = map[int]string{
0: "Auditoria",
1: "Setup e Infraestructura",
2: "Publicidad y Manejo",
3: "Contenido y SEO",
}
var fasesImportCSV = map[string]int{
"0": 0,
"fase 0": 0,
"auditoria": 0,
"auditoría": 0,
"1": 1,
"fase 1": 1,
"setup e infraestructura": 1,
"setup": 1,
"infraestructura": 1,
"2": 2,
"fase 2": 2,
"publicidad y manejo": 2,
"publicidad": 2,
"manejo": 2,
"3": 3,
"fase 3": 3,
"contenido y seo": 3,
"contenido": 3,
"seo": 3,
}
func ExportCatalogoCSV(rows []CatalogoCSVRow) ([]byte, error) {
var buf bytes.Buffer
w := csv.NewWriter(&buf)
if err := w.Write([]string{
"Nombre",
"Categoria",
"Fase",
"Tipo de Pago",
"Precio Base",
"Tiempo de Entrega",
"Entregables",
"Variante",
}); err != nil {
return nil, err
}
for _, r := range rows {
faseLabel, ok := fasesExportCSV[r.Fase]
if !ok {
faseLabel = fmt.Sprintf("Fase %d", r.Fase)
}
tipoLabel := "Mensual"
if strings.EqualFold(strings.TrimSpace(r.TipoPago), "unico") {
tipoLabel = "Pago Unico"
}
rec := []string{
r.Nombre,
r.Categoria,
faseLabel,
tipoLabel,
strconv.FormatFloat(r.PrecioBase, 'f', -1, 64),
r.TiempoEntrega,
strings.Join(r.Entregables, " | "),
r.Variante,
}
if err := w.Write(rec); err != nil {
return nil, err
}
}
w.Flush()
if err := w.Error(); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func PlantillaCatalogoCSV() []byte {
const tpl = `Nombre,Categoria,Fase,Tipo de Pago,Precio Base,Tiempo de Entrega,Entregables,Variante
"SEO On-Page Basico","SEO","Setup e Infraestructura","unico",5000,"7 - 14 dias","Auditoria SEO | Optimizacion de meta tags | Mapa del sitio",
"Manejo de Redes Sociales","Marketing","Publicidad y Manejo","mensual",8000,"Mensual","Publicaciones semanales | Reporte mensual | Gestion de comunidad","Basico"
"Gestion de Google Ads","Paid Media","Publicidad y Manejo","mensual",5000,"Mensual","Configuracion de campanas | Reporte semanal",
"Sitio Web Informativo","Desarrollo Web","Setup e Infraestructura","unico",15000,"15 - 30 dias","Diseno responsivo | Hasta 5 secciones | Formulario de contacto",
"Automatizacion Email Marketing","Automatizaciones","Publicidad y Manejo","unico",8000,"10 - 15 dias","Configuracion de flujos | Plantillas de correo | Integracion CRM",
"CRM Basico","CRM","Publicidad y Manejo","mensual",1000,"Mensual","CRM completo segun plan contratado","basico"
,,,,
"CATEGORIAS DISPONIBLES: SEO / Marketing / Paid Media / Desarrollo Web / Automatizaciones / CRM",,,,,
"FASES: Auditoria / Setup e Infraestructura / Publicidad y Manejo / Contenido y SEO",,,,,
"TIPOS DE PAGO: unico / mensual",,,,,
"ENTREGABLES: separar con | (pipe)",,,,,
"VARIANTE: opcional (ej: Basico, Estandar, Premium)",,,,,
`
return []byte(tpl)
}
func isInstructionLine(line string) bool {
trimmed := strings.TrimSpace(line)
if trimmed == "" {
return true
}
unquoted := strings.ToUpper(strings.TrimPrefix(trimmed, `"`))
for _, prefix := range []string{
"CATEGORIAS",
"CATEGORÍAS",
"FASES:",
"TIPOS DE PAGO",
"TIPOS",
"ENTREGABLES:",
"VARIANTE:",
} {
if strings.HasPrefix(unquoted, prefix) {
return true
}
}
return false
}
func ParseCatalogoCSV(raw []byte) ([]CatalogoCSVRow, error) {
// Strip UTF-8 BOM if present.
raw = bytes.TrimPrefix(raw, []byte{0xEF, 0xBB, 0xBF})
text := strings.ReplaceAll(string(raw), "\r\n", "\n")
rawLines := strings.Split(text, "\n")
var kept []string
for _, l := range rawLines {
if isInstructionLine(l) {
continue
}
kept = append(kept, l)
}
if len(kept) < 2 {
return nil, errors.New("el CSV esta vacio o no tiene datos")
}
r := csv.NewReader(strings.NewReader(strings.Join(kept, "\n")))
r.FieldsPerRecord = -1
r.LazyQuotes = true
r.TrimLeadingSpace = true
// Skip header row.
if _, err := r.Read(); err != nil {
return nil, fmt.Errorf("error leyendo encabezado CSV: %w", err)
}
var rows []CatalogoCSVRow
for {
rec, err := r.Read()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return nil, fmt.Errorf("error leyendo CSV: %w", err)
}
if len(rec) < 5 {
continue
}
get := func(i int) string {
if i >= len(rec) {
return ""
}
return strings.TrimSpace(rec[i])
}
nombre := get(0)
categoria := get(1)
faseStr := strings.ToLower(get(2))
tipoStr := strings.ToLower(get(3))
precioStr := get(4)
tiempoEntrega := get(5)
entregablesStr := get(6)
variante := get(7)
if nombre == "" || categoria == "" || tipoStr == "" || precioStr == "" {
continue
}
fase, ok := fasesImportCSV[faseStr]
if !ok {
continue
}
var tipoPago string
switch tipoStr {
case "unico", "único", "pago unico", "pago único":
tipoPago = "unico"
case "mensual":
tipoPago = "mensual"
default:
continue
}
cleanedPrecio := strings.NewReplacer("$", "", ",", "", " ", "").Replace(precioStr)
precioBase, err := strconv.ParseFloat(cleanedPrecio, 64)
if err != nil || math.IsNaN(precioBase) || math.IsInf(precioBase, 0) || precioBase < 0 {
continue
}
if tiempoEntrega == "" {
tiempoEntrega = "7 - 14 dias"
}
var entregables []string
if entregablesStr != "" {
for _, part := range strings.Split(entregablesStr, "|") {
if p := strings.TrimSpace(part); p != "" {
entregables = append(entregables, p)
}
}
}
rows = append(rows, CatalogoCSVRow{
Nombre: nombre,
Categoria: categoria,
Fase: fase,
TipoPago: tipoPago,
PrecioBase: precioBase,
TiempoEntrega: tiempoEntrega,
Entregables: entregables,
Variante: variante,
})
}
if len(rows) == 0 {
return nil, errors.New("no se encontraron filas validas. Verifica el formato del CSV")
}
return rows, nil
}
+769
View File
@@ -0,0 +1,769 @@
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
}
+276
View File
@@ -0,0 +1,276 @@
package excel
import (
"bytes"
"reflect"
"strings"
"testing"
"time"
"github.com/xuri/excelize/v2"
"cotizador/internal/domain"
)
func f64(v float64) *float64 { return &v }
func str(v string) *string { return &v }
func TestCotizacionExcelDataHasNoObservacionesInternas(t *testing.T) {
rt := reflect.TypeOf(CotizacionExcelData{})
for i := 0; i < rt.NumField(); i++ {
name := strings.ToLower(rt.Field(i).Name)
if strings.Contains(name, "interna") {
t.Fatalf("CotizacionExcelData must never declare internal observations field, found %q", rt.Field(i).Name)
}
}
}
func sheetContains(t *testing.T, f *excelize.File, sheet, substr string) bool {
t.Helper()
rows, err := f.GetRows(sheet)
if err != nil {
t.Fatalf("GetRows(%s): %v", sheet, err)
}
for _, row := range rows {
for _, cell := range row {
if strings.Contains(cell, substr) {
return true
}
}
}
return false
}
func TestBuildCotizacionExcelSingle(t *testing.T) {
fecha := time.Date(2026, 5, 10, 0, 0, 0, 0, time.UTC)
vigencia := domain.CalcularVigencia(fecha)
obs := "Nota visible para el cliente con acentos: diseño y año."
raw, err := BuildCotizacionExcel(CotizacionExcelData{
RazonSocial: "URIEL JARETH CONSULTING",
DomicilioFiscal: "DOMICILIO_SECRETO_NO_IMPRIMIR 123",
Numero: "UJ2605UR001",
ClienteNombre: "Sofía Ramírez",
ClienteEmpresa: "Ramírez Diseño S.A.",
AsesorNombre: "Uriel Jareth",
Fecha: fecha,
Vigencia: vigencia,
Moneda: "MXN",
TipoCambio: "N/A",
Proyecto: "Sitio Web y Campañas",
EsquemaPago: "50/50",
Servicios: []ServicioExcel{
{
Nombre: "Auditoría SEO / Técnica: [2026]*?",
Fase: 0,
TipoPago: "unico",
Precio: 6000,
TiempoEntrega: "7 días",
Entregables: []string{"Diagnóstico técnico", "Roadmap SEO"},
ModeloCobro: "fijo",
},
{
Nombre: "Desarrollo Custom",
Fase: 1,
TipoPago: "unico",
Precio: 14000,
TiempoEntrega: "15 días",
Entregables: []string{"Frontend", "Backend"},
ModeloCobro: "horas",
EsPersonalizado: true,
Horas: f64(20),
TarifaHora: f64(700),
},
{
Nombre: "Retainer Mensual",
Fase: 2,
TipoPago: "mensual",
Precio: 7500,
TiempoEntrega: "Mensual",
Entregables: []string{"Soporte", "Reportes"},
ModeloCobro: "retainer",
MontoMinimo: f64(7500),
HorasIncluidas: f64(10),
TarifaHora: f64(700),
},
{
Nombre: "Desarrollo Custom", // duplicate tab name test
Fase: 3,
TipoPago: "mensual",
Precio: 0,
TiempoEntrega: "Bajo demanda",
ModeloCobro: "demanda",
TarifaHora: f64(700),
},
},
PlanBucefaloNivel: str("premium"), // nil price -> falls back to domain.BucefaloPrecio (4500)
ColorPrimario: "#0400C4",
ColorSecundario: "#0F172A",
IncluirIVA: true,
Observaciones: &obs,
})
if err != nil {
t.Fatalf("BuildCotizacionExcel error: %v", err)
}
f, err := excelize.OpenReader(bytes.NewReader(raw))
if err != nil {
t.Fatalf("excelize.OpenReader error: %v", err)
}
defer f.Close()
sheets := f.GetSheetList()
if len(sheets) != 5 {
t.Fatalf("expected 5 sheets (1 resumen + 4 services), got %d: %v", len(sheets), sheets)
}
if sheets[0] != "HOJA RESUMEN" {
t.Fatalf("expected first sheet HOJA RESUMEN, got %q", sheets[0])
}
// Verify key values in HOJA RESUMEN
if v, _ := f.GetCellValue("HOJA RESUMEN", "B2"); v != "URIEL JARETH CONSULTING" {
t.Errorf("B2 = %q, want URIEL JARETH CONSULTING", v)
}
if v, _ := f.GetCellValue("HOJA RESUMEN", "B3"); v != "UJ2605UR001" {
t.Errorf("B3 = %q, want UJ2605UR001", v)
}
if !sheetContains(t, f, "HOJA RESUMEN", "20 h x $700/hr") {
t.Errorf("HOJA RESUMEN missing horas DetalleModelo")
}
if !sheetContains(t, f, "HOJA RESUMEN", "segun consumo") {
t.Errorf("HOJA RESUMEN missing demanda DetalleModelo")
}
if !sheetContains(t, f, "HOJA RESUMEN", "CRM Bucéfalo - Premium") {
t.Errorf("HOJA RESUMEN missing Plan Bucéfalo row")
}
if !sheetContains(t, f, "HOJA RESUMEN", obs) {
t.Errorf("HOJA RESUMEN missing Observaciones")
}
// Verify DomicilioFiscal is NEVER printed on any sheet.
for _, s := range sheets {
if sheetContains(t, f, s, "DOMICILIO_SECRETO_NO_IMPRIMIR") {
t.Fatalf("sheet %q leaked DomicilioFiscal", s)
}
}
}
func TestBuildCotizacionExcelDoblePropuesta(t *testing.T) {
fecha := time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC)
raw, err := BuildCotizacionExcel(CotizacionExcelData{
RazonSocial: "URIEL JARETH CONSULTING",
Numero: "UJ2606UR002",
ClienteNombre: "Luis Torres",
ClienteEmpresa: "Torres Corp",
AsesorNombre: "Uriel Jareth",
Fecha: fecha,
Vigencia: domain.CalcularVigencia(fecha),
Moneda: "MXN",
Proyecto: "Escalamiento",
EsquemaPago: "Mensual",
EsDoble: true,
IncluirIVA: true,
OpcionesMetadata: map[string]domain.MetaOpcion{
"1": {Titulo: "Básico", Descripcion: "Plan inicial", NoIncluye: "Video"},
"2": {Titulo: "Pro", Descripcion: "Plan avanzado", NoIncluye: "Pauta"},
},
Servicios: []ServicioExcel{
{Nombre: "HOJA RESUMEN", Fase: 0, TipoPago: "unico", Precio: 5000, TiempoEntrega: "5 días", Opcion: str("ambas"), Horas: f64(5)},
{Nombre: "Landing", Fase: 1, TipoPago: "unico", Precio: 10000, TiempoEntrega: "10 días", Opcion: str("1"), Horas: f64(10)},
{Nombre: "Web Pro", Fase: 1, TipoPago: "unico", Precio: 20000, TiempoEntrega: "20 días", Opcion: str("2"), Horas: f64(25)},
{Nombre: "Ads", Fase: 2, TipoPago: "mensual", Precio: 8000, TiempoEntrega: "Mensual", Opcion: str("ambas")},
},
PlanBucefaloNivel: str("basico"),
PlanBucefaloPrecio: f64(1200),
})
if err != nil {
t.Fatalf("BuildCotizacionExcel doble error: %v", err)
}
f, err := excelize.OpenReader(bytes.NewReader(raw))
if err != nil {
t.Fatalf("OpenReader error: %v", err)
}
defer f.Close()
if !sheetContains(t, f, "HOJA RESUMEN", "OPCIÓN 1: Básico") {
t.Errorf("missing OPCIÓN 1 banner")
}
if !sheetContains(t, f, "HOJA RESUMEN", "OPCIÓN 2: Pro") {
t.Errorf("missing OPCIÓN 2 banner")
}
if !sheetContains(t, f, "HOJA RESUMEN", "COMPARATIVA DE OPCIONES") {
t.Errorf("missing COMPARATIVA DE OPCIONES")
}
// Opción 1 único = (5000+10000)*1.16 = $17,400; Opción 2 único = (5000+20000)*1.16 = $29,000
if !sheetContains(t, f, "HOJA RESUMEN", "$17,400") || !sheetContains(t, f, "HOJA RESUMEN", "$29,000") {
t.Errorf("expected IVA-adjusted comparative totals $17,400 and $29,000")
}
if !sheetContains(t, f, "HOJA RESUMEN", "15 h") || !sheetContains(t, f, "HOJA RESUMEN", "30 h") {
t.Errorf("expected comparative hours 15 h and 30 h")
}
}
func TestCatalogoCSVExportPlantillaAndParse(t *testing.T) {
// 1. Plantilla parses cleanly into 6 rows.
tpl := PlantillaCatalogoCSV()
parsedTpl, err := ParseCatalogoCSV(tpl)
if err != nil {
t.Fatalf("ParseCatalogoCSV(PlantillaCatalogoCSV()) error: %v", err)
}
if len(parsedTpl) != 6 {
t.Fatalf("expected 6 rows from plantilla, got %d", len(parsedTpl))
}
if parsedTpl[0].Nombre != "SEO On-Page Basico" || parsedTpl[0].Fase != 1 || parsedTpl[0].TipoPago != "unico" || parsedTpl[0].PrecioBase != 5000 {
t.Errorf("unexpected first plantilla row: %+v", parsedTpl[0])
}
if len(parsedTpl[0].Entregables) != 3 {
t.Errorf("expected 3 entregables in first row, got %v", parsedTpl[0].Entregables)
}
// 2. Round-trip ExportCatalogoCSV -> ParseCatalogoCSV (including commas, quotes, BOM).
orig := []CatalogoCSVRow{
{
Nombre: `Auditoría "Pro", Web & SEO`,
Categoria: "SEO",
Fase: 0,
TipoPago: "unico",
PrecioBase: 4500.5,
TiempoEntrega: "5 - 7 días",
Entregables: []string{"Informe técnico", "Sesión de entrega"},
Variante: "Premium",
},
{
Nombre: "Gestión de Redes",
Categoria: "Marketing",
Fase: 2,
TipoPago: "mensual",
PrecioBase: 8000,
TiempoEntrega: "Mensual",
Entregables: []string{"Calendario editorial", "Reporte mensual"},
Variante: "",
},
}
exported, err := ExportCatalogoCSV(orig)
if err != nil {
t.Fatalf("ExportCatalogoCSV error: %v", err)
}
// Prepend UTF-8 BOM to verify BOM stripping too.
withBOM := append([]byte{0xEF, 0xBB, 0xBF}, exported...)
roundTrip, err := ParseCatalogoCSV(withBOM)
if err != nil {
t.Fatalf("ParseCatalogoCSV round-trip error: %v", err)
}
if !reflect.DeepEqual(roundTrip, orig) {
t.Fatalf("round-trip mismatch:\ngot: %+v\nwant: %+v", roundTrip, orig)
}
// 3. Error cases.
if _, err := ParseCatalogoCSV([]byte("Nombre,Categoria,Fase,Tipo de Pago,Precio Base\n")); err == nil {
t.Errorf("expected error for header-only CSV")
}
if _, err := ParseCatalogoCSV([]byte("Nombre,Categoria,Fase,Tipo de Pago,Precio Base\nFoo,Bar,Invalida,unico,-5\n")); err == nil {
t.Errorf("expected error when no valid rows exist")
}
}