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

97% Statements 97/100
84.21% Branches 16/19
98.14% Functions 53/54
96.96% Lines 96/99

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 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 34527x 27x 27x 27x 27x 27x 27x 27x 27x 27x     27x 27x 27x 27x           27x 27x   27x                                   27x     27x   37x 37x 37x 37x 37x           37x 37x   7x   7x 4x                   37x   37x     2x   2x             2x       1x   1x             37x 37x     1x   1x 1x                                     37x 37x       7x 4x             37x 37x     3x 3x       37x 37x       7x 4x                   37x 37x       7x 4x                   37x     37x       3x             37x 37x     1x             37x 37x     3x       3x     2x                 37x 37x       10x   7x 4x     3x                 37x 37x     1x         1x                       37x 37x   5x   5x       5x   4x         1x               37x 37x   4x     4x     4x       4x   3x                                               37x   37x               7x 7x        
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { concatLatestFrom } from '@ngrx/operators';
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 { catchError, concatMap, distinctUntilChanged, filter, map, mergeMap, switchMap, take } from 'rxjs/operators';
 
import { Order } from 'ish-core/models/order/order.model';
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,
  emitPaypalOrderId,
  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 {
  cancelPaypalOrderCreation,
  createOrder,
  createOrderFail,
  createOrderSuccess,
  loadMoreOrders,
  loadOrder,
  loadOrderByAPIToken,
  loadOrderFail,
  loadOrderSuccess,
  loadOrders,
  loadOrdersFail,
  loadOrdersSuccess,
  processPaypalOrderCreation,
  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, basketId })),
          mapErrorToAction(createOrderFail)
        )
      )
    )
  );
 
  /**
   * After order creation either redirect to a payment provider or show checkout receipt page.
   */
  continueAfterOrderCreation$ = createEffect(
    () =>
      this.actions$.pipe(
        ofType(createOrderSuccess),
        mapToPayload(),
        filter(({ order }) => order?.orderCreation?.status !== 'ROLLED_BACK'),
        concatMap(({ order, basketId }) => {
          Iif (
            order.orderCreation?.status === 'STOPPED' &&
            order.orderCreation.stopAction.type === 'Redirect' &&
            order.orderCreation.stopAction.redirectUrl
          ) {
            location.assign(order.orderCreation.stopAction.redirectUrl);
            return EMPTY;
          } else if (
            order.orderCreation?.status === 'STOPPED' &&
            order.orderCreation.stopAction.exitReason === 'recurring.order'
          ) {
            return from(this.router.navigate(['/checkout/receipt'], { queryParams: { recurringOrderId: basketId } }));
          } 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?.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: orders.orders, query, paging: orders.paging })),
          mapErrorToAction(loadOrdersFail)
        )
      )
    )
  );
 
  loadMoreOrders$ = createEffect(() =>
    this.actions$.pipe(
      ofType(loadMoreOrders),
      mapToPayload(),
      concatLatestFrom(() => this.store.pipe(select(getOrderListQuery))),
      map(([payload, query]) => loadOrders({ query: { ...query, offset: payload.offset, limit: payload.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}` },
              ],
            })
          )
        )
      )
    )
  );
 
  startPaypalOrderCreation$ = createEffect(() =>
    this.actions$.pipe(
      ofType(processPaypalOrderCreation),
      filter(action => !action.payload.orderId),
      switchMap(() =>
        this.store.pipe(
          select(getCurrentBasketId),
          take(1),
          switchMap(basketId =>
            this.orderService.createOrder(basketId, true).pipe(
              map(order =>
                emitPaypalOrderId({
                  paypalOrderId: this.getPaypalOrderId(order),
                  orderId: order.id,
                })
              ),
              catchError(error => [createOrderFail({ error }), emitPaypalOrderId({ orderStatus: 'ERROR' })])
            )
          )
        )
      )
    )
  );
 
  continuePaypalOrderCreation$ = createEffect(() =>
    this.actions$.pipe(
      ofType(processPaypalOrderCreation),
      filter(action => !!action.payload.orderId),
      mapToPayloadProperty('orderId'),
      concatMap(orderId =>
        this.store.pipe(
          select(getCurrentBasketId),
          take(1),
          map(basketId => [orderId, basketId])
        )
      ),
      switchMap(([orderId, basketId]) =>
        this.orderService.continueOrderCreation(orderId).pipe(
          mergeMap(order =>
            order.orderCreation.status === 'ROLLED_BACK'
              ? [
                  cancelPaypalOrderCreation(),
                  emitPaypalOrderId({
                    paypalOrderId: this.getPaypalOrderId(order),
                    orderId: order.id,
                    orderStatus: 'CANCELLED',
                  }),
                ]
              : [
                  createOrderSuccess({ order, basketId }),
                  emitPaypalOrderId({
                    paypalOrderId: this.getPaypalOrderId(order),
                    orderId: order.id,
                    orderStatus: 'SUCCESS',
                  }),
                ]
          ),
          mapErrorToAction(createOrderFail)
        )
      )
    )
  );
 
  cancelPaypalOrderCreation$ = createEffect(
    () =>
      this.actions$.pipe(
        ofType(cancelPaypalOrderCreation),
        concatMap(() => from(this.router.navigate(['/checkout/payment'], { queryParams: { redirect: 'cancel' } })))
      ),
    { dispatch: false }
  );
 
  private getPaypalOrderId(order: Order): string {
    return (
      order.orderCreation?.redirect?.parameters?.find((p: { name: string }) => p.name === 'PayPalOrderID')?.value || ''
    );
  }
}