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

97.93% Statements 95/97
84.37% Branches 27/32
96.22% Functions 51/53
97.91% Lines 94/96

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 345 346 347 348 349 350 351 352 353 354 355 356 357 358 35927x 27x 27x 27x 27x 27x 27x   27x   27x 27x 27x 27x 27x 27x   27x                                                               27x     27x   48x 48x 48x 48x 48x           48x 48x     7x 4x                   48x 48x       14x 8x             48x 48x   5x 5x   5x   1x 1x                     48x 48x     6x 6x             6x       6x 3x                     48x 48x       3x   2x                     48x   48x       2x       2x                   48x 48x     6x   6x   3x                         48x 48x       6x   3x 1x             2x                     48x 48x       5x 2x                   48x 48x           1x         1x       1x                 48x 48x       7x 4x                   48x 48x     7x   7x 4x                   48x 48x               6x             48x 48x   6x           48x 48x                             48x   48x       4x   1x 1x                  
import { Injectable } from '@angular/core';
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 { EMPTY, of } from 'rxjs';
import { concatMap, exhaustMap, filter, map, switchMap, take } from 'rxjs/operators';
 
import { CheckoutStepType } from 'ish-core/models/checkout/checkout-step.type';
import { PaymentInstrument } from 'ish-core/models/payment-instrument/payment-instrument.model';
import { PaymentPaypalService } from 'ish-core/services/payment-paypal/payment-paypal.service';
import { PaymentService } from 'ish-core/services/payment/payment.service';
import { mapToRouterState } from 'ish-core/store/core/router';
import { getLoggedInCustomer } from 'ish-core/store/customer/user';
import { mapErrorToAction, mapToPayload, mapToPayloadProperty, whenTruthy } from 'ish-core/utils/operators';
import { PaypalDataTransferService } from 'ish-core/utils/paypal/paypal-data-transfer/paypal-data-transfer.service';
 
import {
  continueCheckout,
  continueWithFastCheckout,
  createBasketPayment,
  createBasketPaymentFail,
  createBasketPaymentSuccess,
  createPaypalCreditCardBasketPayment,
  deleteBasketPayment,
  deleteBasketPaymentFail,
  deleteBasketPaymentSuccess,
  deletePaypalCreditCardBasketPayment,
  emitPaypalOrderId,
  loadBasket,
  loadBasketEligiblePaymentMethods,
  loadBasketEligiblePaymentMethodsFail,
  loadBasketEligiblePaymentMethodsSuccess,
  setBasketPayment,
  setBasketPaymentFail,
  setBasketPaymentSuccess,
  startRedirectBeforeCheckout,
  startRedirectBeforeCheckoutFail,
  updateBasketPayment,
  updateBasketPaymentFail,
  updateBasketPaymentSuccess,
  updateConcardisCvcLastUpdated,
  updateConcardisCvcLastUpdatedFail,
  updateConcardisCvcLastUpdatedSuccess,
  updatePaymentInstrument,
  updatePaymentInstrumentFail,
  updatePaymentInstrumentSuccess,
  updatePaypalCreditCardPaymentInstrument,
} from './basket.actions';
import { getCurrentBasket, getCurrentBasketId } from './basket.selectors';
 
@Injectable()
export class BasketPaymentEffects {
  constructor(
    private actions$: Actions,
    private store: Store,
    private paymentService: PaymentService,
    private paymentPaypalService: PaymentPaypalService,
    private paypalDataTransferService: PaypalDataTransferService
  ) {}
 
  /**
   * The load basket eligible payment methods effect.
   */
  loadBasketEligiblePaymentMethods$ = createEffect(() =>
    this.actions$.pipe(
      ofType(loadBasketEligiblePaymentMethods),
      exhaustMap(() =>
        this.paymentService.getBasketEligiblePaymentMethods().pipe(
          map(result => loadBasketEligiblePaymentMethodsSuccess({ paymentMethods: result })),
          mapErrorToAction(loadBasketEligiblePaymentMethodsFail)
        )
      )
    )
  );
 
  /**
   * Sets a payment at the current basket.
   */
  setPaymentAtBasket$ = createEffect(() =>
    this.actions$.pipe(
      ofType(setBasketPayment),
      mapToPayloadProperty('id'),
      concatMap(id =>
        this.paymentService.setBasketPayment(id).pipe(
          map(() => setBasketPaymentSuccess()),
          mapErrorToAction(setBasketPaymentFail)
        )
      )
    )
  );
 
