Sync Integ to Master
[sdc.git] / catalog-ui / src / app / view-models / admin-dashboard / user-management / user-management-view-model.ts
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 'use strict';
22 import * as _ from "lodash";
23 import {ModalsHandler} from "app/utils";
24 import {User, IUserProperties, IUser, IAppConfigurtaion} from "app/models";
25 import {UserService} from "../../../ng2/services/user.service";
26
27 interface IUserManagementViewModelScope extends ng.IScope {
28     sdcConfig:IAppConfigurtaion;
29     usersList:Array<IUserProperties>;
30     isLoading:boolean;
31     isNewUser:boolean;
32     sortBy:string;
33     reverse:boolean;
34     tableHeadersList:any;
35     roles:Array<string>;
36     newUser:IUser;
37     currentUser:IUserProperties;
38     userIdValidationPattern:RegExp;
39     editForm:ng.IFormController;
40     getAllUsers():void;
41     editUserRole(user:IUserProperties);
42     sort(sortBy:string):void;
43     createUser():void;
44     deleteUser(userId:string):void;
45     onEditUserPressed(user:IUserProperties):void;
46     saveUserChanges(user:IUserProperties):void;
47     getTitle(role:string):string;
48     clearForm():void;
49
50 }
51
52
53 export class UserManagementViewModel {
54     static '$inject' = [
55         '$scope',
56         'sdcConfig',
57         'UserServiceNg2',
58         'UserIdValidationPattern',
59         '$filter',
60         'ModalsHandler'
61     ];
62
63     constructor(private $scope:IUserManagementViewModelScope,
64                 private sdcConfig:IAppConfigurtaion,
65                 private userService:UserService,
66                 private UserIdValidationPattern:RegExp,
67                 private $filter:ng.IFilterService,
68                 private ModalsHandler:ModalsHandler) {
69
70         this.initScope();
71
72     }
73
74
75     private getAllUsers = ():void => {
76         this.$scope.isLoading = true;
77
78         let onError = (response) => {
79             this.$scope.isLoading = false;
80             console.info('onFaild', response);
81         };
82         let onSuccess = (response:Array<IUserProperties>) => {
83             this.$scope.usersList = response;
84             _.forEach(this.$scope.usersList, (user:any, i:number)=> {
85                 user.index = i;
86             });
87             this.$scope.isLoading = false;
88         };
89         this.userService.getAllUsers().subscribe(onSuccess, onError);
90     };
91
92     private updateUserFilterTerm = (user:IUserProperties):void => {
93         user.filterTerm = user.firstName + ' ' + user.lastName + ' ' + user.userId + ' ' + user.email + ' ' + user.role + ' ' + this.$filter('date')(user.lastLoginTime, "MM/dd/yyyy");
94     };
95
96     private initScope = ():void => {
97         let self = this;
98
99         this.$scope.tableHeadersList = [{title: "First Name", property: 'firstName'}, {
100             title: "Last Name",
101             property: 'lastName'
102         },
103             {
104                 title: this.$filter('translate')("USER_MANAGEMENT_TABLE_HEADER_USER_ID"),
105                 property: 'userId'
106             }, {title: "Email", property: 'email'}, {title: "Role", property: 'role'}, {
107                 title: "Last Active",
108                 property: 'lastLoginTime'
109             }];
110         this.$scope.userIdValidationPattern = this.UserIdValidationPattern;
111         this.$scope.sortBy = 'lastLoginTime';
112         this.$scope.reverse = false;
113         this.$scope.roles = this.sdcConfig.roles;
114         this.$scope.isNewUser = false;
115         this.$scope.currentUser = this.userService.getLoggedinUser();
116         this.getAllUsers();
117
118         let userInfo:IUserProperties = <IUserProperties>{};
119         this.$scope.newUser = new User(userInfo);
120
121         this.$scope.sort = (sortBy:string):void => {//default sort by descending last update. default for alphabetical = ascending
122             this.$scope.isNewUser = false;
123             this.$scope.reverse = (this.$scope.sortBy === sortBy) ? ( !this.$scope.reverse) : this.$scope.reverse = false;
124             this.$scope.sortBy = sortBy;
125         };
126
127         this.$scope.createUser = ():void => {
128
129             let onError = (response) => {
130                 this.$scope.isLoading = false;
131                 console.info('onFaild', response);
132             };
133
134             let onSuccess = (response:IUserProperties) => {
135                 this.$scope.newUser.userInfo.lastLoginTime = "0";
136                 this.$scope.newUser.userInfo.status = response.status;
137                 this.updateUserFilterTerm(this.$scope.newUser.userInfo);
138                 this.$scope.usersList.push(this.$scope.newUser.userInfo);
139                 this.$scope.isNewUser = true;
140                 this.$scope.sortBy = null;
141                 this.$scope.reverse = true;
142                 this.$scope.isLoading = false;
143                 this.$scope.newUser = new User(null);
144                 this.$scope.editForm.$setPristine();
145                 let _self = this;
146                 setTimeout(function () {
147                     _self.$scope.isNewUser = false;
148                 }, 7000);
149             };
150             this.userService.createUser({
151                 userId: this.$scope.newUser.userInfo.userId,
152                 role: this.$scope.newUser.userInfo.role
153             }).subscribe(onSuccess, onError);
154         };
155
156
157         this.$scope.onEditUserPressed = (user:IUserProperties):void => {
158             user.isInEditMode = true;
159             user.tempRole = user.role;
160         };
161
162         this.$scope.editUserRole = (user:IUserProperties):void => {
163             let roleBeforeUpdate:string = user.role;
164             user.role = user.tempRole;
165
166             let onError = (response) => {
167                 this.$scope.isLoading = false;
168                 user.role = roleBeforeUpdate;
169                 console.info('onFaild', response);
170             };
171             let onSuccess = (response:any) => {
172                 this.$scope.isLoading = false;
173                 user.tempRole = user.role;
174                 this.updateUserFilterTerm(user);
175             };
176
177             this.userService.editUserRole(user.userId, user.role).subscribe(onSuccess, onError);
178         };
179
180         this.$scope.saveUserChanges = (user:IUserProperties):void => {
181             if (user.tempRole != user.role) {
182                 this.$scope.editUserRole(user)
183             }
184             user.isInEditMode = false;
185         };
186
187         this.$scope.deleteUser = (userId:string):void => {
188
189             let onOk = ():void => {
190                 this.$scope.isLoading = true;
191
192                 let onError = (response):void => {
193                     this.$scope.isLoading = false;
194                     console.info('onFaild', response);
195                 };
196
197                 let onSuccess = (response:any):void => {
198                     _.remove(this.$scope.usersList, {userId: userId});
199                     this.$scope.isLoading = false;
200                 };
201                 this.userService.deleteUser(userId).subscribe(onSuccess, onError);
202             };
203
204             let title:string = this.$filter('translate')("USER_MANAGEMENT_VIEW_DELETE_MODAL_TITLE");
205             let message:string = this.$filter('translate')("USER_MANAGEMENT_VIEW_DELETE_MODAL_TEXT");
206             this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk);
207         };
208
209         this.$scope.getTitle = (role:string):string => {
210             return role.toLowerCase().replace('governor', 'governance_Rep').replace('_', ' ');
211         };
212
213         this.$scope.clearForm = ():void => {
214             if (!this.$scope.editForm['contactId'].$viewValue && !this.$scope.editForm['role'].$viewValue) {
215                 this.$scope.editForm.$setPristine();
216             }
217             //if(this.$scope.editForm['contactId'].$viewValue === '' && this.$scope.editForm['role'].$viewValue){
218             //    this.$scope.editForm.$setPristine();
219             //}
220         };
221     }
222 }