import {Component, DoCheck, ElementRef, OnDestroy, OnInit, ViewChild, ChangeDetectionStrategy} from '@angular/core'; import {Subscription} from 'rxjs'; import {NavigationEnd, Router} from '@angular/router'; import {AppComponent} from './app.component'; import {AppMainComponent} from './app.main.component'; import {Employee} from './_models/Employee/employee'; import {AuthService} from './_services/auth/auth.service'; import {AuthGuard} from './_guards/auth.guard'; import {User} from './_models/Authentication/user'; import {ApiService} from './app.api.service'; import {MenuService} from './app.menu.service'; import {Bookmark} from './_models/Basic/bookmark'; import {HRMNotificationService} from './app.notification.service'; import {PendingJobDTO} from './_models/Work-Flow/pendingJobDTO'; import {RolePermission} from './_models/Authentication/role'; import {JwtHelperService} from '@auth0/angular-jwt'; import { EnumUserType } from './_models/enums'; import { loadingPanelService } from './hrm-loding panel/loding.panel.service'; import { DataTransferService } from './data.transfer.service'; import { CommonModule } from '@angular/common'; import { HostListener } from '@angular/core'; import { NotificationTriggerService } from './app.topbar.service'; @Component({ standalone: false, selector: 'app-topbar', templateUrl: './app.topbar.component.html', changeDetection: ChangeDetectionStrategy.Eager, styleUrls: ['./app.topbar.component.scss'], }) export class AppTopBarComponent implements OnInit, DoCheck, OnDestroy { model: any = {}; employee: Employee; loginName: string = ''; selectedMenuName: string = 'selected Menu'; bookmarkIcon = 'pi pi-bookmark'; currentRoute: string; pendingJobDTOs: PendingJobDTO[] = []; companyNotification: any[] = []; pendingJobCount: number = 0; notificationCount: number = 0; isSuperUser: boolean = false; swithtypeName: string = undefined; switchUserID: number = undefined; menuItems: any[] = []; activeMenu: string | null = null; activeSubMenu: string | null = null; mobileMenuOpen = false; mobOpenSection: string | null = null; mobOpenSubSection: string | null = null; private closeTimer: any; // Notification panel open/close tracking. Viewed notifications are marked read // only when the panel CLOSES (see ngDoCheck -> onNotificationPanelClosed). private notifPanelWasOpen = false; private subscriptions: Subscription[] = []; // Current payroll type's description, shown left of the Pending Jobs icon for admin // (EnumUserType.User) logins only. Re-read whenever the stored token changes // (login, user switch, payroll-type switch, logout). payrollTypeName: string = ''; private payrollTypeToken: string | null | undefined = undefined; private payrollTypeSub: Subscription | null = null; isScrolled: boolean = false; @HostListener('window:scroll', []) onWindowScroll() { if (this.apiService.isSelService) { this.isScrolled = window.scrollY > 10; } } @ViewChild('ssNotif') ssNotif!: ElementRef; constructor(public app: AppComponent, public appMain: AppMainComponent, public loadingPanel: loadingPanelService, public authService: AuthService, private router: Router, public _auth: AuthGuard, public apiService: ApiService, public menuService: MenuService, public notificationService: HRMNotificationService, private dataTransferService: DataTransferService, private notificationTrigger: NotificationTriggerService) { let x = this.apiService.menuItems; this._auth.menuEvent.subscribe(value => this.getloginUser()); this.bookmarkIcon = this.menuService?.clickedMenuItem?.isBookmarked ? 'pi pi-bookmark-fill' : 'pi pi-bookmark'; this.pendingJobCount = 0; const [navigation] = performance.getEntriesByType('navigation') as PerformanceNavigationTiming[]; if (navigation.type == 'reload') { this.pendingJobDTOs = JSON.parse(localStorage.getItem('pendingjobs')); if (this.pendingJobDTOs != undefined) { this.pendingJobCount = this.pendingJobDTOs != null || this.pendingJobDTOs != undefined ? this.pendingJobDTOs.length : 0; } // Notification list/count are owned by NotificationTriggerService // (it seeds from localStorage and refreshes from the API on load). this.menuService.clickedMenuItem = JSON.parse(localStorage.getItem('selectedMenu')); this.menuService.bookMarkpages = JSON.parse(localStorage.getItem('bookmark')); const jwtHelper = new JwtHelperService(); const user = jwtHelper.decodeToken(localStorage.getItem('token')); if (user != undefined) { this.loginName = user.UserName; this.isSuperUser = true; var spItem = localStorage.getItem('switchUserID'); if (spItem != undefined && spItem != null && spItem != "undefined") { this.isSuperUser = false; this.swithtypeName = "Switch to Super-User"; this.switchUserID = parseInt(localStorage.getItem('switchUserID')); } else if (user.UserType == EnumUserType.SuperUser && (!user.EmployeeID || user.EmployeeID === 0 || user.EmployeeID === "0")) { this.swithtypeName = undefined; } else if (user.UserType == EnumUserType.SuperUser && user.EmployeeID != undefined && user.EmployeeID != 0 && user.EmployeeID != "0") { if(this.authService.getIsFromUser()){ this.swithtypeName = "Switch to Admin"; } else{ this.swithtypeName = "Switch to ESS"; } } } } if (this.pendingJobDTOs != undefined && this.pendingJobDTOs.length != 0) { this.pendingJobDTOs = JSON.parse(localStorage.getItem('pendingjobs')); this.pendingJobCount = this.pendingJobDTOs != null || this.pendingJobDTOs != undefined ? this.pendingJobDTOs.length : 0; } } ngOnInit():void { document.addEventListener('click', (e) => { this.activeMenu = null; this.activeSubMenu = null; this.mobileMenuOpen = false; }); this.loadPendingJobs(); // Notifications: this component is a pure CONSUMER of the shared // NotificationTriggerService store. It never fetches or counts itself. this.notificationTrigger.ensureLoaded(); this.subscriptions.push( this.notificationTrigger.notifications$.subscribe(list => { this.companyNotification = list || []; }), this.notificationTrigger.unreadCount$.subscribe(count => { this.notificationCount = count || 0; }) ); } ngAfterViewInit() { this.subscriptions.push( this.notificationTrigger.notificationSource$.subscribe(() => { this.appMain.onTopbarItemClick(new MouseEvent('click'), this.ssNotif.nativeElement); }) ); } ngDoCheck(): void { // Detect the open -> close transition of the shared notification panel. const isOpen = !!this.ssNotif && this.appMain.activeTopbarItem === this.ssNotif.nativeElement; if (this.notifPanelWasOpen && !isOpen) { this.onNotificationPanelClosed(); } this.notifPanelWasOpen = isOpen; this.syncPayrollTypeName(); } /** * Shows the current payroll type's description for admin logins. Cheap on every * change-detection pass: it only does work when the token in localStorage changed. * The name comes from the server (GetPayrollTypeByLoginID), so it is the payroll * type the API actually scopes data by. */ private syncPayrollTypeName(): void { const token = localStorage.getItem('token'); if (token === this.payrollTypeToken) { return; } this.payrollTypeToken = token; if (this.payrollTypeSub) { this.payrollTypeSub.unsubscribe(); this.payrollTypeSub = null; } let user: any = null; try { user = token ? new JwtHelperService().decodeToken(token) : null; } catch { user = null; } if (!user || user.UserType != EnumUserType.User || !user.PayrollTypeID) { this.payrollTypeName = ''; return; } this.payrollTypeSub = this.authService.GetPayrollTypeByLoginID().subscribe({ next: (payrollType) => { this.payrollTypeName = payrollType?.description ?? ''; }, error: () => { this.payrollTypeName = ''; }, }); } /** * Fires once when the notification panel closes. Hands off to the shared * store: mark the viewed notifications read -> wait -> re-fetch -> republish. * companyNotification + notificationCount then update through the * notifications$ / unreadCount$ subscriptions above - the same path the * dashboard tile uses, so both stay identical. */ onNotificationPanelClosed(): void { this.subscriptions.push( this.notificationTrigger.markVisibleAsReadThenRefresh().subscribe() ); } ngOnDestroy(): void { this.subscriptions.forEach(s => s.unsubscribe()); if (this.payrollTypeSub) { this.payrollTypeSub.unsubscribe(); } } loadBookmark() { this.authService.subject.subscribe( (resp) => { this.menuService.bookMarkpages = resp; }, () => { }, () => { }, ); } loadPendingJobs() { console.log('s2-receive'); this.authService.subject2.subscribe( (resp) => { this.pendingJobDTOs = resp; if (this.pendingJobDTOs != undefined) this.pendingJobCount = this.pendingJobDTOs.length; }, () => { }, () => { }, ); } toggleFullScreen(){ // debugger; this.apiService.isSelServiceFullScreen = !this.apiService.isSelServiceFullScreen; } openNotifLink(url: string) { debugger; if (!url) return; const isExternal = /^https?:\/\//i.test(url); if (isExternal) { window.open(url, '_blank'); } else { this.router.navigateByUrl(url); } } getloginUser() { const jwtHelper = new JwtHelperService(); const user = jwtHelper.decodeToken(localStorage.getItem('token')); this.loginName = user.UserName; this.isSuperUser = true; localStorage.removeItem('switchUserID'); this.switchUserID = undefined; // A fresh login / user-switch just happened - load this user's notifications. this.notificationTrigger.ensureLoaded(); if ((user.UserType == EnumUserType.Employee || user.UserType == EnumUserType.User) && user.EmployeeID != undefined) { // if (this.apiService.isSSO ==true && user.UserType == EnumUserType.User && user.EmployeeID != undefined) { this.isSuperUser = false; this.swithtypeName = "Switch to Super-User"; this.switchUserID = undefined; var userid = undefined; this.authService.getSwitchUserId(EnumUserType.SuperUser).subscribe(next => { if(next == 0){ userid = undefined; this.swithtypeName = undefined; } else{ userid = next; } }, error => { this.swithtypeName = undefined; }, () => { if (userid != 0){ this.switchUserID = userid; localStorage.setItem('switchUserID', JSON.stringify(this.switchUserID)); } }); } else if (user.UserType == EnumUserType.SuperUser && (!user.EmployeeID || user.EmployeeID === 0 || user.EmployeeID === "0")) { this.swithtypeName = undefined; } else if (user.UserType == EnumUserType.SuperUser && user.EmployeeID != undefined && user.EmployeeID != 0 && user.EmployeeID != "0") { if(this.authService.getIsFromUser()){ this.swithtypeName = "Switch to Admin"; } else{ this.swithtypeName = "Switch to ESS"; } } } //ngOnInit() { // this.employee = new Employee(); // this.loadData(); //} loadData() { //this.employeeService.getCurrentEmployee().subscribe( // (resp) => { // this.employee = resp; // }, // () => { }, // () => { // }, //); } login() { this.authService.login(this.model).subscribe(next => { //show notification }, error => { console.log(error); }, () => { this.router.navigate(['/training']); }); } loggedIn() { return this.authService.loggedIn(); } SwitchUser() { //debugger; const jwtHelper = new JwtHelperService(); const user = jwtHelper.decodeToken(localStorage.getItem('token')); this.authService.setIsFromUser(false); if (user.UserType != EnumUserType.SuperUser) { if(user.UserType == EnumUserType.Employee){ this.swithtypeName = "Switch to ESS"; } else if(user.UserType == EnumUserType.User){ this.swithtypeName = "Switch to Admin"; this.authService.setIsFromUser(true); } user.UserID = this.switchUserID; user.UserType = EnumUserType.SuperUser; this.authService.setIsFromSuperUser(false); } else { this.authService.setIsFromSuperUser(true); if(this.swithtypeName === "Switch to Admin"){ user.UserType = EnumUserType.User; } else if(this.swithtypeName === "Switch to ESS"){ user.UserType = EnumUserType.Employee; } this.swithtypeName = "Switch to Super-User"; } return this.switchTheUser(user); } switchTheUser(oUser: User) { const data = { user: oUser, payrollTypeId: oUser.PayrollTypeID, }; debugger; this.loadingPanel.ShowLoadingPanel = true; this.authService.SwtichUserMode(data).subscribe( (resp: any) => { localStorage.setItem('token', resp); ApiService.AuthenticationToken = resp; }, (err: any) => { this.notificationService.showError('Invalid Login-ID or Password'); this.loadingPanel.ShowLoadingPanel = false; }, () => { const jwtHelper = new JwtHelperService(); const user = jwtHelper.decodeToken(localStorage.getItem('token')); if (user.UserType != EnumUserType.SuperUser) { this.swithtypeName = "Switch to ESS"; } else { this.swithtypeName = "Switch to Super-User"; } if (user.ChangePasswordAtNextLogon === 'True') { localStorage.removeItem('menuList'); this._auth.menuEvent.emit(false); } else { this.authService.GetRolePermissionbyUserID().subscribe( (menu: any) => { localStorage.setItem('menuList', JSON.stringify(menu)); }, (errmenu: any) => { }, () => { this._auth.menuEvent.emit(true); this.loadingPanel.ShowLoadingPanel = false; this.appMain.IsSelfService(); if (user.UserType == EnumUserType.Employee) { if(this.apiService.isNewDaswhboard !== undefined){ if(this.apiService.isNewDaswhboard === true){ this.router.navigate(['/ess/self-dashboard']); } else{ this.router.navigate(['/ess/ess-dashboard']); } } else{ this.router.navigate(['/ess/self-dashboard']); } // this.router.navigate(['/ess/ess-dashboard']); } else if (user.UserType == EnumUserType.User) { this.router.navigate(['/ess/landing-page']); } else { this.router.navigate(['/']); } } ); } } ); } logout() { this.pendingJobCount = 0; this.pendingJobDTOs = undefined; this.authService.logout(); //localStorage.removeItem('forgotpass'); //localStorage.removeItem('token'); //localStorage.removeItem('menuList'); ////show notification //this.router.navigate(['/login']); } onBookMark() { const bookmark: Bookmark = new Bookmark(); if (this.menuService.clickedMenuItem !== undefined) { if (this.menuService.clickedMenuItem.isBookmarked === false) { bookmark.link = this.menuService.clickedMenuItem.link; bookmark.description = this.menuService.clickedMenuItem.name; bookmark.menuCode = this.menuService.clickedMenuItem.menuKey; this.menuService.bookMarkpages.push(bookmark); // this.bookmarkIcon = 'pi pi-bookmark-fill' ; this.menuService.clickedMenuItem.isBookmarked = true; this.authService.SaveBookmark(bookmark).subscribe( (x) => { }, (x) => { this.notificationService.showError(x.error); }, () => { this.notificationService.showSuccess('You have successfully bookmarked this page.'); this.getBookmark(); localStorage.setItem('selectedMenu', JSON.stringify(this.menuService.clickedMenuItem)); }); } else { bookmark.link = this.menuService.clickedMenuItem.link; bookmark.description = this.menuService.clickedMenuItem.name; bookmark.menuCode = this.menuService.clickedMenuItem.menuKey; const index = this.menuService.bookMarkpages.findIndex(x => x.menuCode === bookmark.menuCode); this.menuService.bookMarkpages.splice(index, 1); this.menuService.clickedMenuItem.isBookmarked = false; this.authService.deleteBookmarkByMenuKey(bookmark).subscribe( (x) => { }, (x) => { this.notificationService.showError(x.error); }, () => { this.notificationService.showSuccess('You have successfully removed bookmark this page.'); this.getBookmark(); localStorage.setItem('selectedMenu', JSON.stringify(this.menuService.clickedMenuItem)); }); } } } bookMarkedLinkClicked(b: Bookmark) { this.menuService.clickedMenuItem = new RolePermission(); this.menuService.clickedMenuItem.name = b.description; this.menuService.clickedMenuItem.menuKey = b.menuCode; this.menuService.clickedMenuItem.isBookmarked = true; this.router.navigate([b.link]); } ApprovePendingJob(dataItem: PendingJobDTO) { // debugger; this.dataTransferService.setData(dataItem.id); this.router.navigateByUrl(dataItem.link); } getBookmark() { this.authService.getBookmarks() .subscribe( (resp: any) => { if (resp != undefined) { this.menuService.bookMarkpages = resp; } }, (x) => { }, () => { localStorage.removeItem('bookmark'); localStorage.setItem('bookmark', JSON.stringify(this.menuService.bookMarkpages)); }); } handleHrmAiClick(){ //this.router.navigate(['/hrmopen-ai/hrm-open-ai-test']); } openMenu(menuKey: string) { clearTimeout(this.closeTimer); this.activeMenu = menuKey; } scheduleClose() { } toggleMenu(event: Event, menuKey: string) { event.preventDefault(); event.stopPropagation(); this.activeMenu = menuKey; this.activeSubMenu = null; } openSubMenu(menuKey: string) { clearTimeout(this.closeTimer); this.activeSubMenu = menuKey; } closeSubMenu() { } closeAllMenus() { this.activeMenu = null; this.activeSubMenu = null; this.mobileMenuOpen = false; } toggleMobileMenu(event: Event) { event.stopPropagation(); this.mobileMenuOpen = !this.mobileMenuOpen; if (this.mobileMenuOpen) { this.mobOpenSection = null; this.mobOpenSubSection = null; this.appMain.activeTopbarItem = null; // close other dropdowns } } closeMobileMenu() { this.mobileMenuOpen = false; this.mobOpenSection = null; this.mobOpenSubSection = null; } toggleMobSection(menuKey: string) { this.mobOpenSection = this.mobOpenSection === menuKey ? null : menuKey; this.mobOpenSubSection = null; } toggleMobSubSection(menuKey: string) { this.mobOpenSubSection = this.mobOpenSubSection === menuKey ? null : menuKey; } }