2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
8 * Unless otherwise specified, all software contained herein is licensed
9 * under the Apache License, Version 2.0 (the "License");
10 * you may not use this software except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * Unless otherwise specified, all documentation contained herein is licensed
22 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23 * you may not use this documentation except in compliance with the License.
24 * You may obtain a copy of the License at
26 * https://creativecommons.org/licenses/by/4.0/
28 * Unless required by applicable law or agreed to in writing, documentation
29 * distributed under the License is distributed on an "AS IS" BASIS,
30 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31 * See the License for the specific language governing permissions and
32 * limitations under the License.
34 * ============LICENSE_END============================================
39 * bulk user upload controller
43 class BulkUserModalCtrl {
44 constructor($scope, $log, $filter, $q, usersService, applicationsService, confirmBoxService, functionalMenuService, ngDialog,$modal) {
46 // Set to true for copious console output
48 // Roles fetched from app service
49 var appRolesResult = [];
50 // Users fetched from user service
51 var userCheckResult = [];
52 // Requests for user-role assignment built by validator
53 var appUserRolesRequest = [];
57 $log.debug('BulkUserModalCtrl::init');
58 // Angular insists on this.
59 $scope.fileModel = {};
60 // Model for drop-down
61 $scope.adminApps = [];
62 // Enable modal controls
64 this.fileSelected = false;
66 // Flag that indicates background work is proceeding
67 $scope.isProcessing = true;
69 $scope.isProcessedRecords = false;
71 // Load user's admin applications
72 applicationsService.getAdminApps().promise().then(apps => {
74 $log.debug('BulkUserModalCtrl::init: getAdminApps returned' + JSON.stringify(apps));
75 if (!apps || typeof(apps) != 'object') {
76 $log.error('BulkUserModalCtrl::init: getAdminApps returned unexpected data');
80 $log.debug('BulkUserModalCtrl::init: admin apps length is ', apps.length);
82 // Sort app names and populate the drop-down model
83 let sortedApps = apps.sort(getSortOrder('name', true));
84 for (let i = 0; i < sortedApps.length; ++i) {
85 $scope.adminApps.push({
88 value: sortedApps[i].name,
89 title: sortedApps[i].name
92 // Pick the first one in the list
93 $scope.selectedApplication = $scope.adminApps[0];
95 $scope.isProcessing = false;
96 $scope.isProcessedRecords = false;
98 $log.error('BulkUserModalCtrl::init: getAdminApps threw', err);
99 $scope.isProcessing = false;
100 $scope.isProcessedRecords = false;
105 // Answers a function that compares properties with the specified name.
106 let getSortOrder = (prop, foldCase) => {
107 return function(a, b) {
108 let aProp = foldCase ? a[prop].toLowerCase() : a[prop];
109 let bProp = foldCase ? b[prop].toLowerCase() : b[prop];
112 else if (aProp < bProp)
119 //This is a fix for dropdown selection, due to b2b dropdown only update value field
120 $scope.$watch('selectedApplication.value', (newVal, oldVal) => {
121 for(var i=0;i<$scope.adminApps.length;i++){
122 if($scope.adminApps[i].value==newVal){
123 $scope.selectedApplication=angular.copy($scope.adminApps[i]);;
128 // Invoked when user picks an app on the drop-down.
129 $scope.appSelected = () => {
131 $log.debug('BulkUserModalCtrl::appSelected: selectedApplication.id is ' + $scope.selectedApplication.id);
132 this.appSelected = true;
135 // Caches the file name supplied by the event handler.
136 $scope.fileChangeHandler = (event, files) => {
137 this.fileSelected = true;
138 this.fileToRead = files[0];
140 $log.debug("BulkUserModalCtrl::fileChangeHandler: file is ", this.fileToRead);
141 }; // file change handler
144 * Reads the contents of the file, calls portal endpoints
145 * to validate roles, userIds and existing role assignments;
146 * ultimately builds array of requests to be sent.
147 * Creates scope variable with input file contents for
148 * communication with functions.
150 * This function performs a synchronous step-by-step process
151 * using asynchronous promises. The code could all be inline
152 * here but the nesting becomes unwieldy.
154 $scope.readValidateFile = () => {
155 $scope.isProcessing = true;
156 $scope.conformMsg = '';
157 $scope.isProcessedRecords = true;
158 $scope.progressMsg = 'Reading upload file..';
159 var reader = new FileReader();
160 reader.onload = function(event) {
161 $scope.uploadFile = $filter('csvToObj')(reader.result);
163 $log.debug('BulkUserModalCtrl::readValidateFile onload: data length is ' + $scope.uploadFile.length);
164 // sort input by orgUserId
165 $scope.uploadFile.sort(getSortOrder('orgUserId', true));
167 let appid = $scope.selectedApplication.id;
168 $scope.progressMsg = 'Fetching application roles..';
169 functionalMenuService.getManagedRolesMenu(appid).then(function (rolesObj) {
171 $log.debug("BulkUserModalCtrl::readValidateFile: managedRolesMenu returned " + JSON.stringify(rolesObj));
172 appRolesResult = rolesObj;
173 $scope.progressMsg = 'Validating application roles..';
174 $scope.verifyRoles();
176 let userPromises = $scope.buildUserChecks();
178 $log.debug('BulkUserModalCtrl::readValidateFile: userPromises length is ' + userPromises.length);
179 $scope.progressMsg = 'Validating Org Users..';
180 $q.all(userPromises).then(function() {
182 $log.debug('BulkUserModalCtrl::readValidateFile: userCheckResult length is ' + userCheckResult.length);
183 $scope.evalUserCheckResults();
185 let appPromises = $scope.buildAppRoleChecks();
187 $log.debug('BulkUserModalCtrl::readValidateFile: appPromises length is ' + appPromises.length);
188 $scope.progressMsg = 'Querying application for user roles..';
189 $q.all(appPromises).then( function() {
191 $log.debug('BulkUserModalCtrl::readValidateFile: appUserRolesRequest length is ' + appUserRolesRequest.length);
192 $scope.evalAppRoleCheckResults();
194 // Re sort by line for the confirmation dialog
195 $scope.uploadFile.sort(getSortOrder('line', false));
196 // We're done, confirm box may show the table
198 $log.debug('BulkUserModalCtrl::readValidateFile inner-then ends');
199 $scope.progressMsg = 'Done.';
200 $scope.isProcessing = false;
201 $scope.isProcessedRecords = false;
204 $log.error('BulkUserModalCtrl::readValidateFile: failed retrieving user-app roles');
205 $scope.isProcessing = false;
206 $scope.isProcessedRecords = false;
208 ); // then of app promises
211 $log.error('BulkUserModalCtrl::readValidateFile: failed retrieving user info');
212 $scope.isProcessing = false;
213 $scope.isProcessedRecords = false;
215 ); // then of user promises
218 $log.error('BulkUserModalCtrl::readValidateFile: failed retrieving app role info');
219 $scope.isProcessing = false;
220 $scope.isProcessedRecords = false;
222 ); // then of role promise
226 // Invoke the reader on the selected file
227 reader.readAsText(this.fileToRead);
231 * Evaluates the result set returned by the app role service.
232 * Sets an uploadFile array element status if a role is not defined.
233 * Reads and writes scope variable uploadFile.
234 * Reads closure variable appRolesResult.
236 $scope.verifyRoles = () => {
238 $log.debug('BulkUserModalCtrl::verifyRoles: appRoles is ' + JSON.stringify(appRolesResult));
239 // check roles in upload file against defined app roles
240 $scope.uploadFile.forEach( function (uploadRow) {
241 // skip rows that already have a defined status: headers etc.
242 if (uploadRow.status) {
244 $log.debug('BulkUserModalCtrl::verifyRoles: skip row ' + uploadRow.line);
247 uploadRow.role = uploadRow.role.trim();
249 for (var i=0; i < appRolesResult.length; i++) {
250 if (uploadRow.role.toUpperCase() === appRolesResult[i].rolename.trim().toUpperCase()) {
252 $log.debug('BulkUserModalCtrl::verifyRoles: match on role ' + uploadRow.role);
259 $log.debug('BulkUserModalCtrl::verifyRoles: NO match on role ' + uploadRow.role);
260 uploadRow.status = 'Invalid role';
266 * Builds and returns an array of promises to invoke the
267 * searchUsers service for each unique Org User UID in the input.
268 * Reads and writes scope variable uploadFile, which must be sorted by Org User UID.
269 * The promise function writes to closure variable userCheckResult
271 $scope.buildUserChecks = () => {
273 $log.debug('BulkUserModalCtrl::buildUserChecks: uploadFile length is ' + $scope.uploadFile.length);
274 userCheckResult = [];
277 $scope.uploadFile.forEach(function (uploadRow) {
278 if (uploadRow.status) {
280 $log.debug('BulkUserModalCtrl::buildUserChecks: skip row ' + uploadRow.line);
283 // detect repeated UIDs
284 if (prevRow == null || prevRow.orgUserId.toLowerCase() !== uploadRow.orgUserId.toLowerCase()) {
286 $log.debug('BulkUserModalCtrl::buildUserChecks: create request for orgUserId ' + uploadRow.orgUserId);
287 let userPromise = usersService.searchUsers(uploadRow.orgUserId).promise().then( (usersList) => {
288 if (typeof usersList[0] !== "undefined") {
289 userCheckResult.push({
290 orgUserId: usersList[0].orgUserId,
291 firstName: usersList[0].firstName,
292 lastName: usersList[0].lastName,
293 jobTitle: usersList[0].jobTitle
299 $log.debug('BulkUserModalCtrl::buildUserChecks: searchUsers returned null');
302 $log.error('BulkUserModalCtrl::buildUserChecks: searchUsers failed ' + JSON.stringify(error));
304 promises.push(userPromise);
308 $log.debug('BulkUserModalCtrl::buildUserChecks: skip repeated orgUserId ' + uploadRow.orgUserId);
313 }; // buildUserChecks
316 * Evaluates the result set returned by the user service to set
317 * the uploadFile array element status if the user was not found.
318 * Reads and writes scope variable uploadFile.
319 * Reads closure variable userCheckResult.
321 $scope.evalUserCheckResults = () => {
323 $log.debug('BulkUserModalCtrl::evalUserCheckResult: uploadFile length is ' + $scope.uploadFile.length);
324 $scope.uploadFile.forEach(function (uploadRow) {
325 if (uploadRow.status) {
327 $log.debug('BulkUserModalCtrl::evalUserCheckResults: skip row ' + uploadRow.line);
330 let foundorgUserId = false;
331 userCheckResult.forEach(function(userItem) {
332 if (uploadRow.orgUserId.toLowerCase() === userItem.orgUserId.toLowerCase()) {
334 $log.debug('BulkUserModalCtrl::evalUserCheckResults: found orgUserId ' + uploadRow.orgUserId);
338 if (!foundorgUserId) {
340 $log.debug('BulkUserModalCtrl::evalUserCheckResults: NO match on orgUserId ' + uploadRow.orgUserId);
341 uploadRow.status = 'Invalid orgUserId';
344 }; // evalUserCheckResults
347 * Builds and returns an array of promises to invoke the getUserAppRoles
348 * service for each unique Org User in the input file.
349 * Each promise creates an update to be sent to the remote application
350 * with all role names.
351 * Reads scope variable uploadFile, which must be sorted by Org User.
352 * The promise function writes to closure variable appUserRolesRequest
354 $scope.buildAppRoleChecks = () => {
356 $log.debug('BulkUserModalCtrl::buildAppRoleChecks: uploadFile length is ' + $scope.uploadFile.length);
357 appUserRolesRequest = [];
358 let appId = $scope.selectedApplication.id;
361 $scope.uploadFile.forEach( function (uploadRow) {
362 if (uploadRow.status) {
364 $log.debug('BulkUserModalCtrl::buildAppRoleChecks: skip row ' + uploadRow.line);
367 // Because the input is sorted, generate only one request for each Org User
368 if (prevRow == null || prevRow.orgUserId.toLowerCase() !== uploadRow.orgUserId.toLowerCase()) {
370 $log.debug('BulkUserModalCtrl::buildAppRoleChecks: create request for orgUserId ' + uploadRow.orgUserId);
371 let appPromise = usersService.getUserAppRoles(appId, uploadRow.orgUserId,true).promise().then( (userAppRolesResult) => {
372 // Reply for unknown user has all defined roles with isApplied=false on each.
373 if (typeof userAppRolesResult[0] !== "undefined") {
375 $log.debug('BulkUserModalCtrl::buildAppRoleChecks: adding result '
376 + JSON.stringify(userAppRolesResult));
377 appUserRolesRequest.push({
378 orgUserId: uploadRow.orgUserId,
379 userAppRoles: userAppRolesResult
382 $log.error('BulkUserModalCtrl::buildAppRoleChecks: getUserAppRoles returned ' + JSON.stringify(userAppRolesResult));
385 $log.error('BulkUserModalCtrl::buildAppRoleChecks: getUserAppRoles failed ', error);
387 promises.push(appPromise);
390 $log.debug('BulkUserModalCtrl::buildAppRoleChecks: duplicate orgUserId, skip: '+ uploadRow.orgUserId);
395 }; // buildAppRoleChecks
398 * Evaluates the result set returned by the app service and adjusts
399 * the list of updates to be sent to the remote application by setting
400 * isApplied=true for each role name found in the upload file.
401 * Reads and writes scope variable uploadFile.
402 * Reads closure variable appUserRolesRequest.
404 $scope.evalAppRoleCheckResults = () => {
406 $log.debug('BulkUserModalCtrl::evalAppRoleCheckResults: uploadFile length is ' + $scope.uploadFile.length);
407 $scope.uploadFile.forEach(function (uploadRow) {
408 if (uploadRow.status) {
410 $log.debug('BulkUserModalCtrl::evalAppRoleCheckResults: skip row ' + uploadRow.line);
413 // Search for the match in the app-user-roles array
414 appUserRolesRequest.forEach( function (appUserRoleObj) {
415 if (uploadRow.orgUserId.toLowerCase() === appUserRoleObj.orgUserId.toLowerCase()) {
417 $log.debug('BulkUserModalCtrl::evalAppRoleCheckResults: match on orgUserId ' + uploadRow.orgUserId);
418 let roles = appUserRoleObj.userAppRoles;
419 roles.forEach(function (appRoleItem) {
421 // $log.debug('BulkUserModalCtrl::evalAppRoleCheckResults: checking uploadRow.role='
422 // + uploadRow.role + ', appRoleItem.roleName= ' + appRoleItem.roleName);
423 if (uploadRow.role === appRoleItem.roleName) {
424 if (appRoleItem.isApplied) {
426 $log.debug('BulkUserModalCtrl::evalAppRoleCheckResults: existing role '
427 + appRoleItem.roleName);
428 uploadRow.status = 'Role exists';
432 $log.debug('BulkUserModalCtrl::evalAppRoleCheckResults: new role '
433 + appRoleItem.roleName);
434 // After much back-and-forth I decided a clear indicator
435 // is better than blank in the table status column.
436 uploadRow.status = 'OK';
437 appRoleItem.isApplied = true;
439 // This count is not especially interesting.
440 // numberUserRolesSucceeded++;
444 }); // for each result
446 }; // evalAppRoleCheckResults
449 * Sends requests to Portal requesting user role assignment.
450 * That endpoint handles creation of the user at the remote app if necessary.
451 * Reads closure variable appUserRolesRequest.
452 * Invoked by the Next button on the confirmation dialog.
454 $scope.updateDB = () => {
455 $scope.isProcessing = true;
456 $scope.conformMsg = '';
457 $scope.isProcessedRecords = true;
458 $scope.progressMsg = 'Sending requests to application..';
460 $log.debug('BulkUserModalCtrl::updateDB: request length is ' + appUserRolesRequest.length);
461 var numberUsersSucceeded = 0;
463 appUserRolesRequest.forEach(function(appUserRoleObj) {
465 $log.debug('BulkUserModalCtrl::updateDB: appUserRoleObj is ' + JSON.stringify(appUserRoleObj));
466 let updateRequest = {
467 orgUserId: appUserRoleObj.orgUserId,
468 appId: $scope.selectedApplication.id,
469 appRoles: appUserRoleObj.userAppRoles
472 $log.debug('BulkUserModalCtrl::updateDB: updateRequest is ' + JSON.stringify(updateRequest));
473 let updatePromise = usersService.updateUserAppRoles(updateRequest).promise().then(res => {
475 $log.debug('BulkUserModalCtrl::updateDB: updated successfully: ' + JSON.stringify(res));
476 numberUsersSucceeded++;
478 // What to do if one of many fails??
479 $log.error('BulkUserModalCtrl::updateDB failed: ', err);
480 confirmBoxService.showInformation(
481 'Failed to update the user application roles. ' +
482 'Error: ' + err.status).then(isConfirmed => { });
484 // $log.debug('BulkUserModalCtrl::updateDB: finally()');
486 promises.push(updatePromise);
489 // Run all the promises
490 $q.all(promises).then(function(){
491 $scope.conformMsg = 'Processed ' + numberUsersSucceeded + ' users.';
492 $scope.isProcessing = false;
493 $scope.isProcessedRecords = true;
494 $scope.uploadFile = [];
499 // Sets the variable that hides/reveals the user controls
500 $scope.step2 = () => {
501 this.fileSelected = false;
502 $scope.selectedFile = null;
503 $scope.fileModel = null;
507 // Navigate between dialog screens using step number: 1,2,...
508 $scope.navigateBack = () => {
510 this.fileSelected = false;
513 // Opens a dialog to show the data to be uploaded.
514 // Invoked by the upload button on the bulk user dialog.
515 $scope.confirmUpload = () => {
517 $scope.readValidateFile();
518 // Dialog shows progress
520 templateUrl: 'app/views/users/new-user-dialogs/bulk-user.confirm.html',
522 sizeClass: 'modal-medium',
528 // Invoked by the Cancel button on the confirmation dialog.
529 $scope.cancelUpload = () => {
536 BulkUserModalCtrl.$inject = ['$scope', '$log', '$filter', '$q', 'usersService', 'applicationsService', 'confirmBoxService', 'functionalMenuService', 'ngDialog','$modal'];
537 angular.module('ecompApp').controller('BulkUserModalCtrl', BulkUserModalCtrl);
539 angular.module('ecompApp').directive('fileChange', ['$parse', function($parse){
543 link : function($scope, element, attrs, ngModel) {
544 var attrHandler = $parse(attrs['fileChange']);
545 var handler=function(e) {
546 $scope.$apply(function() {
547 attrHandler($scope, { $event:e, files:e.target.files } );
548 $scope.selectedFile = e.target.files[0].name;
551 element[0].addEventListener('change',handler,false);
556 angular.module('ecompApp').filter('csvToObj',function() {
557 return function(input) {
560 var lines = input.split('\n');
561 // Need 1-based index below
562 for (len = lines.length, i = 1; i <= len; ++i) {
563 // Use 0-based index for array
564 line = lines[i - 1].trim();
565 if (line.length == 0) {
566 // console.log("Skipping blank line");
576 if (o.length !== 2) {
577 // other lengths not valid for upload
582 status: 'Failed to find 2 comma-separated values'
586 // console.log("Valid line: ", val);
591 // leave status undefined, this could be valid.
593 if (o[0].toLowerCase() === 'orgUserId') {
594 // not valid for upload, so set status
595 entry.status = 'Header';
597 else if (o[0].trim() == '' || o[1].trim() == '') {
598 // defend against line with only a single comma etc.
599 entry.status = 'Failed to find 2 non-empty values';