72 lines
1.6 KiB
Go
72 lines
1.6 KiB
Go
|
|
package repository
|
||
|
|
|
||
|
|
import (
|
||
|
|
"encoding/json"
|
||
|
|
"fmt"
|
||
|
|
"os"
|
||
|
|
"path/filepath"
|
||
|
|
"sort"
|
||
|
|
"strings"
|
||
|
|
|
||
|
|
"materialanalyzer/internal/model"
|
||
|
|
)
|
||
|
|
|
||
|
|
func LoadProducts(dataDir string) ([]model.Product, error) {
|
||
|
|
files, err := os.ReadDir(dataDir)
|
||
|
|
if err != nil {
|
||
|
|
return nil, fmt.Errorf("read product data dir: %w", err)
|
||
|
|
}
|
||
|
|
|
||
|
|
var products []model.Product
|
||
|
|
for _, f := range files {
|
||
|
|
if f.IsDir() || !strings.EqualFold(filepath.Ext(f.Name()), ".json") {
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
path := filepath.Join(dataDir, f.Name())
|
||
|
|
data, err := os.ReadFile(path)
|
||
|
|
if err != nil {
|
||
|
|
return nil, fmt.Errorf("read %s: %w", path, err)
|
||
|
|
}
|
||
|
|
var batch []model.Product
|
||
|
|
if err := json.Unmarshal(data, &batch); err != nil {
|
||
|
|
return nil, fmt.Errorf("parse %s: %w", path, err)
|
||
|
|
}
|
||
|
|
for _, p := range batch {
|
||
|
|
if strings.TrimSpace(p.SKU) == "" {
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
products = append(products, p)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
sort.Slice(products, func(i, j int) bool {
|
||
|
|
if products[i].Brand != products[j].Brand {
|
||
|
|
return products[i].Brand < products[j].Brand
|
||
|
|
}
|
||
|
|
return products[i].SKU < products[j].SKU
|
||
|
|
})
|
||
|
|
return products, nil
|
||
|
|
}
|
||
|
|
|
||
|
|
func FilterProducts(products []model.Product, skuCSV string, limit int) []model.Product {
|
||
|
|
wanted := map[string]bool{}
|
||
|
|
for _, sku := range strings.Split(skuCSV, ",") {
|
||
|
|
sku = strings.TrimSpace(sku)
|
||
|
|
if sku != "" {
|
||
|
|
wanted[strings.ToLower(sku)] = true
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
out := make([]model.Product, 0, len(products))
|
||
|
|
for _, p := range products {
|
||
|
|
if len(wanted) > 0 && !wanted[strings.ToLower(p.SKU)] {
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
out = append(out, p)
|
||
|
|
if limit > 0 && len(out) >= limit {
|
||
|
|
break
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return out
|
||
|
|
}
|