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

88.46% Statements 161/182
75.47% Branches 40/53
82.14% Functions 46/56
90.47% Lines 152/168

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 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 4745x 5x 5x 5x 5x   5x   5x 5x 5x                         5x         28x   28x   28x     28x 28x 28x 28x       28x   28x   28x                 28x 28x 28x 28x 28x                         23x   23x 2x       21x 21x 21x     21x 21x 21x                     5x     5x         21x 1x       21x   20x     20x     20x                           20x     20x   20x       23x         20x         20x         20x         20x 80x                 20x             20x                       83x 83x   83x 83x 83x           83x 32x   32x     83x       83x     79x     79x           79x         4x 3x 3x 3x   1x               5x               5x       5x             5x 5x 4x               20x 20x   20x 20x 4x 4x 4x 3x   4x 4x           20x 1x 1x 1x 1x                   3x   3x         3x             3x     2x 2x       3x   1x       3x             2x 2x 2x       2x             3x 3x 1x               3x 3x             3x 3x 3x 1x               6x 6x     6x 20x         48x     6x 6x 18x 15x 15x 5x                   3x 3x 3x               3x 3x 3x 7x   3x 3x   2x 2x   1x 1x   1x 1x                 11x 11x 11x 11x 11x               53x 53x 53x 53x 53x               64x           64x      
import { DOCUMENT } from '@angular/common';
import { Inject, Injectable, NgZone } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { BehaviorSubject, Subject, firstValueFrom, race, timer } from 'rxjs';
import { map, take } from 'rxjs/operators';
 
