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

View file

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

View file

@ -7,19 +7,17 @@
class="block p-6 bg-white border border-gray-200 rounded-lg shadow w-full" class="block p-6 bg-white border border-gray-200 rounded-lg shadow w-full"
> >
<div *ngIf="isLoaded; else indicator" [@inOutAnimation]> <div *ngIf="isLoaded; else indicator" [@inOutAnimation]>
<!-- productCode -->
<div>
<!-- productCode --> <input
<div> class="input input-bordered input-xs text-lg text-gray-900 my-2"
<input type="text"
class="input input-bordered input-xs text-lg text-gray-900 my-2" name="productCode"
type="text" [value]="productCode"
name="productCode" (keyup)="onProductCodeChange($event)"
[value]="productCode" [disabled]="!isEditable()"
(keyup)="onProductCodeChange($event)" />
[disabled]="!isEditable()" </div>
/>
</div>
<div class="flex flex-wrap"> <div class="flex flex-wrap">
<h5 class="mb-2 text-xl font-bold text-gray-900"> <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"> <h5 class="mb-2 text-xl font-bold text-gray-900">
{{ recipeDetailForm.getRawValue().otherName }} {{ recipeDetailForm.getRawValue().otherName }}
</h5> </h5>
</div> </div>
<div class="flex items-center mb-2"> <div class="flex items-center mb-2">
<div class="flex items-center"> <div class="flex items-center">
@ -110,7 +107,12 @@
<div *ngIf="hasSubmenu()"> <div *ngIf="hasSubmenu()">
<div *ngFor="let sub of listSubMenuProductcodes()"> <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> </div>
</div> </div>
@ -118,45 +120,52 @@
</div> </div>
<div id="recipeList" class="carousel-item w-full"> <div id="recipeList" class="carousel-item w-full">
<div <div
class="overflow-auto h-[75vh] mb-4 rounded bg-white border border-gray-200 shadow w-1/2" class="overflow-auto h-[75vh] mb-4 rounded bg-white border border-gray-200 shadow"
> >
<app-recipe-list <app-recipe-list
[productCode]="productCode" [productCode]="productCode"
[isSubMenu]="false" [isSubMenu]="false"
(recipeListFormChange)="onRecipeListFormChange($event)" (recipeListFormChange)="onRecipeListFormChange($event)"
></app-recipe-list> ></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>
</div> </div>
</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> </div>
<!-- try pop up modal --> <!-- try pop up modal -->
<!-- TODO: do topping --> <!-- TODO: do topping -->
<div <div
class="sticky bottom-0 col-span-3 max-w-screen-lg flex justify-end bg-white rounded-full drop-shadow-2xl p-3" 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">
<div class="flex justify-center w-full start-0 py-2"> <a
<a href="{{department}}/recipe/{{productCode}}#name" class="btn btn-xs">1</a> href="{{ department }}/recipe/{{ productCode }}#name"
<a href="{{department}}/recipe/{{productCode}}#recipeList" class="btn btn-xs">2</a> class="btn btn-xs"
<a href="{{department}}/recipe/{{productCode}}#toppingSet" class="btn btn-xs">3</a> >1</a
</div> >
<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> --> <!-- <div> Commit Message </div> -->
<!-- <p class="text-2xl mr-8 text-gray-400 dark:text-gray-500">Commit Message</p> --> <!-- <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.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); console.log('Submenus', data);
this.submenus = data; this.submenus = data;
}); });
@ -177,7 +177,7 @@ export class RecipeDetailsComponent implements OnInit {
// TODO: update value in targeted recipe // TODO: update value in targeted recipe
console.log('to_send', to_send); console.log('to_send', to_send);
this._recipeService.editChanges( this._recipeService.editChanges(
this._recipeService.getCurrentCountry(), this._recipeService.getCurrentCountry(this.department),
this._recipeService.getCurrentFile(), this._recipeService.getCurrentFile(),
{ {
...to_send, ...to_send,

View file

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

View file

@ -32,11 +32,13 @@ import {
inRange inRange
} from 'src/app/shared/helpers/recipe'; } from 'src/app/shared/helpers/recipe';
import { RecipeToppingComponent } from '../recipe-topping/recipe-topping.component';
@Component({ @Component({
selector: 'app-recipe-list', selector: 'app-recipe-list',
templateUrl: './recipe-list.component.html', templateUrl: './recipe-list.component.html',
standalone: true, standalone: true,
imports: [NgIf, NgFor, ReactiveFormsModule, FormsModule], imports: [NgIf, NgFor, ReactiveFormsModule, FormsModule, RecipeToppingComponent]
}) })
export class RecipeListComponent implements OnInit { export class RecipeListComponent implements OnInit {
@Input({ required: true }) productCode!: string; @Input({ required: true }) productCode!: string;
@ -324,9 +326,17 @@ export class RecipeListComponent implements OnInit {
// console.log("make material list by category", this.makeListCategory()); // console.log("make material list by category", this.makeListCategory());
this.showMaterialSelector = false; this.showMaterialSelector = false;
this.recipeListData.at(i).get('materialPathId')?.setValue(material); 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) { getTypeForRecipeListAtIndex(i: any) {
@ -501,4 +511,28 @@ export class RecipeListComponent implements OnInit {
this.recipeListData.value[i][key] 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-row py-3 justify-between items-center">
<div class="flex flex-col"> <div class="flex flex-col">
<span <span
>Recipe Version {{ recipesDashboard.configNumber }} | >Recipe Version {{ currentVersion }} |
{{ recipesDashboard.filename }}</span {{ recipesDashboard.filename }}</span
> >
</div> </div>

View file

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

View file

@ -1,3 +1,5 @@
import { Tuple } from "./tuple";
var rangeMaterialMapping: { [key: string]: (id: number) => boolean } = { var rangeMaterialMapping: { [key: string]: (id: number) => boolean } = {
soda: (id: number) => id == 1031, soda: (id: number) => id == 1031,
water: (id: number) => id == 1, water: (id: number) => id == 1,
@ -92,5 +94,24 @@ export var stringParamsDefinition: { [key: string]: string } = {
export var conditionTests: { [key: string]: (arg: any) => boolean } = { export var conditionTests: { [key: string]: (arg: any) => boolean } = {
'not-zero': (arg: any) => arg != 0, 'not-zero': (arg: any) => arg != 0,
'zero': (arg: any) => arg == 0,
'false-if-another-exist': (arg: any) => arg[1] != undefined '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 { type Data struct {
CurrentFile string CurrentFile map[string]string
CurrentCountryID string CurrentCountryID map[string]string
AllRecipeFiles map[string][]helpers.RecipePath DefaultCountryMap []DefaultByCountry
currentRecipe *models.Recipe AllRecipeFiles map[string][]helpers.RecipePath
recipeMap map[string]RecipeWithTimeStamps currentRecipe *models.Recipe
Countries []helpers.CountryName recipeMap map[string]RecipeWithTimeStamps
taoLogger *logger.TaoLogger Countries []helpers.CountryName
taoLogger *logger.TaoLogger
}
type DefaultByCountry struct {
CountryShortName string
CountryLongName string
DefaultFileVersion int
} }
var ( var (
@ -53,46 +60,95 @@ func NewData(taoLogger *logger.TaoLogger) *Data {
defaultFile := "coffeethai02_600.json" defaultFile := "coffeethai02_600.json"
defaultCountry := "tha" defaultCountry := "tha"
// TODO: read 'version' file // TODO: read 'version' file by country
versionPath := path.Join("cofffeemachineConfig", defaultCountry, "version")
taoLogger.Log.Debug("version", zap.Any("version path", versionPath))
// versionFile, err := os.Open(versionPath) // versionPath := path.Join("cofffeemachineConfig", defaultCountry, "version")
content, err := os.ReadFile(versionPath) // taoLogger.Log.Debug("version", zap.Any("version path", versionPath))
if err != nil { // // versionFile, err := os.Open(versionPath)
taoLogger.Log.Debug("Error when open version file", zap.Error(err)) // 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 // initVersion := string(content)
// set latest to default version
latest_version, err := strconv.Atoi(initVersion)
if err != nil { // // read latest version
latest_version = 600 // // 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 defaultForEachCountry := []DefaultByCountry{}
current_version_iter, err := strconv.Atoi(strings.Split(strings.Split(v.Name, "_")[1], ".")[0])
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 { if err != nil {
continue taoLogger.Log.Debug("Error when open version file", zap.Error(err))
} }
if current_version_iter == latest_version { initVersion := string(content)
// taoLogger.Log.Debug("current_version_iter", zap.Any("current_version_iter", current_version_iter))
// set latest // read latest version
latest_version = current_version_iter latest_version, _ := strconv.Atoi(initVersion)
defaultFile = v.Name defaultForEachCountry = append(defaultForEachCountry, DefaultByCountry{CountryShortName: elem.CountryID, CountryLongName: elem.CountryName, DefaultFileVersion: latest_version})
break }
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) defaultRecipe, err := helpers.ReadRecipeFile(defaultCountry, defaultFile)
@ -101,8 +157,8 @@ func NewData(taoLogger *logger.TaoLogger) *Data {
} }
return &Data{ return &Data{
CurrentFile: defaultFile, CurrentFile: currentFileMap,
CurrentCountryID: defaultCountry, CurrentCountryID: CurrentCountryIDMap,
AllRecipeFiles: allRecipeFiles, AllRecipeFiles: allRecipeFiles,
currentRecipe: defaultRecipe, currentRecipe: defaultRecipe,
recipeMap: map[string]RecipeWithTimeStamps{ recipeMap: map[string]RecipeWithTimeStamps{
@ -111,8 +167,9 @@ func NewData(taoLogger *logger.TaoLogger) *Data {
TimeStamps: time.Now().Unix(), TimeStamps: time.Now().Unix(),
}, },
}, },
Countries: countries, Countries: countries,
taoLogger: taoLogger, taoLogger: taoLogger,
DefaultCountryMap: defaultForEachCountry,
} }
} }
@ -122,20 +179,25 @@ func (d *Data) GetRecipe(countryID, filename string) *models.Recipe {
return d.currentRecipe return d.currentRecipe
} }
if filename == "" || filename == d.CurrentFile { if filename == "" || filename == d.CurrentFile[countryID] {
return d.currentRecipe return d.currentRecipe
} }
if recipe, ok := d.recipeMap[filename]; ok { if recipe, ok := d.recipeMap[filename]; ok {
d.CurrentFile = filename d.CurrentFile[countryID] = filename
d.CurrentCountryID = countryID d.CurrentCountryID[countryID] = countryID
return &recipe.Recipe return &recipe.Recipe
} }
// change current version and read new 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.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) recipe, err := helpers.ReadRecipeFile(countryID, filename)
if err != nil { if err != nil {
@ -178,7 +240,7 @@ func (d *Data) GetCurrentRecipe() *models.Recipe {
func (d *Data) GetRecipe01ByProductCode(filename, countryID, productCode string) (models.Recipe01, error) { func (d *Data) GetRecipe01ByProductCode(filename, countryID, productCode string) (models.Recipe01, error) {
if !strings.Contains(filename, "tmp") { if !strings.Contains(filename, "tmp") {
if filename == "" || filename == d.CurrentFile { if filename == "" || filename == d.CurrentFile[countryID] {
fmt.Println("GetRecipe01ByProductCode.ReadCurrent", filename, d.CurrentFile) fmt.Println("GetRecipe01ByProductCode.ReadCurrent", filename, d.CurrentFile)
for _, v := range d.currentRecipe.Recipe01 { for _, v := range d.currentRecipe.Recipe01 {
if v.ProductCode == productCode { if v.ProductCode == productCode {
@ -195,12 +257,18 @@ func (d *Data) GetRecipe01ByProductCode(filename, countryID, productCode string)
} }
} }
d.CurrentFile = filename d.taoLogger.Log.Debug("GetRecipe01ByProductCode", zap.Any("filename", filename), zap.Any("countryID", countryID), zap.Any("productCode", productCode))
d.CurrentCountryID = countryID
if filename == "default" {
filename = d.CurrentFile[countryID]
}
d.CurrentFile[countryID] = filename
d.CurrentCountryID[countryID] = countryID
for _, v := range countries { for _, v := range countries {
if v.CountryName == countryID { if v.CountryName == countryID {
d.CurrentCountryID = v.CountryID d.CurrentCountryID[countryID] = v.CountryID
countryID = v.CountryID countryID = v.CountryID
break break
} }
@ -295,7 +363,7 @@ func (d *Data) GetMaterialSetting(countryID, filename string) []models.MaterialS
} }
if !strings.Contains(filename, "tmp") { if !strings.Contains(filename, "tmp") {
if filename == "" || filename == d.CurrentFile { if filename == "" || filename == d.CurrentFile[countryID] {
copy(result, d.currentRecipe.MaterialSetting) copy(result, d.currentRecipe.MaterialSetting)
d.taoLogger.Log.Debug("GetMaterialSetting", zap.Any("result", result)) d.taoLogger.Log.Debug("GetMaterialSetting", zap.Any("result", result))
return d.currentRecipe.MaterialSetting return d.currentRecipe.MaterialSetting
@ -303,14 +371,20 @@ func (d *Data) GetMaterialSetting(countryID, filename string) []models.MaterialS
if recipe, ok := d.recipeMap[filename]; ok { if recipe, ok := d.recipeMap[filename]; ok {
copy(result, recipe.Recipe.MaterialSetting) copy(result, recipe.Recipe.MaterialSetting)
d.CurrentFile = filename d.CurrentFile[countryID] = filename
d.CurrentCountryID = countryID d.CurrentCountryID[countryID] = countryID
return d.currentRecipe.MaterialSetting return d.currentRecipe.MaterialSetting
} }
} }
d.CurrentFile = filename if filename == "default" {
d.CurrentCountryID = countryID 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) recipe, err := helpers.ReadRecipeFile(countryID, filename)
if err != nil { 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 { func (d *Data) GetMaterialCode(ids []uint64, countryID, filename string) []models.MaterialCode {
var result []models.MaterialCode var result []models.MaterialCode
if filename == "" || filename == d.CurrentFile { if filename == "" || filename == d.CurrentFile[countryID] {
result = d.currentRecipe.MaterialCode result = d.currentRecipe.MaterialCode
} else if recipe, ok := d.recipeMap[filename]; ok { } else if recipe, ok := d.recipeMap[filename]; ok {
d.CurrentFile = filename d.CurrentFile[countryID] = filename
return recipe.Recipe.MaterialCode return recipe.Recipe.MaterialCode
} else { } 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) recipe, err := helpers.ReadRecipeFile(countryID, filename)
if err != nil { 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 { func (d *Data) GetToppings(countryID, filename string) models.Topping {
if filename == "" || filename == d.CurrentFile { if filename == "" || filename == d.CurrentFile[countryID] {
return d.currentRecipe.Topping return d.currentRecipe.Topping
} else if recipe, ok := d.recipeMap[filename]; ok { } else if recipe, ok := d.recipeMap[filename]; ok {
d.CurrentFile = filename d.CurrentFile[countryID] = filename
return recipe.Recipe.Topping 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) recipe, err := helpers.ReadRecipeFile(countryID, filename)
if err != nil { 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) { 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) recipe, err := d.GetRecipe01ByProductCode(filename, countryID, productCode)
if err != nil { 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) { 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) recipe, err := d.GetRecipe01ByProductCode(filename, countryID, productCode)
if err != nil { if err != nil {

View file

@ -1,11 +1,23 @@
package data package data
import ( import (
"fmt"
"os"
"github.com/jmoiron/sqlx" "github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3" _ "github.com/mattn/go-sqlite3"
) )
func NewSqliteDatabase() *sqlx.DB { 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") db := sqlx.MustConnect("sqlite3", "./data/database.db")
return db return db
} }

View file

@ -75,17 +75,7 @@ func (mr *MaterialRouter) GetFullMaterialDetail(w http.ResponseWriter, r *http.R
}) })
} }
// for _, matCode := range matCodes { // mr.taoLogger.Log.Debug("GetFullMaterialDetail", zap.Any("materialDetails", materialDetails))
// 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))
// }
// }
// }
// send result // send result
if err := json.NewEncoder(w).Encode(materialDetails); err != nil { if err := json.NewEncoder(w).Encode(materialDetails); err != nil {