All files / src/app/core/facades checkout.facade.ts

53.78% Statements 64/119
37.5% Branches 18/48
19.04% Functions 12/63
53.57% Lines 60/112

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 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 40952x 52x 52x 52x 52x                 52x 52x 52x                                                                                               52x 52x 52x 52x   52x       52x 7x   7x 7x 7x                   7x                               7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x                                                                                                                               7x 7x   7x                             7x       7x       7x       7x       7x                                   7x                 2x                       3x 1x     1x     2x   1x                     1x 1x       1x 3x 2x             7x                     7x                                                     7x 7x 7x 7x                                                                                                       7x                                       7x           8x 4x        
import { Injectable } from '@angular/core';
import { Store, createSelector, select } from '@ngrx/store';
import { formatISO } from 'date-fns';
import { Subject, combineLatest, iif, merge } from 'rxjs';
import { debounceTime, distinctUntilChanged, filter, map, sample, switchMap, take, tap } from 'rxjs/operators';
 
import { Address } from 'ish-core/models/address/address.model';
import { Attribute } from 'ish-core/models/attribute/attribute.model';
import { CheckoutStepType } from 'ish-core/models/checkout/checkout-step.type';
import { LineItemUpdate } from 'ish-core/models/line-item-update/line-item-update.model';
import { PaymentInstrument } from 'ish-core/models/payment-instrument/payment-instrument.model';
import { PriceType } from 'ish-core/models/price/price.model';
import { Recurrence } from 'ish-core/models/recurrence/recurrence.model';
import { selectQueryParam, selectRouteData } from 'ish-core/store/core/router';
import { getServerConfigParameter } from 'ish-core/store/core/server-config';
import {
  addMessageToMerchant,
  addPromotionCodeToBasket,
  assignBasketAddress,
  continueCheckout,
  createBasket,
  createBasketAddress,
  createBasketPayment,
  deleteBasketAttribute,
  deleteBasketItem,
  deleteBasketItems,
  deleteBasketPayment,
  deleteBasketShippingAddress,
  getBasketEligibleAddresses,
  getBasketEligiblePaymentMethods,
  getBasketEligibleShippingMethods,
  getBasketError,
  getBasketInfo,
  getBasketInvoiceAddress,
  getBasketLastTimeProductAdded,
  getBasketLoading,
  getBasketPromotionError,
  getBasketShippingAddress,
  getBasketValidationResults,
  getCurrentBasket,
  getEligibleFastCheckoutPaymentMethods,
  getSubmittedBasket,
  isBasketInvoiceAndShippingAddressEqual,
  loadBasketEligibleAddresses,
  loadBasketEligiblePaymentMethods,
  loadBasketEligibleShippingMethods,
  loadBasketWithId,
  removePromotionCodeFromBasket,
  setBasketAttribute,
  setBasketDesiredDeliveryDate,
  setBasketPayment,
  startCheckout,
  startFastCheckout,
  startRedirectBeforeCheckout,
  submitOrder,
  updateBasket,
  updateBasketAddress,
  updateBasketCostCenter,
  updateBasketItem,
  updateBasketRecurrence,
  updateBasketShippingMethod,
  updateConcardisCvcLastUpdated,
} from 'ish-core/store/customer/basket';
import { getOrdersError, getSelectedOrder } from 'ish-core/store/customer/orders';
import { getRecurringOrder } from 'ish-core/store/customer/recurring-orders';
import { getLoggedInUser, getUserCostCenters, loadUserCostCenters } from 'ish-core/store/customer/user';
import { whenFalsy, whenTruthy } from 'ish-core/utils/operators';
 
import { AccountFacade } from './account.facade';
 
/* eslint-disable @typescript-eslint/member-ordering */
@Injectable({ providedIn: 'root' })
export class CheckoutFacade {
  private basketChangeInternal$ = new Subject<void>();
 
  constructor(private store: Store, private accountFacade: AccountFacade) {
    if (!SSR) {
      this.store
        .pipe(
          select(getBasketLastTimeProductAdded),
          whenTruthy(),
          sample(this.basketLoading$.pipe(debounceTime(500), whenFalsy()))
        )
        .subscribe(() => this.basketChangeInternal$.next());
    }
  }
 
