import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { AuthGuard } from './_guards/auth.guard'; import { ApiService } from './app.api.service'; import { AuthService } from './_services/auth/auth.service'; import { PayrollType } from './_models/Authentication/payrollType'; import { HRMNotificationService } from './app.notification.service'; import { JwtHelperService } from '@auth0/angular-jwt'; import { loadingPanelService } from './hrm-loding panel/loding.panel.service'; import { Bookmark } from './_models/Basic/bookmark'; import { MenuService } from './app.menu.service'; import { WorkflowService } from './_services/workflow/workflow.service'; import { PendingJobDTO } from './_models/Work-Flow/pendingJobDTO'; import { MsalBroadcastService, MsalService } from '@azure/msal-angular'; import { filter } from 'rxjs/operators'; import { EventMessage, EventType, InteractionStatus } from '@azure/msal-browser'; import { User } from './_models/Authentication/user'; import { GlobalfunctionExtension } from './_models/globalFunctions'; import { AppMainComponent } from './app.main.component'; import { LoadingPanelComponent } from './hrm-loding panel/loading-panel.component'; import { CommonModule } from '@angular/common'; import { ReactiveFormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms'; import { ButtonModule } from '@progress/kendo-angular-buttons'; import { DropDownListModule } from '@progress/kendo-angular-dropdowns'; import { DialogModule } from '@progress/kendo-angular-dialog'; import { InputsModule } from '@progress/kendo-angular-inputs'; import { LabelModule } from '@progress/kendo-angular-label'; import { VersionCheckService } from './version-check.service'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'], changeDetection: ChangeDetectionStrategy.Eager, standalone: false, }) export class LoginComponent implements OnInit { loginForm: FormGroup; loading = false; submitted = false; returnUrl: string; payrollTypes: PayrollType[]; selectedPayrollTypeID: number; versionNumber: string; showModal = false; bookmarks: Bookmark[] = []; /* _wfmovementTrans: PendingJobDTO[] = [];*/ currentUser: User; emailAddress = ''; bannerHeight = '200px'; bannerWidth = '360px'; imgSrc: string= 'assets/layout/images/Logo.png'; appVersion: string = '...'; constructor( private formBuilder: FormBuilder, private route: ActivatedRoute, private router: Router, public userService: AuthService, public apiService: ApiService, private auth: AuthGuard, public notificationService: HRMNotificationService, public loadingPanel: loadingPanelService, public wfService: WorkflowService, public menuService: MenuService, private msalBroadcastService: MsalBroadcastService, private authService: MsalService, public appMain : AppMainComponent, private versionCheck: VersionCheckService ) { // Redirect to home if already logged in -- but only when the app actually started on // the login page. This component sits in app-main's template behind [hidden], not // *ngIf, so its constructor runs once at bootstrap on EVERY route. Redirecting // unconditionally fires before the router's initial navigation and throws away // whatever URL the user opened, landing them on '/' (and from there on // /ess/landing-page or /ess/self-dashboard via DashboardDemoComponent). if (ApiService.AuthenticationToken && window.location.hash.indexOf('/login') > -1) { this.router.navigate(['/']); } this.versionCheck.currentVersion$.subscribe(v => { this.appVersion = v; }); this.showModal = false; } ssoDT : any; nmgtLink : any; currentLink : any; loadFirst : boolean; ngOnInit() { // const x = window.location.href; // this.currentLink = window.location.href.split('/').pop(); this.loadingPanel.ShowLoadingPanel = true; this.userService.getSSOStatus().subscribe( (resp) => { // debugger; this.ssoDT = resp; this.apiService.isSSO = this.ssoDT[0].isSSO; this.apiService.isNewDaswhboard = this.ssoDT[0].isNewDashboard; this.nmgtLink = this.ssoDT[0].nmgtLink; }, (x) => { this.loadingPanel.ShowLoadingPanel = false; }, () => { this.loadingPanel.ShowLoadingPanel = false; // if(this.apiService.currentLink === this.nmgtLink){ // this.apiService.isSSO = false; // } // debugger; if (this.apiService.isSSO === true) { this.msalBroadcastService.msalSubject$ .pipe( filter((msg: EventMessage) => msg.eventType === EventType.LOGIN_SUCCESS), ) .subscribe((result: EventMessage) => { console.log('My Credential is following'); console.log(result); }); this.msalBroadcastService.inProgress$ .pipe( filter((status: InteractionStatus) => status === InteractionStatus.None) ) .subscribe(() => { this.setLoginDisplay(); }); } }); this.showModal = false; this.loginForm = this.formBuilder.group({ username: ['', Validators.required], password: ['', Validators.required], payrolltypeid: [''], }); this.payrollTypes = []; // this.versionNumber = 'v-20240109-01'; this.versionNumber = 'v-' + GlobalfunctionExtension.generateVersionNumber(new Date(2024, 4, 28)) + '-01'; //// get return url from route parameters or default to '/' this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/'; } public payrollTypesImg = [ { id: 1, imagePath: 'assets/payrolltype-img/payrolltype1.png' }, { id: 2, imagePath: 'assets/payrolltype-img/payrolltype2.png' }, { id: 3, imagePath: 'assets/payrolltype-img/payrolltype3.png' }, { id: 4, imagePath: 'assets/payrolltype-img/payrolltype4.png' }, { id: 5, imagePath: 'assets/payrolltype-img/payrolltype5.png' } ]; public getImagePath(typeId: number): string { const typeImage = this.payrollTypesImg.find(img => img.id === typeId); return typeImage ? typeImage.imagePath : 'assets/layout/images/Logo.png'; } public selectPayrollType(typeId: number): void { this.selectedPayrollTypeID = typeId; this.Login(); } setLoginDisplay() { if (this.authService.instance.getAllAccounts().length > 0) { const user = this.authService.instance.getAllAccounts()[0]; this.emailAddress = user.username; this.Login(); } else { this.authService.loginRedirect(); } } // convenience getter for easy access to form fields get f() { return this.loginForm.controls; } onFocusOutEvent(event: any) { } GetPayrollTypeByLoginID() { this.selectedPayrollTypeID = null; this.payrollTypes = []; if (this.f['username'].value.length < 3) { return; } this.loadingPanel.ShowLoadingPanel = true; // Assuming GetPayrollTypesByLoginID is an observable returning payroll types based on the username this.userService.GetPayrollTypesByLoginID(this.f['username'].value).subscribe( (resp: any) => { this.payrollTypes = resp; }, (err: any) => { this.loadingPanel.ShowLoadingPanel = false; this.notificationService.showError(err.error); }, () => { this.loadingPanel.ShowLoadingPanel = false; if (this.payrollTypes !== undefined && this.payrollTypes.length > 1) { const validItem = []; validItem.push(Validators.required); // this.loginForm.controls['payrolltypeid'].setValidators(validItem); // this.loginForm.controls['payrolltypeid'].updateValueAndValidity(); } if (this.payrollTypes !== undefined && this.payrollTypes.length === 1) { this.selectedPayrollTypeID = this.payrollTypes[0].id; this.Login(); } else if (this.payrollTypes !== undefined && this.payrollTypes.length > 1) { this.showModal = true; } else { this.Login(); } } ); // this.userService.GetPayrollTypesByLoginID(this.f['username'].subscribe( // (resp: any) => { // this.payrollTypes = resp; // }, // (err: any) => { // this.loadingPanel.ShowLoadingPanel = false; // this.notificationService.showError(err.error); // }, // () => { // this.loadingPanel.ShowLoadingPanel = false; // if (this.payrollTypes !== undefined && this.payrollTypes.length > 1) { // const validItem = []; // validItem.push(Validators.required); // // this.loginForm.controls['payrolltypeid'].setValidators(validItem); // // this.loginForm.controls['payrolltypeid'].updateValueAndValidity(); // } // if (this.payrollTypes !== undefined && this.payrollTypes.length === 1) { // this.selectedPayrollTypeID = this.payrollTypes[0].id; // this.Login(); // } else if (this.payrollTypes !== undefined && this.payrollTypes.length > 1) { // this.showModal = true; // } else { // this.Login(); // } // } // ); } onPopUpClose() { this.showModal = false; } forgetPassword() { localStorage.setItem('forgotpass', JSON.stringify(true)); localStorage.removeItem('token'); localStorage.removeItem('menuList'); // this.router.navigate(['/forgot-password']); // this.router.navigateByUrl('/forgot-password'); // this.router.navigate(['/forgot-password']); } onSubmit() { debugger; if (this.apiService.isSSO) { this.authService.loginRedirect(); console.log('redirect'); } else { this.GetPayrollTypeByLoginID(); } } private Login() { let params: any; if (this.apiService.isSSO === true) { params = { Username: '', Password: '', payrollTypeid: null, nextPayProcessDate: null, email: this.emailAddress, isSSO: true }; console.log(params); } else { let nextPayrollProcessDate; this.submitted = true; if (this.loginForm.invalid) { return; } if (this.payrollTypes.length > 1 && this.selectedPayrollTypeID === undefined) { this.notificationService.showError('Please select a Access-Type'); return; } if (this.selectedPayrollTypeID != undefined && this.selectedPayrollTypeID != null) { nextPayrollProcessDate = this.payrollTypes.find(x => x.id == this.selectedPayrollTypeID).nextPayProcessDate; } this.loading = true; params = { Username: this.f['username'].value, Password: this.f['password'].value, payrollTypeid: this.selectedPayrollTypeID, nextPayProcessDate: nextPayrollProcessDate, email: '', isSSO: false }; } this.loadingPanel.ShowLoadingPanel = true; this.userService.login(params).subscribe( (resp: any) => { this.loading = false; }, (err: any) => { console.log(err); if(this.apiService.isSSO === true){ this.notificationService.showError('User not found'); } else{ this.notificationService.showError('Invalid Login-ID or Password'); } this.loadingPanel.ShowLoadingPanel = false; }, () => { const jwtHelper = new JwtHelperService(); //Remove Pending Job // this.userService.subject2.next(this._wfmovementTrans); const user = jwtHelper.decodeToken(localStorage.getItem('token')); ApiService.PAYROLLTYPEID = parseInt(user.PayrollTypeID,10); ApiService.USERTYPE = parseInt(user.UserType,10); if (user.ChangePasswordAtNextLogon === 'True') { localStorage.removeItem('menuList'); this.auth.menuEvent.emit(false); this.loadingPanel.ShowLoadingPanel = false; this.router.navigate(['/authentication/change-password']); } else { this.userService.GetRolePermissionbyUserID().subscribe( (menu: any) => { localStorage.setItem('menuList', JSON.stringify(menu)); this.router.navigate(['/']); }, (errmenu: any) => { this.notificationService.showError(errmenu.error); this.loadingPanel.ShowLoadingPanel = false; }, () => { this.loadingPanel.ShowLoadingPanel = false; this.appMain.IsSelfService(); this.loadBookmark(); this.auth.menuEvent.emit(true); } ); } this.showModal = false; } ); } loadBookmark() { this.userService.getBookmarks() .subscribe( (resp: any) => { if (resp != undefined) { this.menuService.bookMarkpages = resp; } }, (x) => { }, () => { localStorage.removeItem('bookmark'); localStorage.setItem('bookmark', JSON.stringify(this.menuService.bookMarkpages)); // console.log(this.bookmarks); //localStorage.setItem('bookmark', JSON.stringify(this.bookmarks)); //this.authService.subject.next(this.bookmarks); /*let menu = JSON.parse(localStorage.getItem('menuList')) .map(x => x.items) .flat(); const flatMenu = menu.filter(x => x.routerLink === '' && x.items !== null).flatMap(x => x.items); const menuToRemove = menu.filter(x => x.routerLink === '' && x.items !== null); menu = menu.filter(x => !menuToRemove.includes(x)); menu = [...menu, ...flatMenu];*/ }); } //loadPendingJobs() { // this.wfService.getPendingJob(0).subscribe( // (resp) => { // this._wfmovementTrans = resp; // }, // () => { // }, // () => { // localStorage.setItem('pendingjobs', JSON.stringify(this._wfmovementTrans)); // this.authService.subject2.next(this._wfmovementTrans); // }, // ); //} onForgotPassword() { localStorage.removeItem('token'); this.router.navigate(['/forgot-password']); } }