fix default file reader bug

This commit is contained in:
pakintada@gmail.com 2024-01-17 17:38:23 +07:00
parent 21109e4bf9
commit db131d10c0
15 changed files with 636 additions and 254 deletions

View file

@ -3,10 +3,15 @@ import { Injectable } from '@angular/core';
import { MaterialCode, MaterialSetting } from '../models/recipe.model';
import { environment } from 'src/environments/environment';
import { Observable } from 'rxjs';
import { ActivatedRoute } from '@angular/router';
import { getCountryMapSwitcher } from 'src/app/shared/helpers/recipe';
@Injectable({ providedIn: 'root' })
export class MaterialService {
constructor(private _httpClient: HttpClient) {}
private department = this._route.snapshot.paramMap.get('department')
constructor(private _httpClient: HttpClient, private _route: ActivatedRoute) {}
getMaterialCodes(
matIds?: number[],
@ -17,7 +22,7 @@ export class MaterialService {
`${environment.api}/materials/code`,
{
params: {
country: country || this.getCurrentCountry(),
country: country || this.getCurrentCountry(this.department!),
filename: filename || this.getCurrentFile(),
mat_ids: matIds?.join(',') || '',
},
@ -36,9 +41,12 @@ export class MaterialService {
}[] | null>{
console.log("getFullMaterialDetail", country, filename);
country = country || this.getCurrentCountry();
country = country || this.getCurrentCountry(this.department!);
filename = filename || this.getCurrentFile();
// finalize fetch from what?
console.log("country, filename", country, filename);
return this._httpClient.get<{
"materialId": number,
"name": string,
@ -57,7 +65,7 @@ export class MaterialService {
`${environment.api}/materials/setting/${id}`,
{
params: {
country: country || this.getCurrentCountry(),
country: country || this.getCurrentCountry(this.department!),
filename: filename || this.getCurrentFile(),
},
withCredentials: true,
@ -71,10 +79,24 @@ export class MaterialService {
return currentRecipeFile;
}
return 'coffeethai02_580.json';
return 'default';
}
getCurrentCountry(): string {
getCurrentCountry(department? : string): string {
// fetch by using department
if(department){
// translate back to full name
let fullname = getCountryMapSwitcher(department);
console.log('Material.service::fullname: ', fullname);
// localStorage.setItem('currentRecipeCountry', fullname);
return fullname;
}
const currentRecipeCountry = localStorage.getItem('currentRecipeCountry');
if (currentRecipeCountry) {
return currentRecipeCountry;

View file

@ -12,6 +12,8 @@ import {
} from '../models/recipe.model';
import { environment } from 'src/environments/environment';
import { RecipeMetaData } from 'src/app/shared/types/recipe';
import { getCountryMapSwitcher } from 'src/app/shared/helpers/recipe';
import { ActivatedRoute } from '@angular/router';
type RecipeOverviewParams = {
filename: string;
@ -38,15 +40,17 @@ export class RecipeService {
private tmp_files: string[] = [];
private department = this._route.snapshot.paramMap.get('department');
private get tmpfiles(): string[] {
return this.tmp_files;
}
constructor(private _httpClient: HttpClient) {}
constructor(private _httpClient: HttpClient, private _route: ActivatedRoute) {}
getRecipesDashboard(
params: RecipeDashboardParams = {
country: this.getCurrentCountry(),
country: this.getCurrentCountry(this.department!),
filename: this.getCurrentFile(),
}
): Observable<RecipesDashboard> {
@ -65,7 +69,7 @@ export class RecipeService {
getRecipeOverview(
params: RecipeOverviewParams = {
country: this.getCurrentCountry(),
country: this.getCurrentCountry(this.department!),
filename: this.getCurrentFile(),
materialIds: [],
offset: 0,
@ -96,7 +100,7 @@ export class RecipeService {
{
params: {
filename: this.getCurrentFile(),
country: this.getCurrentCountry(),
country: this.getCurrentCountry(this.department!),
},
withCredentials: true,
responseType: 'json',
@ -112,7 +116,7 @@ export class RecipeService {
{
params: {
filename: this.getCurrentFile(),
country: this.getCurrentCountry(),
country: this.getCurrentCountry(this.department!),
},
withCredentials: true,
responseType: 'json',
@ -121,19 +125,35 @@ export class RecipeService {
}
getCurrentFile(): string {
// TODO: get default from server
const currentRecipeFile = localStorage.getItem('currentRecipeFile');
if (currentRecipeFile) {
return currentRecipeFile;
}
return 'coffeethai02_580.json';
return 'default';
}
setCurrentFile(filename: string) {
localStorage.setItem('currentRecipeFile', filename);
}
getCurrentCountry(): string {
getCurrentCountry(department?: string): string {
if(department){
// translate back to full name
let fullname = getCountryMapSwitcher(department);
console.log('fullname: ', fullname);
// localStorage.setItem('currentRecipeCountry', fullname);
return fullname;
}
const currentRecipeCountry = localStorage.getItem('currentRecipeCountry');
if (currentRecipeCountry) {
return currentRecipeCountry;

View file

@ -7,19 +7,17 @@
class="block p-6 bg-white border border-gray-200 rounded-lg shadow w-full"
>
<div *ngIf="isLoaded; else indicator" [@inOutAnimation]>
<!-- productCode -->
<div>
<input
class="input input-bordered input-xs text-lg text-gray-900 my-2"
type="text"
name="productCode"
[value]="productCode"
(keyup)="onProductCodeChange($event)"
[disabled]="!isEditable()"
/>
</div>
<!-- productCode -->
<div>
<input
class="input input-bordered input-xs text-lg text-gray-900 my-2"
type="text"
name="productCode"
[value]="productCode"
(keyup)="onProductCodeChange($event)"
[disabled]="!isEditable()"
/>
</div>
<div class="flex flex-wrap">
<h5 class="mb-2 text-xl font-bold text-gray-900">
@ -29,7 +27,6 @@
<h5 class="mb-2 text-xl font-bold text-gray-900">
{{ recipeDetailForm.getRawValue().otherName }}
</h5>
</div>
<div class="flex items-center mb-2">
<div class="flex items-center">
@ -110,7 +107,12 @@
<div *ngIf="hasSubmenu()">
<div *ngFor="let sub of listSubMenuProductcodes()">
<button class="btn btn-sm btn-primary m-2" (click)="selectSubmenu(sub)">{{sub}}</button>
<button
class="btn btn-sm btn-primary m-2"
(click)="selectSubmenu(sub)"
>
{{ sub }}
</button>
</div>
</div>
</div>
@ -118,45 +120,52 @@
</div>
<div id="recipeList" class="carousel-item w-full">
<div
class="overflow-auto h-[75vh] mb-4 rounded bg-white border border-gray-200 shadow w-1/2"
>
<app-recipe-list
[productCode]="productCode"
[isSubMenu]="false"
(recipeListFormChange)="onRecipeListFormChange($event)"
></app-recipe-list>
</div>
</div>
<div id="toppingSet" class="carousel-item w-full">
<div class="overflow-auto h-[75vh] mb-4 rounded bg-white border border-gray-200 shadow">
<app-recipe-toppingset
[productCode]="productCode"
(toppingSetChange)="onToppingListChange($event)"
></app-recipe-toppingset>
class="overflow-auto h-[75vh] mb-4 rounded bg-white border border-gray-200 shadow"
>
<app-recipe-list
[productCode]="productCode"
[isSubMenu]="false"
(recipeListFormChange)="onRecipeListFormChange($event)"
></app-recipe-list>
</div>
</div>
<div id="toppingSet" class="carousel-item w-full">
<div
class="overflow-auto h-[75vh] mb-4 rounded bg-white border border-gray-200 shadow max-w-screen-xl"
>
<app-recipe-toppingset
[productCode]="productCode"
(toppingSetChange)="onToppingListChange($event)"
></app-recipe-toppingset>
</div>
</div>
</div>
<!-- try pop up modal -->
<!-- TODO: do topping -->
<div
class="sticky bottom-0 col-span-3 max-w-screen-lg flex justify-end bg-white rounded-full drop-shadow-2xl p-3"
>
<div class="flex justify-center w-full start-0 py-2">
<a href="{{department}}/recipe/{{productCode}}#name" class="btn btn-xs">1</a>
<a href="{{department}}/recipe/{{productCode}}#recipeList" class="btn btn-xs">2</a>
<a href="{{department}}/recipe/{{productCode}}#toppingSet" class="btn btn-xs">3</a>
</div>
<div class="flex justify-center w-full start-0 py-2">
<a
href="{{ department }}/recipe/{{ productCode }}#name"
class="btn btn-xs"
>1</a
>
<a
href="{{ department }}/recipe/{{ productCode }}#recipeList"
class="btn btn-xs"
>2</a
>
<a
href="{{ department }}/recipe/{{ productCode }}#toppingSet"
class="btn btn-xs"
>3</a
>
</div>
<!-- <div> Commit Message </div> -->
<!-- <p class="text-2xl mr-8 text-gray-400 dark:text-gray-500">Commit Message</p> -->

View file

@ -109,7 +109,7 @@ export class RecipeDetailsComponent implements OnInit {
this.recipeOriginalDetail = { ...this.recipeDetailForm.getRawValue() };
});
this._recipeService.getSubMenus(this._recipeService.getCurrentCountry(), this._recipeService.getCurrentFile(), this.productCode).subscribe((data) => {
this._recipeService.getSubMenus(this._recipeService.getCurrentCountry(this.department), this._recipeService.getCurrentFile(), this.productCode).subscribe((data) => {
console.log('Submenus', data);
this.submenus = data;
});
@ -177,7 +177,7 @@ export class RecipeDetailsComponent implements OnInit {
// TODO: update value in targeted recipe
console.log('to_send', to_send);
this._recipeService.editChanges(
this._recipeService.getCurrentCountry(),
this._recipeService.getCurrentCountry(this.department),
this._recipeService.getCurrentFile(),
{
...to_send,

View file

@ -4,7 +4,8 @@
<th class="px-6 py-3">Is Use</th>
<th class="px-6 py-3">Material ID</th>
<th class="px-6 py-3">Material Name</th>
<th class="px-6 py-3">Settings</th>
<th class="px-6 py-3">Volume</th>
<th class="">Settings</th>
</tr>
</thead>
<tbody
@ -12,32 +13,28 @@
*ngFor="let mat of recipeListData.controls; let i = index"
>
<tr
class="bg-white la border-b hover:bg-secondary"
class="bg-white border-b hover:bg-secondary max-h-4"
formGroupName="{{ i }}"
(mousedown)="initHoldEvent()"
(mouseup)="openRecipeListEditor(i)"
>
<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap">
<td class="font-medium text-gray-900 whitespace-nowrap sticky left-0">
<input type="checkbox" class="toggle" formControlName="isUse" />
</td>
<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap">
<td class="font-medium text-gray-900 whitespace-nowrap sticky">
<input
type="text"
class="input"
class="input w-20"
formControlName="materialPathId"
(click)="openMaterialList(i)"
/>
</td>
<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap">
<td class="font-medium text-gray-900 whitespace-nowrap sticky">
<input type="text" class="input" formControlName="name" />
</td>
<!-- powder -->
<!-- <div *ngIf="getTypeForRecipeListAtIndex(i)['category'] == 'powder'">
</div> -->
<td
class="m-2 px-4 py-4 font-medium text-gray-900 whitespace-nowrap"
class="font-medium text-gray-900 whitespace-nowrap"
*ngIf="
displayByCond(i, 'powderGram', 'not-zero', { compare: undefined })
"
@ -52,89 +49,100 @@
</td>
<td
class="m-2 px-4 py-4 font-medium text-gray-900 whitespace-nowrap"
*ngIf="
displayByCond(i, 'syrupGram', 'not-zero', { compare: undefined }) &&
getTypeForRecipeListAtIndex(i)['category'] == 'syrup'
"
class="font-medium text-gray-900 whitespace-nowrap"
*ngIf="displayByCond(i, 'powderGram', 'zero', { compare: undefined })"
>
<div class="flex items-center space-x-2 bg-purple-300 rounded-md">
<div
class="flex items-center space-x-2 bg-purple-300 rounded-md"
*ngIf="
displayByCond(i, 'syrupGram', 'not-zero', { compare: undefined }) &&
getTypeForRecipeListAtIndex(i)['category'] == 'syrup'
"
>
<p>Volume</p>
<input type="text" class="input w-16" formControlName="syrupGram" />
<p>gram</p>
</div>
</td>
<td
class="m-2 px-4 py-4 space-y-2 font-medium text-gray-900 whitespace-nowrap"
>
<div class="flex items-center justify-center space-x-4 bg-gray-200">
<div
class="flex items-center rounded-md"
*ngIf="isStringParamExist(i)"
>
<div
class="flex items-center rounded-md "
*ngFor="let param of getStringParamOfIndex(i)"
>
<!-- <p>&nbsp;</p> -->
<p *ngIf="param.pkey == 'notail'">tail</p>
<input
type="text"
class="input input-bordered w-16"
placeholder="{{ param.pvalue }}"
(click)="openStringParamEditor(i)"
/>
<p class="m-4" *ngIf="param.pkey == 'esp-v2-press-value'">
mA
</p>
<td class="font-medium text-gray-900 whitespace-nowrap">
<div class="flex flex-row p-2 space-x-3">
<div class="flex items-center justify-center bg-gray-200">
<div class="items-center rounded-md" *ngIf="isStringParamExist(i)">
<div
class="flex items-center rounded-md tooltip"
[attr.data-tip]="param.pkey"
*ngFor="let param of getStringParamOfIndex(i)"
>
<!-- <p>&nbsp;</p> -->
<p *ngIf="param.pkey == 'notail'">tail</p>
<input
type="text"
class="w-8 bg-transparent"
placeholder="{{ param.pvalue }}"
(click)="openStringParamEditor(i)"
/>
<p *ngIf="param.pkey == 'esp-v2-press-value'">mA</p>
</div>
</div>
</div>
</div>
<div
class="flex items-center justify-center space-x-2 rounded-md bg-red-200"
*ngIf="
displayByCond(i, 'waterYield', 'not-zero', { compare: undefined })
"
>
<p>Hot</p>
<input type="text" class="input w-16" formControlName="waterYield" />
<p>ml</p>
</div>
<div
class="flex items-center justify-center space-x-2 rounded-md bg-blue-200"
*ngIf="
displayByCond(i, 'waterCold', 'not-zero', { compare: undefined })
"
>
<p>Cold</p>
<input type="text" class="input w-16" formControlName="waterCold" />
<p>ml</p>
</div>
<div
class="flex items-center justify-center space-x-2 rounded-md bg-green-300"
*ngIf="
displayByCond(i, 'stirTime', 'not-zero', { compare: undefined }) &&
getTypeForRecipeListAtIndex(i)['category'] != 'cup' &&
!isTopping(getTypeForRecipeListAtIndex(i)['id'])
"
>
<p *ngIf="getTypeForRecipeListAtIndex(i)['category'] == 'bean'">
Grinder
</p>
<p *ngIf="getTypeForRecipeListAtIndex(i)['category'] == 'whipper'">
Mix
</p>
<p
<div
class="tooltip flex items-center justify-evenly space-x-2 rounded-md bg-red-200 p-2"
data-tip="Hot"
*ngIf="
getTypeForRecipeListAtIndex(i)['category'] == 'others' &&
(getTypeForRecipeListAtIndex(i)['id'] == 8001 ||
getTypeForRecipeListAtIndex(i)['id'] == 8002)
displayByCond(i, 'waterYield', 'not-zero', { compare: undefined })
"
>
Clean
</p>
<input type="text" class="input w-16" formControlName="stirTime" />
<p>sec</p>
<p>Hot</p>
<input
type="text"
class="w-8 bg-transparent"
formControlName="waterYield"
/>
<p>ml</p>
</div>
<div
class="tooltip flex items-center justify-center space-x-2 rounded-md bg-blue-200 p-2"
data-tip="Cold"
*ngIf="
displayByCond(i, 'waterCold', 'not-zero', { compare: undefined })
"
>
<p>Cold</p>
<input
type="text"
class="w-8 bg-transparent"
formControlName="waterCold"
/>
<p>ml</p>
</div>
<div
class="tooltip flex items-center justify-center space-x-2 rounded-md bg-green-300 p-2"
[attr.data-tip]="
getTooltipForStirTime(getTypeForRecipeListAtIndex(i))
"
*ngIf="
displayByCond(i, 'stirTime', 'not-zero', {
compare: undefined
}) &&
getTypeForRecipeListAtIndex(i)['category'] != 'cup' &&
!isTopping(getTypeForRecipeListAtIndex(i)['id'])
"
>
<p>{{getTooltipForStirTime(getTypeForRecipeListAtIndex(i))}}</p>
<input
type="text"
class="bg-transparent w-8"
formControlName="stirTime"
/>
<p>sec</p>
</div>
</div>
<div class="collapse collapse-open" *ngIf="isTopping(getTypeForRecipeListAtIndex(i)['id'])">
<div class="collapse-title">Topping Settings</div>
<div class="collapse-content">
<app-recipe-topping></app-recipe-topping>
</div>
</div>
</td>
</tr>
@ -291,7 +299,11 @@
<summary class="cursor-pointer">Water</summary>
<div class="flex items-center space-x-2">
<p class="text-base m-4">Hot (waterYield)</p>
<input type="text" class="input w-16" formControlName="waterYield" />
<input
type="text"
class="input w-16"
formControlName="waterYield"
/>
<p class="text-base m-4">ml</p>
</div>

View file

@ -32,11 +32,13 @@ import {
inRange
} from 'src/app/shared/helpers/recipe';
import { RecipeToppingComponent } from '../recipe-topping/recipe-topping.component';
@Component({
selector: 'app-recipe-list',
templateUrl: './recipe-list.component.html',
standalone: true,
imports: [NgIf, NgFor, ReactiveFormsModule, FormsModule],
selector: 'app-recipe-list',
templateUrl: './recipe-list.component.html',
standalone: true,
imports: [NgIf, NgFor, ReactiveFormsModule, FormsModule, RecipeToppingComponent]
})
export class RecipeListComponent implements OnInit {
@Input({ required: true }) productCode!: string;
@ -324,9 +326,17 @@ export class RecipeListComponent implements OnInit {
// console.log("make material list by category", this.makeListCategory());
this.showMaterialSelector = false;
this.recipeListData.at(i).get('materialPathId')?.setValue(material);
console.log('set mat ', material, 'to slot', i);
// query material for its name
let materialName = this.fullMaterialList!.find(
(mat) => mat.materialId == material
)!.name;
this.recipeListData.at(i).get('name')?.setValue(
materialName
);
console.log('set mat ', material, materialName,'to slot', i);
}
getTypeForRecipeListAtIndex(i: any) {
@ -501,4 +511,28 @@ export class RecipeListComponent implements OnInit {
this.recipeListData.value[i][key]
);
}
getTooltipForStirTime = (cat: {
category: string;
name: any;
id: any;
}) => {
switch (cat.category) {
case 'whipper':
return 'Mix';
case 'bean':
return 'Grinder';
case 'others':
if(inRange(8001, 8002, cat.id)){
return 'Clean';
}
break;
default:
break;
}
return '';
};
}

View file

@ -0,0 +1,27 @@
<div>
<input type="checkbox" />
<!-- toppingGroup -->
<ng-select
appendTo="body"
[clearable]="false"
[compareWith]="this.compareFunc"
formControlName="groupID"
>
<ng-option
*ngFor="let item of allToppingsDefinitions"
[value]="item.groupId.toString()"
>
<div>{{ item.name }} ({{ item.groupId }})</div>
</ng-option>
</ng-select>
<!-- defaultSelect -->
<ng-select
>
<!-- <ng-option
*ngFor="let item of getMembersByGroupId(getGroupIdByIndex(this.index))"
[value]="item.defaultId.toString()"
>
<div>{{ item.name }} ({{ item.defaultId }})</div>
</ng-option> -->
</ng-select>
</div>

View file

@ -0,0 +1,91 @@
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NgSelectModule } from '@ng-select/ng-select';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { RecipeService } from 'src/app/core/services/recipe.service';
import { ToppingService } from 'src/app/core/services/topping.service';
import { Topping, ToppingGroup, ToppingSet } from 'src/app/core/models/recipe.model';
@Component({
selector: 'app-recipe-topping',
standalone: true,
imports: [CommonModule, NgSelectModule, FormsModule, ReactiveFormsModule],
templateUrl: './recipe-topping.component.html',
})
export class RecipeToppingComponent implements OnInit {
@Input() index: number = 0;
@Input() toppingSet!: ToppingSet;
@Output() toppingSetChange = new EventEmitter<unknown[]>();
allToppings: Topping | undefined = undefined;
allToppingsDefinitions:
| { groupId: string; name: string; members: string; default: string }[]
| null = [{ groupId: '0', name: 'none', members: '0', default: '0' }];
allToppingMembersByGroup: {
id: string;
members: { id: string; name: string }[];
}[] = [];
constructor(
private _recipeService: RecipeService,
private _toppingService: ToppingService
) {}
ngOnInit(): void {
this._toppingService
.getToppings(
this._recipeService.getCurrentCountry(),
this._recipeService.getCurrentFile()
)
.subscribe((data) => {
this.allToppings = data;
// console.log('allToppings', data);
data.ToppingGroup.forEach((group: ToppingGroup) => {
if (this.allToppingsDefinitions != null) {
// this.allToppingsDefinitions = {};
this.allToppingsDefinitions.push({
groupId: group.groupID,
name: group.name,
members: group.idInGroup,
default: group.idDefault,
});
this.allToppingMembersByGroup.push({
id: group.groupID,
members: this.mapToppingListToMember(group.idInGroup.split(',')),
});
}
});
// console.log(this.allToppingsDefinitions);
// console.log('allToppingMembersByGroup', this.allToppingMembersByGroup);
});
}
compareFunc = (a: any, b: any) => a.toString() === b.toString();
mapToppingListToMember = (mm: string[]) =>
mm.map((m) => {
// find actual topping from toppingList
let actualTopping = this.allToppings!.ToppingList.find((t) => t.id == m);
return {
id: actualTopping!.id,
name: actualTopping?.name == null ? m : actualTopping!.name,
};
});
getMembersByGroupId(groupID: string) {
return this.allToppingMembersByGroup.find((x) => x.id == groupID)?.members;
}
getGroupIdByIndex(i: number) {
// console.log("getGroupId",this.toppingList.value![i])
// return (this.toppingList.value![i] as any).groupID as string;
}
// services
}

View file

@ -11,7 +11,7 @@
<div class="flex flex-row py-3 justify-between items-center">
<div class="flex flex-col">
<span
>Recipe Version {{ recipesDashboard.configNumber }} |
>Recipe Version {{ currentVersion }} |
{{ recipesDashboard.filename }}</span
>
</div>

View file

@ -1,4 +1,5 @@
import {
AfterViewInit,
Component,
ElementRef,
OnDestroy,
@ -24,7 +25,7 @@ import {
tap,
} from 'rxjs';
import * as lodash from 'lodash';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { NgSelectModule } from '@ng-select/ng-select';
import { FormsModule } from '@angular/forms';
import { MaterialService } from 'src/app/core/services/material.service';
@ -32,6 +33,7 @@ import { UserService } from 'src/app/core/services/user.service';
import { UserPermissions } from 'src/app/core/auth/userPermissions';
import { ToppingService } from 'src/app/core/services/topping.service';
import { copy, transformToTSV } from 'src/app/shared/helpers/copy';
import { getCountryMapSwitcher } from 'src/app/shared/helpers/recipe';
@Component({
selector: 'app-recipes',
@ -46,7 +48,7 @@ import { copy, transformToTSV } from 'src/app/shared/helpers/copy';
],
templateUrl: './recipes.component.html',
})
export class RecipesComponent implements OnInit, OnDestroy {
export class RecipesComponent implements OnInit, OnDestroy, AfterViewInit {
recipesDashboard$!: Observable<RecipesDashboard>;
recipeOverviewList!: RecipeOverview[];
selectMaterialFilter: number[] | null = null;
@ -89,9 +91,9 @@ export class RecipesComponent implements OnInit, OnDestroy {
department: string = this.route.parent!.snapshot.params['department'];
copyList: any[] = [];
@ViewChild('table', { static: false }) set content(table: ElementRef) {
// expose element ref for other fn
currentVersion: number | undefined = undefined;
@ViewChild('table', { static: false }) set content(table: ElementRef) {
table.nativeElement.addEventListener(
'scroll',
() => {
@ -109,7 +111,7 @@ export class RecipesComponent implements OnInit, OnDestroy {
take: this.take,
search: this.oldSearchStr,
filename: this._recipeService.getCurrentFile(),
country: this._recipeService.getCurrentCountry(),
country: this._recipeService.getCurrentCountry(this.department),
materialIds: this.selectMaterialFilter || [],
})
.subscribe(({ result, hasMore, totalCount }) => {
@ -134,14 +136,16 @@ export class RecipesComponent implements OnInit, OnDestroy {
private _materialService: MaterialService,
private _toppingService: ToppingService,
private route: ActivatedRoute,
private _userService: UserService
private _userService: UserService,
private _router: Router
) {}
ngOnInit(): void {
console.log('Trigger onInit where department = ', this.department);
this.recipesDashboard$ = this._recipeService
.getRecipesDashboard({
filename: this._recipeService.getCurrentFile(),
country: this._recipeService.getCurrentCountry(),
country: this._recipeService.getCurrentCountry(this.department!),
})
.pipe(
finalize(() => {
@ -151,7 +155,7 @@ export class RecipesComponent implements OnInit, OnDestroy {
take: this.take,
search: this.oldSearchStr,
filename: this._recipeService.getCurrentFile(),
country: this._recipeService.getCurrentCountry(),
country: this._recipeService.getCurrentCountry(this.department!),
materialIds: this.selectMaterialFilter || [],
})
.subscribe(({ result, hasMore, totalCount }) => {
@ -163,9 +167,34 @@ export class RecipesComponent implements OnInit, OnDestroy {
})
);
// FIXME: Lag assigned
this.recipesDashboard$.subscribe((data) => {
this.currentVersion = data.configNumber;
console.log('current version', this.currentVersion);
});
console.log('ngAfterViewInit::department', this.department);
console.log('::CurrentFile', this._recipeService.getCurrentFile());
this._materialService
.getFullMaterialDetail(
this.department,
this._recipeService.getCurrentFile()
)
.subscribe((mat) => {
this.materialDetail = mat;
console.log(this.materialDetail?.length);
// check material detail
console.log('first material', this.materialDetail![0]);
});
// end of FIXME
this._recipeService
.getSavedTmp(
this._recipeService.getCurrentCountry(),
this._recipeService.getCurrentCountry(this.department),
this._recipeService.getCurrentFile()
)
.subscribe({
@ -209,16 +238,6 @@ export class RecipesComponent implements OnInit, OnDestroy {
this.materialList = materials;
});
this._materialService
.getFullMaterialDetail(
this.department,
this._recipeService.getCurrentFile()
)
.subscribe((mat) => {
this.materialDetail = mat;
console.log(this.materialDetail?.length);
});
this._toppingService
.getToppings(this.department, this._recipeService.getCurrentFile())
.subscribe((tp) => {
@ -232,6 +251,10 @@ export class RecipesComponent implements OnInit, OnDestroy {
this.initRecipeSelection();
}
ngAfterViewInit(): void {
console.log('After view on init trigger');
}
setSearch(event: Event) {
console.log((event.target as HTMLInputElement).value);
this.searchStr = (event.target as HTMLInputElement).value;
@ -247,7 +270,7 @@ export class RecipesComponent implements OnInit, OnDestroy {
take: this.take,
search: this.oldSearchStr,
filename: this._recipeService.getCurrentFile(),
country: this._recipeService.getCurrentCountry(),
country: this._recipeService.getCurrentCountry(this.department),
materialIds: this.selectMaterialFilter || [],
})
.subscribe(({ result, hasMore, totalCount }) => {
@ -400,7 +423,14 @@ export class RecipesComponent implements OnInit, OnDestroy {
countrySelected(country: string) {
this.selectedCountry = country;
this.isCountrySelected = true;
localStorage.setItem('currentRecipeCountry', country);
// localStorage.setItem('currentRecipeCountry', country);
// force reload, will fix this later
void this._router
.navigate([`/${getCountryMapSwitcher(country)}/recipes`])
.then(() => {
window.location.reload();
});
}
loadRecipe(recipeFileName: string) {
@ -409,11 +439,18 @@ export class RecipesComponent implements OnInit, OnDestroy {
this.isHasMore = true;
this.isLoadMore = true;
this.oldSearchStr = '';
localStorage.setItem('currentRecipeFile', recipeFileName);
// localStorage.setItem('currentRecipeFile', recipeFileName);
console.log('loadRecipe', recipeFileName, "currentCountry", this.department);
this.recipesDashboard$ = this._recipeService.getRecipesDashboard({
filename: recipeFileName,
country: this.selectedCountry!,
country: this.department!,
});
this.recipesDashboard$.subscribe((data) => {
this.currentVersion = data.configNumber;
console.log('current version', this.currentVersion);
});
this._recipeService
@ -438,7 +475,9 @@ export class RecipesComponent implements OnInit, OnDestroy {
openJsonTab() {
window.open(
environment.api +
`/recipes/${this._recipeService.getCurrentCountry()}/${this._recipeService.getCurrentFile()}/json`,
`/recipes/${this._recipeService.getCurrentCountry(
this.department
)}/${this._recipeService.getCurrentFile()}/json`,
'_blank'
);
}
@ -503,26 +542,22 @@ export class RecipesComponent implements OnInit, OnDestroy {
item.name.toLowerCase().includes(term.toLowerCase()) ||
item.materialId.toString().includes(term);
addToCopyList(data: any){
if(this.copyList.includes(data)){
addToCopyList(data: any) {
if (this.copyList.includes(data)) {
let index = this.copyList.indexOf(data);
this.copyList.splice(index, 1);
} else {
this.copyList = [...this.copyList, data];
}
}
async copyToTsv(data: any){
await copy(transformToTSV(data)).then( (value) => {
async copyToTsv(data: any) {
await copy(transformToTSV(data))
.then((value) => {
console.log('copyToTsv', value);
}).catch( (err) => {
})
.catch((err) => {
console.log('copyToTsvErr', err);
});
}
}
}

View file

@ -1,3 +1,5 @@
import { Tuple } from "./tuple";
var rangeMaterialMapping: { [key: string]: (id: number) => boolean } = {
soda: (id: number) => id == 1031,
water: (id: number) => id == 1,
@ -92,5 +94,24 @@ export var stringParamsDefinition: { [key: string]: string } = {
export var conditionTests: { [key: string]: (arg: any) => boolean } = {
'not-zero': (arg: any) => arg != 0,
'zero': (arg: any) => arg == 0,
'false-if-another-exist': (arg: any) => arg[1] != undefined
}
export var countryMap: Tuple<string, string>[] = [
new Tuple<string, string>('tha', 'Thailand'),
new Tuple<string, string>('mys', 'Malaysia'),
new Tuple<string, string>('aus', 'Australia'),
];
export function getCountryMapSwitcher(param: string) {
console.log("param = ", param);
for (const country of countryMap) {
if(country.first == param || country.second == param){
return country.switchGet(param);
}
}
}

View file

@ -0,0 +1,15 @@
export class Tuple<T, U> {
constructor(public first: T, public second: U) {}
public get(): [T, U] {
return [this.first, this.second];
}
public switchGet(elem: any): any{
if(elem == this.first){
return this.second;
} else {
return this.first;
}
}
}

View file

@ -23,13 +23,20 @@ type RecipeWithTimeStamps struct {
}
type Data struct {
CurrentFile string
CurrentCountryID string
AllRecipeFiles map[string][]helpers.RecipePath
currentRecipe *models.Recipe
recipeMap map[string]RecipeWithTimeStamps
Countries []helpers.CountryName
taoLogger *logger.TaoLogger
CurrentFile map[string]string
CurrentCountryID map[string]string
DefaultCountryMap []DefaultByCountry
AllRecipeFiles map[string][]helpers.RecipePath
currentRecipe *models.Recipe
recipeMap map[string]RecipeWithTimeStamps
Countries []helpers.CountryName
taoLogger *logger.TaoLogger
}
type DefaultByCountry struct {
CountryShortName string
CountryLongName string
DefaultFileVersion int
}
var (
@ -53,46 +60,95 @@ func NewData(taoLogger *logger.TaoLogger) *Data {
defaultFile := "coffeethai02_600.json"
defaultCountry := "tha"
// TODO: read 'version' file
versionPath := path.Join("cofffeemachineConfig", defaultCountry, "version")
taoLogger.Log.Debug("version", zap.Any("version path", versionPath))
// TODO: read 'version' file by country
// versionFile, err := os.Open(versionPath)
content, err := os.ReadFile(versionPath)
// versionPath := path.Join("cofffeemachineConfig", defaultCountry, "version")
// taoLogger.Log.Debug("version", zap.Any("version path", versionPath))
if err != nil {
taoLogger.Log.Debug("Error when open version file", zap.Error(err))
}
// // versionFile, err := os.Open(versionPath)
// content, err := os.ReadFile(versionPath)
initVersion := string(content)
// if err != nil {
// taoLogger.Log.Debug("Error when open version file", zap.Error(err))
// }
// read latest version
// set latest to default version
latest_version, err := strconv.Atoi(initVersion)
// initVersion := string(content)
if err != nil {
latest_version = 600
}
// // read latest version
// // set latest to default version
// latest_version, err := strconv.Atoi(initVersion)
for _, v := range allRecipeFiles[defaultCountry] {
// if err != nil {
// latest_version = 600
// }
// extract filename as version
current_version_iter, err := strconv.Atoi(strings.Split(strings.Split(v.Name, "_")[1], ".")[0])
defaultForEachCountry := []DefaultByCountry{}
for _, elem := range countries {
// generate default of all countries
currentVersionPath := path.Join("cofffeemachineConfig", elem.CountryID, "version")
// this is default version for each country
content, err := os.ReadFile(currentVersionPath)
if err != nil {
continue
taoLogger.Log.Debug("Error when open version file", zap.Error(err))
}
if current_version_iter == latest_version {
// taoLogger.Log.Debug("current_version_iter", zap.Any("current_version_iter", current_version_iter))
// set latest
latest_version = current_version_iter
defaultFile = v.Name
break
initVersion := string(content)
// read latest version
latest_version, _ := strconv.Atoi(initVersion)
defaultForEachCountry = append(defaultForEachCountry, DefaultByCountry{CountryShortName: elem.CountryID, CountryLongName: elem.CountryName, DefaultFileVersion: latest_version})
}
currentFileMap := make(map[string]string)
CurrentCountryIDMap := make(map[string]string)
// all default versions as string
versionsString := ""
// loop default for each country
for _, v := range defaultForEachCountry {
for _, v2 := range allRecipeFiles[v.CountryShortName] {
// extract filename as version
current_version_iter, err := strconv.Atoi(strings.Split(strings.Split(v2.Name, "_")[1], ".")[0])
if err != nil {
continue
}
if current_version_iter == v.DefaultFileVersion {
currentFileMap[v.CountryShortName] = v2.Name
CurrentCountryIDMap[v.CountryShortName] = v.CountryLongName
versionsString = versionsString + v.CountryShortName + ":" + strconv.Itoa(current_version_iter) + ","
break
}
}
}
taoLogger.Log.Debug("defaultFile", zap.Any("defaultFile", defaultFile), zap.Any("latest_version", latest_version))
// for _, v := range allRecipeFiles[defaultCountry] {
// // extract filename as version
// current_version_iter, err := strconv.Atoi(strings.Split(strings.Split(v.Name, "_")[1], ".")[0])
// if err != nil {
// continue
// }
// if current_version_iter == latest_version {
// // taoLogger.Log.Debug("current_version_iter", zap.Any("current_version_iter", current_version_iter))
// // set latest
// latest_version = current_version_iter
// defaultFile = v.Name
// break
// }
// }
taoLogger.Log.Debug("defaultFile", zap.Any("defaultFile", defaultFile), zap.Any("latest_version", versionsString))
defaultRecipe, err := helpers.ReadRecipeFile(defaultCountry, defaultFile)
@ -101,8 +157,8 @@ func NewData(taoLogger *logger.TaoLogger) *Data {
}
return &Data{
CurrentFile: defaultFile,
CurrentCountryID: defaultCountry,
CurrentFile: currentFileMap,
CurrentCountryID: CurrentCountryIDMap,
AllRecipeFiles: allRecipeFiles,
currentRecipe: defaultRecipe,
recipeMap: map[string]RecipeWithTimeStamps{
@ -111,8 +167,9 @@ func NewData(taoLogger *logger.TaoLogger) *Data {
TimeStamps: time.Now().Unix(),
},
},
Countries: countries,
taoLogger: taoLogger,
Countries: countries,
taoLogger: taoLogger,
DefaultCountryMap: defaultForEachCountry,
}
}
@ -122,20 +179,25 @@ func (d *Data) GetRecipe(countryID, filename string) *models.Recipe {
return d.currentRecipe
}
if filename == "" || filename == d.CurrentFile {
if filename == "" || filename == d.CurrentFile[countryID] {
return d.currentRecipe
}
if recipe, ok := d.recipeMap[filename]; ok {
d.CurrentFile = filename
d.CurrentCountryID = countryID
d.CurrentFile[countryID] = filename
d.CurrentCountryID[countryID] = countryID
return &recipe.Recipe
}
// change current version and read new recipe
d.CurrentFile = filename
if filename == "default" {
filename = d.CurrentFile[countryID]
}
d.CurrentFile[countryID] = filename
d.taoLogger.Log.Debug("GetRecipe", zap.String("filename", filename), zap.String("countryID", countryID))
d.CurrentCountryID = countryID
d.CurrentCountryID[countryID] = countryID
recipe, err := helpers.ReadRecipeFile(countryID, filename)
if err != nil {
@ -178,7 +240,7 @@ func (d *Data) GetCurrentRecipe() *models.Recipe {
func (d *Data) GetRecipe01ByProductCode(filename, countryID, productCode string) (models.Recipe01, error) {
if !strings.Contains(filename, "tmp") {
if filename == "" || filename == d.CurrentFile {
if filename == "" || filename == d.CurrentFile[countryID] {
fmt.Println("GetRecipe01ByProductCode.ReadCurrent", filename, d.CurrentFile)
for _, v := range d.currentRecipe.Recipe01 {
if v.ProductCode == productCode {
@ -195,12 +257,18 @@ func (d *Data) GetRecipe01ByProductCode(filename, countryID, productCode string)
}
}
d.CurrentFile = filename
d.CurrentCountryID = countryID
d.taoLogger.Log.Debug("GetRecipe01ByProductCode", zap.Any("filename", filename), zap.Any("countryID", countryID), zap.Any("productCode", productCode))
if filename == "default" {
filename = d.CurrentFile[countryID]
}
d.CurrentFile[countryID] = filename
d.CurrentCountryID[countryID] = countryID
for _, v := range countries {
if v.CountryName == countryID {
d.CurrentCountryID = v.CountryID
d.CurrentCountryID[countryID] = v.CountryID
countryID = v.CountryID
break
}
@ -295,7 +363,7 @@ func (d *Data) GetMaterialSetting(countryID, filename string) []models.MaterialS
}
if !strings.Contains(filename, "tmp") {
if filename == "" || filename == d.CurrentFile {
if filename == "" || filename == d.CurrentFile[countryID] {
copy(result, d.currentRecipe.MaterialSetting)
d.taoLogger.Log.Debug("GetMaterialSetting", zap.Any("result", result))
return d.currentRecipe.MaterialSetting
@ -303,14 +371,20 @@ func (d *Data) GetMaterialSetting(countryID, filename string) []models.MaterialS
if recipe, ok := d.recipeMap[filename]; ok {
copy(result, recipe.Recipe.MaterialSetting)
d.CurrentFile = filename
d.CurrentCountryID = countryID
d.CurrentFile[countryID] = filename
d.CurrentCountryID[countryID] = countryID
return d.currentRecipe.MaterialSetting
}
}
d.CurrentFile = filename
d.CurrentCountryID = countryID
if filename == "default" {
filename = d.CurrentFile[countryID]
}
d.taoLogger.Log.Debug("GetMaterialSetting", zap.Any("filename", filename), zap.Any("countryID", countryID))
d.CurrentFile[countryID] = filename
d.CurrentCountryID[countryID] = countryID
recipe, err := helpers.ReadRecipeFile(countryID, filename)
if err != nil {
@ -349,14 +423,19 @@ func (d *Data) GetMaterialSetting(countryID, filename string) []models.MaterialS
func (d *Data) GetMaterialCode(ids []uint64, countryID, filename string) []models.MaterialCode {
var result []models.MaterialCode
if filename == "" || filename == d.CurrentFile {
if filename == "" || filename == d.CurrentFile[countryID] {
result = d.currentRecipe.MaterialCode
} else if recipe, ok := d.recipeMap[filename]; ok {
d.CurrentFile = filename
d.CurrentFile[countryID] = filename
return recipe.Recipe.MaterialCode
} else {
d.CurrentFile = filename
d.CurrentCountryID = countryID
if filename == "default" {
filename = d.CurrentFile[countryID]
}
d.CurrentFile[countryID] = filename
d.CurrentCountryID[countryID] = countryID
recipe, err := helpers.ReadRecipeFile(countryID, filename)
if err != nil {
@ -411,14 +490,19 @@ func (d *Data) GetMaterialCode(ids []uint64, countryID, filename string) []model
func (d *Data) GetToppings(countryID, filename string) models.Topping {
if filename == "" || filename == d.CurrentFile {
if filename == "" || filename == d.CurrentFile[countryID] {
return d.currentRecipe.Topping
} else if recipe, ok := d.recipeMap[filename]; ok {
d.CurrentFile = filename
d.CurrentFile[countryID] = filename
return recipe.Recipe.Topping
}
d.CurrentFile = filename
d.CurrentCountryID = countryID
if filename == "default" {
filename = d.CurrentFile[countryID]
}
d.CurrentFile[countryID] = filename
d.CurrentCountryID[countryID] = countryID
recipe, err := helpers.ReadRecipeFile(countryID, filename)
if err != nil {
@ -432,6 +516,11 @@ func (d *Data) GetToppings(countryID, filename string) models.Topping {
}
func (d *Data) GetToppingsOfRecipe(countryID, filename string, productCode string) ([]models.ToppingSet, error) {
if filename == "default" {
filename = d.CurrentFile[countryID]
}
recipe, err := d.GetRecipe01ByProductCode(filename, countryID, productCode)
if err != nil {
@ -443,6 +532,11 @@ func (d *Data) GetToppingsOfRecipe(countryID, filename string, productCode strin
}
func (d *Data) GetSubmenusOfRecipe(countryID, filename, productCode string) ([]models.Recipe01, error) {
if filename == "default" {
filename = d.CurrentFile[countryID]
}
recipe, err := d.GetRecipe01ByProductCode(filename, countryID, productCode)
if err != nil {

View file

@ -1,11 +1,23 @@
package data
import (
"fmt"
"os"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
)
func NewSqliteDatabase() *sqlx.DB {
// ensure that database exists
info, err := os.Stat("./data/database.db")
if os.IsNotExist(err) {
fmt.Println("No database found. Check path: ", err)
} else {
fmt.Println("Database existed. ", info)
}
db := sqlx.MustConnect("sqlite3", "./data/database.db")
return db
}

View file

@ -75,17 +75,7 @@ func (mr *MaterialRouter) GetFullMaterialDetail(w http.ResponseWriter, r *http.R
})
}
// for _, matCode := range matCodes {
// for index, matDetail := range materialDetails {
// if matCode.MaterialID == matDetail["materialId"] {
// materialDetails[index]["name"] = matCode.PackageDescription
// } else if matDetail["materialId"].(uint64) > 8110 && matDetail["materialId"].(uint64) <= 8130 {
// slotNum := matDetail["materialId"].(uint64) - 8110
// // mr.taoLogger.Log.Debug("GetFullMaterialDetail", zap.Any("slotNum", matDetail["materialId"]), zap.Any("slotNum", slotNum))
// materialDetails[index]["name"] = "Topping" + strconv.Itoa(int(slotNum))
// }
// }
// }
// mr.taoLogger.Log.Debug("GetFullMaterialDetail", zap.Any("materialDetails", materialDetails))
// send result
if err := json.NewEncoder(w).Encode(materialDetails); err != nil {