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

87.5% Statements 77/88
75% Branches 39/52
90.47% Functions 38/42
87.5% Lines 77/88

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 27423x 23x 23x 23x 23x 23x 23x             23x 23x 23x 23x 23x 23x   23x                               23x     23x   27x 27x 27x 27x       27x                             27x 27x   2x 2x 2x             27x 27x   4x 4x   3x 2x                   27x   27x     3x 3x   1x       1x                         27x 27x         4x   3x                         27x 27x         13x   13x     12x                                 27x 27x       5x   4x                         27x   27x     3x         27x 27x     1x                                       27x 27x     2x   2x       2x           1x 1x 1x 1x             3x       3x 1x 1x       1x 2x     1x   1x 1x     2x 2x            
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 { intersection } from 'lodash-es';
import { EMPTY, Observable, from } from 'rxjs';
import { concatMap, filter, map, withLatestFrom } from 'rxjs/operators';
 
import { BasketFeedbackView } from 'ish-core/models/basket-feedback/basket-feedback.model';
import {
  BasketValidationResultType,
  BasketValidationScopeType,
} from 'ish-core/models/basket-validation/basket-validation.model';
import { CheckoutStepType } from 'ish-core/models/checkout/checkout-step.type';
import { BasketService } from 'ish-core/services/basket/basket.service';
import { getServerConfigParameter } from 'ish-core/store/core/server-config';
import { createOrder } from 'ish-core/store/customer/orders';
import { loadProduct } from 'ish-core/store/shopping/products';
import { mapErrorToAction, mapToPayload, mapToPayloadProperty, whenTruthy } from 'ish-core/utils/operators';
 
import {
  continueCheckout,
  continueCheckoutFail,
  continueCheckoutSuccess,
  continueCheckoutWithIssues,
  continueWithFastCheckout,
  loadBasketEligiblePaymentMethods,
  loadBasketEligibleShippingMethods,
  loadBasketFail,
  startCheckout,
  startCheckoutFail,
  startCheckoutSuccess,
  startFastCheckout,
  submitBasket,
  validateBasket,
} from './basket.actions';
import { getCurrentBasket } from './basket.selectors';
 
@Injectable()
export class BasketValidationEffects {
  constructor(
    private actions$: Actions,
    private store: Store,
    private router: Router,
    private basketService: BasketService
  ) {}
 
  // validation step for each checkout step type
  private validationSteps: { [targetStep: string | number]: { scopes: BasketValidationScopeType[]; route: string } } = {
    [CheckoutStepType.BeforeCheckout]: { scopes: ['Products', 'Promotion', 'Value', 'CostCenter'], route: '/basket' },
    [CheckoutStepType.Addresses]: {
      scopes: ['InvoiceAddress', 'ShippingAddress', 'Addresses'],
      route: '/checkout/address',
    },
    [CheckoutStepType.Shipping]: { scopes: ['Shipping'], route: '/checkout/shipping' },
    [CheckoutStepType.Payment]: { scopes: ['Payment'], route: '/checkout/payment' },
    [CheckoutStepType.Review]: { scopes: ['All', 'CostCenter'], route: '/checkout/review' },
    [CheckoutStepType.Receipt]: { scopes: ['All'], route: 'auto' }, // targetRoute will be calculated in dependence of the validation result
  };
 
  /**
   * Jumps to the first checkout step (no basket acceleration)
   */
  startCheckoutWithoutAcceleration$ = createEffect(() =>
    this.actions$.pipe(
      ofType(startCheckout),
      concatLatestFrom(() => this.store.pipe(select(getServerConfigParameter<boolean>('basket.acceleration')))),
      filter(([, acc]) => !acc),
      map(() => continueCheckout({ targetStep: CheckoutStepType.Addresses }))
    )
  );
 
  /**
   * Check the basket before starting the basket acceleration
   */
  startCheckoutWithAcceleration$ = createEffect(() =>
    this.actions$.pipe(
      ofType(startCheckout),
      concatLatestFrom(() => this.store.pipe(select(getServerConfigParameter<boolean>('basket.acceleration')))),
      filter(([, acc]) => acc),
      concatMap(() =>
        this.basketService.validateBasket(this.validationSteps[CheckoutStepType.BeforeCheckout].scopes).pipe(
          map(basketValidation => startCheckoutSuccess({ basketValidation })),
          mapErrorToAction(startCheckoutFail)
        )
      )
    )
  );
 
  /**
   * Validates the basket and jumps to the next possible checkout step (basket acceleration)
   */
  continueCheckoutWithAcceleration$ = createEffect(
    () =>
      this.actions$.pipe(
        ofType(startCheckoutSuccess),
        mapToPayload(),
        map(payload => payload.basketValidation.results),
        filter(results => results.valid && !results.adjusted),
        concatMap(() =>
          this.basketService
            .validateBasket(this.validationSteps[CheckoutStepType.Review].scopes)
            .pipe(
              concatMap(basketValidation =>
                basketValidation?.results?.valid
                  ? from(this.router.navigate([this.validationSteps[CheckoutStepType.Review].route]))
                  : this.jumpToTargetRoute('auto', basketValidation?.results)
              )
            )
        )
      ),
    { dispatch: false }
  );
 
  /**
   * validates the basket but doesn't change the route
   */
  validateBasket$ = createEffect(() =>
    this.actions$.pipe(
      ofType(validateBasket),
      mapToPayloadProperty('scopes'),
      whenTruthy(),
      concatMap(scopes =>
        this.basketService.validateBasket(scopes).pipe(
          map(basketValidation =>
            basketValidation.results.valid
              ? continueCheckoutSuccess({ targetRoute: undefined, basketValidation })
              : continueCheckoutWithIssues({ targetRoute: undefined, basketValidation })
          ),
          mapErrorToAction(continueCheckoutFail)
        )
      )
    )
  );
 