  checkoutStep$ = this.store.pipe(select(selectRouteData<number>('checkoutStep')));
 
  start() {
    this.store.dispatch(startCheckout());
  }
 
  submitOrder() {
    this.store.dispatch(submitOrder());
  }
 
  continue(targetStep: CheckoutStepType) {
    this.store.dispatch(continueCheckout({ targetStep }));
  }
 
  // BASKET
 
  basket$ = this.store.pipe(select(getCurrentBasket));
  basketChange$ = this.basketChangeInternal$.asObservable();
  basketError$ = this.store.pipe(select(getBasketError));
  basketInfo$ = this.store.pipe(select(getBasketInfo));
  basketLoading$ = this.store.pipe(select(getBasketLoading));
  basketValidationResults$ = this.store.pipe(select(getBasketValidationResults));
  basketItemCount$ = this.basket$.pipe(map(basket => basket?.totalProductQuantity || 0));
  basketItemTotal$ = this.basket$.pipe(map(basket => basket?.totals?.itemTotal));
  basketLineItems$ = this.basket$.pipe(map(basket => (basket?.lineItems?.length ? basket.lineItems : undefined)));
  submittedBasket$ = this.store.pipe(select(getSubmittedBasket));
  basketMaxItemQuantity$ = this.store.pipe(
    select(getServerConfigParameter<number>('basket.maxItemQuantity')),
    map(qty => qty || 100)
  );
 
  loadBasketWithId(basketId: string) {
    this.store.dispatch(loadBasketWithId({ basketId }));
  }
 
  createBasket() {
    this.store.dispatch(createBasket());
  }
 
  deleteBasketItem(itemId: string) {
    this.store.dispatch(deleteBasketItem({ itemId }));
  }
 
  deleteBasketItems() {
    this.store.dispatch(deleteBasketItems());
  }
 
  updateBasketItem(update: LineItemUpdate) {
    if (update.quantity) {
      this.store.dispatch(updateBasketItem({ lineItemUpdate: update }));
    } else {
      this.store.dispatch(deleteBasketItem({ itemId: update.itemId }));
    }
  }
 
  updateBasketItemWarranty(itemId: string, warrantySku: string) {
    this.store.dispatch(updateBasketItem({ lineItemUpdate: { itemId, warrantySku } }));
  }
 
  updateBasketShippingMethod(shippingId: string) {
    this.store.dispatch(updateBasketShippingMethod({ shippingId }));
  }
 
  updateBasketCostCenter(costCenter: string) {
    this.store.dispatch(updateBasketCostCenter({ costCenter }));
  }
 
  updateBasketRecurrence(recurrence: Recurrence) {
    this.store.dispatch(updateBasketRecurrence({ recurrence }));
  }
 
  updateBasketExternalOrderReference(externalOrderReference: string) {
    this.store.dispatch(updateBasket({ update: { externalOrderReference } }));
  }
 
  setBasketCustomAttribute(attribute: Attribute): void {
    this.store.dispatch(setBasketAttribute({ attribute }));
  }
 
  deleteBasketCustomAttribute(attributeName: string): void {
    this.store.dispatch(deleteBasketAttribute({ attributeName }));
  }
 
  setBasketMessageToMerchant(messageToMerchant: string) {
    // eslint-disable-next-line unicorn/no-null
    this.store.dispatch(addMessageToMerchant({ messageToMerchant: messageToMerchant || null }));
  }
 
  // ORDERS
 
  private ordersError$ = this.store.pipe(select(getOrdersError));
  basketOrOrdersError$ = merge(this.basketError$, this.ordersError$);
 
  submittedOrder$ = this.store.pipe(
    select(selectQueryParam('recurringOrderId')),
    switchMap(recurringOrderId =>
      iif(
        () => !!recurringOrderId,
        // fetch recurring order information if recurringOrderId is present
        this.store.pipe(select(getRecurringOrder(recurringOrderId))),
        // otherwise fetch the information for a standard order
        this.store.pipe(select(getSelectedOrder))
      )
    )
  );
 
