update recipe detail and recipe detail list

This commit is contained in:
Kenta420 2023-11-24 17:47:44 +07:00
parent 8b45ed53ee
commit d52cad09fd
16 changed files with 947 additions and 458 deletions

View file

@ -1,3 +1,50 @@
export type RecipeOverview = {
id: string;
productCode: string;
name: string;
otherName: string;
description: string;
lastUpdated: Date;
};
export type RecipesDashboard = {
configNumber: number;
LastUpdated: Date;
filename: string;
};
export type RecipeOverviewList = {
result: RecipeOverview[];
hasMore: boolean;
totalCount: number;
};
export type RecipeDetail = {
name: string;
otherName: string;
description: string;
otherDescription: string;
lastUpdated: Date;
picture: string;
};
export type RecipeDetailMat = {
materialID: number;
name: string;
mixOrder: number;
feedParameter: number;
feedPattern: number;
isUse: boolean;
materialPathId: number;
powderGram: number;
powderTime: number;
stirTime: number;
syrupGram: number;
syrupTime: number;
waterCold: number;
waterYield: number;
};
export interface Recipe {
Timestamp: Date;
MachineSetting: MachineSetting;

View file

@ -1,18 +1,31 @@
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, tap } from 'rxjs';
import { Recipe, Recipe01 } from '../models/recipe.model';
import {
Recipe,
Recipe01,
RecipeDetail,
RecipeDetailMat,
RecipeOverview,
RecipeOverviewList,
RecipesDashboard,
} from '../models/recipe.model';
import { environment } from 'src/environments/environment';
import { RecipeMetaData } from 'src/app/shared/types/recipe';
interface RecipeParams {
type RecipeOverviewParams = {
filename: string;
country: string;
materialIds: number[];
offset: number;
take: number;
search: string;
}
};
type RecipeDashboardParams = {
filename: string;
country: string;
};
interface RecipeFiles {
[key: string]: string[];
@ -25,36 +38,80 @@ export class RecipeService {
constructor(private _httpClient: HttpClient) {}
getRecipes(
params: RecipeParams = {
take: 10,
offset: 0,
search: '',
getRecipesDashboard(
params: RecipeDashboardParams = {
country: this.getCurrentCountry(),
filename: this.getCurrentFile(),
}
): Observable<RecipesDashboard> {
return this._httpClient.get<RecipesDashboard>(
environment.api + '/recipes/dashboard',
{
params: {
country: params.country,
filename: params.filename,
},
withCredentials: true,
responseType: 'json',
}
);
}
getRecipeOverview(
params: RecipeOverviewParams = {
country: this.getCurrentCountry(),
filename: this.getCurrentFile(),
materialIds: [],
offset: 0,
take: 20,
search: '',
}
): Observable<{
fileName: string;
recipes: Recipe;
hasMore: boolean;
}> {
return this._httpClient.get<{
fileName: string;
recipes: Recipe;
hasMore: boolean;
}>(environment.api + '/recipes', {
params: {
offset: params.offset,
take: params.take,
search: params.search,
country: params.country,
filename: params.filename,
material_ids: params.materialIds.join(','),
},
withCredentials: true,
responseType: 'json',
});
): Observable<RecipeOverviewList> {
return this._httpClient.get<RecipeOverviewList>(
environment.api + '/recipes/overview',
{
params: {
country: params.country,
filename: params.filename,
materialIds: params.materialIds.join(','),
offset: params.offset.toString(),
take: params.take.toString(),
search: params.search,
},
withCredentials: true,
responseType: 'json',
}
);
}
getRecipeDetail(productCode: string): Observable<RecipeDetail> {
return this._httpClient.get<RecipeDetail>(
environment.api + '/recipes/' + productCode,
{
params: {
filename: this.getCurrentFile(),
country: this.getCurrentCountry(),
},
withCredentials: true,
responseType: 'json',
}
);
}
getRecipeDetailMat(
productCode: string
): Observable<{ result: RecipeDetailMat[] }> {
return this._httpClient.get<{ result: RecipeDetailMat[] }>(
environment.api + '/recipes/' + productCode + '/mat',
{
params: {
filename: this.getCurrentFile(),
country: this.getCurrentCountry(),
},
withCredentials: true,
responseType: 'json',
}
);
}
getCurrentFile(): string {

View file

@ -1,16 +1,16 @@
<div class="p-4">
<form class="grid grid-cols-3 gap-4 mb-4" [formGroup]="recipeDetail">
<form class="grid grid-cols-3 gap-4 mb-4" [formGroup]="recipeDetailForm">
<div
class="block col-span-1 p-6 bg-white border border-gray-200 rounded-lg shadow"
>
<div *ngIf="isLoaded; else indicator" [@inOutAnimation]>
<div class="flex flex-wrap">
<h5 class="mb-2 text-xl font-bold text-gray-900">
{{ recipeDetail.value.name }}
{{ recipeDetailForm.getRawValue().name }}
</h5>
<h5 class="mb-2 px-3 text-xl font-bold text-gray-900">|</h5>
<h5 class="mb-2 text-xl font-bold text-gray-900">
{{ recipeDetail.value.otherName }}
{{ recipeDetailForm.getRawValue().otherName }}
</h5>
</div>
<div class="flex items-center mb-2">
@ -18,7 +18,8 @@
<p class="text-sm text-gray-500">Last Modify</p>
<p class="ml-2 text-sm text-gray-900">
{{
recipeDetail.value.lastModified | date : "dd/MM/yyyy HH:mm:ss"
recipeDetailForm.getRawValue().lastModified
| date : "dd/MM/yyyy HH:mm:ss"
}}
</p>
</div>
@ -109,11 +110,13 @@
</div>
</div>
<div
class="col-span-3 min-h-[500px] max-h-[500px] overflow-auto mb-4 rounded bg-white border border-gray-200 shadow"
class="col-span-3 overflow-auto mb-4 rounded bg-white border border-gray-200 shadow"
>
<app-recipe-list
[matRecipeList]="materialListIds$"
[parentForm]="recipeDetail"
[parentForm]="recipeDetailForm"
[productCode]="productCode"
[actionRecord]="actionRecord"
[recipeDetailOriginal]="recipeOriginalDetail"
></app-recipe-list>
</div>
<div class="grid grid-cols-2 gap-4 mb-4">

View file

@ -1,32 +1,25 @@
import { DatePipe, NgFor, NgIf } from '@angular/common';
import { CommonModule, DatePipe } from '@angular/common';
import { Component, EventEmitter, OnInit } from '@angular/core';
import {
FormArray,
FormControl,
FormGroup,
ReactiveFormsModule,
} from '@angular/forms';
import { FormBuilder, ReactiveFormsModule } from '@angular/forms';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { isEqual } from 'lodash';
import { BehaviorSubject, Subject, finalize, map } from 'rxjs';
import { Observable, first } from 'rxjs';
import { RecipeService } from 'src/app/core/services/recipe.service';
import { ConfirmModal } from 'src/app/shared/modal/confirm/confirm-modal.component';
import { animate, style, transition, trigger } from '@angular/animations';
import { MaterialService } from 'src/app/core/services/material.service';
import { RecipeMetaData, RecipeDetail } from 'src/app/shared/types/recipe';
import { RecipeListComponent } from './recipe-list/recipe-list.component';
import {
RecipeListComponent,
RecipeListDataFormGroup,
} from './recipe-list/recipe-list.component';
import { MatRecipe } from 'src/app/core/models/recipe.model';
RecipeDetail,
RecipeDetailMat,
} from 'src/app/core/models/recipe.model';
import { Action, ActionRecord } from 'src/app/shared/actionRecord/actionRecord';
import { isEqual } from 'lodash';
@Component({
selector: 'app-recipe-details',
templateUrl: './recipe-details.component.html',
standalone: true,
imports: [
NgIf,
NgFor,
CommonModule,
RouterLink,
ReactiveFormsModule,
ConfirmModal,
@ -44,88 +37,65 @@ import { MatRecipe } from 'src/app/core/models/recipe.model';
})
export class RecipeDetailsComponent implements OnInit {
title: string = 'Recipe Detail';
recipeMetaData: RecipeMetaData | null = null;
originalRecipeDetail: BehaviorSubject<RecipeDetail | null> =
new BehaviorSubject<RecipeDetail | null>(null);
matForRecipeList = this.originalRecipeDetail.pipe(
map((x) => x?.recipe.recipes)
);
recipeDetail$!: Observable<RecipeDetail>;
isLoaded: boolean = false;
isMatLoaded: boolean = false;
actionRecord: ActionRecord<RecipeDetail | RecipeDetailMat> =
new ActionRecord();
recipeOriginalDetail!: typeof this.recipeDetailForm.value;
constructor(
private _formBuilder: FormBuilder,
private _route: ActivatedRoute,
private _router: Router,
private _recipeService: RecipeService
) {}
recipeDetail = new FormGroup({
productCode: new FormControl<string>(''),
name: new FormControl<string>(''),
otherName: new FormControl<string>(''),
description: new FormControl<string>(''),
otherDescription: new FormControl<string>(''),
lastModified: new FormControl<Date>(new Date()),
price: new FormControl<number>(0),
isUse: new FormControl<boolean>(false),
isShow: new FormControl<boolean>(false),
disable: new FormControl<boolean>(false),
productCode!: string;
recipeDetailForm = this._formBuilder.group({
productCode: '',
name: '',
otherName: '',
description: '',
otherDescription: '',
lastModified: new Date(),
price: 0,
isUse: false,
isShow: false,
disable: false,
recipeListData: this._formBuilder.array([]),
});
materialListIds$: Subject<{
ids: number[];
matRecipeList: MatRecipe[];
}> = new Subject<{
ids: number[];
matRecipeList: MatRecipe[];
}>();
ngOnInit() {
this._recipeService
.getRecipesById(this._route.snapshot.params['productCode'])
.pipe(finalize(() => {}))
.subscribe(({ recipe, recipeMetaData }) => {
this.title = recipe.name + ' | ' + recipe.productCode;
this.recipeDetail.patchValue({
productCode: recipe.productCode,
name: recipe.name,
otherName: recipe.otherName,
description: recipe.Description,
otherDescription: recipe.otherDescription,
lastModified: recipe.LastChange,
price: recipe.cashPrice,
isUse: recipe.isUse,
isShow: recipe.isShow,
disable: recipe.disable,
});
this.originalRecipeDetail.next({
recipe: {
lastModified: recipe.LastChange,
productCode: recipe.productCode,
name: recipe.name,
otherName: recipe.otherName,
description: recipe.Description,
otherDescription: recipe.otherDescription,
price: recipe.cashPrice,
isUse: recipe.isUse,
isShow: recipe.isShow,
disable: recipe.disable,
},
recipes: recipe.recipes,
});
this.productCode = this._route.snapshot.params['productCode'];
const ids = recipe.recipes?.map((recipe) => recipe.materialPathId);
this.materialListIds$.next({
ids: ids || [],
matRecipeList: recipe.recipes || [],
});
this.recipeDetail$ = this._recipeService
.getRecipeDetail(this.productCode)
.pipe(first());
this.recipeDetail$.subscribe((detail) => {
this.recipeDetailForm.patchValue(detail);
this.isLoaded = true;
this.recipeOriginalDetail = { ...this.recipeDetailForm.getRawValue() };
});
this.recipeMetaData = recipeMetaData;
this.isLoaded = true;
});
// snap recipe detail form value
this.actionRecord.registerOnAddAction((currAction, allAction) => {
if (currAction.type === 'recipeListData') {
switch (currAction.action) {
case 'add':
break;
case 'delete':
break;
}
}
console.log('Action Record', allAction);
});
}
showConfirmSaveModal: EventEmitter<boolean> = new EventEmitter<boolean>();
@ -137,13 +107,13 @@ export class RecipeDetailsComponent implements OnInit {
confirmCallBack: () => {
console.log('confirm save');
// TODO: update value in targeted recipe
this._recipeService.editChanges(
this._recipeService.getCurrentCountry(),
this._recipeService.getCurrentFile(),
{
...this.recipeDetail,
}
);
// this._recipeService.editChanges(
// this._recipeService.getCurrentCountry(),
// this._recipeService.getCurrentFile(),
// {
// ...this.recipeDetail,
// }
// );
console.log('Sending changes');
this._router.navigate(['/recipes']);
},
@ -176,8 +146,8 @@ export class RecipeDetailsComponent implements OnInit {
get isValueChanged() {
return !isEqual(
this.recipeDetail.value,
this.originalRecipeDetail.getValue()?.recipe
this.recipeOriginalDetail,
this.recipeDetailForm.getRawValue()
);
}
}

View file

@ -1,7 +1,7 @@
<table class="table" [formGroup]="parentForm">
<thead>
<tr class="bg-gray-200">
<th class="px-6 py-3">Enable</th>
<th class="px-6 py-3">Action</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">MixOrder</th>
@ -11,55 +11,57 @@
<th class="px-6 py-3">Syrup Gram</th>
<th class="px-6 py-3">Syrup Time</th>
<th class="px-6 py-3">Water Cold</th>
<th class="px-6 py-3">Water Hot</th>
<th class="px-6 py-3">Water Yield</th>
</tr>
</thead>
<tbody formArrayName="recipes" *ngIf="isMatLoaded">
<tr
*ngFor="let mat of recipeListData.controls; let i = index"
class="bg-white la border-b hover:bg-secondary"
>
<div formGroupName="{{ i }}">
<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap">
<label>
<input
type="checkbox"
class="toggle toggle-sm"
formControlName="enable"
/>
</label>
</td>
<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap">
<input type="text" class="input" formControlName="id" />
</td>
<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap">
<input type="text" class="input" formControlName="name" />
</td>
<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap">
<input type="text" class="input" formControlName="mixOrder" />
</td>
<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap">
<input type="text" class="input" formControlName="stirTime" />
</td>
<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap">
<input type="text" class="input" formControlName="powderGram" />
</td>
<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap">
<input type="text" class="input" formControlName="powderTime" />
</td>
<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap">
<input type="text" class="input" formControlName="SyrupGram" />
</td>
<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap">
<input type="text" class="input" formControlName="SyrupTime" />
</td>
<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap">
<input type="text" class="input" formControlName="waterCold" />
</td>
<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap">
<input type="text" class="input" formControlName="waterHot" />
</td>
</div>
<tbody
formArrayName="recipeListData"
*ngFor="let mat of recipeListData.controls; let i = index"
>
<tr class="bg-white la border-b hover:bg-secondary" formGroupName="{{ i }}">
<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap">
<button
class="btn btn-primary"
(click)="deleteRecipeData(i)"
type="button"
>
Delete
</button>
<button class="btn btn-primary" (click)="addRecipeData()" type="button">
Add
</button>
</td>
<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap">
<input type="text" class="input" formControlName="materialID" />
</td>
<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap">
<input type="text" class="input" formControlName="name" />
</td>
<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap">
<input type="text" class="input" formControlName="mixOrder" />
</td>
<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap">
<input type="text" class="input" formControlName="powderGram" />
</td>
<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap">
<input type="text" class="input" formControlName="powderTime" />
</td>
<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap">
<input type="text" class="input" formControlName="syrupGram" />
</td>
<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap">
<input type="text" class="input" formControlName="syrupTime" />
</td>
<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap">
<input type="text" class="input" formControlName="waterCold" />
</td>
<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap">
<input type="text" class="input" formControlName="waterYield" />
</td>
<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap">
<input type="text" class="input" formControlName="stirTime" />
</td>
</tr>
</tbody>
</table>

View file

@ -2,13 +2,18 @@ import { NgFor, NgIf } from '@angular/common';
import { Component, Input, OnInit } from '@angular/core';
import {
FormArray,
FormBuilder,
FormControl,
FormGroup,
ReactiveFormsModule,
} from '@angular/forms';
import { Observable } from 'rxjs';
import { MatRecipe } from 'src/app/core/models/recipe.model';
import { MaterialService } from 'src/app/core/services/material.service';
import { first } from 'rxjs';
import {
RecipeDetail,
RecipeDetailMat,
} from 'src/app/core/models/recipe.model';
import { RecipeService } from 'src/app/core/services/recipe.service';
import { Action, ActionRecord } from 'src/app/shared/actionRecord/actionRecord';
export interface RecipeListDataFormGroup {
id: FormControl<number | null>;
@ -31,97 +36,86 @@ export interface RecipeListDataFormGroup {
imports: [NgIf, NgFor, ReactiveFormsModule],
})
export class RecipeListComponent implements OnInit {
@Input({ required: true }) matRecipeList!: Observable<{
ids: number[];
matRecipeList: MatRecipe[];
}>;
@Input({ required: true }) parentForm!: FormGroup;
@Input({ required: true }) actionRecord!: ActionRecord<
RecipeDetail | RecipeDetailMat
>;
recipeListData!: FormArray<FormGroup<RecipeListDataFormGroup>>;
@Input({ required: true }) recipeDetailOriginal!: any;
@Input({ required: true }) productCode!: string;
isMatLoaded: boolean = false;
constructor(private _materialService: MaterialService) {}
constructor(
private _recipeService: RecipeService,
private _formBuilder: FormBuilder
) {}
ngOnInit(): void {
this.matRecipeList.subscribe((x) => {
this._materialService.getMaterialCodes(x.ids).subscribe((data) => {
const matList = x.matRecipeList
.map((item) => {
for (let i = 0; i < data.length; i++) {
if (item.materialPathId === 0) {
return {
id: 0,
name: '',
enable: item.isUse,
mixOrder: item.MixOrder,
stirTime: item.stirTime,
powderGram: item.powderGram,
powderTime: item.powderTime,
syrupGram: item.syrupGram,
syrupTime: item.syrupTime,
waterCold: item.waterCold,
waterHot: item.waterYield,
};
}
if (item.materialPathId === data[i].materialID) {
return {
id: data[i].materialID,
name: data[i].PackageDescription,
enable: item.isUse,
mixOrder: item.MixOrder,
stirTime: item.stirTime,
powderGram: item.powderGram,
powderTime: item.powderTime,
syrupGram: item.syrupGram,
syrupTime: item.syrupTime,
waterCold: item.waterCold,
waterHot: item.waterYield,
};
}
}
return {
id: item.materialPathId,
name: '',
enable: item.isUse,
mixOrder: item.MixOrder,
stirTime: item.stirTime,
powderGram: item.powderGram,
powderTime: item.powderTime,
syrupGram: item.syrupGram,
syrupTime: item.syrupTime,
waterCold: item.waterCold,
waterHot: item.waterYield,
};
})
.sort((a, b) => {
return a.id === 0 ? 1 : a.id > b.id ? 1 : -1;
});
this.recipeListData = new FormArray<FormGroup<RecipeListDataFormGroup>>(
matList.map((item) => {
return new FormGroup<RecipeListDataFormGroup>({
id: new FormControl<number>(item.id),
name: new FormControl<string>(item.name),
enable: new FormControl<boolean>(item.enable),
mixOrder: new FormControl<number>(item.mixOrder),
stirTime: new FormControl<number>(item.stirTime),
powderGram: new FormControl<number>(item.powderGram),
powderTime: new FormControl<number>(item.powderTime),
syrupGram: new FormControl<number>(item.syrupGram),
syrupTime: new FormControl<number>(item.syrupTime),
waterCold: new FormControl<number>(item.waterCold),
waterHot: new FormControl<number>(item.waterHot),
});
})
);
this.parentForm.addControl('recipes', this.recipeListData);
console.log(this.parentForm);
this._recipeService
.getRecipeDetailMat(this.productCode)
.pipe(first())
.subscribe(({ result }) => {
if (this.recipeDetailOriginal)
this.recipeDetailOriginal.recipeListData = result;
else this.recipeDetailOriginal = { recipeListData: result };
result.forEach((recipeDetailMat: RecipeDetailMat) => {
this.recipeListData.push(
this._formBuilder.group({
materialID: recipeDetailMat.materialID,
name: recipeDetailMat.name,
enable: recipeDetailMat.isUse,
mixOrder: recipeDetailMat.mixOrder,
stirTime: recipeDetailMat.stirTime,
powderGram: recipeDetailMat.powderGram,
powderTime: recipeDetailMat.powderTime,
syrupGram: recipeDetailMat.syrupGram,
syrupTime: recipeDetailMat.syrupTime,
waterCold: recipeDetailMat.waterCold,
waterYield: recipeDetailMat.waterYield,
})
);
});
this.isMatLoaded = true;
});
});
}
get recipeListData(): FormArray {
return this.parentForm.get('recipeListData') as FormArray;
}
addRecipeData(): void {
const newRecipeDetailMat: RecipeDetailMat = {
materialID: 0,
name: '',
mixOrder: 0,
feedParameter: 0,
feedPattern: 0,
isUse: false,
materialPathId: 0,
powderGram: 0,
powderTime: 0,
stirTime: 0,
syrupGram: 0,
syrupTime: 0,
waterCold: 0,
waterYield: 0,
};
this.recipeListData.push(this._formBuilder.group(newRecipeDetailMat));
this.actionRecord.addAction(
new Action('add', newRecipeDetailMat, 'recipeListData')
);
}
deleteRecipeData(index: number): void {
const recipeDetailMat: RecipeDetailMat =
this.recipeListData.at(index).value;
this.recipeListData.removeAt(index);
this.actionRecord.addAction(
new Action('delete', recipeDetailMat, 'recipeListData')
);
}
}

View file

@ -2,14 +2,17 @@
class="relative overflow-auto max-h-[900px] shadow-md sm:rounded-lg"
#table
>
<table *ngIf="isLoaded" class="table">
<table class="table">
<caption class="p-5 text-lg font-semibold text-left text-gray-900">
<div class="divide-y divide-solid divide-gray-400">
<div
class="divide-y divide-solid divide-gray-400"
*ngIf="recipesDashboard$ | async as recipesDashboard; else loading"
>
<div class="flex flex-row py-3 justify-between items-center">
<div class="flex flex-col">
<span
>Recipe Version {{ recipes?.MachineSetting?.configNumber }} |
{{ currentFile }}</span
>Recipe Version {{ recipesDashboard.configNumber }} |
{{ recipesDashboard.filename }}</span
>
</div>
<div class="flex flex-col ml-5">
@ -106,7 +109,9 @@
<div class="flex flex-col ml-auto">
<span class=""
>Last Updated:
{{ recipes?.Timestamp | date : "dd-MMM-yyyy hh:mm:ss" }}</span
{{
recipesDashboard.configNumber | date : "dd-MMM-yyyy hh:mm:ss"
}}</span
>
</div>
</div>
@ -199,7 +204,7 @@
</thead>
<tbody>
<tr
*ngFor="let recipe of recipes01"
*ngFor="let recipe of recipeOverviewList"
class="bg-white la border-b hover:bg-secondary"
>
<th>
@ -219,9 +224,9 @@
{{ recipe.name }}
</td>
<td class="px-6 py-4">{{ recipe.otherName }}</td>
<td class="px-6 py-4 flex-wrap max-w-xs">{{ recipe.Description }}</td>
<td class="px-6 py-4 flex-wrap max-w-xs">{{ recipe.description }}</td>
<td class="px-6 py-4">
{{ recipe.LastChange | date : "dd-MMM-yyyy hh:mm:ss" }}
{{ recipe.lastUpdated | date : "dd-MMM-yyyy hh:mm:ss" }}
</td>
<td class="px-4 py-4 flex">
<!-- <recipe-modal productCode="{{ recipe.productCode }}"></recipe-modal> -->
@ -249,7 +254,7 @@
</tr>
</tbody>
</table>
<div *ngIf="!isLoaded">
<ng-template #loading>
<div
class="flex w-full items-center justify-center h-56 border border-gray-200 rounded-lg bg-gray-50"
>
@ -272,7 +277,7 @@
</svg>
</div>
</div>
</div>
</ng-template>
<button
class="btn btn-circle fixed z-100 bottom-5 right-1"

View file

@ -6,11 +6,23 @@ import {
ViewChild,
} from '@angular/core';
import { CommonModule, DatePipe } from '@angular/common';
import { Recipe, Recipe01 } from 'src/app/core/models/recipe.model';
import {
Recipe,
Recipe01,
RecipeOverview,
RecipesDashboard,
} from 'src/app/core/models/recipe.model';
import { RecipeService } from 'src/app/core/services/recipe.service';
import { environment } from 'src/environments/environment';
import { RecipeModalComponent } from 'src/app/shared/modal/recipe-details/recipe-modal.component';
import { BehaviorSubject, Subscription, map } from 'rxjs';
import {
BehaviorSubject,
Observable,
Subscription,
finalize,
map,
tap,
} from 'rxjs';
import * as lodash from 'lodash';
import { RouterLink } from '@angular/router';
import { NgSelectModule } from '@ng-select/ng-select';
@ -31,9 +43,8 @@ import { MaterialService } from 'src/app/core/services/material.service';
templateUrl: './recipes.component.html',
})
export class RecipesComponent implements OnInit, OnDestroy {
recipes: Recipe | null = null;
recipes01: Recipe01[] | null = null;
currentFile: string = '';
recipesDashboard$!: Observable<RecipesDashboard>;
recipeOverviewList!: RecipeOverview[];
selectMaterialFilter: number[] | null = null;
materialList: { id: number; name: string | number }[] | null = null;
@ -47,8 +58,8 @@ export class RecipesComponent implements OnInit, OnDestroy {
private offset = 0;
private take = 20;
isLoaded: boolean = false;
isLoadMore: boolean = false;
// isLoaded: boolean = false;
isLoadMore: boolean = true;
isHasMore: boolean = true;
private searchStr = '';
@ -72,7 +83,7 @@ export class RecipesComponent implements OnInit, OnDestroy {
if (isBottom && !this.isLoadMore) {
this.isLoadMore = true;
this._recipeService
.getRecipes({
.getRecipeOverview({
offset: this.offset,
take: this.take,
search: this.oldSearchStr,
@ -80,21 +91,16 @@ export class RecipesComponent implements OnInit, OnDestroy {
country: this._recipeService.getCurrentCountry(),
materialIds: this.selectMaterialFilter || [],
})
.subscribe(({ recipes, hasMore, fileName }) => {
const { Recipe01, ...recipesWithoutRecipe01 } = recipes;
if (this.recipes01 && this.isHasMore) {
this.recipes01 = [...this.recipes01, ...Recipe01];
.subscribe(({ result, hasMore, totalCount }) => {
if (this.recipeOverviewList) {
this.recipeOverviewList =
this.recipeOverviewList.concat(result);
} else {
this.recipes01 = Recipe01;
this.recipeOverviewList = result;
}
this.recipes = {
...recipesWithoutRecipe01,
Recipe01: [],
};
this.currentFile = fileName;
this.offset += 10;
this.isLoadMore = false;
this.isHasMore = hasMore;
this.isLoadMore = false;
});
}
},
@ -108,31 +114,30 @@ export class RecipesComponent implements OnInit, OnDestroy {
) {}
ngOnInit(): void {
this._recipeService
.getRecipes({
offset: this.offset,
take: this.take,
search: this.oldSearchStr,
this.recipesDashboard$ = this._recipeService
.getRecipesDashboard({
filename: this._recipeService.getCurrentFile(),
country: this._recipeService.getCurrentCountry(),
materialIds: this.selectMaterialFilter || [],
})
.subscribe(({ recipes, hasMore, fileName }) => {
const { Recipe01, ...recipesWithoutRecipe01 } = recipes;
if (this.recipes01 && this.isHasMore) {
this.recipes01 = [...this.recipes01, ...Recipe01];
} else {
this.recipes01 = Recipe01;
}
this.recipes = {
...recipesWithoutRecipe01,
Recipe01: [],
};
this.currentFile = fileName;
this.offset += 10;
this.isLoaded = true;
this.isHasMore = hasMore;
});
.pipe(
finalize(() => {
this._recipeService
.getRecipeOverview({
offset: this.offset,
take: this.take,
search: this.oldSearchStr,
filename: this._recipeService.getCurrentFile(),
country: this._recipeService.getCurrentCountry(),
materialIds: this.selectMaterialFilter || [],
})
.subscribe(({ result, hasMore, totalCount }) => {
this.recipeOverviewList = result;
this.offset += 10;
this.isHasMore = hasMore;
this.isLoadMore = false;
});
})
);
this._materialService
.getMaterialCodes()
@ -157,28 +162,22 @@ export class RecipesComponent implements OnInit, OnDestroy {
search(event: Event) {
this.offset = 0;
this.isLoadMore = true;
this.oldSearchStr = this.searchStr;
this._recipeService
.getRecipes({
.getRecipeOverview({
offset: this.offset,
take: this.take,
search: this.searchStr,
search: this.oldSearchStr,
filename: this._recipeService.getCurrentFile(),
country: this._recipeService.getCurrentCountry(),
materialIds: this.selectMaterialFilter || [],
})
.subscribe(({ recipes, hasMore, fileName }) => {
const { Recipe01, ...recipesWithoutRecipe01 } = recipes;
this.recipes01 = Recipe01;
this.recipes = {
...recipesWithoutRecipe01,
Recipe01: [],
};
this.currentFile = fileName;
.subscribe(({ result, hasMore, totalCount }) => {
this.recipeOverviewList = result;
this.offset += 10;
this.isLoaded = true;
this.isHasMore = hasMore;
this.isLoadMore = false;
});
}
@ -282,17 +281,19 @@ export class RecipesComponent implements OnInit, OnDestroy {
loadRecipe(recipeFileName: string) {
// clear all recipes
this.recipes = null;
this.recipes01 = null;
this.offset = 0;
this.isLoaded = false;
this.isHasMore = true;
this.isLoadMore = false;
this.isLoadMore = true;
this.oldSearchStr = '';
localStorage.setItem('currentRecipeFile', recipeFileName);
this.recipesDashboard$ = this._recipeService.getRecipesDashboard({
filename: recipeFileName,
country: this.selectedCountry!,
});
this._recipeService
.getRecipes({
.getRecipeOverview({
offset: this.offset,
take: this.take,
search: this.oldSearchStr,
@ -300,21 +301,11 @@ export class RecipesComponent implements OnInit, OnDestroy {
country: this.selectedCountry!,
materialIds: this.selectMaterialFilter || [],
})
.subscribe(({ recipes, hasMore, fileName }) => {
const { Recipe01, ...recipesWithoutRecipe01 } = recipes;
if (this.recipes01 && this.isHasMore) {
this.recipes01 = [...this.recipes01, ...Recipe01];
} else {
this.recipes01 = Recipe01;
}
this.recipes = {
...recipesWithoutRecipe01,
Recipe01: [],
};
this.currentFile = fileName;
.subscribe(({ result, hasMore, totalCount }) => {
this.recipeOverviewList = result;
this.offset += 10;
this.isLoaded = true;
this.isHasMore = hasMore;
this.isLoadMore = false;
});
}

View file

@ -0,0 +1,59 @@
export class Action<T> {
private _action: string;
private _data: T;
private _type: string;
constructor(action: string, data: T, type: string) {
this._action = action;
this._data = data;
this._type = type;
}
get action(): string {
return this._action;
}
get data(): T {
return this._data;
}
get type(): string {
return this._type;
}
}
export class ActionRecord<T> {
private _actionRecord: Action<T>[];
private _onAddActionCallback: (
currentAction: Action<T>,
actionRecord: Action<T>[]
) => void = () => {};
constructor() {
this._actionRecord = [];
}
getRecord(): Action<T>[] {
return this._actionRecord;
}
addAction(action: Action<T>): void {
this._actionRecord.push(action);
this._onAddActionCallback(action, this._actionRecord);
}
removeAction(action: Action<T>): void {
let index = this._actionRecord.indexOf(action);
this._actionRecord.splice(index, 1);
}
clearAction(): void {
this._actionRecord = [];
}
registerOnAddAction(
fn: (currentAction: Action<T>, actionRecord: Action<T>[]) => void
): void {
this._onAddActionCallback = fn;
}
}

View file

@ -24,22 +24,22 @@ export interface MaterialData {
waterHot: number;
}
export interface RecipeDetail {
recipe: {
lastModified: Date;
productCode: string;
name: string;
otherName: string;
description: string;
otherDescription: string;
price: number;
isUse: boolean;
isShow: boolean;
disable: boolean;
recipes?: MaterialData[];
};
recipes?: MatRecipe[];
}
// export interface RecipeDetail {
// recipe: {
// lastModified: Date;
// productCode: string;
// name: string;
// otherName: string;
// description: string;
// otherDescription: string;
// price: number;
// isUse: boolean;
// isShow: boolean;
// disable: boolean;
// recipes?: MaterialData[];
// };
// recipes?: MatRecipe[];
// }
export interface RecipeDetailEditable {
name: string;

15
server/.vscode/launch.json vendored Normal file
View file

@ -0,0 +1,15 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Debug",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${workspaceRoot}"
}
]
}

View file

@ -0,0 +1,82 @@
package contracts
// ================================== Recipes Dashboard and Overview ==================================
type RecipeOverview struct {
ID int `json:"id"`
ProductCode string `json:"productCode"`
Name string `json:"name"`
OtherName string `json:"otherName"`
Description string `json:"description"`
LastUpdated string `json:"lastUpdated"`
}
type RecipeDashboardRequest struct {
Country string `json:"country"`
Filename string `json:"filename"`
}
type RecipeDashboardResponse struct {
ConfigNumber int `json:"configNumber"`
LastUpdated string `json:"lastUpdated"`
Filename string `json:"filename"`
}
type RecipeOverviewRequest struct {
Take int `json:"take"`
Skip int `json:"skip"`
Search string `json:"search"`
Country string `json:"country"`
Filename string `json:"filename"`
MatIds []int `json:"matIds"`
}
type RecipeOverviewResponse struct {
Result []RecipeOverview `json:"result"`
HasMore bool `json:"hasMore"`
TotalCount int `json:"totalCount"`
}
// ================================== Recipe Detail ==================================
type RecipeDetailRequest struct {
Filename string `json:"filename"`
Country string `json:"country"`
ProductCode string `json:"productCode"`
}
type RecipeDetailResponse struct {
Name string `json:"name"`
OtherName string `json:"otherName"`
Description string `json:"description"`
OtherDescription string `json:"otherDescription"`
LastUpdated string `json:"lastUpdated"`
Picture string `json:"picture"`
}
type RecipeDetailMat struct {
MaterialID uint64 `json:"materialID"`
Name string `json:"name"`
MixOrder int `json:"mixOrder"`
FeedParameter int `json:"feedParameter"`
FeedPattern int `json:"feedPattern"`
IsUse bool `json:"isUse"`
MaterialPathId int `json:"materialPathId"`
PowderGram int `json:"powderGram"`
PowderTime int `json:"powderTime"`
StirTime int `json:"stirTime"`
SyrupGram int `json:"syrupGram"`
SyrupTime int `json:"syrupTime"`
WaterCold int `json:"waterCold"`
WaterYield int `json:"waterYield"`
}
type RecipeDetailMatListRequest struct {
Filename string `json:"filename"`
Country string `json:"country"`
ProductCode string `json:"productCode"`
}
type RecipeDetailMatListResponse struct {
Result []RecipeDetailMat `json:"result"`
}

View file

@ -69,20 +69,20 @@ func NewData() *Data {
}
}
func (d *Data) GetRecipe(countryID, filename string) models.Recipe {
func (d *Data) GetRecipe(countryID, filename string) *models.Recipe {
if countryID == "" {
return *d.currentRecipe
return d.currentRecipe
}
if filename == "" || filename == d.CurrentFile {
return *d.currentRecipe
return d.currentRecipe
}
if recipe, ok := d.recipeMap[filename]; ok {
d.CurrentFile = filename
d.CurrentCountryID = countryID
return recipe.Recipe
return &recipe.Recipe
}
// change current version and read new recipe
@ -92,7 +92,7 @@ func (d *Data) GetRecipe(countryID, filename string) models.Recipe {
if err != nil {
logger.GetInstance().Error("Error when read recipe file", zap.Error(err))
return *d.currentRecipe
return d.currentRecipe
}
d.currentRecipe = recipe
@ -116,23 +116,70 @@ func (d *Data) GetRecipe(countryID, filename string) models.Recipe {
TimeStamps: time.Now().Unix(),
}
return *d.currentRecipe
return d.currentRecipe
}
func (d *Data) GetRecipe01() []models.Recipe01 {
return d.currentRecipe.Recipe01
}
func (d *Data) GetRecipe01ByProductCode(code string) models.Recipe01 {
result := make([]models.Recipe01, 0)
func (d *Data) GetRecipe01ByProductCode(filename, countryID, productCode string) (models.Recipe01, error) {
for _, v := range d.currentRecipe.Recipe01 {
if v.ProductCode == code {
result = append(result, v)
if filename == "" || filename == d.CurrentFile {
for _, v := range d.currentRecipe.Recipe01 {
if v.ProductCode == productCode {
return v, nil
}
}
} else if recipe, ok := d.recipeMap[filename]; ok {
for _, v := range recipe.Recipe.Recipe01 {
if v.ProductCode == productCode {
return v, nil
}
}
}
return result[0]
d.CurrentFile = filename
d.CurrentCountryID = countryID
recipe, err := helpers.ReadRecipeFile(countryID, filename)
if err != nil {
logger.GetInstance().Error("Error when read recipe file", zap.Error(err))
for _, v := range d.currentRecipe.Recipe01 {
if v.ProductCode == productCode {
return v, nil
}
}
}
d.currentRecipe = recipe
// save to map
if len(d.recipeMap) > 5 { // limit keep in memory 5 version
// remove oldest version
var oldestVersion string
var oldestTime int64
for k, v := range d.recipeMap {
if oldestTime == 0 || v.TimeStamps < oldestTime {
oldestTime = v.TimeStamps
oldestVersion = k
}
}
delete(d.recipeMap, oldestVersion)
}
d.recipeMap[filename] = RecipeWithTimeStamps{
Recipe: *d.currentRecipe,
TimeStamps: time.Now().Unix(),
}
for _, v := range d.currentRecipe.Recipe01 {
if v.ProductCode == productCode {
return v, nil
}
}
return models.Recipe01{}, fmt.Errorf("product code: %s not found", productCode)
}
func (d *Data) SetValuesToRecipe(recipe models.Recipe01) {

View file

@ -7,11 +7,12 @@ import (
"net/http"
"os"
"path"
"recipe-manager/contracts"
"recipe-manager/data"
"recipe-manager/models"
"recipe-manager/services/logger"
"recipe-manager/services/recipe"
"recipe-manager/services/sheet"
"sort"
"strconv"
"strings"
@ -20,24 +21,45 @@ import (
)
type RecipeRouter struct {
data *data.Data
sheetService sheet.SheetService
data *data.Data
sheetService sheet.SheetService
recipeService recipe.RecipeService
}
var (
Log = logger.GetInstance()
)
func NewRecipeRouter(data *data.Data, sheetService sheet.SheetService) *RecipeRouter {
func NewRecipeRouter(data *data.Data, recipeService recipe.RecipeService, sheetService sheet.SheetService) *RecipeRouter {
return &RecipeRouter{
data: data,
sheetService: sheetService,
data: data,
recipeService: recipeService,
sheetService: sheetService,
}
}
func (rr *RecipeRouter) Route(r chi.Router) {
r.Route("/recipes", func(r chi.Router) {
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
r.Get("/dashboard", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
country := r.URL.Query().Get("country")
filename := r.URL.Query().Get("filename")
result, err := rr.recipeService.GetRecipeDashboard(&contracts.RecipeDashboardRequest{
Country: country,
Filename: filename,
})
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
json.NewEncoder(w).Encode(result)
})
r.Get("/overview", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
var take, offset uint64 = 10, 0
if newOffset, err := strconv.ParseUint(r.URL.Query().Get("offset"), 10, 64); err == nil {
@ -50,111 +72,105 @@ func (rr *RecipeRouter) Route(r chi.Router) {
country := r.URL.Query().Get("country")
filename := r.URL.Query().Get("filename")
materialIds := r.URL.Query().Get("material_ids")
materialIds := r.URL.Query().Get("materialIds")
var materialIdsUint []uint64
var materialIdsUint []int
for _, v := range strings.Split(materialIds, ",") {
materialIdUint, err := strconv.ParseUint(v, 10, 64)
if err != nil || materialIdUint == 0 {
continue
}
materialIdsUint = append(materialIdsUint, materialIdUint)
materialIdsUint = append(materialIdsUint, int(materialIdUint))
}
countryID, err := rr.data.GetCountryIDByName(country)
result, err := rr.recipeService.GetRecipeOverview(&contracts.RecipeOverviewRequest{
Take: int(take),
Skip: int(offset),
Search: r.URL.Query().Get("search"),
Country: country,
Filename: filename,
MatIds: materialIdsUint,
})
if err != nil {
http.Error(w, fmt.Sprintf("Country Name: %s not found!!!", country), http.StatusNotFound)
http.Error(w, err.Error(), http.StatusNotFound)
return
}
recipe := rr.data.GetRecipe(countryID, filename)
searchQuery := r.URL.Query().Get("search")
if searchQuery != "" {
recipe.Recipe01 = []models.Recipe01{}
for _, v := range rr.data.GetRecipe01() {
if strings.Contains(strings.ToLower(v.ProductCode), strings.ToLower(searchQuery)) ||
strings.Contains(strings.ToLower(v.Name), strings.ToLower(searchQuery)) ||
strings.Contains(strings.ToLower(v.OtherName), strings.ToLower(searchQuery)) {
recipe.Recipe01 = append(recipe.Recipe01, v)
}
}
}
if len(materialIdsUint) > 0 {
resultFilter := []models.Recipe01{}
for _, v := range recipe.Recipe01 {
for _, matID := range materialIdsUint {
for _, recipe := range v.Recipes {
if recipe.IsUse && uint64(recipe.MaterialPathId) == matID {
resultFilter = append(resultFilter, v)
}
}
}
}
recipe.Recipe01 = resultFilter
}
isHasMore := len(recipe.Recipe01) >= int(take+offset)
if isHasMore {
recipe.Recipe01 = recipe.Recipe01[offset : take+offset]
sort.Slice(recipe.Recipe01, func(i, j int) bool {
return recipe.Recipe01[i].ID < recipe.Recipe01[j].ID
})
} else if len(recipe.Recipe01) > int(offset) {
recipe.Recipe01 = recipe.Recipe01[offset:]
} else {
recipe.Recipe01 = []models.Recipe01{}
}
json.NewEncoder(w).Encode(map[string]interface{}{
"fileName": rr.data.CurrentFile,
"recipes": recipe,
"hasMore": isHasMore,
})
json.NewEncoder(w).Encode(result)
})
r.Get("/{product_code}", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
productCode := chi.URLParam(r, "product_code")
recipe := rr.data.GetRecipe01()
recipeMetaData := rr.sheetService.GetSheet(r.Context(), "1rSUKcc5POR1KeZFGoeAZIoVoI7LPGztBhPw5Z_ConDE")
// recipe := rr.data.GetRecipe01()
// recipeMetaData := rr.sheetService.GetSheet(r.Context(), "1rSUKcc5POR1KeZFGoeAZIoVoI7LPGztBhPw5Z_ConDE")
var recipeResult *models.Recipe01
recipeMetaDataResult := map[string]string{}
// var recipeResult *models.Recipe01
// recipeMetaDataResult := map[string]string{}
for _, v := range recipe {
if v.ProductCode == productCode {
recipeResult = &v
break
}
}
// for _, v := range recipe {
// if v.ProductCode == productCode {
// recipeResult = &v
// break
// }
// }
for _, v := range recipeMetaData {
if v[0].(string) == productCode {
recipeMetaDataResult = map[string]string{
"productCode": v[0].(string),
"name": v[1].(string),
"otherName": v[2].(string),
"description": v[3].(string),
"otherDescription": v[4].(string),
"picture": v[5].(string),
}
break
}
}
// for _, v := range recipeMetaData {
// if v[0].(string) == productCode {
// recipeMetaDataResult = map[string]string{
// "productCode": v[0].(string),
// "name": v[1].(string),
// "otherName": v[2].(string),
// "description": v[3].(string),
// "otherDescription": v[4].(string),
// "picture": v[5].(string),
// }
// break
// }
// }
if recipeResult == nil {
http.Error(w, "Not Found", http.StatusNotFound)
// if recipeResult == nil {
// http.Error(w, "Not Found", http.StatusNotFound)
// return
// }
// json.NewEncoder(w).Encode(map[string]interface{}{
// "recipe": recipeResult,
// "recipeMetaData": recipeMetaDataResult,
// })
result, err := rr.recipeService.GetRecipeDetail(&contracts.RecipeDetailRequest{
Filename: r.URL.Query().Get("filename"),
Country: r.URL.Query().Get("country"),
ProductCode: productCode,
})
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
json.NewEncoder(w).Encode(map[string]interface{}{
"recipe": recipeResult,
"recipeMetaData": recipeMetaDataResult,
json.NewEncoder(w).Encode(result)
})
r.Get("/{product_code}/mat", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
productCode := chi.URLParam(r, "product_code")
result, err := rr.recipeService.GetRecipeDetailMat(&contracts.RecipeDetailRequest{
Filename: r.URL.Query().Get("filename"),
Country: r.URL.Query().Get("country"),
ProductCode: productCode,
})
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
json.NewEncoder(w).Encode(result)
})
r.Get("/{country}/{filename}/json", func(w http.ResponseWriter, r *http.Request) {
@ -242,7 +258,12 @@ func (rr *RecipeRouter) Route(r chi.Router) {
Log.Debug("Changes: ", zap.Any("changes", changes))
// TODO: find the matched pd
target_menu := rr.data.GetRecipe01ByProductCode(changes.ProductCode)
target_menu, err := rr.data.GetRecipe01ByProductCode(filename, countryID, changes.ProductCode)
if err != nil {
Log.Error("Error when get recipe by product code", zap.Error(err))
return
}
menu_map := target_menu.ToMap()
change_map := changes.ToMap()

View file

@ -16,6 +16,7 @@ import (
"recipe-manager/routers"
"recipe-manager/services/logger"
"recipe-manager/services/oauth"
"recipe-manager/services/recipe"
"recipe-manager/services/sheet"
"strings"
"sync"
@ -429,8 +430,11 @@ func (s *Server) createHandler() {
return
}
// Recipe Service
rs := recipe.NewRecipeService(database)
// Recipe Router
rr := routers.NewRecipeRouter(database, sheetService)
rr := routers.NewRecipeRouter(database, rs, sheetService)
rr.Route(r)
// Material Router

View file

@ -0,0 +1,192 @@
package recipe
import (
"fmt"
"recipe-manager/contracts"
"recipe-manager/data"
"recipe-manager/models"
"sort"
"strings"
)
type RecipeService interface {
GetRecipeDashboard(request *contracts.RecipeDashboardRequest) (contracts.RecipeDashboardResponse, error)
GetRecipeOverview(request *contracts.RecipeOverviewRequest) (contracts.RecipeOverviewResponse, error)
GetRecipeDetail(request *contracts.RecipeDetailRequest) (contracts.RecipeDetailResponse, error)
GetRecipeDetailMat(request *contracts.RecipeDetailRequest) (contracts.RecipeDetailMatListResponse, error)
}
type recipeService struct {
db *data.Data
}
// GetRecipeDetail implements RecipeService.
func (rs *recipeService) GetRecipeDetail(request *contracts.RecipeDetailRequest) (contracts.RecipeDetailResponse, error) {
recipe, err := rs.db.GetRecipe01ByProductCode(request.Filename, request.Country, request.ProductCode)
if err != nil {
return contracts.RecipeDetailResponse{}, err
}
result := contracts.RecipeDetailResponse{
Name: recipe.Name,
OtherName: recipe.OtherName,
Description: recipe.Description,
OtherDescription: recipe.OtherDescription,
LastUpdated: recipe.LastChange,
Picture: recipe.UriData[len("img="):], // remove "img=" prefix
}
return result, nil
}
// GetRecipeDetailMat implements RecipeService.
func (rs *recipeService) GetRecipeDetailMat(request *contracts.RecipeDetailRequest) (contracts.RecipeDetailMatListResponse, error) {
countryID, err := rs.db.GetCountryIDByName(request.Country)
if err != nil {
return contracts.RecipeDetailMatListResponse{}, fmt.Errorf("country name: %s not found", request.Country)
}
recipe, err := rs.db.GetRecipe01ByProductCode(request.Filename, request.Country, request.ProductCode)
if err != nil {
return contracts.RecipeDetailMatListResponse{}, err
}
matIds := []uint64{}
for _, v := range recipe.Recipes {
if v.IsUse {
matIds = append(matIds, uint64(v.MaterialPathId))
}
}
matsCode := rs.db.GetMaterialCode(matIds, countryID, request.Filename)
result := contracts.RecipeDetailMatListResponse{
Result: []contracts.RecipeDetailMat{},
}
for _, v := range recipe.Recipes {
for _, mat := range matsCode {
if v.MaterialPathId == int(mat.MaterialID) {
result.Result = append(result.Result, contracts.RecipeDetailMat{
MaterialID: mat.MaterialID,
Name: mat.PackageDescription,
MixOrder: v.MixOrder,
FeedParameter: v.FeedParameter,
FeedPattern: v.FeedPattern,
IsUse: v.IsUse,
MaterialPathId: v.MaterialPathId,
PowderGram: v.PowderGram,
PowderTime: v.PowderTime,
StirTime: v.StirTime,
SyrupGram: v.SyrupGram,
SyrupTime: v.SyrupTime,
WaterCold: v.WaterCold,
WaterYield: v.WaterYield,
})
break
}
}
}
// sort by id
sort.Slice(result.Result, func(i, j int) bool {
return result.Result[i].MaterialID < result.Result[j].MaterialID
})
return result, nil
}
func (rs *recipeService) GetRecipeDashboard(request *contracts.RecipeDashboardRequest) (contracts.RecipeDashboardResponse, error) {
countryID, err := rs.db.GetCountryIDByName(request.Country)
if err != nil {
return contracts.RecipeDashboardResponse{}, fmt.Errorf("country name: %s not found", request.Country)
}
recipe := rs.db.GetRecipe(countryID, request.Filename)
result := contracts.RecipeDashboardResponse{
ConfigNumber: recipe.MachineSetting.ConfigNumber,
LastUpdated: recipe.Timestamp,
Filename: request.Filename,
}
return result, nil
}
func (rs *recipeService) GetRecipeOverview(request *contracts.RecipeOverviewRequest) (contracts.RecipeOverviewResponse, error) {
countryID, err := rs.db.GetCountryIDByName(request.Country)
if err != nil {
return contracts.RecipeOverviewResponse{}, fmt.Errorf("country name: %s not found", request.Country)
}
recipe := rs.db.GetRecipe(countryID, request.Filename)
recipeFilter := recipe.Recipe01
result := contracts.RecipeOverviewResponse{}
if request.Search != "" {
searchResult := []models.Recipe01{}
for _, v := range recipeFilter {
if strings.Contains(strings.ToLower(v.ProductCode), strings.ToLower(request.Search)) ||
strings.Contains(strings.ToLower(v.Name), strings.ToLower(request.Search)) ||
strings.Contains(strings.ToLower(v.OtherName), strings.ToLower(request.Search)) {
searchResult = append(searchResult, v)
}
}
recipeFilter = searchResult
}
if len(request.MatIds) > 0 {
matIdsFiltered := []models.Recipe01{}
for _, v := range recipeFilter {
for _, matID := range request.MatIds {
for _, recipe := range v.Recipes {
if recipe.IsUse && recipe.MaterialPathId == matID {
matIdsFiltered = append(matIdsFiltered, v)
}
}
}
}
recipeFilter = matIdsFiltered
}
// Map to contracts.RecipeOverview
for _, v := range recipeFilter {
result.Result = append(result.Result, contracts.RecipeOverview{
ID: v.ID,
ProductCode: v.ProductCode,
Name: v.Name,
OtherName: v.OtherName,
Description: v.Description,
LastUpdated: v.LastChange,
})
}
result.TotalCount = len(result.Result)
result.HasMore = result.TotalCount >= request.Take+request.Skip
if result.HasMore {
result.Result = result.Result[request.Skip : request.Take+request.Skip]
sort.Slice(result.Result, func(i, j int) bool {
return result.Result[i].ID < result.Result[j].ID
})
} else if result.TotalCount > request.Skip {
result.Result = result.Result[request.Skip:]
} else {
result.Result = []contracts.RecipeOverview{}
}
return result, nil
}
func NewRecipeService(db *data.Data) RecipeService {
return &recipeService{
db: db,
}
}