amseltools/internal/dirtoexcel/dirtoexcel.go
Marvin Preuss 9bf0b05ec6
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/tag/woodpecker Pipeline was successful
feat: adds overview sheet with chart
2023-04-12 11:11:29 +00:00

221 lines
4.9 KiB
Go

package dirtoexcel
import (
"fmt"
"math"
"os"
"regexp"
"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<company>[a-zA-Z0-9-]+)(?:_[a-zA-Z]+)?_(?P<value>\d+\.\d{1,2})`
type Value struct {
Company string
Value float64
}
type Categories map[string][]Value
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 {
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)
}
m := map[string]float64{}
for _, i := range item {
m[i.Company] += i.Value
}
valueLength := 0
for k, v := range m {
if err := f.SetCellStr(cat, fmt.Sprintf("A%d", valueLength+1), k); err != nil {
return fmt.Errorf("failed to set cell: %w", err)
}
if err := f.SetCellFloat(cat, fmt.Sprintf("B%d", valueLength+1), v, 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
}