All files / src/app/core/services/payment-paypal payment-paypal.service.ts

100% Statements 33/33
83.33% Branches 20/24
100% Functions 9/9
100% Lines 32/32

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 13228x 28x 28x 28x 28x   28x     28x 28x 28x   28x 28x 28x                                                       28x   7x 7x 7x 7x     7x               1x   1x 1x     1x   1x 1x   1x             1x         1x                   3x             3x 3x 1x       2x                                                    
import { APP_BASE_HREF } from '@angular/common';
import { HttpHeaders } from '@angular/common/http';
import { Inject, Injectable } from '@angular/core';
import { concatLatestFrom } from '@ngrx/operators';
import { Store, select } from '@ngrx/store';
import { Observable } from 'rxjs';
import { concatMap, map, switchMap } from 'rxjs/operators';
 
import { PaymentInstrument } from 'ish-core/models/payment-instrument/payment-instrument.model';
import { ApiService } from 'ish-core/services/api/api.service';
import { PaymentService } from 'ish-core/services/payment/payment.service';
import { getCurrentLocale } from 'ish-core/store/core/configuration';
 
enum ThreeDSecureDecisionStatus {
  ACCEPT = 'ACCEPT',
  DECLINE = 'DECLINE',
}
 
interface PaypalPaymentSourceData {
  data: {
    orderId: string;
    card?: {
      brand: string;
      expiry: string;
      lastDigits: string;
      threeDSecureDecision?: ThreeDSecureDecisionStatus;
    };
    experienceContext?: {
      cancelUrl?: string;
      returnUrl?: string;
    };
    name: string;
  };
  infos?: {
    code: string;
    message: string;
  }[];
}
 
/**
 * The Payment Service handles the interaction with the 'baskets' and 'users' REST API concerning payment functionality.
 */
@Injectable({ providedIn: 'root' })
export class PaymentPaypalService {
  constructor(
    private apiService: ApiService,
    private store: Store,
    private paymentService: PaymentService,
    @Inject(APP_BASE_HREF) private baseHref: string
  ) {}
 
  private basketHeaders = new HttpHeaders({
    'content-type': 'application/json',
    Accept: 'application/vnd.intershop.basket.v1+json',
  });
 
  initializePaypalExperienceContextFlow(
    paymentInstrument: PaymentInstrument
  ): Observable<{ orderId: string; paymentInstrumentId: string }> {
    let loc = `${location.origin}${this.baseHref}`;
    // Remove trailing slash if present
    if (loc.endsWith('/')) {
      loc = loc.slice(0, -1);
    }
 
    return this.paymentService.createBasketPayment(paymentInstrument).pipe(
      concatMap(pi =>
        this.paymentService.setBasketPayment(pi.id).pipe(
          concatLatestFrom(() => this.store.pipe(select(getCurrentLocale))),
          switchMap(([, currentLocale]) => {
            const body = {
              experienceContext: {
                returnUrl: `${loc}/checkout/review;lang=${currentLocale}?redirect=success`,
                cancelUrl: `${loc}/checkout/payment;lang=${currentLocale}?redirect=cancel`,
              },
            };
 
            return this.apiService
              .currentBasketEndpoint()
              .put<PaypalPaymentSourceData>('payments/open-tender/paypal-experience-context', body, {
                headers: this.basketHeaders,
              })
              .pipe(map(response => ({ orderId: response.data.orderId, paymentInstrumentId: pi.id })));
          })
        )
      )
    );
  }
 
  getPaypalPaymentInstrument(
    paymentInstrument: PaymentInstrument
  ): Observable<PaymentInstrument | { errorMessage: string }> {
    return this.apiService
      .currentBasketEndpoint()
      .get<PaypalPaymentSourceData>('payments/open-tender/paypal-experience-context', {
        headers: this.basketHeaders,
      })
      .pipe(
        map(response => {
          const paypalPaymentSourceRO = response.data;
          if (paypalPaymentSourceRO.card?.threeDSecureDecision === ThreeDSecureDecisionStatus.DECLINE) {
            return {
              errorMessage: response.infos[0].message,
            };
          }
          return {
            ...paymentInstrument,
            parameters: [
              {
                name: 'orderId',
                value: paypalPaymentSourceRO.orderId,
              },
              {
                name: 'brand',
                value: paypalPaymentSourceRO.card?.brand || '',
              },
              { name: 'expiry', value: paypalPaymentSourceRO.card?.expiry || '' },
              {
                name: 'lastDigits',
                value: paypalPaymentSourceRO.card?.lastDigits || '',
              },
              {
                name: 'cardHolder',
                value: paypalPaymentSourceRO.name || '',
              },
            ],
          };
        })
      );
  }
}