All files / src/app/core/facades shopping.facade.ts

46.93% Statements 46/98
29.62% Branches 8/27
16.32% Functions 8/49
47.87% Lines 45/94

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287103x 103x 103x 103x 103x   103x 103x   103x 103x 103x 103x 103x                   103x 103x           103x 103x 103x                         103x 103x 103x 103x 103x 103x       103x 42x       42x 42x     71x                                                   42x     18x 18x   18x 18x           18x         36x                 36x 36x           42x                                                                                                                                             42x 42x                                                                           42x             42x   42x                                                                                 42x 42x    
import { Inject, Injectable } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { isEqual } from 'lodash-es';
import { Observable, combineLatest, identity } from 'rxjs';
import { debounce, distinctUntilChanged, filter, map, pairwise, startWith, switchMap, tap } from 'rxjs/operators';
 
import { PRICE_UPDATE } from 'ish-core/configurations/injection-keys';
import { PriceItemHelper } from 'ish-core/models/price-item/price-item.helper';
import { ProductListingID } from 'ish-core/models/product-listing/product-listing.model';
import { ProductCompletenessLevel, ProductHelper } from 'ish-core/models/product/product.model';
import { selectRouteParam } from 'ish-core/store/core/router';
import { addProductToBasket } from 'ish-core/store/customer/basket';
import { getPriceDisplayType } from 'ish-core/store/customer/user';
import {
  getCategory,
  getCategoryIdByRefId,
  getNavigationCategories,
  getNavigationCategoryTree,
  getSelectedCategory,
  loadCategoryByRef,
  loadCategoryTree,
  loadTopLevelCategories,
} from 'ish-core/store/shopping/categories';
import { getAvailableFilter } from 'ish-core/store/shopping/filter';
import {
  getProductListingLoading,
  getProductListingView,
  getProductListingViewType,
  loadMoreProducts,
} from 'ish-core/store/shopping/product-listing';
import { loadProductPrices } from 'ish-core/store/shopping/product-prices';
import { getProductPrice } from 'ish-core/store/shopping/product-prices/product-prices.selectors';
import {
  getFailedProducts,
  getProduct,
  getProductLinks,
  getProductParts,
  getProductVariationCount,
  getProductVariations,
  loadProduct,
  loadProductIfNotLoaded,
  loadProductLinks,
  loadProductParts,
  loadProductVariationsIfNotLoaded,
} from 'ish-core/store/shopping/products';
import { getPromotion, getPromotions, loadPromotion } from 'ish-core/store/shopping/promotions';
import { getSearchTerm, getSuggestSearchResults, suggestSearch } from 'ish-core/store/shopping/search';
import { getWarranty, getWarrantyError, getWarrantyLoading, warrantyActions } from 'ish-core/store/shopping/warranties';
import { toObservable } from 'ish-core/utils/functions';
import { InjectSingle } from 'ish-core/utils/injection';
import { mapToProperty, whenFalsy, whenTruthy } from 'ish-core/utils/operators';
 
/* eslint-disable @typescript-eslint/member-ordering */
@Injectable({ providedIn: 'root' })
export class ShoppingFacade {
  constructor(private store: Store, @Inject(PRICE_UPDATE) private priceUpdate: InjectSingle<typeof PRICE_UPDATE>) {}
 
  // CATEGORY
 
  selectedCategory$ = this.store.pipe(select(getSelectedCategory));
  selectedCategoryId$ = this.store.pipe(select(selectRouteParam('categoryUniqueId')));
 
  category$(uniqueId: string) {
    return this.store.pipe(select(getCategory(uniqueId)));
  }
 
  categoryIdByRefId$(categoryRefId: string) {
    this.store.dispatch(loadCategoryByRef({ categoryId: categoryRefId }));
    return this.store.pipe(select(getCategoryIdByRefId(categoryRefId)));
  }
 
  navigationCategories$(uniqueId?: string) {
    Iif (!uniqueId) {
      this.store.dispatch(loadTopLevelCategories());
    }
    return this.store.pipe(
      select(getNavigationCategories(uniqueId)),
      // prevent to display an empty navigation bar after login/logout);
      filter(categories => !!categories?.length)
    );
  }
 
  navigationCategoryTree$(categoryRef: string, depth: number) {
    this.store.dispatch(loadCategoryTree({ categoryRef, depth }));
    return this.store.pipe(select(getNavigationCategoryTree(categoryRef, depth)));
  }
 
  // PRODUCT
 
  selectedProductId$ = this.store.pipe(select(selectRouteParam('sku')));
 
  product$(sku: string | Observable<string>, level: ProductCompletenessLevel | true) {
    const completenessLevel = level === true ? ProductCompletenessLevel.Detail : level;
    return toObservable(sku).pipe(
      tap(plainSKU => {
        if (level === true) {
          this.store.dispatch(loadProduct({ sku: plainSKU }));
        } else E{
          this.store.dispatch(loadProductIfNotLoaded({ sku: plainSKU, level }));
        }
      }),
      switchMap(plainSKU =>
        this.store.pipe(
          select(getProduct(plainSKU)),
          startWith(undefined),
          pairwise(),
          tap(([prev, curr]) => {
            Iif (
              ProductHelper.isReadyForDisplay(prev, completenessLevel) &&
              !ProductHelper.isReadyForDisplay(curr, completenessLevel)
            ) {
              level === true
                ? this.store.dispatch(loadProduct({ sku: plainSKU }))
                : this.store.dispatch(loadProductIfNotLoaded({ sku: plainSKU, level }));
            }
          }),
          map(([, curr]) => curr),
          filter(p => ProductHelper.isReadyForDisplay(p, completenessLevel))
        )
      )
    );
  }
 
