fix switch department not change country

This commit is contained in:
pakintada@gmail.com 2024-02-08 16:40:06 +07:00
parent d9a7961806
commit adefe31090
6 changed files with 152 additions and 92 deletions

View file

@ -3,6 +3,9 @@ import { CommonModule, NgOptimizedImage } from '@angular/common';
import { Router } from '@angular/router'; import { Router } from '@angular/router';
import { UserService } from '../services/user.service'; import { UserService } from '../services/user.service';
import { UserPermissions } from '../auth/userPermissions'; import { UserPermissions } from '../auth/userPermissions';
import { NotFoundHandler } from 'src/app/shared/helpers/notFoundHandler';
import { AsyncStorage } from 'src/app/shared/helpers/asyncStorage';
import { getCountryMapSwitcher } from 'src/app/shared/helpers/recipe';
@Component({ @Component({
standalone: true, standalone: true,
@ -80,6 +83,9 @@ export class DepartmentComponent {
}, },
]; ];
//
notfoundHandler = new NotFoundHandler();
constructor( constructor(
private router: Router, private router: Router,
private _userService: UserService private _userService: UserService
@ -108,6 +114,19 @@ export class DepartmentComponent {
} }
onClick(id: string) { onClick(id: string) {
// TODO: add handler for redirect
this.notfoundHandler.handleSwitchCountry(id, async () => {
// set country
await AsyncStorage.setItem('currentRecipeCountry', getCountryMapSwitcher(id));
// set filename, don't know which file was a target so use default
await AsyncStorage.setItem('currentRecipeFile', 'default');
}, async () => {
// set country to `tha`
await AsyncStorage.setItem('currentRecipeCountry', 'Thailand');
// set filename, don't know which file was a target so use default
await AsyncStorage.setItem('currentRecipeFile', 'default');
// safely return to recipes
});
void this.router.navigate([`/${id}/recipes`]); void this.router.navigate([`/${id}/recipes`]);
} }
} }

View file