  // SHIPPING
 
  isDesiredDeliveryDateEnabled$ = this.store.pipe(
    select(getServerConfigParameter<boolean>('shipping.desiredDeliveryDate'))
  );
 
  isDesiredDeliveryExcludeSaturday$ = this.store.pipe(
    select(getServerConfigParameter<boolean>('shipping.deliveryExcludeSaturday'))
  );
 
  isDesiredDeliveryExcludeSunday$ = this.store.pipe(
    select(getServerConfigParameter<boolean>('shipping.deliveryExcludeSunday'))
  );
 
  desiredDeliveryDaysMax$ = this.store.pipe(
    select(getServerConfigParameter<number>('shipping.desiredDeliveryDaysMax'))
  );
 
  desiredDeliveryDaysMin$ = this.store.pipe(
    select(getServerConfigParameter<number>('shipping.desiredDeliveryDaysMin'))
  );
 
  setDesiredDeliveryDate(date: Date) {
    this.store.dispatch(
      setBasketDesiredDeliveryDate({ desiredDeliveryDate: date ? formatISO(date, { representation: 'date' }) : '' })
    );
  }
 
  eligibleShippingMethods$() {
    return this.basket$.pipe(
      whenTruthy(),
      take(1),
      tap(() => this.store.dispatch(loadBasketEligibleShippingMethods())),
      switchMap(() => this.store.pipe(select(getBasketEligibleShippingMethods)))
    );
  }
  eligibleShippingMethodsNoFetch$ = this.store.pipe(select(getBasketEligibleShippingMethods));
 
  shippingMethod$(id: string) {
    return this.eligibleShippingMethodsNoFetch$.pipe(
      map(methods => (methods?.length ? methods.find(method => method.id === id) : undefined))
    );
  }
 
  getValidShippingMethod$() {
    return combineLatest([
      this.basket$.pipe(whenTruthy()),
      this.eligibleShippingMethodsNoFetch$.pipe(whenTruthy()),
    ]).pipe(
      // compare baskets only by shippingMethod
      distinctUntilChanged(
        // spell-checker: words prevbasket prevship curbasket curship
        ([prevbasket, prevship], [curbasket, curship]) =>
          prevbasket.commonShippingMethod?.id === curbasket.commonShippingMethod?.id && prevship === curship
      ),
      map(([basket, shippingMethods]) => {
        // if the basket has a  shipping method and it's valid, do nothing
        if (shippingMethods.find(method => method.id === basket.commonShippingMethod?.id)) {
          return basket.commonShippingMethod.id;
        }
        // if there is no shipping method at basket or this basket shipping method is not valid anymore select automatically the 1st valid shipping method
        if (
          shippingMethods?.length &&
          (!basket?.commonShippingMethod?.id ||
            !shippingMethods.find(method => method.id === basket.commonShippingMethod?.id))
        ) {
          return shippingMethods[0].id;
        }
      }),
      whenTruthy(),
      distinctUntilChanged()
    );
  }
 
  // COST CENTER
 
  eligibleCostCenterSelectOptions$(selectRole?: string) {
    this.store.dispatch(loadUserCostCenters());
    return this.store.pipe(
      select(getUserCostCenters),
      whenTruthy(),
      map(costCenters =>
        costCenters
          .filter(costCenter => costCenter.roles.includes(selectRole ? selectRole : 'Buyer'))
          .map(c => ({ label: `${c.id} ${c.name}`, value: c.id }))
      )
    );
  }
 
  // PAYMENT
 
  priceType$ = this.store.pipe(select(getServerConfigParameter<PriceType>('pricing.priceType')));
 
  eligiblePaymentMethods$() {
    return this.basket$.pipe(
      whenTruthy(),
      take(1),
      tap(() => this.store.dispatch(loadBasketEligiblePaymentMethods())),
      switchMap(() => this.store.pipe(select(getBasketEligiblePaymentMethods)))
    );
  }
 
  eligibleFastCheckoutPaymentMethods$ = this.store.pipe(select(getEligibleFastCheckoutPaymentMethods));
  loadEligiblePaymentMethods() {
    this.store.dispatch(loadBasketEligiblePaymentMethods());
  }
 
