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

68.25% Statements 43/63
44.44% Branches 16/36
66.66% Functions 12/18
66.66% Lines 40/60

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 1672x 2x 2x   2x 2x   2x 2x 2x   2x 2x 2x                   2x   7x   7x       7x 7x 5x             7x     7x   7x     7x 7x 7x 7x       7x   7x     5x           5x     7x   20x     7x   7x                     2x     1x             7x                         7x     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';
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 invoice address in the checkout.
 */
@Component({
  selector: 'ish-basket-invoice-address-widget',
  templateUrl: './basket-invoice-address-widget.component.html',
  changeDetection: ChangeDetectionStrategy.Default,
})
export class BasketInvoiceAddressWidgetComponent 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 = {};
    }
  }
  invoiceAddress$: Observable<Address>;
  addresses$: Observable<Address[]>;
  isLoggedIn$: Observable<boolean>;
 
  form = new UntypedFormGroup({});
  fields: FormlyFieldConfig[];
  editAddress: Partial<Address>;
  private emptyOptionLabel = 'checkout.addresses.select_invoice_address.button';
 
  private destroyRef = inject(DestroyRef);
 
  constructor(
    private checkoutFacade: CheckoutFacade,
    private accountFacade: AccountFacade,
    private featureToggleService: FeatureToggleService,
    private featureEventService: FeatureEventService
  ) {}
 
  ngOnInit() {
    this.invoiceAddress$ = this.checkoutFacade.basketInvoiceAddress$;
 
    this.invoiceAddress$
      .pipe(
        map(address =>
          address
            ? 'checkout.addresses.select_a_different_invoice_address.default'
            : 'checkout.addresses.select_invoice_address.button'
        ),
        takeUntilDestroyed(this.destroyRef)
      )
      .subscribe(label => (this.emptyOptionLabel = label));
 
    // prepare data for invoice select drop down
    this.addresses$ = combineLatest([this.eligibleAddresses$, this.invoiceAddress$]).pipe(
      map(([addresses, invoiceAddress]) =>
        addresses?.filter(address => address.invoiceToAddress).filter(address => address.id !== invoiceAddress?.id)
      )
    );
    this.isLoggedIn$ = this.accountFacade.isLoggedIn$;
 
    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, 'invoice'));
          },
        },
      },
    ];
 
    // preassign an invoice address if the user has only one invoice 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.invoiceToAddress && addresses.length === 1) {
          this.checkoutFacade.assignBasketAddress(addresses[0].id, 'invoice');
        }
      });
 
    this.invoiceAddress$.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, 'invoice');
            }
          });
      } else {
        this.checkoutFacade.createBasketAddress(address, 'invoice');
      }
      (this.form.get('id') as UntypedFormControl).setValue('', { emitEvent: false });
    }
  }
 
  cancelEditAddress() {
    this.collapse = true;
  }
}