All files / src/app/pages/checkout-payment/payment-concardis-directdebit payment-concardis-directdebit.component.ts

40.21% Statements 37/92
36.58% Branches 15/41
44% Functions 11/25
38.09% Lines 32/84

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 2601x 1x 1x   1x   1x 1x   1x                                           1x 4x 4x           1x                                 4x 4x 4x     1x                                                                                               4x                                                                                         2x         2x 2x 1x 1x 1x                         2x                                                                                         1x 1x 1x 1x           1x     1x 1x                   1x 1x                            
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Validators } from '@angular/forms';
import { FormlyFieldConfig, FormlyFormOptions } from '@ngx-formly/core';
import { pairwise, startWith } from 'rxjs/operators';
 
import { ScriptLoaderService } from 'ish-core/utils/script-loader/script-loader.service';
import { markAsDirtyRecursive } from 'ish-shared/forms/utils/form-utils';
 
import { ConcardisErrorMessageType, PaymentConcardisComponent } from '../payment-concardis/payment-concardis.component';
 
/* eslint-disable @typescript-eslint/no-explicit-any -- allows access to concardis js functionality */
declare let PayEngine: any;
 
/**
 * The Payment Concardis Directdebit Component renders a form on which the user can enter his concardis direct debit data. Some entry fields are provided by an external host and embedded as iframes. Therefore an external javascript is loaded. See also {@link CheckoutPaymentPageComponent}
 *
 * @example
 * <ish-payment-concardis-directdebit
 [paymentMethod]="paymentMethod"
 [activated]="i === openFormIndex"
 (submitPayment)="createNewPaymentInstrument($event)"
 (cancelPayment)="cancelNewPaymentInstrument()"
></ish-payment-concardis-directdebit>
 */
@Component({
  selector: 'ish-payment-concardis-directdebit',
  templateUrl: './payment-concardis-directdebit.component.html',
  changeDetection: ChangeDetectionStrategy.Default,
})
// eslint-disable-next-line rxjs-angular/prefer-takeuntil
export class PaymentConcardisDirectdebitComponent extends PaymentConcardisComponent implements OnInit {
  constructor(protected scriptLoader: ScriptLoaderService, protected cd: ChangeDetectorRef) {
    super(scriptLoader, cd);
  }
 
  options: FormlyFormOptions;
 
  private handleErrors(controlName: string, message: string) {
    Iif (this.parameterForm.controls[controlName]) {
      this.options.formState = {
        ...this.options.formState,
        errors: {
          ...this.options.formState.errors,
          [controlName]: message,
        },
        changedSinceErrors: {
          ...this.options.formState.changedSinceErrors,
          [controlName]: false,
        },
      };
      this.parameterForm.controls[controlName].updateValueAndValidity();
    }
  }
 
  ngOnInit() {
    super.formInit();
    this.fieldConfig = this.getFieldConfig();
    this.parameterForm.valueChanges
      .pipe(startWith({}), pairwise(), takeUntilDestroyed(this.destroyRef))
      .subscribe(([prevValues, currentValues]) =>
        Object.keys(currentValues).forEach(key => {
          Iif (
            currentValues[key] !== prevValues[key] &&
            this.options.formState.changedSinceErrors?.hasOwnProperty(key)
          ) {
            this.options.formState.changedSinceErrors[key] = true;
            this.parameterForm.get(key).updateValueAndValidity();
          }
        })
      );
  }
 
  /* ---------------------------------------- load concardis script if component is visible ------------------------------------------- */
 
  loadScript() {
    // load script only once if component becomes visible
    Iif (this.activated && !this.scriptLoaded) {
      const merchantId = this.getParamValue(
        'ConcardisPaymentService.MerchantID',
        'checkout.payment.merchantId.error.notFould'
      );
 
      // if merchant Id are missing - don't load script
      Iif (!merchantId) {
        return;
      }
 
      this.scriptLoaded = true;
      this.scriptLoader
        .load(this.getPayEngineURL())
        .pipe(takeUntilDestroyed(this.destroyRef))
        .subscribe({
          next: () => {
            PayEngine.setPublishableKey(merchantId);
          },
          error: error => {
            this.scriptLoaded = false;
            this.errorMessage.general.message = error;
            this.cd.detectChanges();
          },
        });
    }
  }
 
  /**
   * hide fields without labels and enrich mandate reference and mandate text with corresponding values from hosted payment page parameters
   */
  private getFieldConfig(): FormlyFieldConfig[] {
    return this.paymentMethod.parameters.map(param => (param.hide ? this.modifyParam(param) : param));
  }
 
  private modifyParam(p: FormlyFieldConfig): FormlyFieldConfig {
    const param = p;
 
    Iif (param.key === 'mandateReference') {
      param.defaultValue = this.getParamValue('mandateId', '');
    }
 
    Iif (param.key === 'mandateText') {
      param.type = 'ish-checkbox-field';
      param.props.fieldClass = 'offset-md-4 col-md-6';
      param.props.labelClass = '';
      param.props.label = this.getParamValue('mandateText', '');
      param.defaultValue = false;
      param.hide = false;
      param.validators = [Validators.pattern('false')];
    }
    return param;
  }
 
