package data import ( "fmt" "log" "os" "path" "recipe-manager/helpers" "recipe-manager/models" "recipe-manager/services/logger" "strconv" "strings" "time" "reflect" "go.uber.org/zap" ) type RecipeWithTimeStamps struct { Recipe map[string]*models.Recipe TimeStamps int64 } type Data struct { CurrentFile map[string]string CurrentCountryID map[string]string DefaultCountryMap []DefaultByCountry AllRecipeFiles map[string][]helpers.RecipePath currentRecipe map[string]*models.Recipe recipeMap map[string]RecipeWithTimeStamps Countries []helpers.CountryName taoLogger *logger.TaoLogger } type DefaultByCountry struct { CountryShortName string CountryLongName string DefaultFileVersion int } var ( countries = []helpers.CountryName{{ CountryID: "tha", CountryName: "Thailand", }, { CountryID: "mys", CountryName: "Malaysia", }, { CountryID: "aus", CountryName: "Australia", }, } ) func NewData(taoLogger *logger.TaoLogger) *Data { allRecipeFiles := helpers.ScanRecipeFiles(countries) defaultFile := "coffeethai02_600.json" // TODO: read 'version' file by country // versionPath := path.Join("cofffeemachineConfig", defaultCountry, "version") // taoLogger.Log.Debug("version", zap.Any("version path", versionPath)) // // versionFile, err := os.Open(versionPath) // content, err := os.ReadFile(versionPath) // if err != nil { // taoLogger.Log.Debug("Error when open version file", zap.Error(err)) // } // initVersion := string(content) // // read latest version // // set latest to default version // latest_version, err := strconv.Atoi(initVersion) // if err != nil { // latest_version = 600 // } defaultForEachCountry := []DefaultByCountry{} for _, elem := range countries { // generate default of all countries currentVersionPath := path.Join("cofffeemachineConfig", elem.CountryID, "version") // this is default version for each country content, err := os.ReadFile(currentVersionPath) if err != nil { taoLogger.Log.Debug("Error when open version file", zap.Error(err)) } initVersion := string(content) // read latest version latest_version, _ := strconv.Atoi(initVersion) defaultForEachCountry = append(defaultForEachCountry, DefaultByCountry{CountryShortName: elem.CountryID, CountryLongName: elem.CountryName, DefaultFileVersion: latest_version}) } currentFileMap := make(map[string]string) CurrentCountryIDMap := make(map[string]string) currentDefaultFileForEachCountry := make(map[string]*models.Recipe) // all default versions as string versionsString := "" // loop default for each country for _, v := range defaultForEachCountry { for _, v2 := range allRecipeFiles[v.CountryShortName] { // extract filename as version current_version_iter, err := strconv.Atoi(strings.Split(strings.Split(v2.Name, "_")[1], ".")[0]) if err != nil { continue } if current_version_iter == v.DefaultFileVersion { currentFileMap[v.CountryShortName] = v2.Name CurrentCountryIDMap[v.CountryShortName] = v.CountryLongName versionsString = versionsString + v.CountryShortName + ":" + strconv.Itoa(current_version_iter) + "," // do read default defaultRecipe, err := helpers.ReadRecipeFile(v.CountryShortName, v2.Name) if err != nil { log.Panic("Error when read default recipe file for each country:", v.CountryShortName, err) } currentDefaultFileForEachCountry[v.CountryShortName] = defaultRecipe break } } } // for _, v := range allRecipeFiles[defaultCountry] { // // extract filename as version // current_version_iter, err := strconv.Atoi(strings.Split(strings.Split(v.Name, "_")[1], ".")[0]) // if err != nil { // continue // } // if current_version_iter == latest_version { // // taoLogger.Log.Debug("current_version_iter", zap.Any("current_version_iter", current_version_iter)) // // set latest // latest_version = current_version_iter // defaultFile = v.Name // break // } // } // FIXME: default file bug. do assign each default recipe model to each country // taoLogger.Log.Debug("defaultFile", zap.Any("defaultFile", defaultFile), zap.Any("latest_version", versionsString)) // defaultRecipe, err := helpers.ReadRecipeFile(defaultCountry, defaultFile) // if err != nil { // log.Panic("Error when read default recipe file:", err) // } return &Data{ CurrentFile: currentFileMap, CurrentCountryID: CurrentCountryIDMap, AllRecipeFiles: allRecipeFiles, currentRecipe: currentDefaultFileForEachCountry, recipeMap: map[string]RecipeWithTimeStamps{ defaultFile: { Recipe: currentDefaultFileForEachCountry, TimeStamps: time.Now().Unix(), }, }, Countries: countries, taoLogger: taoLogger, DefaultCountryMap: defaultForEachCountry, } } func (d *Data) GetRecipe(countryID, filename string) *models.Recipe { d.taoLogger.Log.Debug("invoke GetRecipe", zap.String("countryID", countryID), zap.String("filename", filename)) if countryID == "" { return d.currentRecipe["tha"] } if filename == "" || filename == d.CurrentFile[countryID] { return d.currentRecipe[countryID] } if recipe, ok := d.recipeMap[filename]; ok { d.CurrentFile[countryID] = filename // d.CurrentCountryID[countryID] = countryID return recipe.Recipe[countryID] } // change current version and read new recipe if filename == "default" { filename = d.CurrentFile[countryID] } // d.CurrentFile[countryID] = filename d.taoLogger.Log.Debug("GetRecipe", zap.String("filename", filename), zap.String("countryID", countryID)) // d.CurrentCountryID[countryID] = countryID recipe, err := helpers.ReadRecipeFile(countryID, filename) if err != nil { d.taoLogger.Log.Error("GetRecipe: Error when read recipe file, Return default recipe", zap.Error(err)) return d.currentRecipe[countryID] } d.currentRecipe[countryID] = recipe // save to map if len(d.recipeMap) > 5 { // limit keep in memory 5 version // remove oldest version var oldestVersion string var oldestTime int64 for k, v := range d.recipeMap { if oldestTime == 0 || v.TimeStamps < oldestTime { oldestTime = v.TimeStamps oldestVersion = k } } delete(d.recipeMap, oldestVersion) } d.recipeMap[filename] = RecipeWithTimeStamps{ Recipe: d.currentRecipe, TimeStamps: time.Now().Unix(), } return d.currentRecipe[countryID] } // func (d *Data) GetRecipe01() []models.Recipe01 { // return d.currentRecipe.Recipe01 // } // func (d *Data) GetCurrentRecipe() *models.Recipe { // return d.currentRecipe // } func (d *Data) GetRecipe01ByProductCode(filename, countryID, productCode string) (models.Recipe01, error) { // try convert if len(countryID) != 3 { for k, v := range d.CurrentCountryID { fmt.Println("GetRecipe01ByProductCode.Iterate", k, v, v == countryID) if v == countryID { countryID = k break } } } fmt.Println("GetRecipe01ByProductCode", filename, countryID, productCode) if !strings.Contains(filename, "tmp") { if filename == "" || filename == d.CurrentFile[countryID] { // , d.CurrentFile, countryID, "result by country id", len(d.currentRecipe[countryID].Recipe01) fmt.Println("GetRecipe01ByProductCode.ReadCurrent::filename", filename) fmt.Println("GetRecipe01ByProductCode.ReadCurrent::countryID", countryID) fmt.Println("GetRecipe01ByProductCode.ReadCurrent::CurrentFile", d.CurrentFile) fmt.Println("GetRecipe01ByProductCode.ReadCurrent::CurrentCountryID", d.CurrentCountryID) for _, v := range d.currentRecipe[countryID].Recipe01 { if v.ProductCode == productCode { return v, nil } } fmt.Println("No result in current recipe", countryID) } else if recipe, ok := d.recipeMap[filename]; ok { fmt.Println("GetRecipe01ByProductCode.ReadMap", filename, d.CurrentFile, recipe.Recipe[countryID], "countryID=", countryID) for _, v := range recipe.Recipe[countryID].Recipe01 { if v.ProductCode == productCode { d.taoLogger.Log.Debug("GetRecipe01ByProductCode.getSuccess", zap.Any("fromFile", filename), zap.Any("whereSource", d.recipeMap)) return v, nil } } d.taoLogger.Log.Debug("GetRecipe01ByProductCode.getFail", zap.Any("fromFile", filename), zap.Any("whereSource", d.recipeMap)) } } d.taoLogger.Log.Debug("GetRecipe01ByProductCode", zap.Any("filename", filename), zap.Any("countryID", countryID), zap.Any("productCode", productCode)) if filename == "default" { filename = d.CurrentFile[countryID] } // d.CurrentFile[countryID] = filename // d.CurrentCountryID[countryID] = countryID for _, v := range countries { if v.CountryName == countryID { // d.CurrentCountryID[countryID] = v.CountryID countryID = v.CountryID break } } recipe, err := helpers.ReadRecipeFile(countryID, filename) if err != nil { d.taoLogger.Log.Error("GetRecipe01ByProductCode: Error when read recipe file, Return default recipe", zap.Error(err)) for _, v := range d.currentRecipe[countryID].Recipe01 { if v.ProductCode == productCode { return v, fmt.Errorf("[DEFAULT]-ERR") } } } d.taoLogger.Log.Debug("GetRecipe01ByProductCode", zap.Any("productCode", productCode), zap.Any("version", recipe.MachineSetting.ConfigNumber)) d.currentRecipe[countryID] = recipe // save to map if len(d.recipeMap) > 5 { // limit keep in memory 5 version // remove oldest version var oldestVersion string var oldestTime int64 for k, v := range d.recipeMap { if oldestTime == 0 || v.TimeStamps < oldestTime { oldestTime = v.TimeStamps oldestVersion = k } } delete(d.recipeMap, oldestVersion) } d.recipeMap[filename] = RecipeWithTimeStamps{ Recipe: d.currentRecipe, TimeStamps: time.Now().Unix(), } for _, v := range d.currentRecipe[countryID].Recipe01 { if v.ProductCode == productCode { // d.taoLogger.Log.Debug("GetRecipe01ByProductCode", zap.Any("productCode", productCode), zap.Any("result", v)) return v, nil } } return models.Recipe01{}, fmt.Errorf("product code: %s not found", productCode) } func (d *Data) SetValuesToRecipe(base_recipe []models.Recipe01, recipe models.Recipe01) { not_found := false global_idx := 0 for index, v := range base_recipe { if v.ProductCode == recipe.ProductCode { // Log.Debug("SetValuesToRecipe", zap.Any("old", v), zap.Any("new", recipe)) // v = recipe // TODO: change only changed values // transform to map base_recipe01_Map := v.ToMap() recipe01_Map := recipe.ToMap() for k, v := range recipe01_Map { if !reflect.DeepEqual(base_recipe01_Map[k], v) { d.taoLogger.Log.Debug("SetValuesToRecipe", zap.Any("key", k), zap.Any("old", base_recipe01_Map[k]), zap.Any("new", v)) base_recipe01_Map[k] = v } } base_recipe[index] = base_recipe[index].FromMap(base_recipe01_Map) not_found = false break } else { not_found = true global_idx = index } } if not_found { base_recipe[global_idx+1] = recipe } } func (d *Data) GetMaterialSetting(countryID, filename string) []models.MaterialSetting { result := make([]models.MaterialSetting, 0) if countryID == "" { copy(result, d.currentRecipe[countryID].MaterialSetting) return result } if !strings.Contains(filename, "tmp") { if filename == "" || filename == d.CurrentFile[countryID] { // copy(result, d.currentRecipe[countryID].MaterialSetting) // d.taoLogger.Log.Debug("GetMaterialSetting", zap.Any("result", result)) return d.currentRecipe[countryID].MaterialSetting } if recipe, ok := d.recipeMap[filename]; ok { copy(result, recipe.Recipe[countryID].MaterialSetting) d.CurrentFile[countryID] = filename // d.CurrentCountryID[countryID] = countryID return d.currentRecipe[countryID].MaterialSetting } } if filename == "default" { filename = d.CurrentFile[countryID] } // d.taoLogger.Log.Debug("GetMaterialSetting", zap.Any("filename", filename), zap.Any("countryID", countryID)) // d.CurrentFile[countryID] = filename // d.CurrentCountryID[countryID] = countryID recipe, err := helpers.ReadRecipeFile(countryID, filename) if err != nil { d.taoLogger.Log.Error("GetMaterialSetting: Error when read recipe file, Return default recipe", zap.Error(err)) copy(result, d.currentRecipe[countryID].MaterialSetting) return d.currentRecipe[countryID].MaterialSetting } // d.taoLogger.Log.Debug("GetMaterialSetting", zap.Any("recipe", recipe.MaterialSetting)) d.currentRecipe[countryID] = recipe // save to map if len(d.recipeMap) > 5 { // limit keep in memory 5 version // remove oldest version var oldestVersion string var oldestTime int64 for k, v := range d.recipeMap { if oldestTime == 0 || v.TimeStamps < oldestTime { oldestTime = v.TimeStamps oldestVersion = k } } delete(d.recipeMap, oldestVersion) } d.recipeMap[filename] = RecipeWithTimeStamps{ Recipe: d.currentRecipe, TimeStamps: time.Now().Unix(), } // copy(result, recipe.MaterialSetting) return recipe.MaterialSetting } func (d *Data) GetMaterialCode(ids []uint64, countryID, filename string) []models.MaterialCode { var result []models.MaterialCode if filename == "" || filename == d.CurrentFile[countryID] { result = d.currentRecipe[countryID].MaterialCode } else if recipe, ok := d.recipeMap[filename]; ok { d.CurrentFile[countryID] = filename return recipe.Recipe[countryID].MaterialCode } else { if filename == "default" { filename = d.CurrentFile[countryID] } // d.CurrentFile[countryID] = filename // d.CurrentCountryID[countryID] = countryID recipe, err := helpers.ReadRecipeFile(countryID, filename) if err != nil { d.taoLogger.Log.Error("GetMaterialCode: Error when read recipe file, Return default recipe", zap.Error(err)) return d.currentRecipe[countryID].MaterialCode } d.currentRecipe[countryID] = recipe // save to map if len(d.recipeMap) > 5 { // limit keep in memory 5 version // remove oldest version var oldestVersion string var oldestTime int64 for k, v := range d.recipeMap { if oldestTime == 0 || v.TimeStamps < oldestTime { oldestTime = v.TimeStamps oldestVersion = k } } delete(d.recipeMap, oldestVersion) } d.recipeMap[filename] = RecipeWithTimeStamps{ Recipe: d.currentRecipe, TimeStamps: time.Now().Unix(), } result = d.currentRecipe[countryID].MaterialCode } if len(ids) == 0 { return result } resultFilter := make([]models.MaterialCode, len(ids)) for _, id := range ids { if id == 0 { continue } for _, m := range result { if m.MaterialID == id { resultFilter = append(resultFilter, m) break } } } return resultFilter } func (d *Data) GetToppings(countryID, filename string) models.Topping { if filename == "" || filename == d.CurrentFile[countryID] { return d.currentRecipe[countryID].Topping } else if recipe, ok := d.recipeMap[filename]; ok { d.CurrentFile[countryID] = filename return recipe.Recipe[countryID].Topping } if filename == "default" { filename = d.CurrentFile[countryID] } // d.CurrentFile[countryID] = filename // d.CurrentCountryID[countryID] = countryID recipe, err := helpers.ReadRecipeFile(countryID, filename) if err != nil { d.taoLogger.Log.Error("GetToppings: Error when read recipe file, Return default recipe", zap.Error(err)) return d.currentRecipe[countryID].Topping } d.currentRecipe[countryID] = recipe return recipe.Topping } func (d *Data) GetToppingsOfRecipe(countryID, filename string, productCode string) ([]models.ToppingSet, error) { if filename == "default" { filename = d.CurrentFile[countryID] } recipe, err := d.GetRecipe01ByProductCode(filename, countryID, productCode) if err != nil { d.taoLogger.Log.Error("GetToppingOfRecipe: Error when read recipe file, Return default recipe", zap.Error(err)) return []models.ToppingSet{}, err } return recipe.ToppingSet, nil } func (d *Data) GetSubmenusOfRecipe(countryID, filename, productCode string) ([]models.Recipe01, error) { if filename == "default" { filename = d.CurrentFile[countryID] } recipe, err := d.GetRecipe01ByProductCode(filename, countryID, productCode) if err != nil { d.taoLogger.Log.Error("GetSubmenusOfRecipe: Error when read recipe file, Return default recipe", zap.Error(err)) return []models.Recipe01{}, err } submenu := recipe.SubMenu if submenu == nil { return []models.Recipe01{}, fmt.Errorf("no submenu") } return submenu, nil } 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) }