All files / src/app/core/utils/paypal/adapters/paypal-buttons paypal-buttons.adapter.ts

98.36% Statements 60/61
88.63% Branches 39/44
96.15% Functions 25/26
98.18% Lines 54/55

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 1625x 5x 5x 5x   5x     5x 5x                             5x   38x     38x 38x 38x 38x 38x                 17x 17x   17x 1x     16x 2x         14x       14x   1x   1x       2x       1x     2x           7x 7x   6x                   6x 5x   1x 1x     1x       7x   7x       9x 9x 9x   9x 24x 5x       4x   1x     9x                       10x 1x     9x       9x 9x     9x 18x       9x              
import { DOCUMENT } from '@angular/common';
import { Inject, Injectable, NgZone } from '@angular/core';
import { Router } from '@angular/router';
import { filter, map, race, switchMap, take, tap, timer } from 'rxjs';
 
import { CheckoutFacade } from 'ish-core/facades/checkout.facade';
import { PaymentMethod } from 'ish-core/models/payment-method/payment-method.model';
import { PaypalComponentsConfig } from 'ish-core/utils/paypal/adapters/paypal-adapters.builder';
import { PAYPAL_BUTTON_STYLING } from 'ish-core/utils/paypal/adapters/paypal-adapters.styling';
import { PaypalDataTransferService } from 'ish-core/utils/paypal/paypal-data-transfer/paypal-data-transfer.service';
import { PaypalComponent } from 'ish-core/utils/paypal/paypal-model/paypal.model';
 
interface PaypalShippingAddress {
  city: string;
  countryCode: string;
  postalCode: string;
  state: string;
}
 
/**
 * Representation of the PayPal SDK Buttons object, responsible for rendering PayPal buttons and handling the associated callbacks for order creation, approval, cancellation, and error handling.
 * Life cycle of this component ends with destroying of parent component PaymentPaypalComponent.
 */
@Injectable()
export class PaypalButtonsAdapter {
  paypalShippingAddress: PaypalShippingAddress;
  serviceAvailable = true;
 
  constructor(
    private ngZone: NgZone,
    private checkoutFacade: CheckoutFacade,
    private paypalDataTransferService: PaypalDataTransferService,
    private router: Router,
    @Inject(DOCUMENT) private document: Document
  ) {}
 
  /**
   * Renders PayPal buttons in the specified container and sets up the necessary callbacks for order creation, approval, cancellation, and error handling.
   * @param config
   * @returns
   */
  renderButtons(config: PaypalComponentsConfig): Promise<void> {
    const containerId = config.containerId;
    const paypalObject = (window as unknown as Record<string, PaypalComponent>)[config.scriptNamespace];
    // Verify element exists right before rendering
    if (!this.document.getElementById(containerId)) {
      throw new Error(`Container element '${containerId}' does not exist in DOM`);
    }
 
    if (!paypalObject?.Buttons) {
      throw new Error(
        `PayPal Buttons not available in loaded paypal sdk script with namespace '${config.scriptNamespace}'`
      );
    }
 
    return paypalObject.Buttons(this.getButtonConfig(config)).render(`#${containerId}`);
  }
 
  private getButtonConfig(config: PaypalComponentsConfig) {
    return {
      style: config.pageType === 'checkout' ? PAYPAL_BUTTON_STYLING.checkout : PAYPAL_BUTTON_STYLING.cart,
      createOrder: () => this.ngZone.run(() => this.createOrderCallback(config.paypalPaymentMethod)),
      onApprove: (data: { payerID: string; orderID: string }) => {
        this.ngZone.run(() => this.onApproveCallback(data));
      },
      // in case the shipping address was changed in the paypal overlay
      onShippingAddressChange: (data: { shippingAddress: PaypalShippingAddress }) => {
        this.paypalShippingAddress = data?.shippingAddress;
      },
      // after the user has cancelled the payment in the paypal overlay
      onCancel: () => {
        this.ngZone.run(() => this.onAbortCallback(config, 'cancel'));
      },
      onError: () => {
        this.ngZone.run(() => this.onAbortCallback(config, this.serviceAvailable ? 'failure' : 'unavailable'));
      },
    };
  }
 
  protected createOrderCallback(paypalPaymentMethod: PaymentMethod): Promise<string> {
    const orderIdPromise = new Promise<string>((resolve, reject) => {
      race(
        this.paypalDataTransferService.paypalOrder$.pipe(
          map(data => data.orderId),
          take(1)
        ),
        timer(30000).pipe(
          map(() => {
            throw new Error('PayPal order ID not available');
          })
        )
      ).subscribe({
        next: orderID => {
          if (orderID) {
            resolve(orderID);
          } else {
            this.serviceAvailable = false;
            reject(new Error('PayPal order ID is empty'));
          }
        },
        error: error => reject(error),
      });
    });
 
    this.checkoutFacade.loadPaypalToken(paypalPaymentMethod.paymentInstruments[0]?.id || paypalPaymentMethod.serviceId);
 
    return orderIdPromise;
  }
 
  protected onApproveCallback(data: { payerID: string; orderID: string }) {
    this.checkoutFacade.basket$.pipe(take(1)).subscribe(basket => {
      const basketAddress = basket?.commonShipToAddress;
      let shippingAddressChanged = false;
 
      if (this.paypalShippingAddress && basketAddress) {
        const normalize = (val: string) => val?.trim()?.toLowerCase();
        shippingAddressChanged =
          normalize(basketAddress.country) !== normalize(this.paypalShippingAddress.countryCode) ||
          normalize(basketAddress.postalCode) !== normalize(this.paypalShippingAddress.postalCode) ||
          normalize(basketAddress.city) !== normalize(this.paypalShippingAddress.city);
      } else if (this.paypalShippingAddress && !basketAddress) {
        // If PayPal has an address but basket doesn't, address has changed
        shippingAddressChanged = true;
      }
 
      this.router.navigate(['/checkout/review'], {
        queryParams: {
          redirect: 'success',
          token: data.orderID,
          PayerID: data.payerID,
          shippingAddressChanged,
        },
      });
    });
  }
 
  protected onAbortCallback(config: PaypalComponentsConfig, reason: 'cancel' | 'failure' | 'unavailable') {
    if (!config.paypalPaymentMethod?.paymentInstruments?.length) {
      return;
    }
 
    this.checkoutFacade.basket$
      .pipe(
        take(1),
        tap(basket => {
          if (basket.payment?.paymentInstrument?.id === config.paypalPaymentMethod.paymentInstruments[0]?.id) {
            this.checkoutFacade.deleteBasketPayment(config.paypalPaymentMethod.paymentInstruments[0]);
          }
        }),
        switchMap(() => this.checkoutFacade.basket$),
        filter(basket => !basket.payment),
        take(1)
      )
      .subscribe(() => {
        this.router.navigate(
          [config.paypalPaymentMethod.capabilities.includes('FastCheckout') ? '/basket' : '/checkout/payment'],
          { queryParams: { redirect: reason } }
        );
      });
  }
}