@ -59,7 +59,7 @@ export class MaterialSettingsComponent implements OnInit {
) {} ) {}
async ngOnInit(): Promise<void> { async ngOnInit(): Promise<void> {
this.notfoundHandler.handleInvalidDepartment(this.department!, () => { this.notfoundHandler.handleInvalidDepartment(this.department!, async () => {
this._router.navigate(['departments']).then(() => { this._router.navigate(['departments']).then(() => {
window.location.reload(); window.location.reload();
}); });

View file

@ -110,20 +110,21 @@ export class RecipesComponent implements OnInit, OnDestroy, AfterViewInit {
const isBottom = scrollTop + clientHeight >= scrollHeight - 10; const isBottom = scrollTop + clientHeight >= scrollHeight - 10;
if (isBottom && !this.isLoadMore) { if (isBottom && !this.isLoadMore) {
this.isLoadMore = true; this.isLoadMore = true;
(await this._recipeService (
.getRecipeOverview({ await this._recipeService.getRecipeOverview({
offset: this.offset, offset: this.offset,
take: this.take, take: this.take,
search: this.oldSearchStr, search: this.oldSearchStr,
filename: this._recipeService.getCurrentFile(), filename: this._recipeService.getCurrentFile(),
country: await this._recipeService.getCurrentCountry(this.department), country: await this._recipeService.getCurrentCountry(
this.department
),
materialIds: this.selectMaterialFilter || [], materialIds: this.selectMaterialFilter || [],
})) })
.subscribe(({ result, hasMore, totalCount }) => { ).subscribe(({ result, hasMore, totalCount }) => {
// console.log("result in scroll", result); // console.log("result in scroll", result);
if (this.recipeOverviewList) { if (this.recipeOverviewList) {
this.recipeOverviewList = this.recipeOverviewList = this.recipeOverviewList.concat(result);
this.recipeOverviewList.concat(result);
} else { } else {
this.recipeOverviewList = result; this.recipeOverviewList = result;
} }
@ -151,12 +152,23 @@ export class RecipesComponent implements OnInit, OnDestroy, AfterViewInit {
// TODO: check if department is legit // TODO: check if department is legit
this.notfoundHandler.handleInvalidDepartment(this.department!, () => { this.notfoundHandler.handleInvalidDepartment(
this._router.navigate(['departments']).then( () => { this.department!,
async () => {
await this._router.navigate(['departments']);
window.location.reload(); window.location.reload();
} ); },
}); async () => {
console.log('error callback', this.department!);
// await AsyncStorage.setItem(
// 'currentRecipeCountry',
// getCountryMapSwitcher(this.department!)
// );
// // get default file that should be opened
}
);
this.recipesDashboard$ = this._recipeService this.recipesDashboard$ = this._recipeService
.getRecipesDashboard({ .getRecipesDashboard({
@ -165,16 +177,18 @@ export class RecipesComponent implements OnInit, OnDestroy, AfterViewInit {
}) })
.pipe( .pipe(
finalize(async () => { finalize(async () => {
(await this._recipeService (
.getRecipeOverview({ await this._recipeService.getRecipeOverview({
offset: this.offset, offset: this.offset,
take: this.take, take: this.take,
search: this.oldSearchStr, search: this.oldSearchStr,
filename: this._recipeService.getCurrentFile(), filename: this._recipeService.getCurrentFile(),
country: await this._recipeService.getCurrentCountry(this.department!), country: await this._recipeService.getCurrentCountry(
this.department!
),
materialIds: this.selectMaterialFilter || [], materialIds: this.selectMaterialFilter || [],
})) })
.subscribe(({ result, hasMore, totalCount }) => { ).subscribe(({ result, hasMore, totalCount }) => {
this.recipeOverviewList = result; this.recipeOverviewList = result;
this.offset += 10; this.offset += 10;
this.isHasMore = hasMore; this.isHasMore = hasMore;
@ -188,12 +202,15 @@ export class RecipesComponent implements OnInit, OnDestroy, AfterViewInit {
this.recipesDashboard$.subscribe(async (data) => { this.recipesDashboard$.subscribe(async (data) => {
this.currentVersion = data.configNumber; this.currentVersion = data.configNumber;
console.log('current version', this.currentVersion); console.log('current version', this.currentVersion);
console.log("data : ", data); console.log('data : ', data);
// set default country and filename if was "default" // set default country and filename if was "default"
let currentFile = this._recipeService.getCurrentFile(); let currentFile = this._recipeService.getCurrentFile();
if(currentFile == "default"){ if (currentFile == 'default') {
await AsyncStorage.setItem('currentRecipeCountry', await this._recipeService.getCurrentCountry(this.department!)); await AsyncStorage.setItem(
'currentRecipeCountry',
await this._recipeService.getCurrentCountry(this.department!)
);
await AsyncStorage.setItem('currentRecipeFile', data.filename); await AsyncStorage.setItem('currentRecipeFile', data.filename);
} }
}); });
@ -201,14 +218,22 @@ export class RecipesComponent implements OnInit, OnDestroy, AfterViewInit {
console.log('ngAfterViewInit::department', this.department); console.log('ngAfterViewInit::department', this.department);
console.log('::CurrentFile', this._recipeService.getCurrentFile()); console.log('::CurrentFile', this._recipeService.getCurrentFile());
(await this._materialService (
.getFullMaterialDetail( await this._materialService.getFullMaterialDetail(
this.department, this.department,
this._recipeService.getCurrentFile() this._recipeService.getCurrentFile()
)) )
.subscribe((mat) => { ).subscribe((mat) => {
this.materialDetail = mat; this.materialDetail = mat;
console.log(this.materialDetail?.length, "[0]=", mat?.at(0), "current country", this._recipeService.getCurrentCountry(), "currentFile", this._recipeService.getCurrentFile()); console.log(
this.materialDetail?.length,
'[0]=',
mat?.at(0),
'current country',
this._recipeService.getCurrentCountry(),
'currentFile',
this._recipeService.getCurrentFile()
);
// check material detail // check material detail
console.log('first material', this.materialDetail![0]); console.log('first material', this.materialDetail![0]);
@ -248,9 +273,7 @@ export class RecipesComponent implements OnInit, OnDestroy, AfterViewInit {
}, },
}); });
(await (await this._materialService.getMaterialCodes())
this._materialService
.getMaterialCodes())
.pipe( .pipe(
map((mat) => map((mat) =>
mat.map((m) => ({ mat.map((m) => ({
@ -263,9 +286,12 @@ export class RecipesComponent implements OnInit, OnDestroy, AfterViewInit {
this.materialList = materials; this.materialList = materials;
}); });
(await this._toppingService (
.getToppings(this.department, this._recipeService.getCurrentFile())) await this._toppingService.getToppings(
.subscribe((tp) => { this.department,
this._recipeService.getCurrentFile()
)
).subscribe((tp) => {
this.toppings = { this.toppings = {
toppingGroup: tp.ToppingGroup, toppingGroup: tp.ToppingGroup,
toppingList: tp.ToppingList, toppingList: tp.ToppingList,
@ -286,26 +312,24 @@ export class RecipesComponent implements OnInit, OnDestroy, AfterViewInit {
} }
async search(event: Event) { async search(event: Event) {
// country // country
let country = await this._recipeService.getCurrentCountry(this.department).then( let country = await this._recipeService
(country) => country .getCurrentCountry(this.department)
); .then((country) => country);
this.offset = 0; this.offset = 0;
this.isLoadMore = true; this.isLoadMore = true;
this.oldSearchStr = this.searchStr; this.oldSearchStr = this.searchStr;
(await this._recipeService (
.getRecipeOverview({ await this._recipeService.getRecipeOverview({
offset: this.offset, offset: this.offset,
take: this.take, take: this.take,
search: this.oldSearchStr, search: this.oldSearchStr,
filename: this._recipeService.getCurrentFile(), filename: this._recipeService.getCurrentFile(),
country: country, country: country,
materialIds: this.selectMaterialFilter || [], materialIds: this.selectMaterialFilter || [],
})) })
.subscribe(({ result, hasMore, totalCount }) => { ).subscribe(({ result, hasMore, totalCount }) => {
this.recipeOverviewList = result; this.recipeOverviewList = result;
this.offset += 10; this.offset += 10;
this.isHasMore = hasMore; this.isHasMore = hasMore;
@ -460,8 +484,7 @@ export class RecipesComponent implements OnInit, OnDestroy, AfterViewInit {
await AsyncStorage.setItem('currentRecipeCountry', country); await AsyncStorage.setItem('currentRecipeCountry', country);
// force reload, will fix this later // force reload, will fix this later
void this._router void this._router.navigate([`/${getCountryMapSwitcher(country)}/recipes`]);
.navigate([`/${getCountryMapSwitcher(country)}/recipes`]);
} }
async loadRecipe(recipeFileName: string) { async loadRecipe(recipeFileName: string) {
@ -474,10 +497,14 @@ export class RecipesComponent implements OnInit, OnDestroy, AfterViewInit {
await AsyncStorage.setItem('currentRecipeFile', recipeFileName); await AsyncStorage.setItem('currentRecipeFile', recipeFileName);
console.log(
'loadRecipe',
recipeFileName,
console.log('loadRecipe', recipeFileName, "currentCountry", this.department, "selectedCountry", this.selectedCountry); 'currentCountry',
this.department,
'selectedCountry',
this.selectedCountry
);
// clear all menus // clear all menus
this.recipeOverviewList = []; this.recipeOverviewList = [];
@ -552,20 +579,18 @@ export class RecipesComponent implements OnInit, OnDestroy, AfterViewInit {
console.log(file_commit.Change_file.split('/')[2]); console.log(file_commit.Change_file.split('/')[2]);
(await this._recipeService (
.getRecipeOverview({ await this._recipeService.getRecipeOverview({
offset: this.offset, offset: this.offset,
take: this.take, take: this.take,
search: this.oldSearchStr, search: this.oldSearchStr,
filename: file_commit.Change_file.split('/')[2], filename: file_commit.Change_file.split('/')[2],
country: country, country: country,
materialIds: this.selectMaterialFilter || [], materialIds: this.selectMaterialFilter || [],
})) })
.subscribe(({ result, hasMore, totalCount }) => { ).subscribe(({ result, hasMore, totalCount }) => {
console.log('loadSavedFile', result); console.log('loadSavedFile', result);
this._recipeService.setCurrentFile( this._recipeService.setCurrentFile(file_commit.Change_file.split('/')[2]);
file_commit.Change_file.split('/')[2]
);
window.location.reload(); window.location.reload();
}); });
} }

View file

@ -89,7 +89,7 @@ export class ToppingsComponent implements OnInit {
async ngOnInit(): Promise<void> { async ngOnInit(): Promise<void> {
this.notfoundHandler.handleInvalidDepartment(this.department!, () => { this.notfoundHandler.handleInvalidDepartment(this.department!, async () => {
this._router.navigate(['departments']).then( () => { this._router.navigate(['departments']).then( () => {
window.location.reload(); window.location.reload();
} ); } );

View file

@ -15,10 +15,23 @@ export class NotFoundHandler {
} }
// if invalid, value is true then do callback // if invalid, value is true then do callback
handleInvalidDepartment(department: string, callback: () => void) { handleInvalidDepartment(department: string, callback: () => Promise<any>, error?: () => Promise<any>) {
let checkCondition = !departmentList().includes(department); let checkCondition = !departmentList().includes(department);
if(checkCondition) { if(checkCondition) {
callback(); callback();
} else {
if(error)
error();
}
}
handleSwitchCountry(country: string, callback: () => Promise<any>, error?: () => Promise<any>) {
let checkCondition = departmentList().includes(country);
if(checkCondition) {
callback();
} else {
if(error)
error();
} }
} }

View file

@ -229,7 +229,7 @@ func (d *Data) GetRecipe(countryID, filename string) *models.Recipe {
if recipe, ok := d.recipeMap[filename]; ok && d.redisClient.HealthCheck() != nil { if recipe, ok := d.recipeMap[filename]; ok && d.redisClient.HealthCheck() != nil {
d.taoLogger.Log.Debug("GetRecipe", zap.Any("ValidOnStored", "return from stored "+filename)) d.taoLogger.Log.Debug("GetRecipe", zap.Any("ValidOnStored", "return from stored "+filename))
d.CurrentFile[countryID] = filename // d.CurrentFile[countryID] = filename
// d.CurrentCountryID[countryID] = countryID // d.CurrentCountryID[countryID] = countryID
// make sure recipe vesion is equal // make sure recipe vesion is equal
@ -265,7 +265,7 @@ func (d *Data) GetRecipe(countryID, filename string) *models.Recipe {
if cached_recipe != nil { if cached_recipe != nil {
d.taoLogger.Log.Debug("GetRecipe", zap.Any("Check on cached recipe invalid", cached_recipe == nil), zap.Any("test config number", cached_recipe.MachineSetting.ConfigNumber)) d.taoLogger.Log.Debug("GetRecipe", zap.Any("Check on cached recipe invalid", cached_recipe == nil), zap.Any("test config number", cached_recipe.MachineSetting.ConfigNumber))
// set to current // set to current
d.CurrentRecipe[countryID] = cached_recipe // d.CurrentRecipe[countryID] = cached_recipe
return cached_recipe return cached_recipe
} }
@ -287,14 +287,17 @@ func (d *Data) GetRecipe(countryID, filename string) *models.Recipe {
//. service is connected. Use from cache //. service is connected. Use from cache
// check healthcheck redis // check healthcheck redis
var return_recipe *models.Recipe = &models.Recipe{}
err = d.redisClient.HealthCheck() err = d.redisClient.HealthCheck()
d.taoLogger.Log.Info("GetRecipe: HealthCheck", zap.Any("result", err)) d.taoLogger.Log.Info("GetRecipe: HealthCheck", zap.Any("result", err))
if d.redisClient.HealthCheck() == nil && cached_recipe != nil { if d.redisClient.HealthCheck() == nil && cached_recipe != nil {
d.taoLogger.Log.Debug("GetRecipeCached", zap.Any("cached_recipe", "yes")) d.taoLogger.Log.Debug("GetRecipeCached", zap.Any("cached_recipe", "yes"))
d.CurrentRecipe[countryID] = cached_recipe // d.CurrentRecipe[countryID] = cached_recipe
return_recipe = cached_recipe
} else { } else {
d.taoLogger.Log.Debug("GetRecipeCached", zap.Any("cached_recipe", "no")) d.taoLogger.Log.Debug("GetRecipeCached", zap.Any("cached_recipe", "no"))
d.CurrentRecipe[countryID] = recipe // d.CurrentRecipe[countryID] = recipe
return_recipe = recipe
} }
// save to map // save to map
@ -316,7 +319,7 @@ func (d *Data) GetRecipe(countryID, filename string) *models.Recipe {
TimeStamps: time.Now().Unix(), TimeStamps: time.Now().Unix(),
} }
return d.CurrentRecipe[countryID] return return_recipe
} }
// func (d *Data) GetRecipe01() []models.Recipe01 { // func (d *Data) GetRecipe01() []models.Recipe01 {