change save file method, add file changes history
This commit is contained in:
parent
519749fd3a
commit
820557a268
12 changed files with 2388 additions and 2036 deletions
|
|
@ -72,7 +72,7 @@
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
class="input input-sm input-bordered input-ghost w-full"
|
class="input input-sm input-bordered input-ghost w-full"
|
||||||
formControlName="description"
|
formControlName="Description"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex items-center">
|
<div class="flex items-center">
|
||||||
|
|
@ -291,8 +291,11 @@
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
class="sticky bottom-0 col-span-3 flex justify-end bg-white rounded-full drop-shadow-2xl p-3"
|
class="sticky bottom-0 col-span-3 flex justify-end bg-white rounded-full drop-shadow-2xl p-3"
|
||||||
>
|
>
|
||||||
|
<!-- <div> Commit Message </div> -->
|
||||||
|
<!-- <p class="text-2xl mr-8 text-gray-400 dark:text-gray-500">Commit Message</p> -->
|
||||||
|
<input type="text" name="commit-message" id="commit-message" placeholder="Commit Message" class="input input-bordered mr-8 w-full max-w-xs" [value]="productCode" (keyup)="onKeyUpCommitMsg($event)"/>
|
||||||
<button
|
<button
|
||||||
(click)="onPressConfirmClose()"
|
(click)="onPressConfirmClose()"
|
||||||
class="btn btn-error w-36 text-white mr-2"
|
class="btn btn-error w-36 text-white mr-2"
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,7 @@ import {
|
||||||
} from 'src/app/core/models/recipe.model';
|
} from 'src/app/core/models/recipe.model';
|
||||||
import { Action, ActionRecord } from 'src/app/shared/actionRecord/actionRecord';
|
import { Action, ActionRecord } from 'src/app/shared/actionRecord/actionRecord';
|
||||||
import { isEqual } from 'lodash';
|
import { isEqual } from 'lodash';
|
||||||
|
import { UserService } from 'src/app/core/services/user.service';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-recipe-details',
|
selector: 'app-recipe-details',
|
||||||
|
|
@ -48,11 +49,14 @@ export class RecipeDetailsComponent implements OnInit {
|
||||||
|
|
||||||
recipeOriginalDetail!: typeof this.recipeDetailForm.value;
|
recipeOriginalDetail!: typeof this.recipeDetailForm.value;
|
||||||
|
|
||||||
|
commit_msg :string = "";
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private _formBuilder: FormBuilder,
|
private _formBuilder: FormBuilder,
|
||||||
private _route: ActivatedRoute,
|
private _route: ActivatedRoute,
|
||||||
private _router: Router,
|
private _router: Router,
|
||||||
private _recipeService: RecipeService
|
private _recipeService: RecipeService,
|
||||||
|
private _userService: UserService
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
productCode!: string;
|
productCode!: string;
|
||||||
|
|
@ -61,7 +65,7 @@ export class RecipeDetailsComponent implements OnInit {
|
||||||
productCode: '',
|
productCode: '',
|
||||||
name: '',
|
name: '',
|
||||||
otherName: '',
|
otherName: '',
|
||||||
description: '',
|
Description: '',
|
||||||
otherDescription: '',
|
otherDescription: '',
|
||||||
lastModified: new Date(),
|
lastModified: new Date(),
|
||||||
price: 0,
|
price: 0,
|
||||||
|
|
@ -70,6 +74,8 @@ export class RecipeDetailsComponent implements OnInit {
|
||||||
disable: false,
|
disable: false,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
repl = []
|
||||||
|
|
||||||
ngOnInit() {
|
ngOnInit() {
|
||||||
this.productCode = this._route.snapshot.params['productCode'];
|
this.productCode = this._route.snapshot.params['productCode'];
|
||||||
|
|
||||||
|
|
@ -77,6 +83,9 @@ export class RecipeDetailsComponent implements OnInit {
|
||||||
.getRecipeDetail(this.productCode)
|
.getRecipeDetail(this.productCode)
|
||||||
.pipe(first());
|
.pipe(first());
|
||||||
this.recipeDetail$.subscribe((detail) => {
|
this.recipeDetail$.subscribe((detail) => {
|
||||||
|
|
||||||
|
console.log('Recipe Detail', detail);
|
||||||
|
|
||||||
this.recipeDetailForm.patchValue(detail);
|
this.recipeDetailForm.patchValue(detail);
|
||||||
this.isLoaded = true;
|
this.isLoaded = true;
|
||||||
this.recipeOriginalDetail = { ...this.recipeDetailForm.getRawValue() };
|
this.recipeOriginalDetail = { ...this.recipeDetailForm.getRawValue() };
|
||||||
|
|
@ -107,19 +116,54 @@ export class RecipeDetailsComponent implements OnInit {
|
||||||
message: 'Do you want to save changes?',
|
message: 'Do you want to save changes?',
|
||||||
confirmCallBack: () => {
|
confirmCallBack: () => {
|
||||||
console.log('confirm save');
|
console.log('confirm save');
|
||||||
// TODO: update value in targeted recipe
|
|
||||||
// this._recipeService.editChanges(
|
// get username
|
||||||
// this._recipeService.getCurrentCountry(),
|
let username:string = ""
|
||||||
// this._recipeService.getCurrentFile(),
|
this._userService.getCurrentUser().subscribe((user) => {
|
||||||
// {
|
username = user.user.name;
|
||||||
// ...this.recipeDetail,
|
|
||||||
// }
|
|
||||||
// );
|
|
||||||
console.log('Sending changes');
|
let to_send = {
|
||||||
this._router.navigate(['/recipes']);
|
edit_by: username,
|
||||||
|
commit_msg: this.commit_msg,
|
||||||
|
productCode: this.productCode,
|
||||||
|
name: this.recipeDetailForm.getRawValue().name,
|
||||||
|
otherName: this.recipeDetailForm.getRawValue().otherName,
|
||||||
|
Description: this.recipeDetailForm.getRawValue().Description,
|
||||||
|
otherDescription: this.recipeDetailForm.getRawValue().otherDescription,
|
||||||
|
LastChange: this.recipeDetailForm.getRawValue().lastModified,
|
||||||
|
price: this.recipeDetailForm.getRawValue().price,
|
||||||
|
// isUse: this,
|
||||||
|
// isShow: null,
|
||||||
|
// disable: null,
|
||||||
|
recipes: [
|
||||||
|
...this.repl
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// TODO: update value in targeted recipe
|
||||||
|
this._recipeService.editChanges(
|
||||||
|
this._recipeService.getCurrentCountry(),
|
||||||
|
this._recipeService.getCurrentFile(),
|
||||||
|
{
|
||||||
|
...to_send,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
console.log('Sending changes');
|
||||||
|
this._router.navigate(['/recipes']);
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
onKeyUpCommitMsg(e: any){
|
||||||
|
this.commit_msg = e.target.value;
|
||||||
|
}
|
||||||
|
|
||||||
confirmClose = {
|
confirmClose = {
|
||||||
title: 'The changes will be lost!',
|
title: 'The changes will be lost!',
|
||||||
message: 'Do you want to close without saving?',
|
message: 'Do you want to close without saving?',
|
||||||
|
|
@ -151,8 +195,9 @@ export class RecipeDetailsComponent implements OnInit {
|
||||||
console.log('Recipe Detail Form Changed', recipeDetail);
|
console.log('Recipe Detail Form Changed', recipeDetail);
|
||||||
}
|
}
|
||||||
|
|
||||||
onRecipeListFormChange(isValueChanged: boolean) {
|
onRecipeListFormChange(repl: unknown[]) {
|
||||||
console.log('Recipe List Form Changed', isValueChanged);
|
console.log('Recipe List Form Changed', repl);
|
||||||
this.isValueChanged ||= isValueChanged;
|
this.repl = repl as never[];
|
||||||
|
this.isValueChanged ||= repl != undefined ? true : false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -23,7 +23,7 @@
|
||||||
<input type="checkbox" class="toggle" formControlName="isUse" />
|
<input type="checkbox" class="toggle" formControlName="isUse" />
|
||||||
</td>
|
</td>
|
||||||
<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap">
|
<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap">
|
||||||
<input type="text" class="input" formControlName="materialID" />
|
<input type="text" class="input" formControlName="materialPathId" />
|
||||||
</td>
|
</td>
|
||||||
<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap">
|
<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap">
|
||||||
<input type="text" class="input" formControlName="name" />
|
<input type="text" class="input" formControlName="name" />
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@ import {
|
||||||
FormGroup,
|
FormGroup,
|
||||||
ReactiveFormsModule,
|
ReactiveFormsModule,
|
||||||
} from '@angular/forms';
|
} from '@angular/forms';
|
||||||
import { isEqual, sortBy } from 'lodash';
|
import { forEach, isEqual, sortBy } from 'lodash';
|
||||||
import { first } from 'rxjs';
|
import { first } from 'rxjs';
|
||||||
import {
|
import {
|
||||||
RecipeDetail,
|
RecipeDetail,
|
||||||
|
|
@ -24,7 +24,7 @@ import { Action, ActionRecord } from 'src/app/shared/actionRecord/actionRecord';
|
||||||
})
|
})
|
||||||
export class RecipeListComponent implements OnInit {
|
export class RecipeListComponent implements OnInit {
|
||||||
@Input({ required: true }) productCode!: string;
|
@Input({ required: true }) productCode!: string;
|
||||||
@Output() recipeListFormChange = new EventEmitter<boolean>();
|
@Output() recipeListFormChange = new EventEmitter<unknown[]>();
|
||||||
|
|
||||||
isMatLoaded: boolean = false;
|
isMatLoaded: boolean = false;
|
||||||
|
|
||||||
|
|
@ -52,7 +52,7 @@ export class RecipeListComponent implements OnInit {
|
||||||
this.recipeListData.push(
|
this.recipeListData.push(
|
||||||
this._formBuilder.group({
|
this._formBuilder.group({
|
||||||
isUse: recipeDetailMat.isUse,
|
isUse: recipeDetailMat.isUse,
|
||||||
materialID: recipeDetailMat.materialID,
|
materialPathId: recipeDetailMat.materialPathId,
|
||||||
name: [{ value: recipeDetailMat.name, disabled: true }],
|
name: [{ value: recipeDetailMat.name, disabled: true }],
|
||||||
mixOrder: recipeDetailMat.mixOrder,
|
mixOrder: recipeDetailMat.mixOrder,
|
||||||
stirTime: recipeDetailMat.stirTime,
|
stirTime: recipeDetailMat.stirTime,
|
||||||
|
|
@ -77,10 +77,22 @@ export class RecipeListComponent implements OnInit {
|
||||||
sortBy(this._recipeListOriginalArray, 'materialID')
|
sortBy(this._recipeListOriginalArray, 'materialID')
|
||||||
)
|
)
|
||||||
) {
|
) {
|
||||||
this.recipeListFormChange.emit(true);
|
|
||||||
|
let emitted_res: any[] = []
|
||||||
|
|
||||||
|
// force type change. temporary solution
|
||||||
|
forEach(value.recipeListData!, (recipeDetailMat: any) => {
|
||||||
|
recipeDetailMat.materialPathId = parseInt(recipeDetailMat.materialPathId!)
|
||||||
|
emitted_res.push(recipeDetailMat)
|
||||||
|
})
|
||||||
|
|
||||||
|
this.recipeListFormChange.emit(emitted_res as unknown[]);
|
||||||
} else {
|
} else {
|
||||||
this.recipeListFormChange.emit(false);
|
this.recipeListFormChange.emit([]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -106,6 +106,36 @@
|
||||||
</div>
|
</div>
|
||||||
</div> -->
|
</div> -->
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<button class="btn bg-primary btn-md border-2" *ngIf="savedTmpfiles.length > 0">
|
||||||
|
<span class="text-base text-gray-700" onclick="select_savefile_modal.showModal()">โหลดเซฟ</span>
|
||||||
|
</button>
|
||||||
|
<!-- todo: add modal -->
|
||||||
|
<dialog id="select_savefile_modal" class="modal">
|
||||||
|
<div class="modal-box max-w-[600px] overflow-visible">
|
||||||
|
<p class="font-bold text-lg m-2">Saved Files</p>
|
||||||
|
<table class="table">
|
||||||
|
<tr class="bg-primary ">
|
||||||
|
<th>Name</th>
|
||||||
|
<th>Comment</th>
|
||||||
|
<!-- <th></th> -->
|
||||||
|
</tr>
|
||||||
|
<tr class="row hover:bg-secondary" *ngFor="let file of savedTmpfiles">
|
||||||
|
<td>{{ file }}</td>
|
||||||
|
<td>"-"</td>
|
||||||
|
<button class="btn bg-blue-400">Select</button>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
<form method="dialog" class="modal-backdrop">
|
||||||
|
<button>close</button>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
|
|
||||||
|
|
||||||
<div class="flex flex-col ml-auto">
|
<div class="flex flex-col ml-auto">
|
||||||
<span class=""
|
<span class=""
|
||||||
>Last Updated:
|
>Last Updated:
|
||||||
|
|
@ -168,6 +198,7 @@
|
||||||
</svg>
|
</svg>
|
||||||
Export
|
Export
|
||||||
</button>
|
</button>
|
||||||
|
<button class="btn rounded-lg"> Upgrade to {{ recipesDashboard.configNumber + 1 }}</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -278,11 +309,4 @@
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</ng-template>
|
</ng-template>
|
||||||
|
|
||||||
<button
|
|
||||||
class="btn btn-circle fixed z-100 bottom-5 right-1"
|
|
||||||
(click)="scrollToTop()"
|
|
||||||
>
|
|
||||||
^
|
|
||||||
</button>
|
|
||||||
</main>
|
</main>
|
||||||
|
|
|
||||||
|
|
@ -65,6 +65,8 @@ export class RecipesComponent implements OnInit, OnDestroy {
|
||||||
private searchStr = '';
|
private searchStr = '';
|
||||||
private oldSearchStr = '';
|
private oldSearchStr = '';
|
||||||
|
|
||||||
|
savedTmpfiles: string[] = [];
|
||||||
|
|
||||||
tableCtx?: ElementRef;
|
tableCtx?: ElementRef;
|
||||||
|
|
||||||
@ViewChild('table', { static: false }) set content(table: ElementRef) {
|
@ViewChild('table', { static: false }) set content(table: ElementRef) {
|
||||||
|
|
@ -139,6 +141,20 @@ export class RecipesComponent implements OnInit, OnDestroy {
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
|
this._recipeService.getSavedTmp(
|
||||||
|
this._recipeService.getCurrentCountry(),
|
||||||
|
this._recipeService.getCurrentFile()
|
||||||
|
).subscribe({
|
||||||
|
next: (files:any) => {
|
||||||
|
console.log("Obtain saves: ", typeof files);
|
||||||
|
if(files != undefined && typeof files === 'object'){
|
||||||
|
// console.log("Obtain saves object: ", files.files[0], typeof files);
|
||||||
|
this.savedTmpfiles = files.files;
|
||||||
|
}
|
||||||
|
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
this._materialService
|
this._materialService
|
||||||
.getMaterialCodes()
|
.getMaterialCodes()
|
||||||
.pipe(
|
.pipe(
|
||||||
|
|
@ -319,6 +335,11 @@ export class RecipesComponent implements OnInit, OnDestroy {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// get tmp files
|
||||||
|
openTmpFilesList(){
|
||||||
|
// TODO: get tmp files to display or
|
||||||
|
}
|
||||||
|
|
||||||
scrollToTop() {
|
scrollToTop() {
|
||||||
const table = this.tableCtx!.nativeElement;
|
const table = this.tableCtx!.nativeElement;
|
||||||
table.scrollTo({ top: 0, behavior: 'smooth' });
|
table.scrollTo({ top: 0, behavior: 'smooth' });
|
||||||
|
|
|
||||||
82
server/data/commit.go
Normal file
82
server/data/commit.go
Normal file
|
|
@ -0,0 +1,82 @@
|
||||||
|
package data
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/jmoiron/sqlx"
|
||||||
|
_ "github.com/mattn/go-sqlite3"
|
||||||
|
"go.uber.org/zap"
|
||||||
|
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/hex"
|
||||||
|
)
|
||||||
|
|
||||||
|
var schema = `
|
||||||
|
CREATE TABLE IF NOT EXISTS commit_log (
|
||||||
|
id VARCHAR(255) PRIMARY KEY,
|
||||||
|
msg VARCHAR(255),
|
||||||
|
created_at DATETIME,
|
||||||
|
editor VARCHAR(255),
|
||||||
|
change_file VARCHAR(255)
|
||||||
|
);
|
||||||
|
`
|
||||||
|
|
||||||
|
type CommitLog struct {
|
||||||
|
Id string `db:"id"`
|
||||||
|
Msg string `db:"msg"`
|
||||||
|
Created_at string `db:"created_at"`
|
||||||
|
Editor string `db:"editor"`
|
||||||
|
Change_file string `db:"change_file"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func HashCommit(n int) (string, error) {
|
||||||
|
// _, err := h.Write([]byte(target))
|
||||||
|
// if err != nil {
|
||||||
|
// Log.Debug("Error when hashing commit", zap.Error(err))
|
||||||
|
// return "", err
|
||||||
|
// }
|
||||||
|
// return string(h.Sum(nil)), nil
|
||||||
|
byt := make([]byte, n)
|
||||||
|
_, err := rand.Read(byt)
|
||||||
|
if err != nil {
|
||||||
|
Log.Debug("Error when hashing commit", zap.Error(err))
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return hex.EncodeToString(byt), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func Insert(c *CommitLog) error {
|
||||||
|
commit_db, err := sqlx.Connect("sqlite3", "./data/database.db")
|
||||||
|
if err != nil {
|
||||||
|
Log.Fatal("Error when connecting to database", zap.Error(err))
|
||||||
|
}
|
||||||
|
// init table in db
|
||||||
|
commit_db.MustExec(schema)
|
||||||
|
|
||||||
|
_, err = commit_db.NamedExec("INSERT INTO commit_log (id, msg, created_at, editor, change_file) VALUES (:id, :msg, :created_at, :editor, :change_file)", c)
|
||||||
|
if err != nil {
|
||||||
|
Log.Error("Error when insert commit log", zap.Error(err))
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// func GetCommitLogOfFilename(filename string) ([]CommitLog, error) {
|
||||||
|
//}
|
||||||
|
// cut .json, split then get pos 2, check `change_file` startwith "filename" then return all quries
|
||||||
|
|
||||||
|
func GetCommitLogs() ([]CommitLog, error) {
|
||||||
|
commit_db, err := sqlx.Connect("sqlite3", "./data/database.db")
|
||||||
|
if err != nil {
|
||||||
|
Log.Fatal("Error when connecting to database", zap.Error(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
var commits []CommitLog
|
||||||
|
err = commit_db.Get(&commits, "SELECT * FROM commit_log", nil)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
Log.Error("Error when get commit log", zap.Error(err))
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return commits, nil
|
||||||
|
}
|
||||||
|
|
@ -1,6 +1,18 @@
|
||||||
package helpers
|
package helpers
|
||||||
|
|
||||||
import "fmt"
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"recipe-manager/services/logger"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"go.uber.org/zap"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
Log = logger.GetInstance()
|
||||||
|
)
|
||||||
|
|
||||||
// DynamicCompare compares two values dynamically and returns true if they are equal.
|
// DynamicCompare compares two values dynamically and returns true if they are equal.
|
||||||
//
|
//
|
||||||
|
|
@ -37,6 +49,12 @@ func DynamicCompare(s interface{}, u interface{}) (bool, error) {
|
||||||
return t == u, nil
|
return t == u, nil
|
||||||
case float64:
|
case float64:
|
||||||
u, ok := u.(float64)
|
u, ok := u.(float64)
|
||||||
|
// Log.Debug("[helpers] DynamicCompare", zap.Any("u", u), zap.Any("ok", ok), zap.Any("test_compare*(t==u)", t == u))
|
||||||
|
|
||||||
|
if t == u {
|
||||||
|
return t == u, nil
|
||||||
|
}
|
||||||
|
|
||||||
if !ok {
|
if !ok {
|
||||||
return false, fmt.Errorf("[float64] cannot compare %T and %T, %v and %v", t, u, s, u)
|
return false, fmt.Errorf("[float64] cannot compare %T and %T, %v and %v", t, u, s, u)
|
||||||
}
|
}
|
||||||
|
|
@ -51,8 +69,112 @@ func DynamicCompare(s interface{}, u interface{}) (bool, error) {
|
||||||
return false, nil
|
return false, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
break
|
||||||
|
case map[string]interface{}:
|
||||||
|
for _, v := range t {
|
||||||
|
if ok, err := DynamicCompare(v, u); err != nil {
|
||||||
|
return false, err
|
||||||
|
} else if !ok {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break
|
||||||
default:
|
default:
|
||||||
return false, fmt.Errorf("[unknown] not in case. Cannot compare %T and %T, %v and %v", t, u, s, u)
|
return false, fmt.Errorf("[unknown] not in case. Cannot compare %T and %T, %v and %v", t, u, s, u)
|
||||||
}
|
}
|
||||||
return false, fmt.Errorf("[unknown] unexpected error")
|
|
||||||
|
if u == nil {
|
||||||
|
return false, fmt.Errorf("[empty] the compared value is nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
return false, fmt.Errorf("[unknown] unexpected error. [old] %v and [new] %v", s, u)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func GetTempFile(filename string, user string, suffix int) string {
|
||||||
|
|
||||||
|
// Check if the temp file exist
|
||||||
|
_, err := os.Stat(filename)
|
||||||
|
|
||||||
|
// Log.Debug("[helpers] GetTempFile", zap.Any("filename", filename), zap.Any("suffix", suffix), zap.Any("err", err))
|
||||||
|
|
||||||
|
// file not exists
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
// Create temp file
|
||||||
|
if suffix == 0 {
|
||||||
|
Log.Debug("[helpers] Suffix 0 GetTempFile", zap.Any("filename", filename))
|
||||||
|
return strings.Replace(filename, ".json", "_"+user+".tmp"+strconv.Itoa(suffix), 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// change extension from json to tmp
|
||||||
|
filename = strings.Replace(filename, ".json", "_"+user+".tmp"+strconv.Itoa(suffix), 1)
|
||||||
|
Log.Debug("[helpers] GetTempFile", zap.Any("filename", filename))
|
||||||
|
return filename
|
||||||
|
} else {
|
||||||
|
|
||||||
|
if strings.Contains(filename, ".tmp") {
|
||||||
|
return GetTempFile(strings.Replace(filename, "_"+user+".tmp"+strconv.Itoa(suffix-1), "_"+user+".tmp"+strconv.Itoa(suffix), 1), user, suffix+1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// recursive call
|
||||||
|
return GetTempFile(strings.Replace(filename, ".json", "_"+user+".tmp"+strconv.Itoa(suffix), 1), user, suffix+1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// func PackTempToRealFile(data *data.Data, countryID string, filename string) {
|
||||||
|
|
||||||
|
// // list file that end with .tmp*
|
||||||
|
// files, err := filepath.Glob(filename + ".tmp*")
|
||||||
|
|
||||||
|
// // for all files, read and get configNumber
|
||||||
|
|
||||||
|
// if err != nil {
|
||||||
|
// Log.Error("[helpers] PackTempToRealFile", zap.Error(err))
|
||||||
|
// }
|
||||||
|
|
||||||
|
// // get configNumber from actual filename.json
|
||||||
|
|
||||||
|
// //
|
||||||
|
// base_recipe := data.GetRecipe(countryID, filename)
|
||||||
|
|
||||||
|
// // read file and apply tmp file from 0 to tmpX.
|
||||||
|
// // - if there is more than 1 user that access this file at the same time,
|
||||||
|
// // pack in order, and if conflict, stop
|
||||||
|
|
||||||
|
// if len(files) == 0 {
|
||||||
|
// return
|
||||||
|
// }
|
||||||
|
|
||||||
|
// // TODO: must check the changes
|
||||||
|
|
||||||
|
// for _, file := range files {
|
||||||
|
// var tmpdata models.Recipe
|
||||||
|
// tmpfile, err := os.Open(file)
|
||||||
|
// if err != nil {
|
||||||
|
// return
|
||||||
|
// }
|
||||||
|
// _ = json.NewDecoder(tmpfile).Decode(&tmpdata)
|
||||||
|
// // apply change
|
||||||
|
|
||||||
|
// // = tmpdata.Recipe01
|
||||||
|
|
||||||
|
// for key, val := range tmpdata.Recipe01 {
|
||||||
|
|
||||||
|
// test_bol, err := DynamicCompare(base_recipe.Recipe01[key], val)
|
||||||
|
|
||||||
|
// if err != nil {
|
||||||
|
// Log.Error("[helpers] PackTempToRealFile", zap.Error(err))
|
||||||
|
// }
|
||||||
|
|
||||||
|
// if !test_bol {
|
||||||
|
// base_recipe.Recipe01[key] = val
|
||||||
|
// }
|
||||||
|
|
||||||
|
// }
|
||||||
|
|
||||||
|
// }
|
||||||
|
|
||||||
|
// // verify changes between tmpX and actual filename.json
|
||||||
|
|
||||||
|
// // if changes, rename tmpX to filename (version +1) .json
|
||||||
|
|
||||||
|
// }
|
||||||
|
|
|
||||||
|
|
@ -15,6 +15,7 @@ type MachineSetting struct {
|
||||||
RecipeTag string `json:"RecipeTag"`
|
RecipeTag string `json:"RecipeTag"`
|
||||||
StrTextShowError []string `json:"strTextShowError"`
|
StrTextShowError []string `json:"strTextShowError"`
|
||||||
ConfigNumber int `json:"configNumber"`
|
ConfigNumber int `json:"configNumber"`
|
||||||
|
Comment []string `json:"Comment"`
|
||||||
TemperatureMax int `json:"temperatureMax"`
|
TemperatureMax int `json:"temperatureMax"`
|
||||||
TemperatureMin int `json:"temperatureMin"`
|
TemperatureMin int `json:"temperatureMin"`
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -15,6 +15,7 @@ import (
|
||||||
"recipe-manager/services/sheet"
|
"recipe-manager/services/sheet"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
|
|
@ -226,7 +227,7 @@ func (rr *RecipeRouter) Route(r chi.Router) {
|
||||||
"productCode": v[0].(string),
|
"productCode": v[0].(string),
|
||||||
"name": v[1].(string),
|
"name": v[1].(string),
|
||||||
"otherName": v[2].(string),
|
"otherName": v[2].(string),
|
||||||
"description": v[3].(string),
|
"Description": v[3].(string),
|
||||||
"otherDescription": v[4].(string),
|
"otherDescription": v[4].(string),
|
||||||
"picture": v[5].(string),
|
"picture": v[5].(string),
|
||||||
})
|
})
|
||||||
|
|
@ -251,23 +252,23 @@ func (rr *RecipeRouter) Route(r chi.Router) {
|
||||||
|
|
||||||
// check request structure
|
// check request structure
|
||||||
|
|
||||||
// FIXME: Request structure bug. Case-sensitive, likely bug at client
|
|
||||||
// uncomment the below code to view the bug
|
|
||||||
|
|
||||||
// var change_request map[string]interface{}
|
|
||||||
// err = json.NewDecoder(r.Body).Decode(&change_request)
|
|
||||||
// if err != nil {
|
|
||||||
// Log.Error("Decode in request failed: ", zap.Error(err))
|
|
||||||
// }
|
|
||||||
// Log.Debug("Request => ", zap.Any("request", change_request))
|
|
||||||
|
|
||||||
// Body
|
// Body
|
||||||
|
var ch_map map[string]interface{}
|
||||||
var changes models.Recipe01
|
var changes models.Recipe01
|
||||||
err = json.NewDecoder(r.Body).Decode(&changes)
|
|
||||||
|
err = json.NewDecoder(r.Body).Decode(&ch_map)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
Log.Error("Decode in request failed: ", zap.Error(err))
|
Log.Error("Decode in request failed: ", zap.Error(err))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// commit request
|
||||||
|
editor := ch_map["edit_by"].(string)
|
||||||
|
Log.Debug("requester", zap.Any("editor", editor))
|
||||||
|
commit_msg := ch_map["commit_msg"].(string)
|
||||||
|
Log.Debug("commit_msg", zap.Any("commit_msg", commit_msg))
|
||||||
|
|
||||||
|
changes = changes.FromMap(ch_map)
|
||||||
|
|
||||||
Log.Debug("Changes: ", zap.Any("changes", changes))
|
Log.Debug("Changes: ", zap.Any("changes", changes))
|
||||||
// TODO: find the matched pd
|
// TODO: find the matched pd
|
||||||
target_menu, err := rr.data.GetRecipe01ByProductCode(filename, countryID, changes.ProductCode)
|
target_menu, err := rr.data.GetRecipe01ByProductCode(filename, countryID, changes.ProductCode)
|
||||||
|
|
@ -303,7 +304,40 @@ func (rr *RecipeRouter) Route(r chi.Router) {
|
||||||
// check if changed
|
// check if changed
|
||||||
// Log.Debug("Check if changed", zap.Any("result", rr.data.GetRecipe01ByProductCode(changes.ProductCode)))
|
// Log.Debug("Check if changed", zap.Any("result", rr.data.GetRecipe01ByProductCode(changes.ProductCode)))
|
||||||
|
|
||||||
file, _ := os.Create(path.Join("./cofffeemachineConfig", countryID, filename))
|
// target saved filename
|
||||||
|
saved_filename := path.Join("./cofffeemachineConfig", countryID, filename)
|
||||||
|
|
||||||
|
// store @ temporary file
|
||||||
|
temp_file_name := helpers.GetTempFile(saved_filename, editor, 0)
|
||||||
|
|
||||||
|
// TODO: push this change, editor, commit_msg into db
|
||||||
|
|
||||||
|
// gen hash
|
||||||
|
commit_hash, err := data.HashCommit(8)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
Log.Error("Error when hash commit", zap.Error(err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
commit := data.CommitLog{
|
||||||
|
|
||||||
|
Id: commit_hash,
|
||||||
|
Msg: commit_msg,
|
||||||
|
Created_at: time.Now().Format("2006-01-02 15:04:05"),
|
||||||
|
Editor: editor,
|
||||||
|
Change_file: temp_file_name,
|
||||||
|
}
|
||||||
|
|
||||||
|
err = data.Insert(&commit)
|
||||||
|
Log.Debug("Commit", zap.Any("attr", commit))
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
Log.Error("Error when insert commit log", zap.Error(err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
file, _ := os.Create(temp_file_name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
Log.Error("Error when tried to create file", zap.Error(err))
|
Log.Error("Error when tried to create file", zap.Error(err))
|
||||||
return
|
return
|
||||||
|
|
@ -311,6 +345,7 @@ func (rr *RecipeRouter) Route(r chi.Router) {
|
||||||
|
|
||||||
encoder := json.NewEncoder(file)
|
encoder := json.NewEncoder(file)
|
||||||
encoder.SetIndent("", " ")
|
encoder.SetIndent("", " ")
|
||||||
|
// err = encoder.Encode(rr.data.GetRecipe(countryID, temp_file_name))
|
||||||
err = encoder.Encode(rr.data.GetRecipe(countryID, filename))
|
err = encoder.Encode(rr.data.GetRecipe(countryID, filename))
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
@ -319,8 +354,47 @@ func (rr *RecipeRouter) Route(r chi.Router) {
|
||||||
|
|
||||||
w.Header().Add("Content-Type", "application/json")
|
w.Header().Add("Content-Type", "application/json")
|
||||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
"status": "OK",
|
"status": "OK",
|
||||||
|
"commit_id": commit_hash,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// get saved files
|
||||||
|
r.Get("/saved/{country}/{filename_version_only}", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
file_version := chi.URLParam(r, "filename_version_only")
|
||||||
|
country := chi.URLParam(r, "country")
|
||||||
|
|
||||||
|
countryID, err := rr.data.GetCountryIDByName(country)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, fmt.Sprintf("Country Name: %s not found!!!", country), http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
recipe_root_path := "./cofffeemachineConfig/"
|
||||||
|
|
||||||
|
// structure
|
||||||
|
full_file_name_targets := []string{}
|
||||||
|
|
||||||
|
files, err := os.ReadDir(recipe_root_path + countryID)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
Log.Error("Error when read directory", zap.Error(err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, file := range files {
|
||||||
|
Log.Debug("File: ", zap.Any("file", file.Name()))
|
||||||
|
if strings.Contains(file.Name(), file_version) && strings.Contains(file.Name(), ".tmp") {
|
||||||
|
full_file_name_targets = append(full_file_name_targets, file.Name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
json.NewEncoder(w).Encode(map[string]interface{}{"files": full_file_name_targets})
|
||||||
|
|
||||||
|
Log.Debug("Saved Files: ", zap.Any("files", full_file_name_targets))
|
||||||
|
})
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,44 +0,0 @@
|
||||||
package cli
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bufio"
|
|
||||||
"os"
|
|
||||||
"recipe-manager/services/logger"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"go.uber.org/zap"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
log_inst = logger.GetInstance()
|
|
||||||
disable_cli = false
|
|
||||||
debug = logger.GetDbgState()
|
|
||||||
)
|
|
||||||
|
|
||||||
func CommandLineListener() {
|
|
||||||
debug = logger.GetDbgState()
|
|
||||||
reader := bufio.NewReader(os.Stdin)
|
|
||||||
for !disable_cli {
|
|
||||||
input, _ := reader.ReadString('\n')
|
|
||||||
input = strings.TrimSpace(input)
|
|
||||||
|
|
||||||
switch input {
|
|
||||||
case "debug":
|
|
||||||
logger.EnableDebug(!logger.GetDbgState())
|
|
||||||
debug = logger.GetDbgState()
|
|
||||||
// log_inst.Info("Debug mode enable from cli", zap.Bool("enable", logger.GetDbgState()))
|
|
||||||
case "ctl":
|
|
||||||
if debug {
|
|
||||||
log_inst.Debug("CMD > ", zap.String("CMD", input))
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
if debug {
|
|
||||||
// log_inst.Debug("CMD > ", zap.String("CMD", input))
|
|
||||||
|
|
||||||
// Add functions here!
|
|
||||||
} else {
|
|
||||||
log_inst.Error("INVALID CMD or CMD DISABLED", zap.String("CMD", input))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -5,8 +5,15 @@ import (
|
||||||
"recipe-manager/contracts"
|
"recipe-manager/contracts"
|
||||||
"recipe-manager/data"
|
"recipe-manager/data"
|
||||||
"recipe-manager/models"
|
"recipe-manager/models"
|
||||||
|
"recipe-manager/services/logger"
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"go.uber.org/zap"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
Log = logger.GetInstance()
|
||||||
)
|
)
|
||||||
|
|
||||||
type RecipeService interface {
|
type RecipeService interface {
|
||||||
|
|
@ -24,12 +31,17 @@ type recipeService struct {
|
||||||
// GetRecipeDetail implements RecipeService.
|
// GetRecipeDetail implements RecipeService.
|
||||||
func (rs *recipeService) GetRecipeDetail(request *contracts.RecipeDetailRequest) (contracts.RecipeDetailResponse, error) {
|
func (rs *recipeService) GetRecipeDetail(request *contracts.RecipeDetailRequest) (contracts.RecipeDetailResponse, error) {
|
||||||
|
|
||||||
|
Log.Debug("GetRecipeDetail", zap.Any("request", request))
|
||||||
|
|
||||||
recipe, err := rs.db.GetRecipe01ByProductCode(request.Filename, request.Country, request.ProductCode)
|
recipe, err := rs.db.GetRecipe01ByProductCode(request.Filename, request.Country, request.ProductCode)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return contracts.RecipeDetailResponse{}, err
|
return contracts.RecipeDetailResponse{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DEBUG: picture
|
||||||
|
Log.Debug("GetRecipeDetail", zap.String("picture", recipe.UriData))
|
||||||
|
|
||||||
result := contracts.RecipeDetailResponse{
|
result := contracts.RecipeDetailResponse{
|
||||||
Name: recipe.Name,
|
Name: recipe.Name,
|
||||||
OtherName: recipe.OtherName,
|
OtherName: recipe.OtherName,
|
||||||
|
|
@ -94,9 +106,9 @@ func (rs *recipeService) GetRecipeDetailMat(request *contracts.RecipeDetailReque
|
||||||
}
|
}
|
||||||
|
|
||||||
// sort by id
|
// sort by id
|
||||||
sort.Slice(result.Result, func(i, j int) bool {
|
// sort.Slice(result.Result, func(i, j int) bool {
|
||||||
return result.Result[i].MaterialID < result.Result[j].MaterialID
|
// return result.Result[i].MaterialID < result.Result[j].MaterialID
|
||||||
})
|
// })
|
||||||
|
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue