import {inject, Injectable} from '@angular/core'; import {HttpClient, HttpHeaders, HttpResponse} from '@angular/common/http'; import {MatDialog} from '@angular/material/dialog'; import {GrocyConfigDialogComponent} from './grocy-config-dialog/grocy-config-dialog.component'; import {map, Observable, of, switchMap, tap} from 'rxjs'; import _ from 'lodash'; import {LS_GROCY_API_KEY, LS_GROCY_URI} from './grocy'; import {BatchScanRow} from '../batch-scan-table/barcode'; const GROCY_API_HEADER = 'GROCY-API-KEY' @Injectable({ providedIn: 'root' }) export class GrocyRestService { readonly http = inject(HttpClient); readonly dialog = inject(MatDialog); private areRequiredKeysPresent(): boolean { const requiredKeys = [LS_GROCY_API_KEY, LS_GROCY_URI] return !!requiredKeys .map(key => localStorage.getItem(key)) .reduce((c, a) => c && a) } private ensureApiKeys(): Observable { if (!this.areRequiredKeysPresent()) { const dialogRef = this.dialog.open(GrocyConfigDialogComponent) return dialogRef.afterClosed() } return of(true) } get(uri: string): Observable> { return this.ensureApiKeys().pipe( switchMap(() => { let headers = new HttpHeaders(); const baseUri = localStorage.getItem(LS_GROCY_URI); headers = headers.set(GROCY_API_HEADER, localStorage.getItem(LS_GROCY_API_KEY)!) return this.http.get(`${baseUri}/api${uri}`, { headers, observe: "response" }) }) ) } getProductIdByBarcode(barcode: string): Observable { return this.get(`/stock/products/by-barcode/${barcode}`).pipe( map(response => { if (response.ok) { return _.get(response.body, 'product.id') as unknown as string; } return null; }) ) } goToGrocyProductPageUri(productId: string) { const baseUri = localStorage.getItem(LS_GROCY_URI); if (window) { window.open(`${baseUri}/product/${productId}`, '_blank')?.focus(); } } getProductId(row: BatchScanRow): Observable { if(row.productId) { return of(row.productId); } return this.getProductIdByBarcode(row.barcode).pipe( tap(productId => row.productId = row.productId ?? productId) ) } }