import { Injectable } from '@angular/core'; import { Store } from '@ngrx/store'; import { take, map, withLatestFrom, filter, switchMap } from 'rxjs/operators'; import { ROLE_SUPER_ADMIN, ROLE_SYSTEM_ADMIN, UserProfileModel, } from '../models'; import { Observable } from 'rxjs'; import { AngularFireMessaging } from '@angular/fire/compat/messaging'; import { MwAuthService } from './auth.service'; import { MwUserApiService } from './user-api.service'; import * as userReducers from '../@store/user.reducer'; import * as userActions from '../@store/user.actions'; import { environment } from 'projects/core/src//environment'; @Injectable() export class MwUserService { static nextId = 0; id: string = `${environment.clientId}-${MwUserService.nextId++}`; constructor( private readonly store: Store, private readonly userApiService: MwUserApiService, private readonly afMessaging: AngularFireMessaging, private readonly authService: MwAuthService ) {} get userLanguage$(): Observable { return this.store.select(userReducers.getUserLanguage); } get userProfile$(): Observable { return this.authService.loggedIn$.pipe( filter((isLoggedIn) => isLoggedIn), switchMap(() => this.authService.userData$), filter((userData) => !!userData), switchMap(() => this.store.select(userReducers.getUserProfile)) ); } get isSuperAdmin$(): Observable { return this.userProfile$.pipe( map( (userProfile) => userProfile?.roles.findIndex((t) => t === ROLE_SUPER_ADMIN) !== -1 ) ); } get messages$(): Observable { return this.afMessaging.messages.pipe( withLatestFrom(this.userProfile$), filter(([message, userProfile]) => { const data = (message as any)?.data; const companyNotMatch = data && data.CompanyId && Number(data.CompanyId) !== userProfile?.companyId; const userNotMatch = data && data.UserId && Number(data.UserId) !== userProfile?.userId; if (companyNotMatch || userNotMatch) { return false; } return true; }), map(([message]) => message) ); } get isSystemAdmin$(): Observable { return ( this.isSuperAdmin$ || this.userProfile$.pipe( map( (userProfile) => userProfile?.roles.findIndex((t) => t === ROLE_SYSTEM_ADMIN) !== -1 ) ) ); } changeLanguage(language: string): void { this.store.dispatch(userActions.changeLanguage({ userLanguage: language })); } changeCompany(): void { this.store.dispatch( userActions.changeCompany({ selectedCompanyId: undefined }) ); } setActiveCompanyById(companyId: number, language?: string): void { this.userApiService .getCompany(companyId) .pipe(take(1)) .subscribe((company) => this.store.dispatch( userActions.setActiveCompany({ company, hasManyCompanies: false, language, }) ) ); } }