Taobin-Recipe-Manager/client/src/app/core/services/recipe.service.ts
pakintada@gmail.com 2b8745679f fix(CurrentRecipePointer): 🐛 Fix cache recipe
Remove continue last opened version
2024-04-11 16:59:37 +07:00

382 lines
10 KiB
TypeScript

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, tap } from 'rxjs';
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';
import { getCountryMapSwitcher } from 'src/app/shared/helpers/recipe';
import { ActivatedRoute } from '@angular/router';
import { AsyncStorage } from 'src/app/shared/helpers/asyncStorage';
import { SocketIOService } from 'src/app/shared/services/websocket.service';
import { UserService } from './user.service';
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[];
}
@Injectable({ providedIn: 'root' })
export class RecipeService {
private countries: string[] = [];
private recipeFiles: RecipeFiles = {};
private tmp_files: string[] = [];
private department = this._route.snapshot.paramMap.get('department');
private get tmpfiles(): string[] {
return this.tmp_files;
}
constructor(
private _httpClient: HttpClient,
private _route: ActivatedRoute,
private _user: UserService,
// private _socket: SocketIOService
) {
// this._socket.checkIn(this._user.getCurrentUser()!.name, 'recipe:response');
}
shareHttpClient() {
return this._httpClient;
}
getRecipesDashboard(
params: any = {
country: this.getCurrentCountry(this.department!),
filename: this.getCurrentFile(),
}
): Observable<RecipesDashboard> {
// test socket service
// this._socket.getPayload(`${this._user.getCurrentUser()!.name}:recipe:response:cache`)?.subscribe({
// next: (c: any)=> {
// console.log("cache from server", c);
// }
// });
// this._socket.sendTopic('recipe:dashboard', {
// room: 'recipe:response',
// topic: 'recipe:dashboard',
// user: this._user.getCurrentUser()!.name,
// country: params.country,
// filename: params.filename,
// });
// return this._socket.getPayload(
// `recipe:dashboard:${this._user.getCurrentUser()!.name}:payload`
// )!;
return this._httpClient.get<RecipesDashboard>(
environment.api + '/recipes/dashboard',
{
params: {
country: params.country,
filename: params.filename,
},
withCredentials: true,
responseType: 'json',
}
);
}
async getRecipeOverview(
params: any = {
country: this.getCurrentCountry(this.department!),
filename: this.getCurrentFile(),
materialIds: [],
offset: 0,
take: 20,
search: '',
}
): Promise<Observable<RecipeOverviewList>> {
console.log("overview: ", params);
// this._socket.sendTopic('recipe:overview', {
// room: 'recipe:response',
// topic: 'recipe:overview',
// user: this._user.getCurrentUser()!.name,
// ...params
// });
// return this._socket.getPayload(
// `recipe:overview:${this._user.getCurrentUser()!.name}:payload`
// )!;
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',
}
);
}
async getRecipeDetail(
productCode: string
): Promise<Observable<RecipeDetail>> {
let asyncCountry = await this.getCurrentCountry(this.department!);
// console.log('get detail by asyncCountry', asyncCountry);
return this._httpClient.get<RecipeDetail>(
environment.api + '/recipes/' + productCode,
{
params: {
filename: this.getCurrentFile(),
country: asyncCountry,
},
withCredentials: true,
responseType: 'json',
}
);
}
async getRecipeDetailMat(
productCode: string
): Promise<Observable<{ result: RecipeDetailMat[] }>> {
let asyncCountry = await this.getCurrentCountry(this.department!);
return this._httpClient.get<{ result: RecipeDetailMat[] }>(
environment.api + '/recipes/' + productCode + '/mat',
{
params: {
filename: this.getCurrentFile(),
country: asyncCountry,
},
withCredentials: true,
responseType: 'json',
}
);
}
getCurrentFile(): string {
// get default from server
const currentRecipeFile = localStorage.getItem('currentRecipeFile');
if (currentRecipeFile) {
return currentRecipeFile;
}
return 'default';
}
setCurrentFile(filename: string) {
localStorage.setItem('currentRecipeFile', filename);
}
async getCurrentCountry(department?: string): Promise<string> {
if (department) {
// translate back to full name
let fullname = getCountryMapSwitcher(department);
console.log('fullname: ', fullname);
// localStorage.setItem('currentRecipeCountry', fullname);
await AsyncStorage.setItem('currentRecipeCountry', fullname);
return fullname;
}
// const currentRecipeCountry = localStorage.getItem('currentRecipeCountry');
const currentRecipeCountry = await AsyncStorage.getItem<string>(
'currentRecipeCountry'
);
if (currentRecipeCountry) {
return currentRecipeCountry;
}
return 'Thailand';
}
getRecipesById(id: string): Observable<{
recipe: Recipe01;
recipeMetaData: RecipeMetaData;
}> {
return this._httpClient.get<{
recipe: Recipe01;
recipeMetaData: RecipeMetaData;
}>(environment.api + '/recipes/' + id, {
withCredentials: true,
responseType: 'json',
});
}
getRecipeCountries(): Observable<string[]> {
return this._httpClient
.get<string[]>(environment.api + '/recipes/countries', {
withCredentials: true,
responseType: 'json',
})
.pipe(tap((countries) => (this.countries = countries)));
}
getRecipeFiles(country: string): Observable<string[]> {
return this._httpClient
.get<string[]>(environment.api + '/recipes/' + country + '/versions', {
withCredentials: true,
responseType: 'json',
})
.pipe(tap((files) => (this.recipeFiles[country] = files)));
}
getRecipeFileCountries(): string[] {
return this.countries;
}
getRecipeFileNames(country: string): string[] | null {
return this.recipeFiles[country] ?? null;
}
editChanges(country: string, filename: string, change: any) {
console.log('target version = ', filename);
console.log('change in edit: ', change);
return this._httpClient
.post<{
status: string;
}>(
environment.api + ('/recipes/edit/' + country + '/' + filename),
JSON.stringify(change),
{
withCredentials: true,
responseType: 'json',
}
)
.subscribe({
next(value) {
console.log(value);
},
});
}
upgradeRecipe(country: string, filename: string, ctx: any) {
return this._httpClient.post<any>(
environment.api + ('/recipes/upgrade/' + country + '/' + filename),
ctx,
{
withCredentials: true,
responseType: 'json',
}
);
}
getSavedTmp(country: string, filename: string) {
console.log('loading saved .tmp* file', country, filename);
// do split filename
filename = filename.split('_')[1];
// this._user.getCurrentUser().subscribe((user) => {
// this.user = user.user;
// })
return this._httpClient.get<string[]>(
environment.api + ('/recipes/saved/' + country + '/' + filename),
{
withCredentials: true,
}
);
// .subscribe({
// next(value) {
// console.log( value);
// },
// });
}
getSubMenus(country: string, filename: string, productCode: string) {
console.log('getSubMenus', country, filename, productCode);
return this._httpClient.get<Recipe01[]>(
environment.api +
'/recipes/' +
country +
'/' +
filename +
'/' +
productCode +
'/submenus',
{
withCredentials: true,
responseType: 'json',
}
);
}
async getRawRecipeOfProductCode(
country: string,
filename: string,
productCode: string
): Promise<Observable<{}>> {
return this._httpClient.get<{}>(
environment.api +
'/recipes/' +
country +
'/' +
filename +
'/' +
productCode +
'/raw_full',
{
withCredentials: true,
responseType: 'json',
}
);
}
getPatchListOfCurrentFile(
country: string,
filename: string
): Observable<any> {
console.log('try get patches', country, filename);
return this._httpClient.get<any>(
environment.api + '/recipes/patch/get/' + country + '/' + filename,
{ withCredentials: true, responseType: 'json' }
);
}
async sortRecipe(
country: string,
filename: string,
sortKey: string,
ascending: boolean
): Promise<Observable<any>> {
return this._httpClient.post<any>(
environment.api + '/recipes/sort/' + country + '/' + filename,
JSON.stringify({
sortKey: sortKey,
ascending: ascending,
}),
{ withCredentials: true, responseType: 'json' }
);
}
}