All files / src/app/core/store/customer/orders orders.effects.ts

100% Statements 77/77
86.84% Branches 33/38
100% Functions 38/38
100% Lines 77/77

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 25323x 23x 23x 23x 23x 23x 23x 23x 23x   23x 23x 23x 23x 23x 23x   23x                               23x     23x   31x 31x 31x 31x 31x           31x 31x   7x   7x 4x                   31x   31x     2x   2x           1x 1x   1x             31x 31x     1x   1x 1x                                     31x 31x       10x 7x             31x 31x   3x 3x       31x 31x       7x 4x                   31x 31x       7x 4x                   31x     31x       3x             31x 31x     1x             31x 31x     3x       3x     2x                 31x 31x       10x   7x 4x     3x                 31x 31x     1x         1x                        
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Actions, concatLatestFrom, createEffect, ofType } from '@ngrx/effects';
import { routerNavigatedAction } from '@ngrx/router-store';
import { Store, select } from '@ngrx/store';
import { TranslateService } from '@ngx-translate/core';
import { isEqual } from 'lodash-es';
import { EMPTY, from, merge, race } from 'rxjs';
import { concatMap, distinctUntilChanged, filter, map, mergeMap, switchMap, take } from 'rxjs/operators';
 
import { OrderService } from 'ish-core/services/order/order.service';
import { ofUrl, selectQueryParam, selectQueryParams, selectRouteParam } from 'ish-core/store/core/router';
import { setBreadcrumbData } from 'ish-core/store/core/viewconf';
import { continueCheckoutWithIssues, getCurrentBasketId, loadBasket } from 'ish-core/store/customer/basket';
import { getLoggedInUser } from 'ish-core/store/customer/user';
import { mapErrorToAction, mapToPayload, mapToPayloadProperty, whenTruthy } from 'ish-core/utils/operators';
 
import {
  createOrder,
  createOrderFail,
  createOrderSuccess,
  loadMoreOrders,
  loadOrder,
  loadOrderByAPIToken,
  loadOrderFail,
  loadOrderSuccess,
  loadOrders,
  loadOrdersFail,
  loadOrdersSuccess,
  selectOrder,
  selectOrderAfterRedirect,
  selectOrderAfterRedirectFail,
} from './orders.actions';
import { getOrder, getOrderListQuery, getSelectedOrder } from './orders.selectors';
 
@Injectable()
export class OrdersEffects {
  constructor(
    private actions$: Actions,
    private orderService: OrderService,
    private router: Router,
    private store: Store,
    private translateService: TranslateService
  ) {}
 
  /**
   * Creates an order based on the given basket.
   */
  createOrder$ = createEffect(() =>
    this.actions$.pipe(
      ofType(createOrder),
      concatLatestFrom(() => this.store.pipe(select(getCurrentBasketId))),
      mergeMap(([, basketId]) =>
        this.orderService.createOrder(basketId, true).pipe(
          map(order => createOrderSuccess({ order })),
          mapErrorToAction(createOrderFail)
        )
      )
    )
  );
 
  /**
   * After order creation either redirect to a payment provider or show checkout receipt page.
   */
  continueAfterOrderCreation$ = createEffect(
    () =>
      this.actions$.pipe(
        ofType(createOrderSuccess),
        mapToPayloadProperty('order'),
        filter(order => !order?.orderCreation || order.orderCreation.status !== 'ROLLED_BACK'),
        concatMap(order => {
          if (
            order.orderCreation &&
            order.orderCreation.status === 'STOPPED' &&
            order.orderCreation.stopAction.type === 'Redirect' &&
            order.orderCreation.stopAction.redirectUrl
          ) {
            location.assign(order.orderCreation.stopAction.redirectUrl);
            return EMPTY;
          } else {
            return from(this.router.navigate(['/checkout/receipt'], { queryParams: { orderId: order.id } }));
          }
        })
      ),
    { dispatch: false }
  );
 
  rollbackAfterOrderCreation$ = createEffect(() =>
    this.actions$.pipe(
      ofType(createOrderSuccess),
      mapToPayloadProperty('order'),
      filter(order => order.orderCreation && order.orderCreation.status === 'ROLLED_BACK'),
      concatMap(order =>
        from(this.router.navigate(['/checkout/payment'], { queryParams: { error: true } })).pipe(
          mergeMap(() => [
            loadBasket(),
            continueCheckoutWithIssues({
              targetRoute: undefined,
              basketValidation: {
                basket: undefined,
                results: {
                  valid: false,
                  adjusted: false,
                  errors: order.infos,
                },
              },
            }),
          ])
        )
      )
    )
  );
 
