import { Component, OnInit, ViewChild, HostListener } from '@angular/core'; import { FormControl } from '@angular/forms'; import { CommonfunctionService } from '../../services/commonfunction.service'; import { SpriteStyleService } from '../../services/spritestyle.service'; import { ItemService } from '../../services/item.service'; import { ItemVariantService } from '../../services/item.variant.service'; import { BsModalRef, BsModalService } from 'ngx-bootstrap'; import { AuthenticationService } from '../../services/authentication.service'; import { MessengerService } from '../../services/messenger.service'; import { SignUpModalComponent } from '../../views/custom-portal-pages/header-components/sign-up-modal/sign-up-modal.component'; import { LoginModalComponent } from '../../views/custom-portal-pages/header-components/login-modal/login-modal.component'; import { MatSidenav } from '@angular/material/sidenav/sidenav'; import { Router } from '@angular/router'; import { NGXLogger } from 'ngx-logger'; import { CartService } from '../../services/cart.service'; @Component({ selector: 'app-customer-portal', templateUrl: './customer-portal-layout.component.html', styleUrls: ['./customer-portal-layout.component.css'] }) export class CustomerPortalLayoutComponent implements OnInit { @ViewChild('sidenav', { static: false }) sidemenu: MatSidenav; @ViewChild('cartContainer', { static: false }) cartContainer; bsModalRef: BsModalRef; userLoggedIn: boolean = false; walletValue: number; isAdmin: false; hide; title = 'espl-cp'; transparentBgJson: { "background-color": string, 'border-top': string, 'border-left': string, 'border-right': string, color: string }; loadedCache: boolean; contentDisplayed: boolean = true; cartDisplayed: boolean = false; locationDropdown: FormControl; locationsArray = []; categories = []; isNotificationExists: boolean; userLocation: any; notificationMessage: any; allItemsloaded: boolean = false; userSSO: number; allItems: any; promoandKeyItems: any; itemsInCart:[]; cartItemsCount: number; constructor(private cartService: CartService,private messengerService: MessengerService, private spriteService: SpriteStyleService, private commonFunction: CommonfunctionService, private logger: NGXLogger, private router: Router , private itemService: ItemService, private itemVariantService: ItemVariantService, private auth: AuthenticationService, private modalService: BsModalService) { this.transparentBgJson = { "background-color": 'transparent', 'border-top': "none", 'border-left': 'none', 'border-right': 'none', color: 'white' } this.locationDropdown = new FormControl(); } async ngOnInit(): Promise { this.cartService.getItemsInCart().subscribe(result => { this.itemsInCart = JSON.parse(result) || []; this.cartItemsCount = this.cartService.getSum(this.itemsInCart,"numItems"); }); // let categoryLookup = {}; this.isNotificationExists = true; if (typeof (Storage) !== 'undefined') { // Check if local storage key does not exist and add the cached item. if(localStorage.getItem('user')) {       let user = JSON. parse(localStorage.getItem('user')); this.userLoggedIn = true; this.userLocation = user.location; this.walletValue = user.wallet; this.isAdmin = user.isAdmin; this.userSSO = user.username; this.hide = false; } else { this.userLoggedIn = false; } if(localStorage.customerItemsLastUpdatedDate == null ) { await this.updateLocalStorageForHomePageData(); this.updateLocalStorageWithNonKeyPromoItems(); } else { if ( localStorage.promoOrKeyItems == null || localStorage.locations == null || localStorage.sliders == null || localStorage.categories == null || localStorage.config == null) { await this.updateLocalStorageForHomePageData(); } else { await this.verifyLastUpdatedAndCacheUpdate(); } if(localStorage.nonKeyOrPromoItems == null){ this.updateLocalStorageWithNonKeyPromoItems(); } } } else { // If local storage is not supported then directly data will be feteched from server. //TODO: this.logger.debug('localstorage is not supported so reading directly from server.'); } } /* updates non key and non promo items to local storage */ updateLocalStorageWithNonKeyPromoItems() { this.itemService.getNonkeyandpromoitems(this.userLocation).subscribe((itemsData: {status: string, message: string, data}) => { this.allItemsloaded= true; this.allItems = [...this.promoandKeyItems, ...itemsData.data.items]; localStorage.nonKeyOrPromoItems = JSON.stringify(itemsData.data.items); //TODO: using ISO string. need to check with different timezones. localStorage.customerItemsLastUpdatedDate = new Date().toISOString(); this.messengerService.nonPromoAndKeyDatafn(itemsData.data.items); }); } // Check if local storage key exists and cache timestamp item is different. // If timestamp is same then wont update the localstorage key otherwise update it with latest data. private async verifyLastUpdatedAndCacheUpdate() { const lastUpdatedDateObj = await this.itemService.getCustomerItemsLastUpdatedDates(); const cacheLastUpdatedDate = new Date(localStorage.customerItemsLastUpdatedDate); if ( new Date(lastUpdatedDateObj['data']['lastUpdatedDate']) > cacheLastUpdatedDate) { if (new Date(lastUpdatedDateObj['data']['genericKeyPromoUpdatedDate']) > cacheLastUpdatedDate) { this.logger.debug('Cache Timestamp lastUpdatedDate key is behind. so, updating localStorage.'); await this.updateLocalStorageForHomePageData(); } else { this.logger.debug('Cache Timestamp is same with generic so not updating localStorage key'); this.categories = JSON.parse(localStorage.getItem('categories')).sort(this.commonFunction.sortByProperty('display_order')); this.locationsArray = JSON.parse(localStorage.getItem('locations')); let config = JSON.parse(localStorage.getItem('config')); this.notificationMessage = config.notification; this.isNotificationExists = config.has_notification; this.locationDropdown.setValue(config.location_id); this.loadedCache = true; let promoOrKeyItems = JSON.parse(localStorage.getItem('promoOrKeyItems')); this.messengerService.promoKeyDatafn(promoOrKeyItems); this.messengerService.categoryDatafn(this.categories); this.spriteService.addHomePageStyleSheet(); this.messengerService.sliderDatafn(JSON.parse(localStorage.getItem('sliders'))); } if( new Date(lastUpdatedDateObj['data']['nonKeyPromoUpdatedDate']) > cacheLastUpdatedDate ) { this.logger.debug('Cache Timestamp lastUpdatedDate key is behind. so, updating localStorage.'); this.updateLocalStorageWithNonKeyPromoItems(); } else { let nonKeyOrPromoItems = JSON.parse(localStorage.getItem('nonKeyOrPromoItems')); this.messengerService.nonPromoAndKeyDatafn(nonKeyOrPromoItems); } } else { this.logger.debug('Cache Timestamp is same so not updating localStorage key'); this.categories = JSON.parse(localStorage.getItem('categories')).sort(this.commonFunction.sortByProperty('display_order')); this.locationsArray = JSON.parse(localStorage.getItem('locations')); let config = JSON.parse(localStorage.getItem('config')); this.notificationMessage = config.notification; this.isNotificationExists = config.has_notification; this.locationDropdown.setValue(config.location_id); this.loadedCache = true; this.allItemsloaded = true; let promoOrKeyItems = JSON.parse(localStorage.getItem('promoOrKeyItems')); let nonKeyOrPromoItems = JSON.parse(localStorage.getItem('nonKeyOrPromoItems')); this.allItems = [...nonKeyOrPromoItems, ...promoOrKeyItems ]; this.messengerService.promoKeyDatafn(promoOrKeyItems); this.messengerService.categoryDatafn(this.categories); this.messengerService.nonPromoAndKeyDatafn(nonKeyOrPromoItems); this.spriteService.addHomePageStyleSheet(); this.messengerService.sliderDatafn(JSON.parse(localStorage.getItem('sliders'))); } } /* @usage: updates promoOrKeyItems and nonKeyOrPromoItems variables of local storage with server cache data, when location gets changes @purpose: called when there is a change in location*/ locationChanged(selectedLocationObj) { this.itemVariantService.getLocationBasedVariants(selectedLocationObj.location_id).subscribe((items: {status, message, data}) => { this.locationDropdown.setValue(selectedLocationObj.location_id); localStorage.promoOrKeyItems = JSON.stringify(items.data.keyorpromoitems); localStorage.nonKeyOrPromoItems = JSON.stringify(items.data.nonkeyorpromoitems); this.allItems = [...items.data.keyorpromoitems, ...items.data.nonkeyorpromoitems]; let config = JSON.parse(localStorage.config); config.location_id = selectedLocationObj.location_id; localStorage.config = JSON.stringify(config); this.messengerService.promoKeyDatafn(items.data.keyorpromoitems); this.messengerService.nonPromoAndKeyDatafn(items.data.nonkeyorpromoitems); this.spriteService.removeHomePageStyleSheet(); this.spriteService.addHomePageStyleSheet(); }); } /* @usage: adds/ updates local storage variables based on default/user's location with lastest data available on server cache. @purpose: called when any of the local storage variable need is missing. Is called only when the page is refreshed*/ private async updateLocalStorageForHomePageData(): Promise { this.router.navigate(['/home']); let homePageData = await this.itemService.getHomePageItems(this.userLoggedIn, this.userLocation); this.categories = homePageData['data']['categories'].sort(this.commonFunction.sortByProperty('display_order')).slice(0,10); this.locationsArray = homePageData['data']['locations']; this.userLocation = this.userLoggedIn? this.userLocation : homePageData['data']['locations'].find(location => location.is_default).location_id; if(this.userLoggedIn) this.locationDropdown.setValue(this.userLocation) else this.locationDropdown.setValue(this.userLocation); this.promoandKeyItems = homePageData['data']['items']; this.isNotificationExists = homePageData['data']['configurations'].has_notification; this.notificationMessage = homePageData['data']['configurations'].notification; this.logger.debug("updating Local Storage for generic data") localStorage.promoOrKeyItems = JSON.stringify(homePageData['data']['items']); localStorage.categories = JSON.stringify(homePageData['data']['categories']); localStorage.locations = JSON.stringify(homePageData['data']['locations']); localStorage.sliders = JSON.stringify(homePageData['data']['sliders']); homePageData['data']['configurations'].location_id = this.userLocation; localStorage.config = JSON.stringify(homePageData['data']['configurations']); localStorage.org = JSON.stringify(homePageData['data']['org']); //TODO: using ISO string. need to check with different timezones. localStorage.customerItemsLastUpdatedDate = new Date().toISOString(); this.loadedCache = true; this.messengerService.promoKeyDatafn(homePageData['data']['items']); this.messengerService.categoryDatafn(homePageData['data']['categories']); this.spriteService.addHomePageStyleSheet(); this.messengerService.sliderDatafn(homePageData['data']['sliders']); } /* @usage: called click on login button @purpose:To open the login Dialog. */ login() { this.sidemenu.close(); this.bsModalRef = this.modalService.show(LoginModalComponent, { initialState: { title: 'Login', } }); this.bsModalRef.content.event.subscribe(modelResult => { if (modelResult) { if (localStorage.getItem('user')) { this.userLoggedIn = true; let user = JSON.parse(localStorage.getItem('user')); this.userLocation = user.location; this.walletValue = user.wallet; this.isAdmin = user.isAdmin; this.userSSO = user.username; // this.locationDropdown.setValue(user.location); let locationObject = { location_id : user.location } this.locationChanged(locationObject); } } }); } /* @purpose: To open the modal to sign up */ signUpPopup() { this.sidemenu.close(); this.bsModalRef = this.modalService.show(SignUpModalComponent, { initialState: { title: 'Sign Up', } }); this.bsModalRef.content.event.subscribe(modelResult => { if (modelResult) { // this.userLoggedIn = true; if (localStorage.getItem('user')) { this.userLoggedIn = true; let user = JSON.parse(localStorage.getItem('user')); this.userLocation = user.location; this.walletValue = user.wallet; this.isAdmin = user.isAdmin; this.userSSO = user.username; // this.locationDropdown.setValue(user.location); let locationObject = { location_id : user.location } this.locationChanged(locationObject); } } }); } //To logout the current user logout() { this.sidemenu.close(); this.userLoggedIn = false; this.auth.logout(); } openMyOrders() { this.sidemenu.close(); this.router.navigate(['/home/myOrders']); } private showCart() { this.cartDisplayed = true; window.scroll({ top: 0, left: 0, behavior: 'smooth' }); var width = (window.innerWidth > 0) ? window.innerWidth : screen.width; const selector: HTMLElement = window.document.querySelector( 'app-customer-portal' ); if(width>768) // Items images will be displayed when device width is more than 768px { this.contentDisplayed = true; selector.removeAttribute("style"); } else { this.contentDisplayed = false; // Move the position of hidden html elements so that occupied space is not visibile in device mode selector.setAttribute("style","margin-top:-10000px") } } /* Hide cart if click outside of cart area */ @HostListener('document:mouseup', ['$event']) clickout(event) { if (event && event.target && event.target.id === "btn-close-espl-cart" || this.cartContainer && this.cartContainer.esplcart && !this.cartContainer.esplcart.nativeElement.contains(event.target)) { this.cartDisplayed = false; this.contentDisplayed = true; const selector: HTMLElement = window.document.querySelector( 'app-customer-portal' ); selector.removeAttribute("style"); } } }