import { Component, OnInit, Renderer2, ViewChild, ElementRef, OnDestroy } from '@angular/core'; // import { ROUTES } from '../..//home/sidebar/sidebar.component'; import { Router, ActivatedRoute } from '@angular/router'; import { Location, LocationStrategy, PathLocationStrategy } from '@angular/common'; import { OktaAuthService } from '@okta/okta-angular'; import Utils from '../../shared/utils'; import * as Constants from '../../shared/constants'; import { environment } from '../../../environments/environment'; // service declaration import { SharedService } from '../../shared/shared.service'; import { UserService } from '../../services/user.service'; import { CartService } from '../../services/cart.service'; // modal declaration import { IWCToken, INotification } from '../../shared/modal/common'; import { Logon, User } from '../../shared/modal/user'; declare var $: any; @Component({ moduleId: module.id, selector: 'navbar-cmp', templateUrl: './navbar.component.html', styleUrls: ['./navbar.component.css'] }) export class NavbarComponent implements OnInit, OnDestroy { private COMPONENT_NAME: string = 'NavbarComponent'; karmaTestResult: any = {}; rtStoreId: number = Constants.STORE_ID_RT; private listTitles: any[]; location: Location; private nativeElement: Node; private toggleButton; private sidebarVisible: boolean; @ViewChild('navbar-cmp') button; // my declaration errorMessage: string; user: User; unReadNotificationCount: number; showSalesStats: boolean = false; showAccountInfo: boolean = false; showStoreInfo: boolean = false; showChannels: boolean = false; todayDate = new Date(); storeItems: any[]; showSettings: boolean = false; storeId: number; // updating storeid wcToken: IWCToken; userId: number; window: any; constructor(location: Location, private renderer: Renderer2, private element: ElementRef, private route: ActivatedRoute, public router: Router, public oktaAuth: OktaAuthService, public sharedService: SharedService, public userService: UserService, private cartService: CartService) { this.location = location; this.nativeElement = element.nativeElement; this.sidebarVisible = false; this.window = window; } ngOnInit() { const METHOD_NAME: string = 'ngOnInit()'; const body = document.getElementsByTagName('body')[0]; // if ($(window).width() < 768) { body.classList.add('nav-close'); // } this.sharedService.updateErrorMessage(null); this.sharedService.storeId.subscribe((val: number) => { this.storeId = val; }); const navbar: HTMLElement = this.element.nativeElement; this.toggleButton = navbar.getElementsByClassName('navbar-toggle')[0]; // getting the user information this.user = this.userService.getUser(); this.userId = this.user.userId; if (window.location.hostname.includes('cnry')) { this.user.envName = "cnry"; } if (!this.user) { this.user = new User('tomuat66', null, null, null, null, null, null, null); } else { if (!this.user.notifications) { this.getNotifications(this.storeId, this.user.userId); } else { this.getNotificationsReadCounts(); } if (this.user.permissions.canAccessRTS && this.user.retailStoreId && !this.user.taxAreaId) { this.updateRetailStoreDetail(this.user.retailStoreId); } } if ($('script')[0].src.indexOf('walkme') === -1 && $('script')[1].src.indexOf('walkme') === -1) { this.window.walkMeFunction(); } $('#walkme-player').show(); } ngOnDestroy(): void { const METHOD_NAME: string = 'ngOnDestroy()'; this.user = null; this.wcToken = null; this.storeItems = null; this.listTitles = null; this.karmaTestResult = null; } openMenuItems(): void { this.showSettings = false; this.showSalesStats = false; this.showAccountInfo = false; this.showStoreInfo = false; this.showChannels = false; if ($('.dropdown-header.settings').hasClass('open')) { $('.dropdown-header.settings').removeClass('open'); } if ($('.dropdown-header.address').hasClass('open')) { $('.dropdown-header.address').removeClass('open'); } } showMyFavorites(): void { this.router.navigate(['home/profile']); if ($('.dropdown').hasClass('open')) { $('.dropdown').removeClass('open'); } } getTitle() { const METHOD_NAME: string = 'getTitle()'; let titlee = window.location.pathname; titlee = titlee.substring(1); for (let item = 0; item < this.listTitles.length; item++) { if (this.listTitles[item].path === titlee) { return this.listTitles[item].title; } } return 'Dashboard'; } sidebarToggle() { const METHOD_NAME: string = 'sidebarToggle()'; const toggleButton = this.toggleButton; const body = document.getElementsByTagName('body')[0]; this.sidebarVisible = toggleButton.classList ? toggleButton.classList.contains('toggled') : null; if (this.sidebarVisible === false) { setTimeout(function () { toggleButton.classList.add('toggled'); }, 500); body.classList.add('nav-open'); body.classList.remove('nav-close'); this.sidebarVisible = true; } else { this.toggleButton.classList.remove('toggled'); this.sidebarVisible = false; body.classList.remove('nav-open'); body.classList.add('nav-close'); } } getNotifications(storeId: number, userId: number) { const METHOD_NAME: string = 'getNotifications()'; console.log('NavbarComponent.notifications()>>Start.'); this.errorMessage = ''; // this.sharedService.showSpinner(true); this.userService.getNotifications(storeId, userId).subscribe( data => { this.karmaTestResult = data; // this.sharedService.showSpinner(false); console.log('NavbarComponent.notifications()>>Success.'); this.user.notifications = data; this.userService.setUser(this.user); this.getNotificationsReadCounts(); }, error => { // this.sharedService.showSpinner(false); // this.sharedService.showErrorMessage(error, true); console.log('Server error.'); console.log('NavbarComponent.notifications()>>Error.'); }); console.log('NavbarComponent.notifications()>>End.'); } getNotificationsReadCounts(): void { const METHOD_NAME: string = 'getNotificationsReadCounts()'; this.unReadNotificationCount = 0; for (let i = 0; i < this.user.notifications.length; i++) { this.user.notifications[i].isCollapsed = true; if (!this.user.notifications[i].isRead) { this.unReadNotificationCount++ }; } console.log('NavbarComponent.notifications()>>Unread count:' + this.unReadNotificationCount); } expandNotification(event: any, item: INotification): void { const METHOD_NAME: string = 'expandNotification()'; console.log('NavbarComponent.expandNotification()>>Start.'); const exapnd: boolean = false; event.stopPropagation(); item.isCollapsed = !item.isCollapsed; console.log('NavbarComponent.expandNotification()>>End.'); this.updateNotification(item); // Calling update notification } updateNotification(item: INotification): void { const METHOD_NAME: string = 'updateNotification()'; console.log('NavbarComponent.updateNotification()>>Start.'); if (!item.isRead) {// Start- Calling update notification API const requestParams: any = { 'ids': [item.id] }; this.userService.updateNotifications(Constants.STORE_ID_CD, this.user.userId, requestParams).subscribe(data => { this.karmaTestResult = data; return this.user.notifications.filter((notification) => { if (notification.id === data.ids[0]) { notification.isRead = true; this.unReadNotificationCount--; } }); }) console.log('NavbarComponent.updateNotification()>>End.'); }// End- Calling update notification API } logout() { const METHOD_NAME: string = 'logout()'; console.log('NavbarComponent.notifications()>>Start.'); this.errorMessage = ''; this.sharedService.showSpinner(true); this.userService.logout(this.storeId, this.user.userId).subscribe( data => { this.karmaTestResult = data; this.sharedService.showSpinner(false); this.sharedService.showClearAll(true); this.sharedService.setAppDefault(); this.sharedService.clearSessionStorage(true); this.sharedService.clearLocalStorage(); console.log('NavbarComponent.logout()>>Success.'); console.log('NavbarComponent.notifications()>>Unread count:' + this.unReadNotificationCount); if (!this.window.envCheck) { $('#walkme-player').hide(); } //this.router.navigate(['login']); this.redirectLoginPage();//redirecting to login page }, error => { console.log('Server error.'); this.errorMessage = 'Server error'; this.sharedService.showSpinner(false); this.sharedService.showClearAll(true); this.sharedService.setAppDefault(); this.sharedService.clearSessionStorage(true); this.sharedService.clearLocalStorage(); //this.router.navigate(['login']); this.redirectLoginPage();//redirecting to login page }); } swithChannel(storeId: number): void { const METHOD_NAME: string = 'swithChannel()'; const cart = this.cartService.getCart(); if (cart && cart.status !== 'P10' && cart.status !== 'C') { // checking for if order is submitted or submitted queued and order exists this.sharedService.showErrorMessage('_ERR_CART_IN_PROGRESS', false); } else { this.reLogin(storeId); } console.log('NavbarComponent.swithChannel()>>End.'); } reLogin(storeId: number): void { const METHOD_NAME: string = 'reLogin()'; console.log('NavbarComponent.reLogin()>>Start.'); this.errorMessage = ''; this.sharedService.showSpinner(true); const logon: Logon = new Logon(); logon.logonId = this.user.logonId.toLowerCase(); logon.logonPassword = this.user.password; this.userService.login(storeId, logon).subscribe( data => { this.karmaTestResult = data; this.sharedService.showSpinner(false); // @Hema -LoginPoc console.log('NavbarComponent.login()>>login success..'); this.wcToken = data; this.user.WCToken = data.WCToken; this.user.WCTrustedToken = data.WCTrustedToken; this.user.personalizationID = data.personalizationID; this.checkForChannels(storeId); for (const channel of this.user.channels) { channel.active = channel.storeId === this.storeId ? true : false; } this.userService.setUser(this.user); }, error => { this.sharedService.showSpinner(false); this.errorMessage = this.sharedService.getErrorMessage(error); console.error('error=>' + error); }); console.log('LoginComponent.login()>>End.'); } // Show Settings to change sidebar color changeSettingStatus(status) { const METHOD_NAME: string = 'changeSettingStatus()'; this.showSettings = status; } checkForChannels(storeId: number): void { if (this.user.channels && this.user.channels.length > 0) { // clearing all local and session data this.sharedService.updateStoreId(storeId); this.sharedService.setAppDefault(); this.sharedService.clearSessionStorage(false); this.sharedService.clearLocalStorage(); this.sharedService.initializeCatalog(); this.router.navigate(['home/search']); } else { this.errorMessage = 'Not authorized for any channel.'; } } /** * This function is used to refresh sales stats for the logged in user * @param {boolean} showSalesStats contains true/false * @returns void */ refreshSalesStats(showSalesStats: boolean): void { const METHOD_NAME: string = 'RefreshSalesStats()'; if (showSalesStats) { this.errorMessage = ''; this.sharedService.showSpinner(true); this.userService.getProfile(this.storeId, this.userId).subscribe( data => { this.karmaTestResult = data; this.sharedService.showSpinner(false); console.log('RefreshSalesStats()>>User prfile refresh success..'); this.user.salesStats = data.salesStats; this.userService.setUser(this.user); }, error => { this.sharedService.showSpinner(false); this.errorMessage = this.sharedService.getErrorMessage(error); console.error('error=>' + error); }); } } /** * This function is used to refresh sales stats for the logged in user * @param {number} retailStoreId contains retail store# * @returns void */ updateRetailStoreDetail(retailStoreId: number): void { const METHOD_NAME: string = 'updateRetailStoreDetail()'; this.sharedService.showSpinner(true); this.userService.getRetailStoreDetail(this.storeId, this.userId, retailStoreId).subscribe(result => { this.karmaTestResult = result; this.sharedService.showSpinner(false); console.log('Retail store detail update success..'); this.user = Object.assign(this.user, result); this.userService.setUser(this.user); if (this.user.zipCode) { const zipCode = Utils.trimZipCode(this.user.zipCode); // getting current cart updates this.sharedService.showSpinner(true); // spinner this.cartService.lookupNpaList(this.storeId, 123456789, zipCode).subscribe(result => { this.karmaTestResult = result; this.sharedService.showSpinner(false); // spinner if (result && !result.hasOwnProperty('errorCode')) { this.user.marketCode = result[0].marketCode ? result[0].marketCode : null; this.user.marketName = result[0].marketName ? result[0].marketName : null; this.user.regionName = result[0].regionName ? result[0].regionName : null; this.userService.setUser(this.user); } else { console.log('T-Mobile Service is not found for given zip code:' + zipCode); } }, error => { this.sharedService.showSpinner(false); // spinner console.log('T-Mobile Service is not found for given zip code:' + zipCode); //this.sharedService.showErrorMessage(error, true); // console.error('error=>' + error); }); } }, error => { this.sharedService.showSpinner(false); this.errorMessage = this.sharedService.getErrorMessage(error); console.error('error=>' + error); }); } mobileNumber(phoneNumber: string): string { if (phoneNumber && phoneNumber.indexOf('-') === -1 && phoneNumber.length === 10) { return phoneNumber.substring(0, 3) + '-' + phoneNumber.substring(3, 6) + '-' + phoneNumber.substring(6); } else { return phoneNumber; } } async redirectLoginPage(): Promise { if (environment.oktaEnable) { await this.oktaAuth.logout(); this.oktaAuth.loginRedirect('/login') } else { this.router.navigate(['login']); } } }