  startRedirectBeforeCheckout$ = createEffect(() =>
    this.actions$.pipe(
      ofType(startRedirectBeforeCheckout),
      concatLatestFrom(() => this.store.pipe(select(getCurrentBasket))),
      map(([, basket]) => basket?.payment?.paymentInstrument.id),
      concatMap(paymentInstrumentId =>
        this.paymentService.sendRedirectUrls(paymentInstrumentId).pipe(
          concatMap(paymentData => {
            location.assign(paymentData?.redirect?.redirectUrl);
            return EMPTY;
          }),
          mapErrorToAction(startRedirectBeforeCheckoutFail)
        )
      )
    )
  );
 
  /**
   * Creates a payment instrument at the current basket or user respectively - and saves it as payment at basket.
   */
  createBasketPaymentInstrument$ = createEffect(() =>
    this.actions$.pipe(
      ofType(createBasketPayment),
      mapToPayload(),
      concatLatestFrom(() => this.store.pipe(select(getLoggedInCustomer))),
      map(([payload, customer]) => ({
        saveForLater: payload.saveForLater,
        paymentInstrument: payload.paymentInstrument,
        customerNo: customer?.customerNo,
      })),
      concatMap(payload => {
        const createPayment$ =
          payload.customerNo && payload.saveForLater
            ? this.paymentService.createUserPayment(payload.customerNo, payload.paymentInstrument)
            : this.paymentService.createBasketPayment(payload.paymentInstrument);
 
        return createPayment$.pipe(
          concatMap(pi => [setBasketPayment({ id: pi.id }), createBasketPaymentSuccess()]),
          mapErrorToAction(createBasketPaymentFail)
        );
      })
    )
  );
 
  /**
   * For Paypal credit card it is necessary to create a temporary payment instrument. Means the payment instrument is not transferred to the ngrx store.
   * Otherwise the paypal iframe us not working correctly because change detection is triggered.
   */
  createPaypalCreditCardBasketPayment$ = createEffect(() =>
    this.actions$.pipe(
      ofType(createPaypalCreditCardBasketPayment),
      mapToPayload(),
      concatMap(payload =>
        this.paymentPaypalService.initializePaypalExperienceContextFlow(payload.paymentInstrument).pipe(
          map(response =>
            emitPaypalOrderId({ orderId: response.orderId, paymentInstrumentId: response.paymentInstrumentId })
          ),
          mapErrorToAction(setBasketPaymentFail)
        )
      )
    )
  );
 
  /**
   * Transfer PayPal order data after successful order ID retrieval.
   */
  emitPaypalOrderData$ = createEffect(
    () =>
      this.actions$.pipe(
        ofType(emitPaypalOrderId),
        mapToPayload(),
        concatMap(payload => {
          this.paypalDataTransferService.emitPaypalOrderData({
            orderId: payload.orderId,
            paymentInstrumentId: payload.paymentInstrumentId,
          });
          return EMPTY;
        })
      ),
    { dispatch: false }
  );
 
  /**
   * Deletes the temporary PayPal payment instrument. If an error message is provided,
   * emits setBasketPaymentFail action. Otherwise, no action is dispatched.
   */
  deletePaypalCreditCardBasketPayment$ = createEffect(() =>
    this.actions$.pipe(
      ofType(deletePaypalCreditCardBasketPayment),
      mapToPayload(),
      concatLatestFrom(() => this.store.pipe(select(getCurrentBasket))),
      concatMap(([payload, basket]) =>
        this.paymentService.deleteBasketPaymentInstrument(basket, payload.paymentInstrument).pipe(
          concatMap(() =>
            payload.errorMessage
              ? of(setBasketPaymentFail({ error: { name: 'HttpErrorResponse', message: payload.errorMessage } }))
              : EMPTY
          ),
          mapErrorToAction(setBasketPaymentFail)
        )
      )
    )
  );
 
  /**
   * Submits PayPal payment instrument data after approval and updates the payment instrument in the store.
   */
  submitPaypalPaymentInstrumentDataAfterApproval$ = createEffect(() =>
    this.actions$.pipe(
      ofType(updatePaypalCreditCardPaymentInstrument),
      mapToPayload(),
      concatMap(payload =>
        this.paymentPaypalService.getPaypalPaymentInstrument(payload.paymentInstrument).pipe(
          concatMap(response => {
            if ('errorMessage' in response && response.errorMessage) {
              return [
                deletePaypalCreditCardBasketPayment({
                  paymentInstrument: payload.paymentInstrument,
                  errorMessage: response.errorMessage,
                }),
              ];
            }
            return [
              updatePaymentInstrument({ paymentInstrument: response as PaymentInstrument }),
              continueCheckout({ targetStep: CheckoutStepType.Review }),
            ];
          }),
          mapErrorToAction(setBasketPaymentFail)
        )
      )
    )
  );
 