  loadOrders$ = createEffect(() =>
    this.actions$.pipe(
      ofType(loadOrders),
      mapToPayloadProperty('query'),
      switchMap(query =>
        this.orderService.getOrders(query).pipe(
          map(orders => loadOrdersSuccess({ orders, query, allRetrieved: orders.length < query.limit })),
          mapErrorToAction(loadOrdersFail)
        )
      )
    )
  );
 
  loadMoreOrders$ = createEffect(() =>
    this.actions$.pipe(
      ofType(loadMoreOrders),
      concatLatestFrom(() => this.store.pipe(select(getOrderListQuery))),
      map(([, query]) => loadOrders({ query: { ...query, offset: (query.offset ?? 0) + query.limit } }))
    )
  );
 
  loadOrder$ = createEffect(() =>
    this.actions$.pipe(
      ofType(loadOrder),
      mapToPayloadProperty('orderId'),
      concatMap(orderId =>
        this.orderService.getOrder(orderId).pipe(
          map(order => loadOrderSuccess({ order })),
          mapErrorToAction(loadOrderFail)
        )
      )
    )
  );
 
  /**
   * Loads an anonymous user`s order using the given api token and orderId.
   */
  loadOrderByAPIToken$ = createEffect(() =>
    this.actions$.pipe(
      ofType(loadOrderByAPIToken),
      mapToPayload(),
      concatMap(payload =>
        this.orderService.getOrderByToken(payload.orderId, payload.apiToken).pipe(
          map(order => loadOrderSuccess({ order })),
          mapErrorToAction(loadOrderFail)
        )
      )
    )
  );
 
  /**
   * Selects and loads an order.
   */
  loadOrderForSelectedOrder$ =
    !SSR &&
    createEffect(() =>
      this.actions$.pipe(
        ofType(selectOrder),
        mapToPayloadProperty('orderId'),
        whenTruthy(),
        map(orderId => loadOrder({ orderId }))
      )
    );
 
  /**
   * Triggers a SelectOrder action if route contains orderId query or route parameter.
   */
  routeListenerForSelectingOrder$ = createEffect(() =>
    merge(
      this.store.pipe(ofUrl(/^\/account\/orders.*/), select(selectRouteParam('orderId'))),
      this.store.pipe(ofUrl(/^\/checkout\/receipt/), select(selectQueryParam('orderId')))
    ).pipe(map(orderId => selectOrder({ orderId })))
  );
 
  /**
   * Returning from redirect after checkout (before customer is logged in).
   * Waits until the customer is logged in and triggers the handleOrderAfterRedirect action afterwards.
   */
  returnFromRedirectAfterOrderCreation$ = createEffect(() =>
    this.store.pipe(
      ofUrl(/^\/checkout\/(receipt|payment)/),
      select(selectQueryParams),
      filter(({ redirect, orderId }) => redirect && orderId),
      distinctUntilChanged(isEqual),
      switchMap(queryParams =>
        // SelectOrderAfterRedirect will be triggered either after a user is logged in or after the paid order is loaded (anonymous user)
        race([
          this.store.pipe(select(getLoggedInUser), whenTruthy(), take(1)),
          this.store.pipe(select(getOrder(queryParams.orderId)), whenTruthy(), take(1)),
        ]).pipe(map(() => selectOrderAfterRedirect({ params: queryParams })))
      )
    )
  );
 
  /**
   * Returning from redirect after checkout success case (after customer is logged in).
   * Sends success state with payment query params to the server and selects/loads order.
   */
  selectOrderAfterRedirect$ = createEffect(() =>
    this.actions$.pipe(
      ofType(selectOrderAfterRedirect),
      mapToPayloadProperty('params'),
      concatMap(params =>
        this.orderService.updateOrderPayment(params.orderId, params).pipe(
          map(orderId => {
            if (params.redirect === 'success') {
              return selectOrder({ orderId });
            } else {
              // cancelled payment
              return loadBasket();
            }
          }),
          mapErrorToAction(selectOrderAfterRedirectFail)
        )
      )
    )
  );
 
  setOrderBreadcrumb$ = createEffect(() =>
    this.actions$.pipe(
      ofType(routerNavigatedAction),
      switchMap(() =>
        this.store.pipe(
          ofUrl(/^\/account\/orders\/.*/),
          select(getSelectedOrder),
          whenTruthy(),
          map(order =>
            setBreadcrumbData({
              breadcrumbData: [
                { key: 'account.order_history.link', link: '/account/orders' },
                { text: `${this.translateService.instant('account.orderdetails.breadcrumb')} - ${order.documentNo}` },
              ],
            })
          )
        )
      )
    )
  );
}