Fix routing when notfound

This commit is contained in:
pakintada@gmail.com 2024-02-08 11:26:16 +07:00
parent f38f894dce
commit 9ccea7f635
7 changed files with 152 additions and 52 deletions

View file

@ -171,10 +171,10 @@ const routes: Routes = [
// loadComponent: () => // loadComponent: () =>
// import('./core/notfound.component').then((m) => m.NotfoundComponent), // import('./core/notfound.component').then((m) => m.NotfoundComponent),
// }, // },
{ // {
path: '**', // path: '**',
redirectTo: 'departments', // redirectTo: 'departments',
}, // },
]; ];
@NgModule({ @NgModule({

View file

@ -1,6 +1,7 @@
import { Component, OnInit } from '@angular/core'; import { Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser'; import { Title } from '@angular/platform-browser';
import Lang from './shared/helpers/lang'; import Lang from './shared/helpers/lang';
import { AsyncStorage } from './shared/helpers/asyncStorage';
@Component({ @Component({
selector: 'app-root', selector: 'app-root',
@ -10,9 +11,14 @@ import Lang from './shared/helpers/lang';
export class AppComponent implements OnInit { export class AppComponent implements OnInit {
constructor(private titleService: Title) {} constructor(private titleService: Title) {}
ngOnInit(): void { async ngOnInit(): Promise<void> {
this.titleService.setTitle('Recipe Manager | Tao Bin'); this.titleService.setTitle('Recipe Manager | Tao Bin');
// lang // lang
Lang.initLanguageSwitcher(); Lang.initLanguageSwitcher();
// set default country and filename
await AsyncStorage.setItem('currentRecipeCountry', 'Thailand');
await AsyncStorage.setItem('currentFile', 'default');
} }
} }

View file

@ -1,4 +1,5 @@
import { Component } from '@angular/core'; import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({ @Component({
selector: 'app-notfound', selector: 'app-notfound',
@ -6,5 +7,14 @@ import { Component } from '@angular/core';
template: `<h1>Not Found!!!</h1>` template: `<h1>Not Found!!!</h1>`
}) })
export class NotfoundComponent { export class NotfoundComponent {
constructor(private router: Router) {
// do set country and filename
console.log('not found');
this.router.navigate(['/departments']).then(
() => {
console.log('redirected');
window.location.reload();
}
);
}
} }

View file

@ -1,8 +1,16 @@
import { CommonModule, NgIf } from '@angular/common'; import { CommonModule, NgIf } from '@angular/common';
import { Component, OnInit } from '@angular/core'; import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'; import {
FormArray,
FormBuilder,
FormGroup,
FormsModule,
ReactiveFormsModule,
} from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { MaterialSetting } from 'src/app/core/models/recipe.model'; import { MaterialSetting } from 'src/app/core/models/recipe.model';
import { MaterialService } from 'src/app/core/services/material.service'; import { MaterialService } from 'src/app/core/services/material.service';
import { NotFoundHandler } from 'src/app/shared/helpers/notFoundHandler';
import { getCategories, getMaterialType } from 'src/app/shared/helpers/recipe'; import { getCategories, getMaterialType } from 'src/app/shared/helpers/recipe';
@Component({ @Component({
@ -29,18 +37,34 @@ export class MaterialSettingsComponent implements OnInit {
currentFormIndex: number | undefined = undefined; currentFormIndex: number | undefined = undefined;
// mandatory form // mandatory form
materialSettingForm = this.formBuilder.group({ materialSettingForm = this.formBuilder.group(
materialSetting: this.formBuilder.array([]), {
}, { updateOn: 'blur' }); materialSetting: this.formBuilder.array([]),
},
{ updateOn: 'blur' }
);
notfoundHandler = new NotFoundHandler();
department: string = this.route.parent!.snapshot.params['department'];
// getter // getter
get materialSetting() { get materialSetting() {
return this.materialSettingForm.get('materialSetting') as FormArray; return this.materialSettingForm.get('materialSetting') as FormArray;
} }
constructor(private _materialService: MaterialService, private formBuilder: FormBuilder) {} constructor(
private _materialService: MaterialService,
private formBuilder: FormBuilder,
private _router: Router,
private route: ActivatedRoute
) {}
async ngOnInit(): Promise<void> { async ngOnInit(): Promise<void> {
this.notfoundHandler.handleInvalidDepartment(this.department!, () => {
this._router.navigate(['departments']).then(() => {
window.location.reload();
});
});
// do fetch material settings // do fetch material settings
(await this._materialService.getFullMaterialDetail()).subscribe((data) => { (await this._materialService.getFullMaterialDetail()).subscribe((data) => {
this.allMaterials = data; this.allMaterials = data;
@ -66,17 +90,16 @@ export class MaterialSettingsComponent implements OnInit {
this.allMaterials!.forEach((mat) => { this.allMaterials!.forEach((mat) => {
let category = getMaterialType(mat.materialId); let category = getMaterialType(mat.materialId);
// try again // try again
if(category == 'others' && mat.type.includes("true")){ if (category == 'others' && mat.type.includes('true')) {
// extract type // extract type
let type = mat.type.split(","); let type = mat.type.split(',');
type.forEach((t)=>{ type.forEach((t) => {
let tt = t.split(":"); let tt = t.split(':');
// powder:true -> powder-[0] | true-[1] // powder:true -> powder-[0] | true-[1]
category = tt[1] == "true" ? tt[0] : category; category = tt[1] == 'true' ? tt[0] : category;
}); });
if(!Object.keys(catMap).includes(category)){ if (!Object.keys(catMap).includes(category)) {
catMap[category] = []; catMap[category] = [];
} }
} else if (category == 'others') { } else if (category == 'others') {
@ -109,8 +132,7 @@ export class MaterialSettingsComponent implements OnInit {
return catList; return catList;
}; };
createMaterialSettingFormGroup(mat_set: MaterialSetting) {
createMaterialSettingFormGroup(mat_set: MaterialSetting){
return this.formBuilder.group({ return this.formBuilder.group({
materialName: mat_set.materialName, materialName: mat_set.materialName,
materialId: mat_set.materialId, materialId: mat_set.materialId,
@ -139,48 +161,60 @@ export class MaterialSettingsComponent implements OnInit {
isUse: mat_set.isUse, isUse: mat_set.isUse,
pay_rettry_max_count: mat_set.pay_rettry_max_count, pay_rettry_max_count: mat_set.pay_rettry_max_count,
feed_mode: mat_set.feed_mode, feed_mode: mat_set.feed_mode,
MaterialParameter: mat_set.MaterialParameter MaterialParameter: mat_set.MaterialParameter,
}); });
} }
// open material id modal // open material id modal
async openMaterialSettingModal(id: string){ async openMaterialSettingModal(id: string) {
// set current material // set current material
(await this._materialService.getMaterialSettingById(parseInt(id))).subscribe( (
(data) => { await this._materialService.getMaterialSettingById(parseInt(id))
this.currentMaterialSettings = data; ).subscribe((data) => {
this.currentMaterialSettings = data;
// do create form, if not exist // do create form, if not exist
// - find matching form // - find matching form
// - if not exist, create new form // - if not exist, create new form
let pushableFlag = false; let pushableFlag = false;
// filter find index // filter find index
let foundFormIndex = this.materialSetting.controls.findIndex((control) => { let foundFormIndex = this.materialSetting.controls.findIndex(
return (control.value as any).id == id (control) => {
}); return (control.value as any).id == id;
console.log("found form index", foundFormIndex);
if(foundFormIndex < 0){
foundFormIndex = this.materialSetting.length - 1 < 0 ? 0 : this.materialSetting.length;
pushableFlag = true;
} }
);
if(pushableFlag){ console.log('found form index', foundFormIndex);
this.materialSetting.push(this.createMaterialSettingFormGroup(data));
console.log('push new form', this.materialSetting);
}
// export index if (foundFormIndex < 0) {
this.currentFormIndex = foundFormIndex; foundFormIndex =
this.materialSetting.length - 1 < 0 ? 0 : this.materialSetting.length;
console.log('material setting', data, "at index", foundFormIndex, "current form index", this.currentFormIndex); pushableFlag = true;
// console.log("keys of material settings", Object.keys(data));
console.log('material setting', data.isUse, typeof data.isUse);
(document.getElementById("material_settings_modal_"+id) as any)!.showModal();
} }
);
if (pushableFlag) {
this.materialSetting.push(this.createMaterialSettingFormGroup(data));
console.log('push new form', this.materialSetting);
}
// export index
this.currentFormIndex = foundFormIndex;
console.log(
'material setting',
data,
'at index',
foundFormIndex,
'current form index',
this.currentFormIndex
);
// console.log("keys of material settings", Object.keys(data));
console.log('material setting', data.isUse, typeof data.isUse);
(document.getElementById(
'material_settings_modal_' + id
) as any)!.showModal();
});
} }
} }

View file

@ -35,6 +35,7 @@ import { ToppingService } from 'src/app/core/services/topping.service';
import { copy, transformToTSV } from 'src/app/shared/helpers/copy'; import { copy, transformToTSV } from 'src/app/shared/helpers/copy';
import { getCountryMapSwitcher } from 'src/app/shared/helpers/recipe'; import { getCountryMapSwitcher } from 'src/app/shared/helpers/recipe';
import { AsyncStorage } from 'src/app/shared/helpers/asyncStorage'; import { AsyncStorage } from 'src/app/shared/helpers/asyncStorage';
import { NotFoundHandler } from 'src/app/shared/helpers/notFoundHandler';
@Component({ @Component({
selector: 'app-recipes', selector: 'app-recipes',
@ -95,6 +96,8 @@ export class RecipesComponent implements OnInit, OnDestroy, AfterViewInit {
currentVersion: number | undefined = undefined; currentVersion: number | undefined = undefined;
notfoundHandler = new NotFoundHandler();
@ViewChild('table', { static: false }) set content(table: ElementRef) { @ViewChild('table', { static: false }) set content(table: ElementRef) {
table.nativeElement.addEventListener( table.nativeElement.addEventListener(
'scroll', 'scroll',
@ -146,7 +149,13 @@ export class RecipesComponent implements OnInit, OnDestroy, AfterViewInit {
async ngOnInit(): Promise<void> { async ngOnInit(): Promise<void> {
console.log('Trigger onInit where department = ', this.department); console.log('Trigger onInit where department = ', this.department);
// TODO: check if department is legit
this.notfoundHandler.handleInvalidDepartment(this.department!, () => {
this._router.navigate(['departments']).then( () => {
window.location.reload();
} );
});
this.recipesDashboard$ = this._recipeService this.recipesDashboard$ = this._recipeService

View file

@ -14,6 +14,8 @@ import {
import { NgSelectModule } from '@ng-select/ng-select'; import { NgSelectModule } from '@ng-select/ng-select';
import { forEach } from 'lodash'; import { forEach } from 'lodash';
import { RecipeListComponent } from '../recipes/recipe-details/recipe-list/recipe-list.component'; import { RecipeListComponent } from '../recipes/recipe-details/recipe-list/recipe-list.component';
import { ActivatedRoute, Router } from '@angular/router';
import { NotFoundHandler } from 'src/app/shared/helpers/notFoundHandler';
@Component({ @Component({
selector: 'app-toppings', selector: 'app-toppings',
@ -28,6 +30,10 @@ import { RecipeListComponent } from '../recipes/recipe-details/recipe-list/recip
], ],
}) })
export class ToppingsComponent implements OnInit { export class ToppingsComponent implements OnInit {
department: string = this.route.parent!.snapshot.params['department'];
notfoundHandler = new NotFoundHandler();
onRecipeListFormChange($event: unknown[]) { onRecipeListFormChange($event: unknown[]) {
console.log("recipe list form change",$event); console.log("recipe list form change",$event);
} }
@ -76,10 +82,20 @@ export class ToppingsComponent implements OnInit {
private _httpClient: HttpClient, private _httpClient: HttpClient,
private _recipeService: RecipeService, private _recipeService: RecipeService,
private _toppingService: ToppingService, private _toppingService: ToppingService,
private _formBuilder: FormBuilder private _formBuilder: FormBuilder,
private route: ActivatedRoute,
private _router: Router
) {} ) {}
async ngOnInit(): Promise<void> { async ngOnInit(): Promise<void> {
this.notfoundHandler.handleInvalidDepartment(this.department!, () => {
this._router.navigate(['departments']).then( () => {
window.location.reload();
} );
});
// initialize // initialize
( (
await this._toppingService.getToppingGroups( await this._toppingService.getToppingGroups(

View file

@ -0,0 +1,25 @@
// list all department in short name
export function departmentList() {
return [
'tha',
'mys',
'aus',
'alpha-3'
];
}
export class NotFoundHandler {
constructor() {
// do nothing
}
// if invalid, value is true then do callback
handleInvalidDepartment(department: string, callback: () => void) {
let checkCondition = !departmentList().includes(department);
if(checkCondition) {
callback();
}
}
}