import { Component, Input, OnInit, OnDestroy, OnChanges, SimpleChanges, NgZone, ViewChild, ElementRef, ChangeDetectorRef, AfterContentChecked } from '@angular/core'; import { Subscription, Observable, Subject } from 'rxjs'; import { debounceTime, takeUntil, take } from 'rxjs/operators'; import { WptDialog, WptDialogRef } from '@arrow/warpaint/dialog'; import { TranslateService } from '@ngx-translate/core'; import { BuyAllModalComponent } from '../buy-all-modal/buy-all-modal.component'; import { AddedDialogComponent, AddedDialogData } from '@arrow/bom/cart'; // TODO: BM-1019 try moving to cart2 or unifying (see buy-all-get-quote.component.ts) import { HooksService } from '@arrow/bom/hooks'; import { AddQuoteWarningComponent } from '../add-quote-warning/add-quote-warning.component'; import { Utils, ArrowService, DialogService, AnalyticsService, BomItemService, BomModel, BomService, UserService, SocketsService, BuyingOptionModel, ItemSelection, BomMessage, MessageBusService, BomQuantity, AnalyticsEvent, ApiSocketListenAction } from '@arrow/bom/core'; import { ConfigService } from '@arrow/bom/config'; import { LoggerService } from '@arrow/bom/logger'; import { Cart2Service, CartStatus } from '@arrow/bom/cart2'; import { AddCartWarningComponent } from '../add-cart-warning/add-cart-warning.component'; export interface Match { bo: BuyingOptionModel; mfrSeo: string; partSeo: string; } @Component({ selector: 'bom-buy-all-get-quote', templateUrl: 'buy-all-get-quote.component.html', styleUrls: ['buy-all-get-quote.component.scss'] }) export class BuyAllGetQuoteComponent implements OnInit, OnDestroy, OnChanges, AfterContentChecked { @Input() partsNumber: number; @Input() bomId: string; @Input() bom: BomModel; @Input() bomLoading: boolean; @Input() hasCartLimit: boolean; private _analyticData$: Observable; subscriptions: Array = []; loading: boolean = false; email: string = null; cartStatus: CartStatus; cartLoading: boolean = true; cartLimit: number = 150; quoteCartCount: any; isPartialSelection: boolean = false; isAnyPartPurchasable: boolean = true; selectionInverted: boolean = false; available = true; totals: any; isMyArrow = false; totalParts: number = 0; private updateCartStatusSubject$: Subject = new Subject(); private debounceCartStatusUpdate: number = 1500; @ViewChild('availableTotal') availableTotalEl: ElementRef; @ViewChild('requestedTotal') requestedTotalEl: ElementRef; // Selection stuff private _purchasablePartsIds: string[] = []; private _selectedParts: string[] = []; private _purchasableParts: any[] = []; private _analyticsData: any; private _killSig$$ = new Subject(); // Kill signal for observables constructor( private _messageBus: MessageBusService, private _utils: Utils, private _analyticsService: AnalyticsService, private _arrowService: ArrowService, private _bomItemService: BomItemService, private _dialogService: DialogService, private _bomService: BomService, private _loggerService: LoggerService, private _wptDialog: WptDialog, private _hooks: HooksService, private _translate: TranslateService, private _sockets: SocketsService, private _cart2: Cart2Service, private _zone: NgZone, private userService: UserService, private configService: ConfigService, private changeDetector: ChangeDetectorRef, ) { this._analyticData$ = _sockets.observeAction(ApiSocketListenAction.ADD_TO_CART_METRICS); } ngOnInit() { this.isMyArrow = this.configService.getTarget() === 'myarrow'; this.cartStatus = new CartStatus(); this.updateCartStatusSubject$ .pipe(debounceTime(this.debounceCartStatusUpdate)) .pipe(takeUntil(this._killSig$$)) .subscribe(x => { this._updateCartStatus(this.bomId); }); this._messageBus .from('ch:cart') .pipe(takeUntil(this._killSig$$)) .subscribe((message: BomMessage) => (this.cartLoading = message.payload)); this._bomItemService.selectionChanged$ .pipe(takeUntil(this._killSig$$)) .subscribe((selection: ItemSelection) => { this._selectedParts = selection.rowIds; this.isPartialSelection = this._bomItemService.isPartialSelection( this.bom.parts ); this.selectionInverted = selection.selectionInverted; this.isAnyPartPurchasable = this._hasPurchasableParts( this.isPartialSelection ); }); this._bomItemService.selectAllToggle$ .pipe(takeUntil(this._killSig$$)) .subscribe(selection => { if (selection) { this._selectedParts = this._purchasablePartsIds.slice(0); // clone array } else { this._selectedParts = []; } }); this._sockets .observeAction(ApiSocketListenAction.BOM_TOTALS) .pipe(takeUntil(this._killSig$$)) .subscribe((data: any) => { this._zone.run(() => { this.totals = data; }) }); this._bomService.bomActiveQty.subscribe( data => { this.updateBomActiveQtyName(data); }, err => { console.log(err); } ); } private updateBomActiveQtyName(qtyColumnData: BomQuantity) { this.bom.activeQuantity = qtyColumnData.name; } ngOnChanges(changes: SimpleChanges) { if (changes['bomLoading']) { this.bom.progress = 0; } if (changes['partsNumber'] && !changes['partsNumber'].firstChange) { this.updateCartStatusSubject$.next(); } } ngAfterContentChecked(): void { this.changeDetector.detectChanges(); } ngOnDestroy() { this._killSig$$.next(); this._killSig$$.complete(); } /** * Cart url * @returns correct cart url */ private _getViewCartUrl() { const viewCartUrl = this._arrowService.uikit && this._arrowService.uikit.config.cart.cart ? this._arrowService.uikit.config.cart.cart : `${this.configService.getRoute('cart')}`; return viewCartUrl; } /** * @param partsData * @return purchasable parts */ private _setPurchasableParts(partsData: any) { const purchasableRowIds = partsData.rowIds; this._purchasablePartsIds = purchasableRowIds.slice(); this._purchasableParts = partsData.rowIds.map( (rowId: string, index: number) => { return { rowIds: rowId, sourcePartId: partsData.sourcePartIds[index], quantity: partsData.quantities[index], region: partsData.regions[index] }; } ); this.isAnyPartPurchasable = this._hasPurchasableParts( this.isPartialSelection ); } private _hasPurchasableParts(isPartialSelection: boolean): boolean { const arePurchasablePartsInBom = this._purchasablePartsIds.length > 0; if (isPartialSelection) { return ( arePurchasablePartsInBom && this._purchasablePartsIds.reduce((acc: boolean, rowId: string) => { return ( !!this._bomItemService .getSelection() .rowIds.find(id => id === rowId) || acc ); }, false) ); } else { return arePurchasablePartsInBom; } } // /** // * After request to api has returned dislpays a success/error message modal. // * @param data - data object returned from the api. // */ private _onQuoteRequestApiResponse(data: any): void { this._messageBus.to('ch:loader', { payload: false }); let message = ''; if (data.payload) { message = this._translate.instant( 'Your-quote-will-be-sent-to-the-provided-email-address.' ); } else { message = this._translate.instant( 'Unable-to-send-quote-to-the-provided-email-address.' ); } this._dialogService.alert( this._translate.instant('Request-Quote'), message ); } // /** // * Shows the buy-all confirmation modal // * @param data - data object returned from the api. // */ private _showBuyAllConfirmationModal(data: any) { const ref: WptDialogRef = this._wptDialog.open( BuyAllModalComponent, { data: data, position: { top: '10px', right: '15px' } } ); ref.beforeClosed().subscribe((response: any) => { if (response) window.open( this.configService.arrowUrl + this._getViewCartUrl(), '_blank' ); }); } /** * Shows the request quote modal * @param target - origin target * @param totalParts */ private _openRequestQuoteModal(target: string) { const selectedPartsLength = this._selectedParts.length; let requestedCount = this.isPartialSelection && selectedPartsLength ? selectedPartsLength : this.totals.rowCount; if (target === 'myarrow') { this.subscriptions.push( this._cart2.requestQuoteCount().subscribe((data: any) => { this.quoteCartCount = data; if ( requestedCount <= this.quoteCartCount.remainingLineItems && this.quoteCartCount.lineItemCount <= this.quoteCartCount.maxLineItems ) { this.loading = true; this._submitQuoteRequestMyArrow(this.bom, this.bomId); } else { this._analyticsService.googleTrackEvent(AnalyticsEvent.CLICK, { category: 'BOM', action: 'LimitHit', label: 1, value: 1 }); this._wptDialog.open(AddQuoteWarningComponent, { data: this.quoteCartCount, maxWidth: 420 }); } }) ); return; } this._dialogService .prompt( this._translate.instant('Request-Quote'), this._translate.instant('Email-the-quote-to:'), `${this.email}`, this._translate.instant('Enter-email') ) .subscribe((value: string | boolean) => { if (typeof value !== 'string') return; this._messageBus.to('ch:loader', { payload: true }); if (this.bomId && value && this._utils.isValidEmail(value)) { this._analyticsService .track('sendQuote', { email: value }) .subscribe(); this._makeQuoteRequestArrow(this.bomId, value); } else { this._messageBus.to('ch:loader', { payload: false }); // TODO tech debt | handle invalid email better. Prevent // submitting quote request until email is deemed valid // Tickets: ARW-17849 and ARW-17850 this._dialogService .alert( this._translate.instant('Invalid-Email'), this._translate.instant( 'Quote-not-sent.-Please-enter-a-valid-email.' ) ) .subscribe(() => { this._openRequestQuoteModal(target); }); } }); } /** * track analytics events for quote * @param analyticsData * @param bom */ private _trackQuoteAnalytics(analyticsData: any, bom: BomModel): void { if (!analyticsData) return; const selection = this._bomItemService.getSelection(); let analyticsEvent = 'Quote All'; if (!!selection.rowIds.length && selection.rowIds.length !== bom.parts) analyticsEvent = 'Quote Selected'; const missedStock = analyticsData.PotentialPartPrice > 0 ? analyticsData.PotentialPartPrice - analyticsData.AvailablePartPrice : '0'; this._analyticsService.googleTrackEvent(AnalyticsEvent.CLICK, { category: 'BOM', action: analyticsEvent, label: analyticsData.NumberOfLinesAdded ? analyticsData.NumberOfLinesAdded : '0', value: analyticsData.NumberOfLinesAdded ? analyticsData.NumberOfLinesAdded : '0', bomAvailablePartPrice: analyticsData.AvailablePartPrice ? analyticsData.AvailablePartPrice : '0', bomPotentialPartPrice: analyticsData.PotentialPartPrice ? analyticsData.PotentialPartPrice : '0', bomMissedStock: analyticsData ? missedStock : '0', bomNumberNonpurchaseableItemsAttempted: analyticsData.NonPurchasableCount ? analyticsData.NonPurchasableCount : '0' }); } /** * quote bom for my arrow * @param bom * @param bomId */ private _submitQuoteRequestMyArrow(bom: BomModel, bomId: string) { this._analyticData$.pipe(take(1)).subscribe(analyticsData => { return (this._analyticsData = analyticsData); }); const selection = this._bomItemService.getSelection(); // sending invalid string for email, since it's not used for 'myarrow' and empty string trips the API this._bomService.requestQuote(bomId, 'none', selection).subscribe( response => { this.loading = false; const payload = response.payload; // TODO: Review hooks after this [ticket] is done // const afterAddToQuoteCb = this.hooks['afterAddToQuote']; // if(afterAddToQuoteCb && typeof afterAddToQuoteCb === 'function') afterAddToQuoteCb(); if (payload && payload.itemsAddedCount) this._hooks.refresh(); this._trackQuoteAnalytics(this._analyticsData, bom); return this._wptDialog.open(AddedDialogComponent, { data: { quoteOnlyMode: true, addedToCartCount: 0, addedToQuoteCount: payload ? payload.itemsAddedCount : 0, notAddedCount: 0 } }); }, error => { this.loading = false; this._dialogService.alert( this._translate.instant( 'An-error-has-occurred-while-requesting-quote' ), error ); } ); } private _makeQuoteRequestArrow(bomId: string, email: string): void { if (bomId && email) { const selection: ItemSelection = this._bomItemService.getSelection(); this._bomService.requestQuote(bomId, email, selection).subscribe( response => { this._onQuoteRequestApiResponse(response); if (!this._bomItemService.isPartialSelection(this.bom.parts)) { this._analyticsService.googleTrackEvent(AnalyticsEvent.CLICK, { category: 'BOM', action: 'quoteAll', label: this.bom.parts, value: this.bom.parts }); } else { const partCount = selection.selectionInverted ? this.bom.parts - selection.rowIds.length : selection.rowIds.length; this._analyticsService.googleTrackEvent(AnalyticsEvent.CLICK, { category: 'BOM', action: 'quoteSelected', label: partCount, value: partCount }); } }, error => { this._onQuoteRequestApiResponse({}); this._dialogService.alert('An error has occurred', error); } ); } } /** * Updates the cart status * @param bomId */ private _updateCartStatus(bomId: string) { const selection = this._bomItemService.getSelection(); this._cart2.getPurchasablePartsList(bomId, selection).subscribe( (data: any) => { this._messageBus.to('ch:cart', { payload: false }); if ( data && data.status && data.status.statusCode === 200 && data.payload && data.payload.rowIds ) { this.cartStatus.cartInfo = data.payload; this._setPurchasableParts(data.payload); } else { if (data && data.status && data.status.statusCode === 401) { this._dialogService.alert(null, data.status.statusMsg); this._loggerService.warn(data.status.statusMsg); } else { this._loggerService.warn( '"/checkout" call returned a non-200 error | data: ' + JSON.stringify(data) ); } return; } }, () => { this.cartLoading = false; } ); } /** * Buy all button click handler. * @param isPartialSelection * @param bomId * @param bom */ onBuyClick(isPartialSelection: boolean, bomId: string, bom: BomModel) { let analyticsEvent = 'Buy Selected'; const selection = this._bomItemService.getSelection(); if (!isPartialSelection) { analyticsEvent = 'Buy All'; } // check if there is any cart limit if (this.hasCartLimit && this.isMyArrow) { let partsToCart; // get number of items that user want to sent to cart if (selection.selectionInverted) { partsToCart = bom.parts - selection.rowIds.length; } else { partsToCart = selection.rowIds.length === 0 ? bom.parts : selection.rowIds.length; } // get cart limit for myarrow this._cart2.requestCartCountMyArrow().subscribe(cartCount => { if (partsToCart <= cartCount.remainingLineItems) { this.cartLoading = true; this._cart2 .add(bomId, selection, bom.parts, analyticsEvent) .subscribe(() => (this.cartLoading = false)); } else { //display shopping cart warning dialog this._wptDialog.open(AddCartWarningComponent, { data: cartCount.lineItemMax, maxWidth: 420 }); this.cartLoading = false; this._analyticsService.googleTrackEvent(AnalyticsEvent.CLICK, { category: 'BOM', action: 'ShoppingCartLimitHit', label: 1, value: 1 }); } }); } else { this.cartLoading = true; this._cart2 .add(bomId, selection, bom.parts, analyticsEvent) .subscribe(() => (this.cartLoading = false)); } } // ▼ ▼ ▼ Public Methods ▼ ▼ ▼ /** * Gets user info to check for the default email and opens a modal */ onClickRequestQuote() { if (this.userService.isAnonymous) return; this.email = this.userService.email || ''; this._openRequestQuoteModal(this.configService.getTarget()); return false; } changeTotal(available) { this.available = available; this._analyticsService.googleTrackEvent(AnalyticsEvent.CLICK, { category: 'BOM', action: 'Total', label: available ? 'Available' : 'Requested' }); } setRequestedTotalAriaLabel(available) { if (!available){ return 'Requested total, ' + this.requestedTotalEl?.nativeElement?.innerText } return 'Requested total' } setAvailableTotalAriaLabel(available) { if (available){ return 'Available total, ' + this.availableTotalEl?.nativeElement?.innerText } return 'Available total' } }