All files / src/app/pages/checkout-payment/payment-cybersource-creditcard payment-cybersource-creditcard.component.ts

56.75% Statements 42/74
47.82% Branches 11/23
53.33% Functions 8/15
57.14% Lines 40/70

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 2311x                       1x 1x 1x     1x   1x 1x                     1x     5x 5x 60x 60x   5x 35x                                 5x   5x 5x   5x                       5x             5x 5x       5x                                                                                                             3x   3x   1x 1x   1x 1x                                       2x 1x             1x   1x                     3x       4x 4x 4x                                                   1x 1x 1x     1x      
import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  DestroyRef,
  EventEmitter,
  Input,
  OnChanges,
  OnInit,
  Output,
  inject,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { range } from 'lodash-es';
 
import { Attribute } from 'ish-core/models/attribute/attribute.model';
import { PaymentMethod } from 'ish-core/models/payment-method/payment-method.model';
import { SelectOption } from 'ish-core/models/select-option/select-option.model';
import { ScriptLoaderService } from 'ish-core/utils/script-loader/script-loader.service';
import { markAsDirtyRecursive } from 'ish-shared/forms/utils/form-utils';
 
/* eslint-disable @typescript-eslint/no-explicit-any -- allows access to cybersource js functionality */
declare let Flex: any;
 
@Component({
  selector: 'ish-payment-cybersource-creditcard',
  templateUrl: './payment-cybersource-creditcard.component.html',
  styleUrls: ['./payment-cybersource-creditcard.component.scss'],
  changeDetection: ChangeDetectionStrategy.Default,
})
export class PaymentCybersourceCreditcardComponent implements OnChanges, OnInit {
  cyberSourceCreditCardForm: FormGroup;
 
  constructor(protected scriptLoader: ScriptLoaderService, protected cd: ChangeDetectorRef) {
    this.monthOptions = range(1, 13)
      .map(n => n.toString().padStart(2, '0'))
      .map(n => ({ label: n, value: n }));
 
    const currentYear = new Date().getFullYear();
    this.yearOptions = range(currentYear, currentYear + 7).map(n => ({
      label: n.toString(),
      value: n.toString(),
    }));
  }
 
  monthOptions: SelectOption[];
  yearOptions: SelectOption[];
 
  /**
   * cybersource payment method, needed to get configuration parameters
   */
  @Input({ required: true }) paymentMethod: PaymentMethod;
 
  /**
   * should be set to true by the parent, if component is visible
   */
  @Input() activated = false;
 
  @Output() cancelPayment = new EventEmitter<void>();
  @Output() submitPayment = new EventEmitter<{ parameters: Attribute<string>[]; saveAllowed: boolean }>();
 
  private destroyRef = inject(DestroyRef);
 
  private microform: any;
 
  // visible-for-testing
  expirationMonthVal: string;
  // visible-for-testing
  expirationYearVal: string;
 
  /**
   * error messages from host
   */
  errorMessage = {
    general: { message: '' },
    number: { message: '' },
    securityCode: { message: '' },
  };
 
  ngOnInit() {
    this.cyberSourceCreditCardForm = new FormGroup({});
    this.cyberSourceCreditCardForm.addControl(
      'expirationMonth',
      new FormControl('', [Validators.required, Validators.pattern('[0-9]{2}')])
    );
    this.cyberSourceCreditCardForm.addControl(
      'expirationYear',
      new FormControl('', [Validators.required, Validators.pattern('[0-9]{4}')])
    );
  }
 
  /**
   * load concardis script if component is shown
   */
  ngOnChanges() {
    Iif (this.paymentMethod) {
      this.loadScript();
    }
  }
 
  /**
   * gets a parameter value from payment method
   * sets the general error message (key) if the parameter is not available
   */
  private getParamValue(name: string, errorMessage: string): string {
    const parameter = this.paymentMethod.hostedPaymentPageParameters.find(param => param.name === name);
    Iif (!parameter?.value) {
      this.errorMessage.general.message = errorMessage;
      return;
    }
    return parameter.value;
  }
 
