Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get Personal info according to the user role #1579

Merged
merged 13 commits into from
Aug 24, 2022
11 changes: 6 additions & 5 deletions src/app/shared/enum/role.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,19 @@ export enum Role {
parent = 'parent',
unauthorized = 'unauthorized',
techAdmin = 'techadmin',
ministryadmin= 'ministryadmin',
ProviderDeputy = 'ProviderDeputy',
ProviderAdmin = 'ProviderAdmin',
all = 'all',
child = 'child',
None = 'None'
}

export enum cardType {
provider = 'provider',
parent = 'parent',
child = 'child',
user = 'user',
export enum PersonalInfoRole {
provider = 'Provider',
parent = 'Parent',
techadmin = 'TechAdmin',
ministryadmin = 'MinistryAdmin',
}

export enum RoleLinks {
Expand Down
8 changes: 7 additions & 1 deletion src/app/shared/models/user.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,18 @@ export class User implements Person {
email?: string;
phoneNumber?: string;
role: string;
dateOfBirth: string;

constructor(info, id: string) {
this.firstName = info.firstName;
this.lastName = info.lastName;
this.middleName = info.middleName;
this.gender = info.gender;
if(info.gender){
this.gender = info.gender;
}
if(info.dateOfBirth){
this.dateOfBirth = info.dateOfBirth;
}
this.phoneNumber = info.phoneNumber;
this.id = id;
}
Expand Down
8 changes: 8 additions & 0 deletions src/app/shared/pipes/join.pipe.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { JoinPipe } from './join.pipe';

describe('JoinPipe', () => {
it('create an instance', () => {
const pipe = new JoinPipe();
expect(pipe).toBeTruthy();
});
});
10 changes: 10 additions & 0 deletions src/app/shared/pipes/join.pipe.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
name: 'join',
})
export class JoinPipe implements PipeTransform {
transform(input: Array<any>, propertyName: string, sep = ', '): string {
return input.map(value => value[propertyName]).join(sep);
}
}
22 changes: 12 additions & 10 deletions src/app/shared/services/user/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,28 @@ import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { User } from '../../models/user.model';
import { map } from 'rxjs/operators';
import { PersonalInfoRole } from '../../enum/role';

@Injectable({ providedIn: 'root' })
export class UserService {

constructor(private http: HttpClient) { }
constructor(private http: HttpClient) {}

/**
* gets user data
* @return object of type User
* This method get Personal Info according to teh user role
* @param userRole: PersonalInfoRole
* @return user: User
*/
getUserById(id): Observable<User> {
return this.http.get<User>(`/api/v1/User/GetUserById/${id}`);
getPersonalInfo(userRole: PersonalInfoRole): Observable<User> {
return this.http.get<User>(`/api/v1/${userRole}/GetPersonalInfo`);
}

/**
* This method update Provider
* This method update Personal Info according to teh user role
* @param userRole: PersonalInfoRole
* @param user: User
* @return user: User
*/
updateUser(user: User): Observable<object> {
return this.http.put('/api/v1/User/Update', user);
updatePersonalInfo(userRole: PersonalInfoRole, user: User): Observable<User> {
return this.http.put<User>(`/api/v1/${userRole}/UpdatePersonalInfo`, user);
}
}
5 changes: 4 additions & 1 deletion src/app/shared/shared.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ import { AchievementCardComponent } from '../shell/details/details-tabs/achievem
import { InstitutionHierarchyComponent } from './components/institution-hierarchy/institution-hierarchy.component';
import { StarsComponent } from '../shell/details/details-tabs/reviews/stars/stars.component';
import { ErrorPageComponent } from './components/error-page/error-page.component';
import { JoinPipe } from './pipes/join.pipe';

@NgModule({
declarations: [
Expand Down Expand Up @@ -116,6 +117,7 @@ import { ErrorPageComponent } from './components/error-page/error-page.component
ErrorPageComponent,
AchievementCardComponent,
StarsComponent,
JoinPipe,
],

imports: [
Expand Down Expand Up @@ -181,7 +183,8 @@ import { ErrorPageComponent } from './components/error-page/error-page.component
ImageCropperModalComponent,
InfoFormComponent,
AchievementCardComponent,
StarsComponent
StarsComponent,
JoinPipe
]
})
export class SharedModule { }
20 changes: 20 additions & 0 deletions src/app/shared/store/registration.actions.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import { HttpErrorResponse, HttpResponse } from "@angular/common/http";
import { PersonalInfoRole } from "../enum/role";
import { User } from "../models/user.model";

export class Login {
static readonly type = '[user] logins';
constructor(public payload: boolean) { }
Expand Down Expand Up @@ -29,3 +33,19 @@ export class RegisterUser {
static readonly type = '[user] change register status';
constructor() { }
}
export class UpdateUser {
static readonly type = '[user] update User';
constructor(public userRole: PersonalInfoRole, public user: User) { }
}
export class OnUpdateUserFail {
static readonly type = '[user] update User fail';
constructor(public payload: HttpErrorResponse) { }
}
export class OnUpdateUserSuccess {
static readonly type = '[user] update User success';
constructor(public payload: PersonalInfoRole) { }
}
export class GetUserPersonalInfo {
static readonly type = '[user] get User';
constructor(public userRole: PersonalInfoRole) { }
}
106 changes: 66 additions & 40 deletions src/app/shared/store/registration.state.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { PersonalInfoRole } from './../enum/role';
import { Injectable } from '@angular/core';
import { State, Action, StateContext, Selector } from '@ngxs/store';
import {
Expand All @@ -7,6 +8,10 @@ import {
OnAuthFail,
CheckRegistration,
GetProfile,
OnUpdateUserSuccess,
UpdateUser,
OnUpdateUserFail,
GetUserPersonalInfo,
} from './registration.actions';
import { OidcSecurityService } from 'angular-auth-oidc-client';
import jwt_decode from 'jwt-decode';
Expand All @@ -16,14 +21,17 @@ import { ProviderService } from '../services/provider/provider.service';
import { ParentService } from '../services/parent/parent.service';
import { Parent } from '../models/parent.model';
import { TechAdmin } from '../models/techAdmin.model';
import { tap } from 'rxjs/operators';
import { catchError, tap } from 'rxjs/operators';
import { Provider } from '../models/provider.model';
import { Router } from '@angular/router';
import { Role } from '../enum/role';
import { UserService } from '../services/user/user.service';
import { Observable } from 'rxjs';
import { Observable, of, throwError } from 'rxjs';
import { TechAdminService } from '../services/tech-admin/tech-admin.service';
import { SignalRService } from '../services/signalR/signal-r.service';
import { MarkFormDirty, ShowMessageBar } from './app.actions';
import { HttpErrorResponse } from '@angular/common/http';

export interface RegistrationStateModel {
isAuthorized: boolean;
isLoading: boolean;
Expand All @@ -45,7 +53,7 @@ export interface RegistrationStateModel {
parent: undefined,
techAdmin: undefined,
role: Role.unauthorized,
subrole: null
subrole: null,
},
})
@Injectable()
Expand All @@ -55,8 +63,8 @@ export class RegistrationState {
return state.isAuthorized;
}
@Selector()
static isLoading(state: RegistrationStateModel): boolean {
return state.isLoading
static isLoading(state: RegistrationStateModel): boolean {
return state.isLoading;
}
@Selector()
static isRegistered(state: RegistrationStateModel): boolean {
Expand Down Expand Up @@ -121,29 +129,22 @@ export class RegistrationState {
}

@Action(CheckAuth)
CheckAuth({
patchState,
dispatch,
}: StateContext<RegistrationStateModel>): void {
CheckAuth({ patchState, dispatch }: StateContext<RegistrationStateModel>): void {
patchState({ isLoading: true });
this.oidcSecurityService.checkAuth().subscribe((auth) => {
console.log('is authenticated', auth);
this.oidcSecurityService.checkAuth().subscribe((auth: boolean) => {
patchState({ isAuthorized: auth });
if (auth) {
if (auth) {
const token = jwt_decode(this.oidcSecurityService.getToken());
const id = token['sub'];
const subrole = token['subrole'];

this.userService.getUserById(id).subscribe((user) => {
patchState({ subrole: subrole , user: user, isLoading: false });
dispatch(new CheckRegistration());
});
const role = token['role'];
patchState({ subrole, role });

dispatch(new GetUserPersonalInfo(PersonalInfoRole[role])).subscribe(() => dispatch(new CheckRegistration()));
} else {
patchState({ isLoading: false });
patchState({ role: Role.unauthorized });
patchState({ role: Role.unauthorized, isLoading: false });
}
});
}
}

@Action(OnAuthFail)
onAuthFail(): void {
Expand All @@ -155,16 +156,11 @@ export class RegistrationState {
}

@Action(CheckRegistration)
checkRegistration({
dispatch,
getState,
}: StateContext<RegistrationStateModel>): void {
checkRegistration({ dispatch, getState }: StateContext<RegistrationStateModel>): void {
const state = getState();
this.signalRservice.startConnection();

state.user.isRegistered
? dispatch(new GetProfile())
: this.router.navigate(['/create-provider', '']);
state.user.isRegistered ? dispatch(new GetProfile()) : this.router.navigate(['/create-provider', '']);
}

@Action(GetProfile)
Expand All @@ -174,24 +170,54 @@ export class RegistrationState {
): Observable<Parent> | Observable<Provider> {
const state = getState();
patchState({ role: state.user.role as Role });

switch (state.user.role) {
case Role.parent:
return this.parentService
.getProfile()
.pipe(tap((parent: Parent) => patchState({ parent: parent })));
return this.parentService.getProfile().pipe(tap((parent: Parent) => patchState({ parent: parent })));
case Role.techAdmin:
return this.techAdminService
.getProfile()
.pipe(
tap((techAdmin: TechAdmin) => patchState({ techAdmin: techAdmin }))
);
.pipe(tap((techAdmin: TechAdmin) => patchState({ techAdmin: techAdmin })));
default:
return this.providerService
.getProfile()
.pipe(
tap((provider: Provider) => patchState({ provider: provider }))
);
return this.providerService.getProfile().pipe(tap((provider: Provider) => patchState({ provider: provider })));
}
}

@Action(GetUserPersonalInfo)
getUserPersonalInfo(
{ patchState }: StateContext<RegistrationStateModel>,
{ userRole }: GetUserPersonalInfo
): Observable<User> {
patchState({ isLoading: true });
return this.userService
.getPersonalInfo(userRole)
.pipe(tap((user: User) => patchState({ user: user, isLoading: false })));
}

@Action(UpdateUser)
updateUser({ dispatch }: StateContext<RegistrationStateModel>, { userRole, user }: UpdateUser): Observable<object> {
return this.userService.updatePersonalInfo(userRole, user).pipe(
tap((res: User) => dispatch(new OnUpdateUserSuccess(userRole))),
catchError((error: HttpErrorResponse) => of(dispatch(new OnUpdateUserFail(error))))
);
}

@Action(OnUpdateUserFail)
onUpdateUserFail({ dispatch }: StateContext<RegistrationStateModel>, { payload }: OnUpdateUserFail): void {
throwError(payload);
dispatch(new ShowMessageBar({ message: 'На жаль виникла помилка', type: 'error' }));
}

@Action(OnUpdateUserSuccess)
onUpdateUserSuccess({ dispatch }: StateContext<RegistrationStateModel>, { payload }: OnUpdateUserSuccess): void {
dispatch([
new MarkFormDirty(false),
new GetUserPersonalInfo(payload),
new ShowMessageBar({
message: 'Особиста інформація успішно відредагована',
type: 'success',
}),
]);
this.router.navigate(['/personal-cabinet/config']);
}
}
12 changes: 0 additions & 12 deletions src/app/shared/store/user.actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,18 +246,6 @@ export class OnUpdateProviderSuccess {
static readonly type = '[user] update Provider success';
constructor(public payload) { }
}
export class UpdateUser {
static readonly type = '[user] update User';
constructor(public payload: User) { }
}
export class OnUpdateUserFail {
static readonly type = '[user] update User fail';
constructor(public payload: HttpErrorResponse) { }
}
export class OnUpdateUserSuccess {
static readonly type = '[user] update User success';
constructor(public payload) { }
}
export class UpdateApplication {
static readonly type = '[user] update Application';
constructor(public payload: ApplicationUpdate) { }
Expand Down
Loading