  updatePaymentInstrument$ = createEffect(() =>
    this.actions$.pipe(
      ofType(updatePaymentInstrument),
      mapToPayload(),
      concatMap(payload =>
        this.paymentService.updatePaymentInstrument(payload.paymentInstrument).pipe(
          concatMap(() => [updatePaymentInstrumentSuccess(), loadBasketEligiblePaymentMethods()]),
          mapErrorToAction(updatePaymentInstrumentFail)
        )
      )
    )
  );
 
  /**
   * Checks, if the page is called with redirect query params and sends them to the server ( only RedirectBeforeCheckout)
   */
  sendPaymentRedirectData$ = createEffect(() =>
    this.actions$.pipe(
      ofType(routerNavigatedAction),
      mapToRouterState(),
      // don't do anything in case of RedirectAfterCheckout
      filter(
        routerState =>
          /\/checkout\/(payment|review).*/.test(routerState.url) &&
          routerState.queryParams.redirect &&
          !routerState.queryParams.orderId
      ),
      switchMap(routerState =>
        this.store.pipe(
          select(getCurrentBasketId),
          whenTruthy(),
          take(1),
          map(() => updateBasketPayment({ params: routerState.queryParams }))
        )
      )
    )
  );
 
  /**
   * Updates a basket payment concerning redirect data.
   */
  updateBasketPayment$ = createEffect(() =>
    this.actions$.pipe(
      ofType(updateBasketPayment),
      mapToPayloadProperty('params'),
      concatMap(params =>
        this.paymentService.updateBasketPayment(params).pipe(
          map(() => updateBasketPaymentSuccess()),
          mapErrorToAction(updateBasketPaymentFail)
        )
      )
    )
  );
 
  /**
   * Deletes a payment instrument and the related payment at the current basket.
   */
  deleteBasketPaymentInstrument$ = createEffect(() =>
    this.actions$.pipe(
      ofType(deleteBasketPayment),
      mapToPayloadProperty('paymentInstrument'),
      concatLatestFrom(() => this.store.pipe(select(getCurrentBasket))),
      concatMap(([paymentInstrument, basket]) =>
        this.paymentService.deleteBasketPaymentInstrument(basket, paymentInstrument).pipe(
          map(() => deleteBasketPaymentSuccess()),
          mapErrorToAction(deleteBasketPaymentFail)
        )
      )
    )
  );
 
  /**
   * Triggers a LoadBasket action after successful interaction with the Basket API.
   */
  loadBasketAfterBasketChangeSuccess$ = createEffect(() =>
    this.actions$.pipe(
      ofType(
        setBasketPaymentSuccess,
        setBasketPaymentFail,
        updateBasketPaymentSuccess,
        updatePaymentInstrumentSuccess,
        deleteBasketPaymentSuccess
      ),
      map(() => loadBasket())
    )
  );
 
  /**
   * Triggers a LoadEligiblePaymentMethods action after successful delete a eligible Payment Instrument.
   */
  loadBasketEligiblePaymentMethodsAfterChange$ = createEffect(() =>
    this.actions$.pipe(
      ofType(deleteBasketPaymentSuccess, createBasketPaymentSuccess),
      map(() => loadBasketEligiblePaymentMethods())
    )
  );
  /**
   * Update CvcLastUpdated for Concardis Credit Card.
   */
  updateConcardisCvcLastUpdated$ = createEffect(() =>
    this.actions$.pipe(
      ofType(updateConcardisCvcLastUpdated),
      mapToPayloadProperty('paymentInstrument'),
      concatMap(paymentInstrument =>
        this.paymentService.updateConcardisCvcLastUpdated(paymentInstrument).pipe(
          map(pi => updateConcardisCvcLastUpdatedSuccess({ paymentInstrument: pi })),
          mapErrorToAction(updateConcardisCvcLastUpdatedFail)
        )
      )
    )
  );
 
  /**
   * The redirect fast checkout payment method effect.
   */
  continueWithFastCheckout$ = createEffect(
    () =>
      this.actions$.pipe(
        ofType(continueWithFastCheckout),
        mapToPayloadProperty('paymentId'),
        switchMap(paymentInstrumentId =>
          this.paymentService.setBasketFastCheckoutPayment(paymentInstrumentId).pipe(
            concatMap(redirectUrl => {
              location.assign(redirectUrl);
              return EMPTY;
            }),
            mapErrorToAction(setBasketPaymentFail)
          )
        )
      ),
    { dispatch: false }
  );
}