  /**
   * Validates the basket before the user is allowed to jump to the next basket step
   */
  validateBasketAndContinueCheckout$ = createEffect(() =>
    this.actions$.pipe(
      ofType(continueCheckout),
      mapToPayloadProperty('targetStep'),
      whenTruthy(),
      concatMap(targetStep => {
        const targetRoute = this.validationSteps[targetStep].route;
 
        return this.basketService.validateBasket(this.validationSteps[targetStep - 1].scopes).pipe(
          withLatestFrom(this.store.pipe(select(getCurrentBasket))),
          concatMap(([basketValidation, basket]) =>
            basketValidation.results.valid
              ? targetStep === CheckoutStepType.Receipt && !basketValidation.results.adjusted
                ? basket.approval?.approvalRequired
                  ? [continueCheckoutSuccess({ targetRoute: undefined, basketValidation }), submitBasket()]
                  : [continueCheckoutSuccess({ targetRoute: undefined, basketValidation }), createOrder()]
                : [continueCheckoutSuccess({ targetRoute, basketValidation })]
              : [continueCheckoutWithIssues({ targetRoute, basketValidation })]
          ),
          mapErrorToAction(continueCheckoutFail)
        );
      })
    )
  );
 
  /**
   * Validation the basket before starting the fast checkout effect.
   */
  startFastCheckoutProcess$ = createEffect(() =>
    this.actions$.pipe(
      ofType(startFastCheckout),
      mapToPayloadProperty('paymentId'),
      concatMap(paymentId =>
        this.basketService.validateBasket(this.validationSteps[0].scopes).pipe(
          map(basketValidation =>
            basketValidation.results.valid
              ? continueWithFastCheckout({ targetRoute: undefined, basketValidation, paymentId })
              : continueCheckoutWithIssues({ targetRoute: undefined, basketValidation })
          ),
          mapErrorToAction(startCheckoutFail)
        )
      )
    )
  );
 
  /**
   * Jumps to the next checkout step after basket validation. In case of adjustments related data like product data, eligible shipping methods etc. are loaded.
   */
  jumpToNextCheckoutStep$ = createEffect(
    () =>
      this.actions$.pipe(
        ofType(continueCheckoutSuccess, continueCheckoutWithIssues),
        mapToPayload(),
        concatMap(payload => this.jumpToTargetRoute(payload.targetRoute, payload.basketValidation?.results))
      ),
    { dispatch: false }
  );
 
  loadDataForNextCheckoutStep$ = createEffect(() =>
    this.actions$.pipe(
      ofType(continueCheckoutSuccess, continueCheckoutWithIssues),
      mapToPayload(),
      filter(payload => payload.basketValidation?.results.adjusted && !!payload.basketValidation.results.infos),
      map(payload => payload.basketValidation),
      concatMap(validation => {
        // Load eligible shipping methods if shipping infos are available
        if (validation.scopes.includes('Shipping')) {
          return [loadBasketEligibleShippingMethods()];
          // Load eligible payment methods if payment infos are available
        } else if (validation.scopes.includes('Payment')) {
          return [loadBasketEligiblePaymentMethods()];
        } else {
          // Load products if product related infos are available
          return validation.results.infos
            .filter(info => info.parameters?.productSku)
            .map(info => loadProduct({ sku: info.parameters.productSku }));
        }
      })
    )
  );
 
  // if the basket is expired or doesn't exist - clear the basket and go to cart page
  handleBasketNotFoundError$ = createEffect(() =>
    this.actions$.pipe(
      ofType(startCheckoutFail, continueCheckoutFail),
      mapToPayloadProperty('error'),
      filter(error => error?.code === 'basket.not_found.error' || error?.errors[0]?.code === 'basket.not_found.error'),
      concatMap(error =>
        from(
          this.router.navigate([this.validationSteps[CheckoutStepType.BeforeCheckout].route], {
            queryParams: { error: true },
          })
        ).pipe(map(() => loadBasketFail({ error })))
      )
    )
  );
 
  private extractScopes(elements: BasketFeedbackView[]): string[] {
    return elements
      ?.filter(el => !!el.parameters?.scopes?.length)
      .reduce((acc, el) => [...acc, ...el.parameters.scopes], [])
      .filter((val, idx, arr) => !!val && arr.indexOf(val) === idx);
  }
 
  /**
   * Navigates to the target route, in case targetRoute equals 'auto' the target route will be calculated based on the calculation result
   */
  private jumpToTargetRoute(targetRoute: string, results: BasketValidationResultType): Observable<boolean> {
    Iif (!targetRoute || !results) {
      return EMPTY;
    }
 
    if (targetRoute === 'auto') {
      let scopes = this.extractScopes(results.errors);
      Iif (!scopes?.length) {
        scopes = this.extractScopes(results.infos);
      }
 
      const foundKey = Object.keys(this.validationSteps).find(
        key => intersection(this.validationSteps[key].scopes, scopes).length
      );
 
      const foundStep = this.validationSteps[foundKey];
 
      if (foundStep) {
        return from(this.router.navigate([foundStep.route], { queryParams: { error: true } }));
      }
      // otherwise stay on the current page
    } else if (results.valid && !results.adjusted) {
      return from(this.router.navigate([targetRoute]));
    }
 
    return EMPTY;
  }
}