  /**
   * call back function to submit data, get a response token from provider and send data in case of success
   */
  // visible-for-testing
  submitCallback(
    error: { message: { properties: { key: string; code: number; message: string; messageKey: string }[] } | string },
    result: {
      paymentInstrumentId: string;
      attributes: {
        accountHolder: string;
        iban: string;
        bic: string;
        mandateReference: string;
        mandate: {
          mandateReference: string;
          createdDateTime: string;
          mandateText: string;
          directDebitType: string;
        };
        createdAt: string;
      };
    }
  ) {
    Iif (this.parameterForm.invalid) {
      this.formSubmitted = true;
      markAsDirtyRecursive(this.parameterForm);
    }
 
    this.resetErrors();
    if (error) {
      this.mapErrorMessage(error.message);
    } else if (this.parameterForm.valid) {
      this.submitPayment.emit({
        parameters: [
          { name: 'paymentInstrumentId', value: result.paymentInstrumentId },
          { name: 'accountHolder', value: result.attributes.accountHolder },
          { name: 'IBAN', value: result.attributes.iban },
          { name: 'BIC', value: result.attributes.bic },
          { name: 'mandateReference', value: result.attributes.mandate.mandateReference },
          { name: 'mandateText', value: result.attributes.mandate.mandateText },
          { name: 'mandateCreatedDateTime', value: result.attributes.mandate.createdDateTime },
        ],
        saveAllowed: this.paymentMethod.saveAllowed && this.parameterForm.get('saveForLater').value,
      });
    }
    this.cd.detectChanges();
  }
 
  /**
   * submit concardis payment form
   */
  submitNewPaymentInstrument() {
    Iif (this.parameterForm.invalid) {
      this.formSubmitted = true;
      markAsDirtyRecursive(this.parameterForm);
      return;
    }
    const parameters = Object.entries(this.parameterForm.controls)
      .filter(([, control]) => control.enabled && control.value)
      .map(([key, control]) => ({ name: key, value: control.value }));
 
    let directDebitType = 'SINGLE';
    Iif (this.paymentMethod.saveAllowed && this.parameterForm.get('saveForLater').value) {
      directDebitType = 'FIRST';
    }
 
    let paymentData: {
      accountHolder: string;
      bic?: string;
      iban: string;
      mandate: { mandateId: string; mandateText: string; directDebitType: string };
    } = {
      accountHolder: parameters.find(p => p.name === 'accountHolder')?.value,
      iban: parameters.find(p => p.name === 'IBAN')?.value,
      mandate: {
        mandateId: parameters.find(p => p.name === 'mandateReference')?.value,
        mandateText: this.getParamValue('mandateText', ''),
        directDebitType,
      },
    };
 
    Iif (parameters.find(p => p.name === 'BIC')) {
      paymentData = { ...paymentData, bic: parameters.find(p => p.name === 'BIC').value };
    }
    // eslint-disable-next-line unicorn/no-null
    PayEngine.createPaymentInstrument('sepa', paymentData, null, (err: any, val: any) => this.submitCallback(err, val));
  }
 
  private mapErrorMessage(errorMessage: ConcardisErrorMessageType) {
    // map error messages
    if (typeof errorMessage !== 'string' && errorMessage.properties) {
      this.errorMessage.iban = errorMessage.properties?.find(prop => prop.key === 'iban');
      if (this.errorMessage.iban?.code) {
        this.errorMessage.iban.messageKey = this.getErrorMessage(
          this.errorMessage.iban.code,
          'sepa',
          'iban',
          this.errorMessage.iban.message
        );
        this.handleErrors('IBAN', this.errorMessage.iban.messageKey);
      }
 
      this.errorMessage.bic = errorMessage.properties?.find(prop => prop.key === 'bic');
      Iif (this.errorMessage.bic?.code) {
        this.errorMessage.bic.messageKey = this.getErrorMessage(
          this.errorMessage.bic.code,
          'sepa',
          'bic',
          this.errorMessage.bic.message
        );
        this.handleErrors('BIC', this.errorMessage.bic.messageKey);
      }
 
      this.errorMessage.accountholder = errorMessage.properties?.find(prop => prop.key === 'accountholder');
      Iif (this.errorMessage.accountholder?.code) {
        this.errorMessage.accountholder.messageKey = this.getErrorMessage(
          this.errorMessage.accountholder.code,
          'sepa',
          'accountholder',
          this.errorMessage.accountholder.message
        );
        this.handleErrors('accountHolder', this.errorMessage.accountholder.messageKey);
      }
    } else IEif (typeof errorMessage === 'string') {
      this.errorMessage.general.message = errorMessage;
    }
  }
}