add load from select save

This commit is contained in:
pakintada@gmail.com 2023-12-27 08:38:14 +07:00
parent f721517f25
commit 17030c72ce
10 changed files with 229 additions and 53 deletions

View file

@ -129,6 +129,10 @@ export class RecipeService {
return 'coffeethai02_580.json'; return 'coffeethai02_580.json';
} }
setCurrentFile(filename: string) {
localStorage.setItem('currentRecipeFile', filename);
}
getCurrentCountry(): string { getCurrentCountry(): string {
const currentRecipeCountry = localStorage.getItem('currentRecipeCountry'); const currentRecipeCountry = localStorage.getItem('currentRecipeCountry');
if (currentRecipeCountry) { if (currentRecipeCountry) {

View file

@ -122,40 +122,40 @@ export class RecipeDetailsComponent implements OnInit {
// get username // get username
let username:string = "" let username:string = ""
this._userService.currentUser.pipe(map((user) => {
if (user)
username = user.name;
let to_send = { username = this._userService.getCurrentUser()!.name;
edit_by: username,
commit_msg: this.commit_msg,
productCode: this.productCode, let to_send = {
name: this.recipeDetailForm.getRawValue().name, edit_by: username,
otherName: this.recipeDetailForm.getRawValue().otherName, commit_msg: this.commit_msg,
Description: this.recipeDetailForm.getRawValue().Description, productCode: this.productCode,
otherDescription: this.recipeDetailForm.getRawValue().otherDescription, name: this.recipeDetailForm.getRawValue().name != this.recipeOriginalDetail.name ? this.recipeDetailForm.getRawValue().name : this.recipeOriginalDetail.name,
LastChange: this.recipeDetailForm.getRawValue().lastModified, otherName: this.recipeDetailForm.getRawValue().otherName != this.recipeOriginalDetail.otherName ? this.recipeDetailForm.getRawValue().otherName : this.recipeOriginalDetail.otherName,
price: this.recipeDetailForm.getRawValue().price, Description: this.recipeDetailForm.getRawValue().Description != this.recipeOriginalDetail.Description ? this.recipeDetailForm.getRawValue().Description : this.recipeOriginalDetail.Description,
// isUse: this, otherDescription: this.recipeDetailForm.getRawValue().otherDescription != this.recipeOriginalDetail.otherDescription ? this.recipeDetailForm.getRawValue().otherDescription : this.recipeOriginalDetail.otherDescription,
// isShow: null, LastChange: this.recipeDetailForm.getRawValue().lastModified != this.recipeOriginalDetail.lastModified ? this.recipeDetailForm.getRawValue().lastModified : this.recipeOriginalDetail.lastModified,
// disable: null, price: this.recipeDetailForm.getRawValue().price != this.recipeOriginalDetail.price ? this.recipeDetailForm.getRawValue().price : this.recipeOriginalDetail.price,
recipes: [ // isUse: this,
...this.repl // isShow: null,
], // disable: null,
recipes: [
...(this.repl.length <= 0 ? [] : this.repl)
],
}
// TODO: update value in targeted recipe
console.log('to_send', to_send);
this._recipeService.editChanges(
this._recipeService.getCurrentCountry(),
this._recipeService.getCurrentFile(),
{
...to_send,
} }
);
console.log('Sending changes');
// TODO: update value in targeted recipe void this._router.navigate(['/'+this.department+'/recipes']);
this._recipeService.editChanges(
this._recipeService.getCurrentCountry(),
this._recipeService.getCurrentFile(),
{
...to_send,
}
);
console.log('Sending changes');
void this._router.navigate(['/'+this.department+'/recipes']);
}))
@ -194,11 +194,11 @@ export class RecipeDetailsComponent implements OnInit {
isValueChanged: boolean = false; isValueChanged: boolean = false;
onRecipeDetailFormChange(recipeDetail: typeof this.recipeDetailForm.value) { onRecipeDetailFormChange(recipeDetail: typeof this.recipeDetailForm.value) {
console.log('Recipe Detail Form Changed', recipeDetail); // console.log('Recipe Detail Form Changed', recipeDetail);
} }
onRecipeListFormChange(repl: unknown[]) { onRecipeListFormChange(repl: unknown[]) {
console.log('Recipe List Form Changed', repl); // console.log('Recipe List Form Changed', repl);
this.repl = repl as never[]; this.repl = repl as never[];
this.isValueChanged ||= repl != undefined; this.isValueChanged ||= repl != undefined;
} }

View file

@ -72,8 +72,8 @@ export class RecipeListComponent implements OnInit {
}); });
this.recipeListForm.valueChanges.subscribe((value) => { this.recipeListForm.valueChanges.subscribe((value) => {
console.log(value.recipeListData); // console.log(value.recipeListData);
console.log(this._recipeListOriginalArray); // console.log(this._recipeListOriginalArray);
if ( if (
!isEqual( !isEqual(
sortBy(value, 'materialID'), sortBy(value, 'materialID'),

View file

@ -150,7 +150,7 @@
<td>{{ file.Msg }}</td> <td>{{ file.Msg }}</td>
<td>{{ file.Editor }}</td> <td>{{ file.Editor }}</td>
<td>{{ file.Created_at }}</td> <td>{{ file.Created_at }}</td>
<button class="btn bg-blue-400">Select</button> <button class="btn bg-blue-400" (click)="loadSavedFile(file)">Select</button>
</tr> </tr>
</table> </table>
</div> </div>

View file

@ -154,8 +154,12 @@ export class RecipesComponent implements OnInit, OnDestroy {
next: (files:any) => { next: (files:any) => {
console.log("Obtain saves: ", typeof files, files); console.log("Obtain saves: ", typeof files, files);
if(files != undefined && typeof files === 'object'){ if(files != undefined && typeof files === 'object'){
// console.log("Obtain saves object: ", files.files[0], typeof files); if(files.files != null){
this.savedTmpfiles = files.files; console.log("Obtain saves object: ", files.files[0], typeof files);
this.savedTmpfiles = files.files;
} else {
this.showSaveNoti = false;
}
// let svf = (document.getElementById('select_savefile_modal') as HTMLInputElement)!.checked; // let svf = (document.getElementById('select_savefile_modal') as HTMLInputElement)!.checked;
// console.log("isSavedModalOpened",svf) // console.log("isSavedModalOpened",svf)
} }
@ -384,6 +388,44 @@ export class RecipesComponent implements OnInit, OnDestroy {
this.saveTab = true; this.saveTab = true;
} }
loadSavedFile(file_commit: any) {
this.showSaveNoti = false;
this.saveTab = false;
console.log('loadSavedFile', file_commit, this.department);
let country = this.department!;
switch(country){
case "tha":
country = "Thailand";
break;
case "aus":
country = "Australia";
break;
case "mys":
country = "Malaysia";
break;
case "alpha-3":
country = "alpha-3";
break;
}
console.log(file_commit.Change_file.split("/")[2]);
this._recipeService
.getRecipeOverview({
offset: this.offset,
take: this.take,
search: this.oldSearchStr,
filename: file_commit.Change_file.split("/")[2],
country: country,
materialIds: this.selectMaterialFilter || [],
}).subscribe(({ result, hasMore, totalCount }) => {
console.log('loadSavedFile', result);
this._recipeService.setCurrentFile(file_commit.Change_file.split("/")[2]);
});
}
ngOnDestroy(): void { ngOnDestroy(): void {
if (this.currentCountryFilterSubScription) { if (this.currentCountryFilterSubScription) {
this.currentCountryFilterSubScription.unsubscribe(); this.currentCountryFilterSubScription.unsubscribe();

View file

@ -88,6 +88,11 @@ func GetCommitLogOfFilename(countryId string, filename string) ([]CommitLog, err
for _, v := range commits { for _, v := range commits {
if strings.Contains(v.Change_file, countryId) { if strings.Contains(v.Change_file, countryId) {
// do convert time format
v.Created_at = strings.Replace(v.Created_at, "T", " ", -1)
v.Created_at = strings.Replace(v.Created_at, "Z", "", -1)
commitsByCountryID = append(commitsByCountryID, v) commitsByCountryID = append(commitsByCountryID, v)
} }
} }

View file

@ -8,6 +8,8 @@ import (
"recipe-manager/services/logger" "recipe-manager/services/logger"
"time" "time"
"reflect"
"go.uber.org/zap" "go.uber.org/zap"
) )
@ -84,6 +86,7 @@ func (d *Data) GetRecipe(countryID, filename string) *models.Recipe {
// change current version and read new recipe // change current version and read new recipe
d.CurrentFile = filename d.CurrentFile = filename
d.taoLogger.Log.Debug("GetRecipe", zap.String("filename", filename), zap.String("countryID", countryID))
d.CurrentCountryID = countryID d.CurrentCountryID = countryID
recipe, err := helpers.ReadRecipeFile(countryID, filename) recipe, err := helpers.ReadRecipeFile(countryID, filename)
@ -183,15 +186,41 @@ func (d *Data) GetRecipe01ByProductCode(filename, countryID, productCode string)
return models.Recipe01{}, fmt.Errorf("product code: %s not found", productCode) return models.Recipe01{}, fmt.Errorf("product code: %s not found", productCode)
} }
func (d *Data) SetValuesToRecipe(recipe models.Recipe01) { // FIXME: saved in log but not actual file
for index, v := range d.currentRecipe.Recipe01 { 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 { if v.ProductCode == recipe.ProductCode {
// Log.Debug("SetValuesToRecipe", zap.Any("old", v), zap.Any("new", recipe)) // Log.Debug("SetValuesToRecipe", zap.Any("old", v), zap.Any("new", recipe))
// v = recipe // v = recipe
d.currentRecipe.Recipe01[index] = 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("value", v), zap.Any("old", base_recipe01_Map[k]), zap.Any("new", recipe01_Map[k]))
base_recipe01_Map[k] = v
}
}
base_recipe[index] = base_recipe[index].FromMap(base_recipe01_Map)
not_found = false
break 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 { func (d *Data) GetMaterialSetting(countryID, filename string) []models.MaterialSetting {

Binary file not shown.

View file

@ -77,7 +77,7 @@ func DynamicCompare(s interface{}, u interface{}) (bool, error) {
} }
if u == nil { if u == nil {
return false, fmt.Errorf("[empty] the compared value is nil") return false, fmt.Errorf("[empty] the compared value is nil while t is %T", s)
} }
return false, fmt.Errorf("[unknown] unexpected error. [old] %v and [new] %v", s, u) return false, fmt.Errorf("[unknown] unexpected error. [old] %v and [new] %v", s, u)

View file

@ -57,6 +57,8 @@ func (rr *RecipeRouter) Route(r chi.Router) {
r.Post("/edit/{country}/{filename}", rr.updateRecipe) r.Post("/edit/{country}/{filename}", rr.updateRecipe)
r.Post("/upgrade/{country}/{filename}", rr.ApplyTmpChanges)
r.Get("/saved/{country}/{filename_version_only}", rr.getSavedRecipes) r.Get("/saved/{country}/{filename_version_only}", rr.getSavedRecipes)
r.Get("/countries", func(w http.ResponseWriter, r *http.Request) { r.Get("/countries", func(w http.ResponseWriter, r *http.Request) {
@ -347,16 +349,16 @@ func (rr *RecipeRouter) updateRecipe(w http.ResponseWriter, r *http.Request) {
// Find changes // Find changes
for key, val := range menuMap { for key, val := range menuMap {
// rr.taoLogger.Log.Debug("..DynamicCompare.key", zap.Any("key", key))
testBool, err := helpers.DynamicCompare(val, changeMap[key]) testBool, err := helpers.DynamicCompare(val, changeMap[key])
if err != nil { // if err != nil {
rr.taoLogger.Log.Error("RecipeRouter.UpdateRecipe", zap.Error(errors.WithMessage(err, "DynamicCompare in request failed"))) // rr.taoLogger.Log.Error("RecipeRouter.UpdateRecipe", zap.Error(errors.WithMessage(err, "DynamicCompare in request failed")))
http.Error(w, "Internal Error", http.StatusInternalServerError) // http.Error(w, "Internal Error", http.StatusInternalServerError)
return // return
} // }
if !testBool { if !testBool && err == nil {
menuMap[key] = changeMap[key] menuMap[key] = changeMap[key]
} }
} }
@ -364,7 +366,7 @@ func (rr *RecipeRouter) updateRecipe(w http.ResponseWriter, r *http.Request) {
// Apply changes // Apply changes
tempRecipe := models.Recipe01{} tempRecipe := models.Recipe01{}
tempRecipe = tempRecipe.FromMap(menuMap) tempRecipe = tempRecipe.FromMap(menuMap)
rr.data.SetValuesToRecipe(tempRecipe) rr.data.SetValuesToRecipe(targetRecipe.Recipe01, tempRecipe)
rr.taoLogger.Log.Debug("ApplyChange", zap.Any("status", "passed")) rr.taoLogger.Log.Debug("ApplyChange", zap.Any("status", "passed"))
// check if changed // check if changed
@ -385,7 +387,7 @@ func (rr *RecipeRouter) updateRecipe(w http.ResponseWriter, r *http.Request) {
Id: commit_hash, Id: commit_hash,
Msg: commit_msg, Msg: commit_msg,
Created_at: time.Now().Format("2006-01-02 15:04:05"), Created_at: time.Now().Local().Format("2006-01-02 15:04:05"),
Editor: editor, Editor: editor,
Change_file: temp_file_name, Change_file: temp_file_name,
} }
@ -401,7 +403,11 @@ func (rr *RecipeRouter) updateRecipe(w http.ResponseWriter, r *http.Request) {
encoder := json.NewEncoder(file) encoder := json.NewEncoder(file)
encoder.SetIndent("", " ") encoder.SetIndent("", " ")
err = encoder.Encode(rr.data.GetRecipe(countryID, filename)) // full
err = encoder.Encode(targetRecipe)
// partial
// err = encoder.Encode(changes)
if err != nil { if err != nil {
rr.taoLogger.Log.Error("RecipeRouter.UpdateRecipe", zap.Error(errors.WithMessage(err, "Error when write file"))) rr.taoLogger.Log.Error("RecipeRouter.UpdateRecipe", zap.Error(errors.WithMessage(err, "Error when write file")))
@ -429,6 +435,8 @@ func (rr *RecipeRouter) getSavedRecipes(w http.ResponseWriter, r *http.Request)
commits, err := data.GetCommitLogOfFilename(countryID, file_version) commits, err := data.GetCommitLogOfFilename(countryID, file_version)
rr.taoLogger.Log.Debug("RecipeRouter.getSavedRecipes", zap.Any("commits", commits))
if err != nil { if err != nil {
return return
@ -440,6 +448,94 @@ func (rr *RecipeRouter) getSavedRecipes(w http.ResponseWriter, r *http.Request)
json.NewEncoder(w).Encode(map[string]interface{}{"files": commits}) json.NewEncoder(w).Encode(map[string]interface{}{"files": commits})
} }
func (rr *RecipeRouter) ApplyTmpChanges(w http.ResponseWriter, r *http.Request) {
filename := chi.URLParam(r, "filename")
country := chi.URLParam(r, "country")
countryID, err := rr.data.GetCountryIDByName(country)
if err != nil {
rr.taoLogger.Log.Error("RecipeRouter.UpdateRecipe", zap.Error(err))
http.Error(w, fmt.Sprintf("Country Name: %s not found!!!", country), http.StatusNotFound)
return
}
var legit_changes map[string]interface{}
target_recipe := rr.data.GetRecipe(countryID, filename)
new_file_version := target_recipe.MachineSetting.ConfigNumber + 1
show_to_current := legit_changes["no_upgrade"].(bool)
if show_to_current {
new_file_version = target_recipe.MachineSetting.ConfigNumber
}
err = json.NewDecoder(r.Body).Decode(&legit_changes)
if err != nil {
rr.taoLogger.Log.Error("ApplyErr", zap.Any("err", err))
return
}
user_selected_tmp := legit_changes["selected_files"].([]string)
for select_tmp := range user_selected_tmp {
// open selected
current_temp_file, err := os.ReadFile(user_selected_tmp[select_tmp])
if err != nil {
rr.taoLogger.Log.Error("TmpFile", zap.Any("Open", "tried to open but failed => "+user_selected_tmp[select_tmp]))
continue
}
// load to model
temp_recipe := models.Recipe01{}
json.Unmarshal(current_temp_file, &temp_recipe)
// apply set value
rr.data.SetValuesToRecipe(target_recipe.Recipe01, temp_recipe)
rr.taoLogger.Log.Debug("ApplyTmpChanges", zap.Any("Update|Push", string(rune(temp_recipe.ID))+":"+temp_recipe.ProductCode))
}
// export
exported_filename := "coffeethai02_" + string(rune(new_file_version))
if countryID != "tha" {
exported_filename += "_" + countryID
}
exported_filename += ".json"
full_exported_path := "cofffeemachineConfig/" + countryID + "/" + exported_filename
outfile, _ := os.Create(full_exported_path)
target_recipe.MachineSetting.ConfigNumber = new_file_version
encoder := json.NewEncoder(outfile)
encoder.SetIndent("", " ")
err = encoder.Encode(target_recipe)
if err != nil {
rr.taoLogger.Log.Error("UpgradeToFullRecipeFailed", zap.Any("File", err))
http.Error(w, "Internal Error", http.StatusInternalServerError)
return
}
w.Header().Add("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"status": "OK",
"version": new_file_version,
"path": full_exported_path,
})
delete_files := legit_changes["del_after_upgrade"].(bool)
if delete_files && !show_to_current {
for seleted_file := range user_selected_tmp {
os.Remove(user_selected_tmp[seleted_file])
}
}
}
func (rr *RecipeRouter) doMergeJson(w http.ResponseWriter, r *http.Request) { func (rr *RecipeRouter) doMergeJson(w http.ResponseWriter, r *http.Request) {
// TODO: v2, change to binary instead // TODO: v2, change to binary instead
if !binaryAPIhandler(w, r) { if !binaryAPIhandler(w, r) {