All files / src/app/core/store/customer/basket basket-items.effects.ts

98.5% Statements 66/67
70.96% Branches 22/31
100% Functions 36/36
98.48% Lines 65/66

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 19223x 23x 23x 23x 23x 23x     23x 23x 23x 23x   23x                                     23x     23x   25x 25x 25x 25x 25x             25x 25x       6x 6x     4x 4x 3x       25x 25x     8x   8x 7x 4x       1x   1x 1x                         25x 25x     3x       25x 25x     7x 7x   7x 4x                   25x 25x     1x 1x             25x 25x       7x 4x                   25x 25x     7x 4x                   25x 25x   10x       25x   25x     2x 1x           7x         7x       7x      
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Actions, concatLatestFrom, createEffect, ofType } from '@ngrx/effects';
import { Store, select } from '@ngrx/store';
import { from } from 'rxjs';
import { concatMap, debounceTime, filter, map, mergeMap, switchMap, toArray, window } from 'rxjs/operators';
 
import { LineItemUpdate } from 'ish-core/models/line-item-update/line-item-update.model';
import { BasketItemUpdateType, BasketItemsService } from 'ish-core/services/basket-items/basket-items.service';
import { BasketService } from 'ish-core/services/basket/basket.service';
import { getProductEntities, loadProduct } from 'ish-core/store/shopping/products';
import { mapErrorToAction, mapToPayload, mapToPayloadProperty } from 'ish-core/utils/operators';
 
import {
  addItemsToBasket,
  addItemsToBasketFail,
  addItemsToBasketSuccess,
  addProductToBasket,
  createBasketFail,
  createBasketSuccess,
  deleteBasketItem,
  deleteBasketItemFail,
  deleteBasketItemSuccess,
  deleteBasketItems,
  deleteBasketItemsFail,
  deleteBasketItemsSuccess,
  loadBasket,
  updateBasketItem,
  updateBasketItemFail,
  updateBasketItemSuccess,
  validateBasket,
} from './basket.actions';
import { getCurrentBasket, getCurrentBasketId } from './basket.selectors';
 
@Injectable()
export class BasketItemsEffects {
  constructor(
    private actions$: Actions,
    private router: Router,
    private store: Store,
    private basketService: BasketService,
    private basketItemsService: BasketItemsService
  ) {}
 
  /**
   * Add a product to the current basket.
   * Triggers the internal action that handles the actual adding of the product to the basket.
   */
  addProductToBasket$ = createEffect(() =>
    this.actions$.pipe(
      ofType(addProductToBasket),
      mapToPayload(),
      // add unit
      concatLatestFrom(() => this.store.pipe(select(getProductEntities))),
      map(([val, entities]) => ({ ...val, unit: entities[val.sku]?.packingUnit })),
      // accumulate all actions
      window(this.actions$.pipe(ofType(addProductToBasket), debounceTime(500))),
      mergeMap(window$ => window$.pipe(toArray())),
      filter(items => items.length > 0),
      map(items => addItemsToBasket({ items }))
    )
  );
 
  addItemsToBasket$ = createEffect(() =>
    this.actions$.pipe(
      ofType(addItemsToBasket),
      mapToPayload(),
      concatLatestFrom(() => this.store.pipe(select(getCurrentBasketId))),
      concatMap(([{ items }, basketId]) => {
        if (basketId) {
          return this.basketItemsService.addItemsToBasket(items).pipe(
            map(payload => addItemsToBasketSuccess(payload)),
            mapErrorToAction(addItemsToBasketFail)
          );
        } else {
          return this.basketService.createBasket().pipe(
            switchMap(basket =>
              this.basketItemsService.addItemsToBasket(items).pipe(
                mergeMap(payload => [createBasketSuccess({ basket }), addItemsToBasketSuccess(payload)]),
                mapErrorToAction(addItemsToBasketFail)
              )
            ),
            mapErrorToAction(createBasketFail)
          );
        }
      })
    )
  );
  /**
   * Reload products when they are added to basket to update price and availability information
   */
  loadProductsForAddItemsToBasket$ = createEffect(() =>
    this.actions$.pipe(
      ofType(addItemsToBasket),
      mapToPayload(),
      mergeMap(payload => [...payload.items.map(item => loadProduct({ sku: item.sku }))])
    )
  );
 
  updateBasketItem$ = createEffect(() =>
    this.actions$.pipe(
      ofType(updateBasketItem),
      mapToPayloadProperty('lineItemUpdate'),
      concatLatestFrom(() => this.store.pipe(select(getCurrentBasket))),
      filter(([payload, basket]) => !!basket.lineItems && !!payload),
      concatMap(([lineItem]) =>
        this.basketItemsService.updateBasketItem(lineItem.itemId, this.determineUpdateItemPayload(lineItem)).pipe(
          map(payload => updateBasketItemSuccess(payload)),
          mapErrorToAction(updateBasketItemFail)
        )
      )
    )
  );
 
  /**
   * Validates the basket after an update item error occurred
   */
  validateBasketAfterUpdateFailure$ = createEffect(() =>
    this.actions$.pipe(
      ofType(updateBasketItemFail),
      mapToPayload(),
      concatLatestFrom(() => this.store.pipe(select(getCurrentBasket))),
      map(() => validateBasket({ scopes: ['Products'] }))
    )
  );
 
  /**
   * Delete basket item effect.
   */
  deleteBasketItem$ = createEffect(() =>
    this.actions$.pipe(
      ofType(deleteBasketItem),
      mapToPayloadProperty('itemId'),
      concatMap(itemId =>
        this.basketItemsService.deleteBasketItem(itemId).pipe(
          map(info => deleteBasketItemSuccess({ itemId, info })),
          mapErrorToAction(deleteBasketItemFail)
        )
      )
    )
  );
 
  /**
   * Delete all basket items effect.
   */
  deleteBasketItems$ = createEffect(() =>
    this.actions$.pipe(
      ofType(deleteBasketItems),
      concatMap(() =>
        this.basketItemsService.deleteBasketItems().pipe(
          map(info => deleteBasketItemsSuccess({ info })),
          mapErrorToAction(deleteBasketItemsFail)
        )
      )
    )
  );
 
  /**
   * Triggers a LoadBasket action after successful interaction with the Basket API.
   */
  loadBasketAfterBasketItemsChangeSuccess$ = createEffect(() =>
    this.actions$.pipe(
      ofType(addItemsToBasketSuccess, updateBasketItemSuccess, deleteBasketItemSuccess, deleteBasketItemsSuccess),
      map(() => loadBasket())
    )
  );
 
  redirectToBasketIfBasketInteractionHasInfo$ = createEffect(
    () =>
      this.actions$.pipe(
        ofType(addItemsToBasketSuccess, updateBasketItemSuccess, deleteBasketItemSuccess),
        mapToPayloadProperty('info'),
        filter(info => !!info?.[0]?.message),
        concatMap(() => from(this.router.navigate(['/basket'], { queryParams: { error: true } })))
      ),
    { dispatch: false }
  );
 
  private determineUpdateItemPayload(lineItem: LineItemUpdate): BasketItemUpdateType {
    const payload: BasketItemUpdateType = {
      quantity: lineItem.quantity > 0 ? { value: lineItem.quantity, unit: lineItem.unit } : undefined,
      product: lineItem.sku,
    };
 
    Iif (lineItem.warrantySku || lineItem.warrantySku === '') {
      // eslint-disable-next-line unicorn/no-null
      return { ...payload, warranty: lineItem.warrantySku ? lineItem.warrantySku : null };
    } // undefined is not working here
    return payload;
  }
}