  private loadScript() {
    // spell-checker: words flexkey
    // load script only once if component becomes visible
    Iif (this.activated) {
      const flexkeyId = this.getParamValue('flexkeyId', 'checkout.credit_card.flexkeyId.error.notFound');
 
      this.scriptLoader
        .load('https://flex.cybersource.com/cybersource/assets/microform/0.11/flex-microform.min.js')
        .pipe(takeUntilDestroyed(this.destroyRef))
        .subscribe(() => {
          // the capture context that was requested server-side for this transaction
          const captureContext = flexkeyId;
 
          // setup
          const flex = new Flex(captureContext);
          this.microform = flex.microform();
          const cardNumber = this.microform.createField('number');
          const securityCode = this.microform.createField('securityCode');
 
          cardNumber.load('#number-container');
          securityCode.load('#securityCode-container');
        });
    }
  }
 
  // visible-for-testing
  submitCallback(error: { details: { location: string; message: string }[] }, token: string) {
    this.resetErrors();
 
    if (error) {
      // handling error
      for (const detail of error.details) {
        switch (detail.location) {
          case 'number': {
            this.errorMessage.number.message = 'checkout.credit_card.number.error.invalid';
            break;
          }
          case 'securityCode': {
            this.errorMessage.securityCode.message = 'checkout.credit_card.cvc.error.invalid';
            break;
          }
          case 'expirationMonth': {
            this.cyberSourceCreditCardForm.controls.expirationMonth.setErrors({
              customError: 'checkout.credit_card.expiryMonth.error.invalid',
            });
            break;
          }
          case 'expirationYear': {
            this.cyberSourceCreditCardForm.controls.expirationYear.setErrors({
              customError: 'checkout.credit_card.expiryMonth.error.invalid',
            });
            break;
          }
        }
      }
    } else if (!this.cyberSourceCreditCardForm.invalid) {
      const tokenSplit = token.split('.');
      const payloadJson: {
        data: { number: string; type: string; expirationMonth: string; expirationYear: string };
        iss: string;
        exp: string;
        iat: string;
        jti: string;
      } = JSON.parse(window.atob(tokenSplit[1]));
 
      this.submitPayment.emit({
        parameters: [
          { name: 'token', value: token },
          { name: 'tokenExpiryTime', value: payloadJson.exp },
          { name: 'cardType', value: payloadJson.data.type },
          { name: 'maskedCardNumber', value: payloadJson.data.number },
          { name: 'expirationDate', value: `${this.expirationMonthVal}/${this.expirationYearVal}` },
        ],
        saveAllowed: this.paymentMethod.saveAllowed && this.cyberSourceCreditCardForm.get('saveForLater').value,
      });
    }
    this.cd.detectChanges();
  }
 
  private resetErrors() {
    this.errorMessage.general.message = undefined;
    this.errorMessage.number.message = undefined;
    this.errorMessage.securityCode.message = undefined;
  }
 
  /**
   * submit cybersource payment form
   */
  submitNewPaymentInstrument() {
    if (this.cyberSourceCreditCardForm.invalid) {
      markAsDirtyRecursive(this.cyberSourceCreditCardForm);
    } else {
      this.expirationMonthVal = this.cyberSourceCreditCardForm.controls.expirationMonth.value;
      this.expirationYearVal = this.cyberSourceCreditCardForm.controls.expirationYear.value;
 
      const options = {
        expirationMonth: this.expirationMonthVal,
        expirationYear: this.expirationYearVal,
      };
 
      this.microform.createToken(options, (error: any, token: any) => this.submitCallback(error, token));
    }
  }
 
  /**
   * cancel new payment instrument, hides and resets the parameter form
   */
  cancelNewPaymentInstrument() {
    this.resetErrors();
    this.cyberSourceCreditCardForm.reset();
    Iif (this.cyberSourceCreditCardForm.get('saveForLater')) {
      this.cyberSourceCreditCardForm.get('saveForLater').setValue(true);
    }
    this.cancelPayment.emit();
  }
}