amseltools/internal/dirtoexcel/dirtoexcel.go

252 lines
5.3 KiB
Go
Raw Permalink Normal View History

2023-03-29 15:26:21 +02:00
package dirtoexcel
import (
"fmt"
"math"
"os"
"regexp"
2023-04-14 10:14:17 +02:00
"sort"
2023-03-29 15:26:21 +02:00
"strconv"
2023-04-11 19:15:16 +02:00
"strings"
2023-03-29 15:26:21 +02:00
"time"
2023-04-05 10:24:32 +02:00
"github.com/lmittmann/tint"
2023-03-29 15:26:21 +02:00
"github.com/spf13/cobra"
"github.com/xuri/excelize/v2"
2023-04-05 10:24:32 +02:00
"golang.org/x/exp/slog"
2023-03-29 15:26:21 +02:00
)
func init() {
2023-04-05 10:24:32 +02:00
slog.SetDefault(slog.New(tint.Options{
Level: slog.LevelDebug,
TimeFormat: time.Kitchen,
}.NewHandler(os.Stderr)))
2023-03-29 15:26:21 +02:00
}
2023-04-13 13:33:03 +02:00
const re = `^(?P<company>[a-zA-Z0-9-\s]+)(?:_[a-zA-Z0-9]+)?_(?P<value>\d+\.\d{1,2})`
2023-04-11 19:15:16 +02:00
type Value struct {
Company string
Value float64
}
2023-04-14 10:14:17 +02:00
type Values []Value
type Categories map[string]Values
2023-04-11 19:15:16 +02:00
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":
2023-04-12 10:31:26 +02:00
c["NonFood"] = append(c["NonFood"], Value{Company: company, Value: fValue})
2023-04-11 19:15:16 +02:00
default:
c["Other"] = append(c["Other"], Value{Company: company, Value: fValue})
}
return nil
}
2023-03-29 15:26:21 +02:00
func Run(cmd *cobra.Command, args []string) {
outfile, err := cmd.Flags().GetString("out")
if err != nil {
2023-04-05 10:24:32 +02:00
slog.Error("failed to get outfile string", "error", err)
os.Exit(1)
2023-03-29 15:26:21 +02:00
}
if outfile == "" {
outfile = fmt.Sprintf("%d.xlsx", time.Now().Unix())
}
if err := Create(outfile, args[0]); err != nil {
2023-04-05 10:24:32 +02:00
slog.Error("failed to create excel", "error", err)
os.Exit(1)
2023-03-29 15:26:21 +02:00
}
}
func Create(out, dir string) error {
2023-04-05 10:24:32 +02:00
log := slog.With("dir", dir, "out", out)
2023-03-29 15:26:21 +02:00
2023-04-11 19:15:16 +02:00
c := Categories{}
2023-03-29 15:26:21 +02:00
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)
}
2023-04-11 19:15:16 +02:00
// Extract data from filenames. Filling them into categories.
for _, i := range files {
if i.IsDir() {
2023-03-29 15:26:21 +02:00
continue
}
2023-04-11 19:15:16 +02:00
log.Info("found", "file", i.Name())
2023-03-29 15:26:21 +02:00
2023-04-11 19:15:16 +02:00
res := r.FindAllStringSubmatch(i.Name(), -1)
2023-03-29 15:26:21 +02:00
if res == nil {
2023-04-13 13:33:03 +02:00
log.Error("couldnt find match", "file", i.Name())
2023-03-29 15:26:21 +02:00
return fmt.Errorf("nothing found")
}
if len(res) != 1 || len(res[0]) != 3 {
return fmt.Errorf("strange numbers of matches")
}
company := res[0][1]
2023-04-11 19:15:16 +02:00
value := res[0][2]
2023-04-11 19:15:16 +02:00
log.Debug("extracted", slog.String("company", company), slog.String("value", value))
2023-04-11 19:15:16 +02:00
if err := c.Insert(company, value); err != nil {
return fmt.Errorf("failed to insert data: %w", err)
}
}
2023-04-12 13:11:29 +02:00
if _, err := f.NewSheet("Overview"); err != nil {
return fmt.Errorf("failed to add overview sheet: %w", err)
}
catLength := 0
2023-04-11 19:15:16 +02:00
for cat, item := range c {
2023-03-29 15:26:21 +02:00
2023-04-12 13:11:29 +02:00
if _, err := f.NewSheet(cat); err != nil {
2023-04-11 19:15:16 +02:00
return fmt.Errorf("failed to create new sheet: %w", err)
2023-03-29 15:26:21 +02:00
}
2023-04-14 10:14:17 +02:00
item = CalcAndSort(item)
2023-04-11 19:15:16 +02:00
2023-04-12 13:11:29 +02:00
valueLength := 0
2023-04-11 19:15:16 +02:00
2023-04-14 10:14:17 +02:00
for _, i := range item {
if err := f.SetCellStr(cat, fmt.Sprintf("A%d", valueLength+1), i.Company); err != nil {
2023-04-11 19:15:16 +02:00
return fmt.Errorf("failed to set cell: %w", err)
}
2023-04-14 10:14:17 +02:00
if err := f.SetCellFloat(cat, fmt.Sprintf("B%d", valueLength+1), i.Value, 2, 64); err != nil {
2023-04-11 19:15:16 +02:00
return fmt.Errorf("failed to set cell: %w", err)
}
2023-04-12 13:11:29 +02:00
valueLength += 1
2023-04-12 10:31:26 +02:00
}
2023-04-12 13:11:29 +02:00
if err := createCategoryChart(cat, valueLength, f); err != nil {
2023-04-12 10:31:26 +02:00
return fmt.Errorf("failed to create category chart: %w", err)
2023-03-29 15:26:21 +02:00
}
2023-04-12 13:11:29 +02:00
// 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)
2023-03-29 15:26:21 +02:00
}
if err := f.SaveAs(out); err != nil {
return fmt.Errorf("failed to save excel: %w", err)
}
log.Info("created excel")
return nil
}
2023-04-12 10:31:26 +02:00
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
}
2023-04-14 10:14:17 +02:00
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
}