  failedProducts$ = this.store.pipe(select(getFailedProducts));
 
  // remove all SKUs from the productSKUs that are also contained in the failed products
  excludeFailedProducts$(productSKUs: string[] | Observable<string[]>) {
    return combineLatest([toObservable(productSKUs), this.store.pipe(select(getFailedProducts))]).pipe(
      distinctUntilChanged<[string[], string[]]>(isEqual),
      map(([skus, failed]) => skus.filter(sku => !failed.includes(sku)))
    );
  }
 
  productPrices$(sku: string | Observable<string>, fresh = false) {
    return toObservable(sku).pipe(
      whenTruthy(),
      switchMap(plainSKU =>
        combineLatest([
          this.store.pipe(
            select(getProductPrice(plainSKU)),
            // reset state when updates are forced
            this.priceUpdate === 'always' || fresh ? startWith(undefined) : identity,
            distinctUntilChanged(),
            tap(prices => {
              Iif (!prices) {
                this.store.dispatch(loadProductPrices({ skus: [plainSKU] }));
              }
            }),
            whenTruthy()
          ),
          this.store.pipe(select(getPriceDisplayType)),
        ]).pipe(map(args => PriceItemHelper.selectPricing(...args)))
      )
    );
  }
 
  private lazyLoadVariations(sku: string | Observable<string>) {
    return this.product$(sku, ProductCompletenessLevel.List).pipe(
      whenTruthy(),
      filter(ProductHelper.isMasterProduct),
      mapToProperty('sku'),
      distinctUntilChanged(),
      tap(sku => {
        this.store.dispatch(loadProductVariationsIfNotLoaded({ sku }));
      })
    );
  }
 
  productVariations$(sku: string | Observable<string>) {
    return this.lazyLoadVariations(sku).pipe(switchMap(sku => this.store.pipe(select(getProductVariations(sku)))));
  }
 
  productVariationCount$(sku: string | Observable<string>) {
    return this.lazyLoadVariations(sku).pipe(
      switchMap(plainSKU => this.store.pipe(select(getProductVariationCount(plainSKU))))
    );
  }
 
  // CHECKOUT
 
  addProductToBasket(sku: string, quantity: number, warrantySku?: string) {
    this.store.dispatch(addProductToBasket({ sku, quantity, warrantySku }));
  }
 
  // PRODUCT LISTING
 
  productListingView$(id: ProductListingID | Observable<ProductListingID>) {
    return toObservable(id).pipe(
      whenTruthy(),
      tap(id => this.store.dispatch(loadMoreProducts({ id }))),
      switchMap(id => this.store.pipe(select(getProductListingView(id))))
    );
  }
 
  productListingViewType$ = this.store.pipe(select(getProductListingViewType));
  productListingLoading$ = this.store.pipe(select(getProductListingLoading));
 
  loadMoreProducts(id: ProductListingID, page: number) {
    this.store.dispatch(loadMoreProducts({ id, page }));
  }
 
  // PRODUCT LINKS
 
  productLinks$(sku: string | Observable<string>) {
    return toObservable(sku).pipe(
      whenTruthy(),
      switchMap(plainSKU =>
        this.store.pipe(
          select(getProductLinks(plainSKU)),
          tap(links => {
            Iif (!links) {
              this.store.dispatch(loadProductLinks({ sku: plainSKU }));
            }
          })
        )
      )
    );
  }
 
  // PRODUCT RETAIL SET / BUNDLES
 
  productParts$(sku: string | Observable<string>) {
    return toObservable(sku).pipe(
      whenTruthy(),
      tap(plainSKU => {
        this.store.dispatch(loadProductParts({ sku: plainSKU }));
      }),
      switchMap(plainSKU => this.store.pipe(select(getProductParts(plainSKU))))
    );
  }
 
  // SEARCH
 
  searchTerm$ = this.store.pipe(select(getSearchTerm));
  searchResults$(searchTerm: Observable<string>) {
    return searchTerm.pipe(
      tap(term => this.store.dispatch(suggestSearch({ searchTerm: term }))),
      switchMap(term => this.store.pipe(select(getSuggestSearchResults(term))))
    );
  }
  searchLoading$ = this.store.pipe(select(getProductListingLoading));
 
  searchItemsCount$ = this.searchTerm$.pipe(
    debounce(() => this.store.pipe(select(getProductListingLoading), whenFalsy())),
    switchMap(term =>
      this.store.pipe(
        select(getProductListingView({ type: 'search', value: term })),
        map(view => view.itemCount)
      )
    )
  );
 
  // FILTER
 
  currentFilter$(withCategoryFilter: boolean) {
    return this.store.pipe(
      select(getAvailableFilter),
      whenTruthy(),
      map(x => (withCategoryFilter ? x : { ...x, filter: x.filter?.filter(f => f.id !== 'CategoryUUIDLevelMulti') }))
    );
  }
 
  // PROMOTIONS
 
  promotion$(promotionId: string) {
    this.store.dispatch(loadPromotion({ promoId: promotionId }));
    return this.store.pipe(select(getPromotion(promotionId)));
  }
 
  promotions$(promotionIds: string[]) {
    promotionIds.forEach(promotionId => {
      this.store.dispatch(loadPromotion({ promoId: promotionId }));
    });
    return this.store.pipe(select(getPromotions(promotionIds)));
  }
 
  // WARRANTIES
 
  warrantyById$(warrantyId: string) {
    this.store.dispatch(warrantyActions.loadWarranty({ warrantyId }));
    return this.store.pipe(select(getWarranty(warrantyId)));
  }
 
  warrantyError$ = this.store.pipe(select(getWarrantyError));
  warrantyLoading$ = this.store.pipe(select(getWarrantyLoading));
}