All files / src/app/shared/formly-address-forms/components/formly-address-form formly-address-form.component.ts

69.76% Statements 30/43
61.53% Branches 8/13
45.45% Functions 5/11
70.73% Lines 29/41

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 1503x 3x     3x   3x     3x                                             3x           4x             4x       4x     4x           4x 4x                 1x 1x   1x 1x     1x     1x       1x       1x 1x 1x 1x     1x         5x                                               4x 4x 4x       4x                                            
import { ChangeDetectionStrategy, Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { FormlyFieldConfig, FormlyFormOptions } from '@ngx-formly/core';
import { Observable } from 'rxjs';
import { filter, map, shareReplay, tap } from 'rxjs/operators';
 
import { AppFacade } from 'ish-core/facades/app.facade';
import { Address } from 'ish-core/models/address/address.model';
import { SelectOption } from 'ish-core/models/select-option/select-option.model';
import { AddressFormConfigurationProvider } from 'ish-shared/formly-address-forms/configurations/address-form-configuration.provider';
 
/**
 * Address Form Component that reconfigures itself when a new country is selected.
 * Gets field configurations from the `AddressFormConfigurationProvider`.
 *
 * @param parentForm - the parent FormGroup that the address form will belong to
 * @param businessCustomer - whether the address form is for a business customer
 * @param shortForm - whether the address form is in long or short format
 * @param prefilledAddress - a collection of key-value pairs that will be used to prefill the form
 *
 * @example
 * <ish-formly-address-form
      [businessCustomer]="isBusinessCustomer$ | async"
      [shortForm]="true"
      [parentForm]="formGroup"
   ></ish-formly-address-form>
 */
@Component({
  selector: 'ish-formly-address-form',
  templateUrl: './formly-address-form.component.html',
  changeDetection: ChangeDetectionStrategy.Default,
})
export class FormlyAddressFormComponent implements OnInit, OnChanges {
  @Input({ required: true }) parentForm: FormGroup;
  @Input() businessCustomer: boolean;
  @Input() shortForm: boolean;
  @Input() prefilledAddress: Partial<Address>;
 
  private countryCode = '';
 
  private countries$: Observable<SelectOption[]>;
 
  addressForm: FormGroup;
  addressModel: { [key: string]: unknown; countryCode: string };
  addressFields: FormlyFieldConfig[];
  addressOptions: FormlyFormOptions = {
    formState: {},
  };
 
  constructor(private appFacade: AppFacade, private afcProvider: AddressFormConfigurationProvider) {}
 
  ngOnInit(): void {
    this.countries$ = this.appFacade.countries$()?.pipe(
      filter(countries => !!countries?.length),
      map(countries => countries?.map(country => ({ value: country.countryCode, label: country.name }))),
      tap(() => this.fillForm(this.prefilledAddress)),
      shareReplay(1)
    );
    this.initForm();
    this.parentForm?.setControl('address', this.addressForm);
  }
 
  ngOnChanges(c: SimpleChanges) {
    this.fillForm(c.prefilledAddress?.currentValue);
  }
 
  handleCountryChange(model: { countryCode: string }) {
    // extract old and new countryCode
    const prevCountryCode = this.countryCode;
    this.countryCode = model.countryCode;
 
    if (model.countryCode !== prevCountryCode) {
      const configuration = this.afcProvider.getConfiguration(model.countryCode, this.businessCustomer, this.shortForm);
 
      // assign new form, model and fields
      this.addressForm = new FormGroup({
        countryCode: new FormControl(''),
      });
      this.addressModel = {
        countryCode: model.countryCode,
        ...configuration.getModel(this.addressModel),
      };
      this.addressFields = [this.createCountrySelectField()].concat(
        configuration.getFieldConfiguration(model.countryCode)
      );
 
      this.addressModel.countryCode = model.countryCode;
      this.addressForm.updateValueAndValidity();
      if (model.countryCode) {
        this.addressForm.get('countryCode').markAsDirty();
      }
 
      this.parentForm?.setControl('address', this.addressForm);
    }
  }
 
  private createCountrySelectField(): FormlyFieldConfig {
    return {
      type: 'ish-fieldset-field',
      fieldGroup: [
        {
          key: 'countryCode',
          type: 'ish-select-field',
          props: {
            required: true,
            label: 'account.address.country.label',
            forceRequiredStar: true,
            placeholder: 'account.option.select.text',
            options: this.countries$,
          },
          validation: {
            messages: {
              required: 'account.address.country.error.default',
            },
          },
        },
      ],
    };
  }
 
  private initForm() {
    const configuration = this.afcProvider.getConfiguration('default', this.businessCustomer, this.shortForm);
    this.addressForm = new FormGroup({});
    this.addressModel = {
      countryCode: '',
      ...configuration.getModel(),
    };
    this.addressFields = [this.createCountrySelectField()].concat(configuration.getFieldConfiguration());
  }
 
  private fillForm(prefilledAddress: Partial<Address> = {}) {
    Iif (!this.addressForm) {
      return;
    }
    Iif (Object.keys(prefilledAddress).length === 0) {
      this.addressModel = {
        countryCode: '',
      };
    }
 
    this.addressModel.countryCode = prefilledAddress.countryCode;
    this.handleCountryChange(this.addressModel);
    this.addressModel = {
      countryCode: this.addressModel.countryCode,
      ...prefilledAddress,
    };
    this.addressForm.updateValueAndValidity();
  }
}