package dirtoexcel import ( "fmt" "math" "os" "regexp" "sort" "strconv" "strings" "time" "github.com/lmittmann/tint" "github.com/spf13/cobra" "github.com/xuri/excelize/v2" "golang.org/x/exp/slog" ) func init() { slog.SetDefault(slog.New(tint.Options{ Level: slog.LevelDebug, TimeFormat: time.Kitchen, }.NewHandler(os.Stderr))) } const re = `^(?P[a-zA-Z0-9-\s]+)(?:_[a-zA-Z0-9]+)?_(?P\d+\.\d{1,2})` type Value struct { Company string Value float64 } type Values []Value type Categories map[string]Values func (c Categories) Insert(company, value string) error { fValue, err := strconv.ParseFloat(value, 32) if err != nil { return fmt.Errorf("failed to convert string to float: %w", err) } fValue = math.Round(fValue*100) / 100 company = strings.ToUpper(company) switch company { case "ALDI", "EDEKA": c["Food"] = append(c["Food"], Value{Company: company, Value: fValue}) case "AMAZON": c["NonFood"] = append(c["NonFood"], Value{Company: company, Value: fValue}) default: c["Other"] = append(c["Other"], Value{Company: company, Value: fValue}) } return nil } func Run(cmd *cobra.Command, args []string) { outfile, err := cmd.Flags().GetString("out") if err != nil { slog.Error("failed to get outfile string", "error", err) os.Exit(1) } if outfile == "" { outfile = fmt.Sprintf("%d.xlsx", time.Now().Unix()) } if err := Create(outfile, args[0]); err != nil { slog.Error("failed to create excel", "error", err) os.Exit(1) } } func Create(out, dir string) error { log := slog.With("dir", dir, "out", out) c := Categories{} f := excelize.NewFile() defer func() { if err := f.Close(); err != nil { log.Error("failed to close excel file") } }() files, err := os.ReadDir(dir) if err != nil { return fmt.Errorf("failed to read dir: %w", err) } r, err := regexp.Compile(re) if err != nil { return fmt.Errorf("failed to compile regex: %w", err) } // Extract data from filenames. Filling them into categories. for _, i := range files { if i.IsDir() { continue } log.Info("found", "file", i.Name()) res := r.FindAllStringSubmatch(i.Name(), -1) if res == nil { log.Error("couldnt find match", "file", i.Name()) return fmt.Errorf("nothing found") } if len(res) != 1 || len(res[0]) != 3 { return fmt.Errorf("strange numbers of matches") } company := res[0][1] value := res[0][2] log.Debug("extracted", slog.String("company", company), slog.String("value", value)) if err := c.Insert(company, value); err != nil { return fmt.Errorf("failed to insert data: %w", err) } } if _, err := f.NewSheet("Overview"); err != nil { return fmt.Errorf("failed to add overview sheet: %w", err) } catLength := 0 for cat, item := range c { if _, err := f.NewSheet(cat); err != nil { return fmt.Errorf("failed to create new sheet: %w", err) } item = CalcAndSort(item) valueLength := 0 for _, i := range item { if err := f.SetCellStr(cat, fmt.Sprintf("A%d", valueLength+1), i.Company); err != nil { return fmt.Errorf("failed to set cell: %w", err) } if err := f.SetCellFloat(cat, fmt.Sprintf("B%d", valueLength+1), i.Value, 2, 64); err != nil { return fmt.Errorf("failed to set cell: %w", err) } valueLength += 1 } if err := createCategoryChart(cat, valueLength, f); err != nil { return fmt.Errorf("failed to create category chart: %w", err) } // Add to overview. if err := f.SetCellStr("Overview", fmt.Sprintf("A%d", catLength+1), cat); err != nil { return fmt.Errorf("failed to set category to overview: %w", err) } if err := f.SetCellFormula("Overview", fmt.Sprintf("B%d", catLength+1), fmt.Sprintf("=SUM(%s!B1:B%d)", cat, valueLength)); err != nil { return fmt.Errorf("failed to set sum to overview: %w", err) } if err := createCategoryChart("Overview", catLength+1, f); err != nil { return fmt.Errorf("failed to create overview chat: %w", err) } catLength += 1 } if err := f.DeleteSheet("Sheet1"); err != nil { return fmt.Errorf("failed to remove default sheet: %w", err) } if err := f.SaveAs(out); err != nil { return fmt.Errorf("failed to save excel: %w", err) } log.Info("created excel") return nil } func createCategoryChart(category string, length int, f *excelize.File) error { if err := f.AddChart(category, "C1", &excelize.Chart{ Type: excelize.Doughnut, Series: []excelize.ChartSeries{ { Name: "Amount", Categories: fmt.Sprintf("%s!A1:A%d", category, length), Values: fmt.Sprintf("%s!B1:B%d", category, length), }, }, Format: excelize.GraphicOptions{ OffsetX: 15, OffsetY: 10, }, Legend: excelize.ChartLegend{ Position: "right", }, Title: excelize.ChartTitle{ Name: category, }, PlotArea: excelize.ChartPlotArea{ ShowCatName: false, ShowLeaderLines: false, ShowPercent: true, ShowSerName: false, ShowVal: false, }, ShowBlanksAs: "zero", }); err != nil { return fmt.Errorf("failed to create chart: %w", err) } return nil } func CalcAndSort(v Values) Values { n := Values{} for _, i := range v { added := false for k, v := range n { if i.Company == v.Company { n[k].Value += i.Value added = true break } } if !added { n = append(n, i) } } // Sorting for company names. sort.SliceStable(n, func(i, j int) bool { return n[i].Company < n[j].Company }) return n }