add file select for multiple country

This commit is contained in:
Kenta420 2023-10-20 17:05:24 +07:00
parent e5eee656d5
commit 652ecbbf1f
9 changed files with 294 additions and 47 deletions

View file

@ -2,11 +2,12 @@ package data
import (
"encoding/json"
"fmt"
"log"
"os"
"path/filepath"
"recipe-manager/helpers"
"recipe-manager/models"
"sort"
"time"
)
@ -40,44 +41,34 @@ type RecipeWithTimeStamps struct {
type Data struct {
CurrentVersion string
AllVersions []string
AllRecipeFiles map[string][]helpers.RecipePath
currentRecipe *models.Recipe
recipeMap map[string]RecipeWithTimeStamps
Countries []helpers.CountryName
}
func NewData() *Data {
files, err := filepath.Glob("cofffeemachineConfig/coffeethai02_*.json")
if err != nil {
log.Panic("Error when scan recipe files:", err)
countries := []helpers.CountryName{{
CountryID: "thai",
CountryName: "Thailand",
}, {
CountryID: "mys",
CountryName: "Malaysia",
}, {
CountryID: "aus",
CountryName: "Australia",
},
}
sort.Slice(files, func(i, j int) bool {
file1, err := os.Stat(files[i])
if err != nil {
log.Panic("Error when get file info:", err)
}
file2, err := os.Stat(files[j])
if err != nil {
log.Panic("Error when get file info:", err)
}
return file1.ModTime().After(file2.ModTime())
})
for i := 0; i < len(files); i++ {
files[i] = filepath.Base(files[i])
}
allRecipeFiles := helpers.ScanRecipeFiles(countries)
defaultVersion := "coffeethai02_580.json"
defaultRecipe := readFile(defaultVersion)
return &Data{
CurrentVersion: defaultVersion,
AllVersions: files,
AllRecipeFiles: allRecipeFiles,
currentRecipe: defaultRecipe,
recipeMap: map[string]RecipeWithTimeStamps{
defaultVersion: {
@ -85,6 +76,7 @@ func NewData() *Data {
TimeStamps: time.Now().Unix(),
},
},
Countries: countries,
}
}
@ -225,3 +217,21 @@ func (d *Data) GetMaterialCode(ids []uint64, version string) []models.MaterialCo
return resultFilter
}
func (d *Data) GetCountryNameByID(countryID string) (string, error) {
for _, country := range d.Countries {
if country.CountryID == countryID {
return country.CountryName, nil
}
}
return "", fmt.Errorf("country ID: %s not found", countryID)
}
func (d *Data) GetCountryIDByName(countryName string) (string, error) {
for _, country := range d.Countries {
if country.CountryName == countryName {
return country.CountryID, nil
}
}
return "", fmt.Errorf("country name: %s not found", countryName)
}