All files / src/app/shared/components/checkout/basket-shipping-address-widget basket-shipping-address-widget.component.ts

69.11% Statements 47/68
48.71% Branches 19/39
65% Functions 13/20
67.69% Lines 44/65

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 1862x 2x 2x   2x 2x   2x 2x 2x   2x 2x 2x                   2x   9x   9x       8x 8x 6x                     9x     9x   9x     9x 9x 9x 9x   9x           9x 9x 9x   9x     6x           6x     9x   36x       9x       11x   9x                     6x     1x             9x                         9x     2x 1x   1x   2x                                                                                                        
import { ChangeDetectionStrategy, Component, DestroyRef, Input, OnInit, Output, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { UntypedFormControl, UntypedFormGroup } from '@angular/forms';
import { FormlyFieldConfig } from '@ngx-formly/core/lib/core';
import { BehaviorSubject, Observable, combineLatest } from 'rxjs';
import { filter, map, take } from 'rxjs/operators';
 
import { AccountFacade } from 'ish-core/facades/account.facade';
import { CheckoutFacade } from 'ish-core/facades/checkout.facade';
import { FeatureToggleService } from 'ish-core/feature-toggle.module';
import { Address } from 'ish-core/models/address/address.model';
import { FeatureEventService } from 'ish-core/utils/feature-event/feature-event.service';
import { whenTruthy } from 'ish-core/utils/operators';
import { FormsService } from 'ish-shared/forms/utils/forms.service';
 
/**
 * Standalone widget component for selecting and setting the basket shipping address in the checkout.
 */
@Component({
  selector: 'ish-basket-shipping-address-widget',
  templateUrl: './basket-shipping-address-widget.component.html',
  changeDetection: ChangeDetectionStrategy.Default,
})
export class BasketShippingAddressWidgetComponent implements OnInit {
  @Input({ required: true }) eligibleAddresses$: Observable<Address[]>;
  @Input() showErrors = true;
 
  @Output() collapseChange = new BehaviorSubject(true);
 
  @Input()
  set collapse(value: boolean) {
    this.collapseChange.next(value);
    if (value) {
      this.editAddress = {};
    }
  }
 
  shippingAddress$: Observable<Address>;
  addresses$: Observable<Address[]>;
  displayAddAddressLink$: Observable<boolean>;
 
  basketInvoiceAndShippingAddressEqual$: Observable<boolean>;
  basketShippingAddressDeletable$: Observable<boolean>;
 
  form = new UntypedFormGroup({});
  fields: FormlyFieldConfig[];
  editAddress: Partial<Address>;
  private emptyOptionLabel = 'checkout.addresses.select_shipping_address.button';
 
  private destroyRef = inject(DestroyRef);
 
  constructor(
    private accountFacade: AccountFacade,
    private checkoutFacade: CheckoutFacade,
    private featureToggleService: FeatureToggleService,
    private featureEventService: FeatureEventService
  ) {
    this.form = new UntypedFormGroup({
      id: new UntypedFormControl(''),
    });
  }
 
  ngOnInit() {
    this.shippingAddress$ = this.checkoutFacade.basketShippingAddress$;
    this.basketInvoiceAndShippingAddressEqual$ = this.checkoutFacade.basketInvoiceAndShippingAddressEqual$;
    this.basketShippingAddressDeletable$ = this.checkoutFacade.basketShippingAddressDeletable$;
 
    this.shippingAddress$
      .pipe(
        map(address =>
          address
            ? 'checkout.addresses.select_a_different_shipping_address.default'
            : 'checkout.addresses.select_shipping_address.button'
        ),
        takeUntilDestroyed(this.destroyRef)
      )
      .subscribe(label => (this.emptyOptionLabel = label));
 
    // prepare data for shipping select drop down
    this.addresses$ = combineLatest([this.eligibleAddresses$, this.shippingAddress$]).pipe(
      map(([addresses, shippingAddress]) =>
        addresses?.filter(address => address.shipToAddress).filter(address => address.id !== shippingAddress?.id)
      )
    );
 
    this.displayAddAddressLink$ = combineLatest([
      this.collapseChange,
      this.accountFacade.isLoggedIn$,
      this.basketInvoiceAndShippingAddressEqual$,
    ]).pipe(map(([collapseChange, loggedIn, addressesEqual]) => collapseChange && (loggedIn || addressesEqual)));
 
    this.fields = [
      {
        key: 'id',
        type: 'ish-select-field',
        props: {
          fieldClass: 'col-12',
          options: FormsService.getAddressOptions(this.addresses$),
          placeholder: this.emptyOptionLabel,
        },
        hooks: {
          onInit: field => {
            field.form
              .get('id')
              .valueChanges.pipe(whenTruthy(), takeUntilDestroyed(this.destroyRef))
              .subscribe(addressId => this.checkoutFacade.assignBasketAddress(addressId, 'shipping'));
          },
        },
      },
    ];
 
    // preassign a shipping address if the user has only one shipping address
    combineLatest([this.addresses$, this.checkoutFacade.basket$])
      .pipe(
        // prevent assigning the address at an anonymous basket after login
        filter(([addresses, basket]) => !!basket?.customerNo && !!addresses?.length),
        take(1),
        takeUntilDestroyed(this.destroyRef)
      )
      .subscribe(([addresses, basket]) => {
        Iif (!basket.commonShipToAddress && addresses.length === 1) {
          this.checkoutFacade.assignBasketAddress(addresses[0].id, 'shipping');
        }
      });
 
    this.shippingAddress$.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => (this.collapse = true));
  }
  showAddressForm(address?: Address) {
    if (address) {
      this.editAddress = { ...address };
    } else {
      this.editAddress = {};
    }
    this.collapse = false;
  }
 
  saveAddress(address: Address) {
    if (this.editAddress && Object.keys(this.editAddress).length > 0) {
      if (this.featureToggleService.enabled('addressDoctor')) {
        const id = this.featureEventService.sendNotification('addressDoctor', 'check-address', {
          address,
        });
 
        this.featureEventService
          .eventResultListener$('addressDoctor', 'check-address', id)
          .pipe(whenTruthy(), take(1), takeUntilDestroyed(this.destroyRef))
          .subscribe(({ data }) => {
            Iif (data) {
              this.checkoutFacade.updateBasketAddress(data);
              this.collapse = true;
            }
          });
      } else {
        this.checkoutFacade.updateBasketAddress(address);
        this.collapse = true;
      }
    } else {
      if (this.featureToggleService.enabled('addressDoctor')) {
        const id = this.featureEventService.sendNotification('addressDoctor', 'check-address', {
          address,
        });
 
        this.featureEventService
          .eventResultListener$('addressDoctor', 'check-address', id)
          .pipe(whenTruthy(), take(1), takeUntilDestroyed(this.destroyRef))
          .subscribe(({ data }) => {
            Iif (data) {
              this.checkoutFacade.createBasketAddress(data, 'shipping');
            }
          });
      } else {
        this.checkoutFacade.createBasketAddress(address, 'shipping');
      }
      (this.form.get('id') as UntypedFormControl).setValue('', { emitEvent: false });
    }
  }
 
  cancelEditAddress() {
    this.collapse = true;
  }
 
  deleteAddress(address: Address) {
    this.checkoutFacade.deleteBasketAddress(address.id);
  }
}