File

feature-libs/cart/quick-order/components/cart-quick-order-form/cart-quick-order-form.component.ts

Implements

OnInit OnDestroy

Metadata

changeDetection ChangeDetectionStrategy.OnPush
selector cx-cart-quick-order-form
templateUrl ./cart-quick-order-form.component.html

Index

Properties
Methods

Constructor

constructor(activeCartService: ActiveCartService, eventService: EventService, formBuilder: FormBuilder, globalMessageService: GlobalMessageService)
Parameters :
Name Type Optional
activeCartService ActiveCartService No
eventService EventService No
formBuilder FormBuilder No
globalMessageService GlobalMessageService No

Methods

applyQuickOrder
applyQuickOrder()
Returns : void
Protected buildForm
buildForm()
Returns : void
Protected getValidCount
getValidCount(value: number)
Parameters :
Name Type Optional
value number No
Returns : number
ngOnDestroy
ngOnDestroy()
Returns : void
ngOnInit
ngOnInit()
Returns : void
Protected resetForm
resetForm()
Returns : void
Protected watchAddEntryFailEvent
watchAddEntryFailEvent()
Returns : void
Protected watchAddEntrySuccessEvent
watchAddEntrySuccessEvent()
Returns : void
Protected watchQuantityChange
watchQuantityChange()
Returns : void

Properties

cart$
Type : Observable<Cart>
Default value : this.activeCartService.getActive()
Protected cartEventsSubscription
Type : Subscription
Default value : new Subscription()
cartIsLoading$
Type : Observable<boolean>
Default value : this.activeCartService .isStable() .pipe(map((loaded) => !loaded))
min
Type : number
Default value : 1
Protected minQuantityValue
Type : number
Default value : 1
quickOrderForm
Type : FormGroup
Protected subscription
Type : Subscription
Default value : new Subscription()
import {
  ChangeDetectionStrategy,
  Component,
  OnDestroy,
  OnInit,
} from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import {
  ActiveCartService,
  Cart,
  CartAddEntryFailEvent,
  CartAddEntrySuccessEvent,
  EventService,
  GlobalMessageService,
  GlobalMessageType,
} from '@spartacus/core';
import { Observable, Subscription } from 'rxjs';
import { first, map } from 'rxjs/operators';

