package v2 import ( "encoding/json" "fmt" "net/http" "os" "path" "recipe-manager/data" "recipe-manager/models" modelsV2 "recipe-manager/models/v2" "recipe-manager/services/logger" "time" "github.com/go-chi/chi/v5" ) type recipeRouter struct { data *data.Data taoLogger *logger.TaoLogger } func NewRecipeRouter(data *data.Data, taoLogger *logger.TaoLogger) *recipeRouter { return &recipeRouter{ data: data, taoLogger: taoLogger, } } func (rr *recipeRouter) Route(r chi.Router) { r.Route("/recipes", func(r chi.Router) { r.Get("/dashboard", func(w http.ResponseWriter, r *http.Request) { w.Header().Add("Content-Type", "application/json") countryID := r.URL.Query().Get("country_id") filename := r.URL.Query().Get("filename") recipes := rr.data.GetRecipe(countryID, filename) result := make([]modelsV2.DashboardRecipe, 0, len(recipes.Recipe01)) for _, recipe := range recipes.Recipe01 { dashboardRecipe := modelsV2.DashboardRecipe{ ProductCode: recipe.ProductCode, Name: recipe.Name, NameENG: recipe.OtherName, InUse: recipe.IsUse, LastUpdated: recipe.LastChange, Image: "", } if recipe.SubMenu != nil && len(recipe.SubMenu) > 0 { dashboardRecipe.SubRecipe = make([]*modelsV2.DashboardRecipe, 0, len(recipe.SubMenu)) for _, subMenu := range recipe.SubMenu { dashboardRecipe.SubRecipe = append(dashboardRecipe.SubRecipe, &modelsV2.DashboardRecipe{ ProductCode: subMenu.ProductCode, Name: subMenu.Name, NameENG: subMenu.OtherName, InUse: subMenu.IsUse, LastUpdated: recipe.LastChange, Image: "", }) } } result = append(result, dashboardRecipe) } if err := json.NewEncoder(w).Encode(result); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } }) r.Post("/", func(w http.ResponseWriter, r *http.Request) { w.Header().Add("Content-Type", "application/json") var recipe models.Recipe if err := json.NewDecoder(r.Body).Decode(&recipe); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } countryID := r.URL.Query().Get("country_id") filename := fmt.Sprintf("coffeethai02_%d_%s.json", recipe.MachineSetting.ConfigNumber, time.Now().Format("2-1-2006_15-04-05")) // TODO: validate recipe data // recipeID, err := rr.data.CreateRecipe(recipe) // if err != nil { // http.Error(w, err.Error(), http.StatusInternalServerError) // return // } // write file to disk recipePath := path.Join("./cofffeemachineConfig", countryID, filename) _, err := os.Stat(recipePath) if os.IsNotExist(err) { file, err := os.Create(recipePath) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer file.Close() encoder := json.NewEncoder(file) encoder.SetIndent("", " ") if err := encoder.Encode(recipe); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } } else { http.Error(w, "File already exists", http.StatusInternalServerError) return } w.WriteHeader(http.StatusCreated) }) }) }