import { Injectable, EventEmitter } from '@angular/core'; import { BehaviorSubject, of, Subject, Subscription } from 'rxjs'; import { GraphQLService } from '../utils/graphql.service'; import { Utils } from '../utils/utils'; import { CommonQuery } from './common.query'; import { forEach } from 'lodash'; import { ToastService } from '../components/generic/toast/toast.service'; import { TOAST_DURATION } from '../../lib/utils/global.const'; import { Router } from '@angular/router'; const clone = require('rfdc')(); @Injectable({ providedIn: 'root', }) export class UserConfigService { private userConfig = { userId: '', firstName: '', lastName: '', defaultApp: '', email: '', locale: '', applications: [], }; private userConfig$: Subscription; private applicationConfig = new Subject(); private config = new BehaviorSubject({}); private dpconfig = new BehaviorSubject({}); private headerconfig = new BehaviorSubject({}); private landingconfig = new BehaviorSubject({}); systemDown = new Subject(); cast = this.config.asObservable(); systemDownCast = this.systemDown.asObservable(); applicationcast = this.applicationConfig.asObservable(); headercast = this.headerconfig.asObservable(); refreshEmitter: EventEmitter = new EventEmitter(); landingCast = this.landingconfig.asObservable(); currentApp: string; iopUrl = new BehaviorSubject(''); iopUrl$ = this.iopUrl.asObservable(); timer; constructor(private graphQL: GraphQLService, private toastService: ToastService, private router: Router) {} getAppConfig(appName = '') { this.currentApp = appName; if (this.userConfig['applications'].length > 0) { this.getApplicationSpecificConfig(appName); } else { this.loadUserConfig(appName); } } getUserConfig() { const { userId, firstName, lastName, defaultApp, email, locale } = this.userConfig; return { userId, firstName, lastName, defaultApp, email, locale }; } refreshPage(data) { this.refreshEmitter.emit(data); } getApplicationsForUser() { const { applications = [] } = this.userConfig; return applications; } setMockUserConfig(config) { this.userConfig = config; } getApplicationNameBasedOnRoute() { const urlString = this.router.url.split('/').join(''); if (urlString.includes('demand-forecasting')) { return 'df'; } else if (urlString.includes('predictive-ordering')) { return 'dpo'; } else if (urlString.includes('data-management')) { return 'dmgmt'; } else if (urlString.includes('trade-promotion')) { return 'tpo'; } else if (urlString.includes('collaborative-planning')) { return 'cp'; } else if (urlString.includes('collaborative-planningdriver-analysis')) { return 'cp_mvp'; } else if (urlString.includes('control-center')) { return 'cc'; } } private loadUserConfig(appName) { localStorage.removeItem("espUserToken"); // clear user token as we don't need to pass for user config this.userConfig$ = this.graphQL.query(CommonQuery.getUserConfig()).subscribe( response => { this.userConfig$?.unsubscribe(); if (response && response['data'] && response['data']['userConfiguration'] && response['data']['userConfiguration']['error']) { const toastConfig = { message: response['data']['userConfiguration']['error'], onClose: this.closeToast.bind(this), }; this.toastService.showResponseToast('error', toastConfig); setTimeout(() => { this.toastService.deleteToasts(); }, TOAST_DURATION); Utils.showError('getAppConfig()', response['data']['userConfiguration']['error']); if (window.location.href.indexOf('localhost') === -1) { window.location.href = '/home'; } } else if (response && response['data'] && response['data']['userConfiguration'] && response['data']['userConfiguration']['user']) { this.userConfig = clone(response['data']['userConfiguration']['user']); // set espUserToken if (this.userConfig["espUserToken"]) { localStorage.setItem("espUserToken", this.userConfig["espUserToken"]); } this.customDebounce(this.addAuditLogs, 1000, [appName, 'login']); this.getApplicationSpecificConfig(appName); this.handleDefaultApplication(appName, this.userConfig.defaultApp); } }, error => { Utils.showError('getAppConfig()', error); } ); } private handleDefaultApplication(appName, defaultApp) { const defaultAppConfig = this.userConfig['applications'].filter(application => application.applicationName === defaultApp)[0]; if(defaultAppConfig?.configJson?.isDirectNavigation && appName === 'home') { window.location.href = `/${defaultApp}`; } else { this.getApplicationSpecificConfig(appName); this.landingconfig.next(this.userConfig); } } private getShortName() { const { firstName, lastName } = this.userConfig; return `${firstName.charAt(0)}${lastName.charAt(0)}`; } private getFullName() { const { firstName, lastName } = this.userConfig; return firstName + ' ' + lastName; } private getUserId() { const { userId } = this.userConfig; return userId; } private getApplicationSpecificConfig(appName) { let config = {}; if (appName === '') { appName = this.userConfig.defaultApp; } forEach(this.userConfig['applications'], appConfig => { appConfig['i18n']['translations']['header'] = appConfig['i18n']['translations'][appConfig.applicationName]; if (appName === appConfig.applicationName) { config = appConfig; config['shortUserName'] = this.getShortName(); config['userFullName'] = this.getFullName(); config['userId'] = this.getUserId(); } }); if (config['shortUserName']) { this.config.next(config); this.headerconfig.next(config); this.applicationConfig.next({userConfig:this.userConfig,appId:config['applicationId']}); } } closeToast() { this.toastService.deleteToasts(); } addAuditLogs(appName, eventType) { const queryParams = { applicationName: appName, applicationUrl: window.location.href, eventType, dataSource: "Table" } this.graphQL .mutate(CommonQuery.addAuditLogs(), queryParams) .subscribe( response => { if(localStorage.getItem('CONSOLE_EVENT_LOGGER') === 'true') { console.log(`LOGGER: ${queryParams.applicationName} | ${queryParams.eventType} `); } } ); } customDebounce(callback, wait: number, argument: any[]) { clearTimeout(this.timer); this.timer = setTimeout(() => callback.apply(this, argument), wait); } }