@Component({
  selector: 'cx-cart-quick-order-form',
  templateUrl: './cart-quick-order-form.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CartQuickOrderFormComponent implements OnInit, OnDestroy {
  quickOrderForm: FormGroup;
  cartIsLoading$: Observable<boolean> = this.activeCartService
    .isStable()
    .pipe(map((loaded) => !loaded));
  cart$: Observable<Cart> = this.activeCartService.getActive();
  min = 1;

  protected subscription: Subscription = new Subscription();
  protected cartEventsSubscription: Subscription = new Subscription();
  protected minQuantityValue: number = 1;

  constructor(
    protected activeCartService: ActiveCartService,
    protected eventService: EventService,
    protected formBuilder: FormBuilder,
    protected globalMessageService: GlobalMessageService
  ) {}

  ngOnInit(): void {
    this.buildForm();
    this.watchQuantityChange();
  }

  ngOnDestroy(): void {
    this.subscription?.unsubscribe();
    this.cartEventsSubscription?.unsubscribe();
  }

  applyQuickOrder(): void {
    if (this.quickOrderForm.invalid) {
      this.quickOrderForm.markAllAsTouched();
      return;
    }

    const productCode = this.quickOrderForm.get('productCode')?.value;
    const quantity = this.quickOrderForm.get('quantity')?.value;

    this.watchAddEntrySuccessEvent();
    this.watchAddEntryFailEvent();

    if (productCode && quantity) {
      this.activeCartService.addEntry(productCode, quantity);
    }
  }

  protected buildForm(): void {
    this.quickOrderForm = this.formBuilder.group({
      productCode: ['', [Validators.required]],
      quantity: [
        this.minQuantityValue,
        { updateOn: 'blur', validators: [Validators.required] },
      ],
    });
  }

  protected watchQuantityChange(): void {
    this.subscription.add(
      this.quickOrderForm
        .get('quantity')
        ?.valueChanges.subscribe((value) =>
          this.quickOrderForm
            .get('quantity')
            ?.setValue(this.getValidCount(value), { emitEvent: false })
        )
    );
  }

  protected watchAddEntrySuccessEvent(): void {
    this.cartEventsSubscription.add(
      this.eventService
        .get(CartAddEntrySuccessEvent)
        .pipe(first())
        .subscribe((data: CartAddEntrySuccessEvent) => {
          let key = 'quickOrderCartForm.stockLevelReached';
          let productTranslation;
          let messageType = GlobalMessageType.MSG_TYPE_WARNING;

          if (data.quantityAdded) {
            key =
              data.quantityAdded > 1
                ? 'quickOrderCartForm.entriesWereAdded'
                : 'quickOrderCartForm.entryWasAdded';

            productTranslation =
              data.quantityAdded > 1
                ? 'quickOrderCartForm.products'
                : 'quickOrderCartForm.product';

            messageType = GlobalMessageType.MSG_TYPE_CONFIRMATION;
          }

          this.globalMessageService.add(
            {
              key,
              params: {
                product: data?.entry?.product?.name || productTranslation,
                quantity: data.quantityAdded,
              },
            },
            messageType
          );
          this.resetForm();
        })
    );
  }

  protected watchAddEntryFailEvent(): void {
    this.cartEventsSubscription.add(
      this.eventService
        .get(CartAddEntryFailEvent)
        .pipe(first())
        .subscribe(() => {
          this.globalMessageService.add(
            {
              key: 'quickOrderCartForm.noResults',
            },
            GlobalMessageType.MSG_TYPE_ERROR
          );
        })
    );
  }

  protected getValidCount(value: number) {
    if (value < this.min || !value) {
      value = this.min;
    }

    return value;
  }

  protected resetForm(): void {
    this.quickOrderForm.reset();
  }
}
<ng-container *ngIf="cart$ | async as cart">
  <div class="cx-cart-quick-order-form-title">
    {{ 'quickOrderCartForm.title' | cxTranslate }}
  </div>
  <div class="form-group">
    <form (ngSubmit)="applyQuickOrder()" [formGroup]="quickOrderForm">
      <div class="cx-cart-quick-order-form-container">
        <span class="cx-cart-quick-order-form-productID">
          <label class="cx-cart-quick-order-form-label">
            {{ 'quickOrderCartForm.productCodeLabel' | cxTranslate }}
          </label>
          <input
            aria-required="true"
            class="form-control input-product-code"
            formControlName="productCode"
            placeholder="{{
              'quickOrderCartForm.productCodePlaceholder' | cxTranslate
            }}"
            type="text"
          />
        </span>

        <span class="cx-cart-quick-order-form-qty">
          <label class="cx-cart-quick-order-form-label">
            {{ 'quickOrderCartForm.quantityLabel' | cxTranslate }}
          </label>
          <input
            aria-required="true"
            class="form-control input-quantity"
            formControlName="quantity"
            type="number"
          />
        </span>
        <button
          [class.disabled]="cartIsLoading$ | async"
          [disabled]="cartIsLoading$ | async"
          class="btn btn-block btn-action apply-quick-order-button"
          type="submit"
        >
          {{ 'quickOrderCartForm.addToCart' | cxTranslate }}
        </button>
        <cx-form-errors
          aria-live="assertive"
          aria-atomic="true"
          [control]="quickOrderForm.get('productCode')"
        ></cx-form-errors>
        <cx-form-errors
          aria-live="assertive"
          aria-atomic="true"
          [control]="quickOrderForm.get('quantity')"
        ></cx-form-errors>
      </div>
    </form></div
></ng-container>
Legend
Html element
Component
Html element with directive

result-matching ""

    No results matching ""