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 }