import { hasAccess } from './../@store/user.reducer'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { CompanyViewModel, UserProfileViewModel } from '../models'; import { MwHttpService } from 'projects/core/src//http'; import { catchError, map, tap } from 'rxjs/operators'; import { environment } from 'projects/core/src//environment'; import { NotificationTokenRegisterViewModel } from '../models/notification-token-view.model'; import { MwProgressBarService } from 'projects/core/src//services'; import { LanguageChangeRequest } from '../models/language-change.model'; @Injectable() export class MwUserApiService { static nextId = 0; id: string = `${environment.clientId}-${MwUserApiService.nextId++}`; constructor( private readonly http: MwHttpService, private readonly progressBarService: MwProgressBarService ) {} getCompanies(companyId?: number): Observable { const localCompanyId = companyId || 0; this.progressBarService.show(); const query = localCompanyId > 0 ? `?$filter=CompanyId eq ${companyId}` : ''; return this.http .authGet('/integration/v1/user/companies' + query) .pipe(tap(() => this.progressBarService.hide())); } getCompany(id: number): Observable { return this.http .authGet( `/integration/v1/user/companies?$filter=CompanyId eq ${id}` ) .pipe(map((companies) => companies[0] || null)); } getProfile(companyId?: number): Observable { const localCompanyId = companyId || 0; const url = `/integration/v1/user/companies/${localCompanyId}/profile`; return this.http .authPost(url, { ignoreNotifyStatusCodes: [405], body: { actions: [] }, }) .pipe(catchError(() => this.http.authGet(url))); } registerFcmToken( token: string ): Observable { return this.http.authPost( `/notification/v1/Companies/{companyId}/register`, { body: { token }, ignoreNotifyStatusCodes: [404], } ); } hasAccess(actions: string[]): Observable> { return this.http .authPost>(`/user/access`, { body: actions, ignoreNotifyStatusCodes: [404], }) .pipe(catchError(() => this.hasAccessFallback(actions))); } hasAccessFallback(actions: string[]): Observable> { const result = this.http .authPost<{ actions: string[] }>( `/integration/v1/user/companies/{companyId}/profile`, { body: { actions } } ) .pipe( map((data) => actions.reduce( (prev, curr) => ({ ...prev, [curr]: data.actions.findIndex((t) => t === curr) !== -1, }), {} ) ) ); return result; } changeLanguage(language: string): Observable { const url = `/integration/v1/Companies/{companyId}/Users/preference/language`; return this.http.authPost(url, { body: { language }, }); } }