  setBasketPayment(paymentName: string) {
    this.store.dispatch(setBasketPayment({ id: paymentName }));
  }
 
  startFastCheckout(paymentName: string) {
    this.store.dispatch(startFastCheckout({ paymentId: paymentName }));
  }
 
  createBasketPayment(paymentInstrument: PaymentInstrument, saveForLater = false) {
    this.store.dispatch(createBasketPayment({ paymentInstrument, saveForLater }));
  }
 
  deleteBasketPayment(paymentInstrument: PaymentInstrument) {
    this.store.dispatch(deleteBasketPayment({ paymentInstrument }));
  }
 
  startRedirectBeforeCheckout() {
    this.store.dispatch(startRedirectBeforeCheckout());
  }
 
  // ADDRESSES
 
  basketInvoiceAddress$ = this.store.pipe(select(getBasketInvoiceAddress));
  basketShippingAddress$ = this.store.pipe(select(getBasketShippingAddress));
  basketInvoiceAndShippingAddressEqual$ = this.store.pipe(select(isBasketInvoiceAndShippingAddressEqual));
  basketShippingAddressDeletable$ = this.store.pipe(
    select(
      createSelector(
        getLoggedInUser,
        getBasketEligibleAddresses,
        getBasketShippingAddress,
        (user, addresses, shippingAddress): boolean =>
          !!shippingAddress &&
          !!user &&
          addresses?.length > 1 &&
          (!user.preferredInvoiceToAddressUrn || user.preferredInvoiceToAddressUrn !== shippingAddress.urn) &&
          (!user.preferredShipToAddressUrn || user.preferredShipToAddressUrn !== shippingAddress.urn)
      )
    )
  );
 
  /**
   * Determines the eligible addresses of baskets that have an invoice address.
   * This ensures that the basket has at least one address.
   */
  eligibleAddresses$() {
    return this.basket$.pipe(
      whenTruthy(),
      filter(basket => basket.invoiceToAddress !== undefined),
      take(1),
      tap(() => this.store.dispatch(loadBasketEligibleAddresses())),
      switchMap(() => this.store.pipe(select(getBasketEligibleAddresses)))
    );
  }
 
  assignBasketAddress(addressId: string, scope: 'invoice' | 'shipping' | 'any') {
    this.store.dispatch(assignBasketAddress({ addressId, scope }));
  }
 
  createBasketAddress(address: Address, scope: 'invoice' | 'shipping' | 'any') {
    Iif (!address || !scope) {
      return;
    }
 
    this.store.dispatch(createBasketAddress({ address, scope }));
  }
 
  updateBasketAddress(address: Address) {
    this.store.dispatch(updateBasketAddress({ address }));
  }
 
  deleteBasketAddress(addressId: string) {
    this.store.dispatch(deleteBasketShippingAddress({ addressId }));
  }
 
  // PROMOTIONS
 
  promotionError$ = this.store.pipe(select(getBasketPromotionError));
 
  addPromotionCodeToBasket(code: string) {
    this.store.dispatch(addPromotionCodeToBasket({ code }));
  }
 
  removePromotionCodeFromBasket(code: string) {
    this.store.dispatch(removePromotionCodeFromBasket({ code }));
  }
 
  updateConcardisCvcLastUpdated(paymentInstrument: PaymentInstrument) {
    this.store.dispatch(updateConcardisCvcLastUpdated({ paymentInstrument }));
  }
 
  // RECURRING ORDERS
 
  // A basket can be used for a recurring order if
  //  - the user is logged in
  //  - the user is not logged in and there is no invoice address (exclude guest checkout)
  //  - there are no quote items in the basket
  canUseBasketForRecurringOrder$ = combineLatest([
    this.accountFacade.isLoggedIn$,
    this.basketInvoiceAddress$,
    this.basketLineItems$,
  ]).pipe(
    map(([isLoggedIn, invoiceAddress, lineItems]) => {
      const hasQuoteItems = (lineItems || []).some(item => item.quote);
      return (isLoggedIn || !invoiceAddress) && !hasQuoteItems;
    })
  );
}