import { CheckoutFacade } from 'ish-core/facades/checkout.facade';
import { PaymentMethod } from 'ish-core/models/payment-method/payment-method.model';
import { PAYPAL_CART_FIELDS_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 {
  PaypalCardFieldError,
  PaypalCardFieldsComponent,
  PaypalCardFieldsIndividualField,
  PaypalCardFieldsStateObject,
  PaypalStateObject,
} from 'ish-core/utils/paypal/paypal-model/paypal.model';
 
/**
 * Representation of the PayPal SDK Card Fields object, responsible for rendering PayPal card fields 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 PaypalCardFieldsAdapter {
  paymentMethod: PaymentMethod;
  cardField: PaypalCardFieldsComponent;
 
  /** Emits when the card fields form should be closed */
  closeForm$ = new Subject<void>();
  /** Emits true when the card fields is start to submit  */
  loadingIframe$ = new BehaviorSubject<boolean>(false);
  /** Emits true when the card fields is start to submit  */
  renderError$ = new Subject<string>();
 
  /** Error state observables for each field */
  nameFieldError$ = new BehaviorSubject<boolean>(false);
  numberFieldError$ = new BehaviorSubject<boolean>(false);
  cvvFieldError$ = new BehaviorSubject<boolean>(false);
  expiryFieldError$ = new BehaviorSubject<boolean>(false);
 
  private creditCardPaymentInstrumentId: string;
  /** Flag to prevent blur validation during field reset */
  private isResetting = false;
  /** Flag to prevent prevent double submission */
  private processing = false;
  // Store rendered field instances for later access
  private fields: Record<
    string,
    {
      containerId: string;
      instance: PaypalCardFieldsIndividualField;
    }
  > = {};
 
  constructor(
    private ngZone: NgZone,
    private checkoutFacade: CheckoutFacade,
    private paypalDataTransferService: PaypalDataTransferService,
    private translateService: TranslateService,
    @Inject(DOCUMENT) private document: Document
  ) {}
 
  /**
   * Creates and renders PayPal card fields in the specified containers.
   *
   * @param scriptNamespace - The PayPal SDK namespace on the window object
   * @param config - Configuration for the card fields
   * @returns Promise that resolves when all fields are rendered
   */
  async renderCardFields(scriptNamespace: string, paymentMethod: PaymentMethod): Promise<void> {
    // Access PayPal SDK from window object
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const paypalObject = (window as any)[scriptNamespace];
 
    if (!paypalObject?.CardFields) {
      return Promise.reject(new Error(`PayPal CardFields not available on namespace '${scriptNamespace}'`));
    }
 
    // Reset state for reinitialization
    this.processing = false;
    this.isResetting = false;
    this.creditCardPaymentInstrumentId = undefined;
 
    // Run PayPal SDK operations inside Angular zone to ensure proper event handling
    return this.ngZone.run(async () => {
      try {
        this.cardField = paypalObject.CardFields({
          createOrder: () => this.ngZone.run(() => this.createOrderCallback()),
          onApprove: () => this.ngZone.run(() => this.onApproveCallback()),
          onError: () => {
            this.ngZone.run(() => this.onErrorCallback());
          },
          onCancel: () => {
            this.ngZone.run(() => this.onCancelCallback());
          },
          inputEvents: {
            onFocus: (data: PaypalCardFieldsStateObject) => {
              this.ngZone.run(() => this.handleFieldFocus(data));
            },
            onBlur: (data: PaypalCardFieldsStateObject) => {
              this.ngZone.run(() => this.handleFieldBlur(data));
            },
          },
        }) as PaypalCardFieldsComponent;
 
        if (!this.cardField.isEligible()) {
          console.warn('PayPal CardFields: Not eligible for rendering');
        }
 
        // Check if card fields are eligible
        if (this.cardField.isEligible()) {
          // Render individual fields outside Angular zone for proper iframe interaction
          await this.renderIndividualFields();
 
          // set payment method for use in createOrder and onApprove callbacks
          this.paymentMethod = paymentMethod;
 
          // Setup submit and cancel button handlers
          this.setupHandlerForButtons();
        }
      } catch (error) {
        console.error('PayPal card fields rendering failed:', error);
        return Promise.reject(error);
      }
    });
  }
 
  /**
   * Renders individual card input fields (name, number, CVV, expiry).
   */
  protected async renderIndividualFields(): Promise<void> {
    // Clear any existing fields from previous renders
    this.cleanupExistingFields();
 
    // Wait for DOM to be fully ready before rendering
    await new Promise<void>(resolve => setTimeout(resolve, 100));
 
    const fieldConfigs = [
      {
        key: 'name',
        containerId: 'card-name-field-container',
        factory: () => this.cardField.NameField({ style: PAYPAL_CART_FIELDS_STYLING, placeholder: '' }),
      },
      {
        key: 'number',
        containerId: 'card-number-field-container',
        factory: () => this.cardField.NumberField({ style: PAYPAL_CART_FIELDS_STYLING, placeholder: '' }),
      },
      {
        key: 'cvv',
        containerId: 'card-cvv-field-container',
        factory: () => this.cardField.CVVField({ style: PAYPAL_CART_FIELDS_STYLING, placeholder: '' }),
      },
      {
        key: 'expiry',
        containerId: 'card-expiry-field-container',
        factory: () => this.cardField.ExpiryField({ style: PAYPAL_CART_FIELDS_STYLING }),
      },
    ];
 
    // Render fields sequentially - PayPal SDK may have issues with parallel rendering
    for (const config of fieldConfigs) {
      await this.renderSingleField(config, 0);
    }
  }
 
  /**
   * Cleans up existing field instances before reinitialization.
   */
  private cleanupExistingFields(): void {
    // Clear containers in DOM
    Object.values(this.fields).forEach(field => {
      const container = this.document.getElementById(field.containerId);
      Iif (container) {
        container.innerHTML = '';
      }
    });
    // Reset fields record
    this.fields = {};
  }
 
  /**
   * Renders a single card field with retry capability.
   * @param config - Field configuration
   * @param attempt - Current attempt number (0-based)
   */
  private async renderSingleField(
    config: { key: string; containerId: string; factory(): PaypalCardFieldsIndividualField },
    attempt: number
  ): Promise<void> {
    const maxRetries = 3;
    const retryDelay = 500;
 
    try {
      const container = this.document.getElementById(config.containerId);
      Iif (!container) {
        console.warn(`PayPal CardFields: Container '#${config.containerId}' not found in DOM`);
        return;
      }
 
      // Ensure container is empty before rendering
      if (container.innerHTML) {
        container.innerHTML = '';
        // Small delay after clearing to let DOM settle
        await new Promise<void>(resolve => setTimeout(resolve, 50));
      }
 
      this.fields[config.key] = {
        containerId: config.containerId,
        instance: config.factory(),
      };
      await this.fields[config.key].instance.render(`#${config.containerId}`);
 
      // Small delay after render to let iframe initialize
      await new Promise<void>(resolve => setTimeout(resolve, 100));
 
      // Verify that PayPal SDK actually rendered content in the container
      Iif (!container.hasChildNodes() && attempt < maxRetries) {
        // Retry if we haven't exceeded max attempts
        delete this.fields[config.key];
        await new Promise<void>(resolve => setTimeout(resolve, retryDelay));
        return this.renderSingleField(config, attempt + 1);
      }
      Iif (!container.hasChildNodes() && attempt === maxRetries) {
        this.renderError$.next('checkout.payment.paypal.script.render.error.message');
      }
    } catch (error) {
      // On error, retry if possible
      if (attempt < maxRetries) {
        delete this.fields[config.key];
        await new Promise<void>(resolve => setTimeout(resolve, retryDelay));
        return this.renderSingleField(config, attempt + 1);
      }
      this.renderError$.next('checkout.payment.paypal.script.render.error.message');
    }
  }
 
  /**
   * Handles field focus events to hide any existing error messages and re-enable submit button.
   */
  private handleFieldFocus(data: PaypalCardFieldsStateObject): void {
    this.hideFieldError(data.emittedBy);
  }
 
  /**
   * Handles field blur events to validate and show errors if necessary.
   */
  private handleFieldBlur(data: PaypalCardFieldsStateObject): void {
    // Skip validation during field reset to prevent race conditions
    Iif (this.isResetting) {
      return;
    }
 
    const fieldConfig: Record<string, { fieldState: { isValid: boolean; isEmpty: boolean } }> = {
      name: { fieldState: data.fields.cardNameField },
      number: { fieldState: data.fields.cardNumberField },
      cvv: { fieldState: data.fields.cardCvvField },
      expiry: { fieldState: data.fields.cardExpiryField },
    };
 
    const config = fieldConfig[data.emittedBy];
    if (config && !config.fieldState.isValid) {
      config.fieldState.isEmpty ? this.hideFieldError(data.emittedBy) : this.showFieldError(data.emittedBy);
    }
  }
 
  /**
   * Sets up the submit button and cancel button event handler for card field submission/cancellation.
   */
  private setupHandlerForButtons(): void {
    const submitButton = this.document.getElementById('card-field-submit-button');
    const cancelButton = this.document.getElementById('card-field-cancel-button');
 
    if (submitButton) {
      submitButton.addEventListener('click', () => {
        this.ngZone.run(async () => {
          if (!this.processing) {
            this.cardField.submit().catch(() => {
              this.validationErrorHandler(this.cardField.getState());
            });
            this.loadingIframe$.next(true);
            this.processing = true;
          }
        });
      });
    }
 
    if (cancelButton) {
      cancelButton.addEventListener('click', () => {
        this.ngZone.run(() => {
          this.resetFieldValues();
          this.closeForm$.next();
        });
      });
    }
  }
 
  /**
   * Paypal Order Id creation callback. Creates a basket payment and waits for the orderId from the service.
   */
  protected async createOrderCallback(): Promise<string> {
    const orderId = this.waitForOrderData();
 
    this.checkoutFacade.createPaypalCreditCardBasketPayment({
      id: undefined,
      paymentMethod: this.paymentMethod.id,
    });
 
    return orderId;
  }
 
  /**
   * Waits for the PayPal order data from the service with a timeout.
   */
  private waitForOrderData(): Promise<string> {
    const orderData$ = this.paypalDataTransferService.paypalOrder$.pipe(
      take(1),
      map(data => {
        this.creditCardPaymentInstrumentId = data.paymentInstrumentId;
        return data.orderId;
      })
    );
 
    const timeout$ = timer(3000).pipe(
      map(() => {
        throw new Error('PayPal order ID not received within 3 seconds');
      })
    );
 
    return firstValueFrom(race(orderData$, timeout$));
  }
 
  /**
   * Handles PayPal payment approval.
   */
  protected async onApproveCallback() {
    this.loadingIframe$.next(false);
    this.resetFieldValues();
    this.checkoutFacade.submitPaypalPaymentInstrument({
      id: this.creditCardPaymentInstrumentId,
      paymentMethod: this.paymentMethod.id,
    });
    this.processing = false;
  }
 
  /**
   * Handles PayPal payment errors.
   */
  protected async onErrorCallback() {
    this.loadingIframe$.next(false);
    if (this.creditCardPaymentInstrumentId) {
      this.checkoutFacade.deletePaypalPayment(
        {
          id: this.creditCardPaymentInstrumentId,
          paymentMethod: this.paymentMethod.id,
        },
        this.translateService.instant('checkout.payment.paypal.error.message')
      );
    }
    this.resetFieldValues();
    this.processing = false;
  }
 
  /**
   * Handles PayPal payment cancellation.
   */
  protected onCancelCallback(): void {
    this.loadingIframe$.next(false);
    this.processing = false;
    if (this.creditCardPaymentInstrumentId) {
      this.checkoutFacade.deletePaypalPayment({
        id: this.creditCardPaymentInstrumentId,
        paymentMethod: this.paymentMethod.id,
      });
    }
  }
 
  private resetFieldValues(): void {
    this.isResetting = true;
    const allFields = Object.keys(this.fields);
 
    // Clear field values
    allFields.forEach(key => {
      this.fields[key].instance.clear();
    });
 
    // Remove error styles multiple times to ensure we override PayPal's internal async validation
    // PayPal SDK sets 'invalid' class internally during blur, timing is unpredictable
    const removeInvalidClass = () => allFields.forEach(field => this.hideFieldError(field));
 
    // Multiple attempts at different timings to catch PayPal's async validation
    const delays = [50, 150, 300];
    delays.forEach((delay, index) => {
      setTimeout(() => {
        removeInvalidClass();
        if (index === delays.length - 1) {
          this.isResetting = false;
        }
      }, delay);
    });
  }
 
  /**
   * Default error handler for PayPal card fields.
   */
  private validationErrorHandler(statePromise: Promise<PaypalStateObject>): void {
    statePromise.then(stateObject => {
      const cardFieldsState = stateObject?.value ?? (stateObject as unknown as PaypalCardFieldsStateObject);
      this.handleSubmitError(cardFieldsState);
    });
  }
 
  /**
   * Handles card field validation errors.
   */
  private handleSubmitError(state: PaypalCardFieldsStateObject): void {
    this.loadingIframe$.next(false);
    this.processing = false;
    state.errors.forEach(error => {
      switch (error) {
        case PaypalCardFieldError.InvalidName:
          this.showFieldError('name');
          break;
        case PaypalCardFieldError.InvalidNumber:
          this.showFieldError('number');
          break;
        case PaypalCardFieldError.InvalidCvv:
          this.showFieldError('cvv');
          break;
        case PaypalCardFieldError.InvalidExpiry:
          this.showFieldError('expiry');
          break;
      }
    });
  }
 
  /**
   * Displays error message for a specific field and marks the input as invalid.
   */
  private showFieldError(fieldName: string): void {
    const field = this.fields[fieldName];
    if (field) {
      this.setFieldErrorState(fieldName, true);
      field.instance.addClass('invalid');
      field.instance.setAttribute('aria-invalid', 'true');
    }
  }
 
  /**
   * Hides error message, classes and aria attribute for a specific field
   */
  private hideFieldError(fieldName: string): void {
    const field = this.fields[fieldName];
    if (field) {
      this.setFieldErrorState(fieldName, false);
      field.instance.removeClass('invalid');
      field.instance.setAttribute('aria-invalid', 'false');
    }
  }
 
  /**
   * Updates the error state observable for a specific field.
   */
  private setFieldErrorState(fieldName: string, hasError: boolean): void {
    const errorSubjects: Record<string, BehaviorSubject<boolean>> = {
      name: this.nameFieldError$,
      number: this.numberFieldError$,
      cvv: this.cvvFieldError$,
      expiry: this.expiryFieldError$,
    };
    errorSubjects[fieldName]?.next(hasError);
  }
}