(function () { "use strict"; var app = angular.module("usersAdmin"); var templatePath = modulesSharedResourcesUrl + "Modules/UsersAdmin/Views/"; var profileTemplatePath = modulesSharedResourcesUrl + "Modules/UsersAdmin/ProfileViews/"; app.directive("usersList", [ "config", "$rootScope", "usersAdminDataContext", "usersAdminService", "common", "$location", "$modal", "$filter", "$timeout", "$q", "user", "rolesAdminDataContext", "$routeParams", "userServiceDataContext", "OrganisationAdminService", "terminology", "myUsersDataContext", "tenantService", function ( config, $rootScope, usersAdminDataContext, usersAdminService, common, $location, $modal, $filter, $timeout, $q, user, rolesAdminDataContext, $routeParams, userServiceDataContext, OrganisationAdminService, terminology, myUsersDataContext, tenantService ) { return { restrict: "E", templateUrl: templatePath + "userslist.html", scope: { //the isolated scope for this directive addUser: "=", }, link: link, }; function link($scope, elem, attrs) { // Set the log notifiers up var getLogFn = common.logger.getLogFn; var logSuccess = getLogFn("usersList", "success"); var logError = getLogFn("usersList", "error"); $scope.invite = $location.search().invite; $scope.orderByPredicate = "lastName"; $scope.organisationId = $routeParams.organisationId; $scope.editMode = false; $scope.terminology = terminology; $scope.users = []; $scope.selectedUsers = []; $scope.organisations = []; $scope.newOrganisations = []; $scope.organisationType = []; $scope.groupType = []; $scope.visibleUserCount = 28; var userIds = []; $scope.groups = []; $scope.ready = false; $scope.roles = []; $scope.listdisplay = 2; $scope.appCode = config.appCode; $scope.selectedGroup = $scope.groupType[0]; if (config.appCode === "CUPPA") { $scope.listdisplay = 2; } $scope.availableUserStatuses = []; $scope.users.selectAll = false; user.getProfile().then(function (me) { $scope.meId = me.userId; }); // Watch for changes to the task class $scope.$watchCollection( "selectedUsers", function (newValue, oldValue) { if (newValue.length > 0) { $scope.editMode = true; } else { $scope.editMode = false; } }, true ); $scope.setRoleSelection = function () { $scope.selectedRole = $scope.selectedRole; }; $scope.setUserStatusSelection = function () { $scope.selectedUserStatus = $scope.selectedUserStatus; }; $scope.setVisibleUserCount = function () { setGroups(); }; // Make sure we clear any previously selected user usersAdminService.setManagingUser(null); function setGroups() { if ($scope.selectedOrg) { $scope.addedGroups = []; for (i in $scope.organisations) { if ( $scope.organisations[i].type !== 0 && $scope.organisations[i].parentId === $scope.selectedOrg ) { $scope.addedGroups.push($scope.organisations[i]); } } $scope.groupType.push($scope.addedGroups); applyArray($scope, "groupType"); } } function applyArray(container, key) { setTimeout(function () { var tempArray = container[key]; container[key] = []; $scope.$apply(); container[key] = tempArray; $scope.$apply(); }, 0); } function getUsersAndOrgs() { return usersAdminService.getAllUsers().then(function (data) { var users = data.users; var orgDictionary = data.organisations; $scope.users = users; $scope.organisations = []; $scope.users.map(function (theUser) { if (theUser) { userIds.push(theUser.id); theUser.userId = theUser.id; if (theUser.organisations) { theUser.organisations = theUser.organisations.map(function ( orgId ) { return orgDictionary[orgId]; }); } return theUser; } }); if ($scope.organisationUserView) { $scope.organisation = orgDictionary[$scope.organisationId]; $scope.organisations = orgDictionary; if ( $scope.organisation.type === 0 || $scope.organisation.type === 2 ) $scope.organisationView = true; if ( $scope.organisation.type === 7 || $scope.organisation.type === 8 || $scope.organisation.type === 9 ) $scope.employerView = true; generateTypes(); } else { $scope.organisations = orgDictionary; generateTypes(); } $timeout(function () { $(".selectpicker").selectpicker("refresh"); }); $scope.userIds = userIds; $scope.allUsers = users; $scope.userAllocations = {}; $scope.ready = true; if ($scope.invite && !$scope.invited) { $scope.inviteUsers(); $scope.invited = true; } getAvailableUserStatuses(); }); } function getAvailableUserStatuses() { OrganisationAdminService.getTopLevelOrg().then(function (data) { tenantService .getUserStatus(data.id) .then(function (d) { angular.forEach(d, function (v, key) { var ar = { "id": v.name, "name": v.name, "description": v.description, "roleId": v.roleId } $scope.availableUserStatuses.push(ar); }); }); }); } function generateTypes() { $scope.organisationType = []; $scope.groupType = []; for (var i in $scope.organisations) { var org = $scope.organisations[i]; if (org.type === 0) { if (!$scope.organisationType.some(o => o.id === org.id)) { $scope.organisationType.push(org); } if ($scope.organisationId === org.id) { $scope.selectedOrg = $scope.organisationId; $scope.organisationUserView = true; } } else { if (!$scope.groupType.some(o => o.id === org.id)) { $scope.groupType.push(org); } if ($scope.organisationId === org.id) { $scope.selectedGroup = $scope.organisationId; $scope.organisationUserView = true; } } } } function flatten(arr) { return arr.reduce(function (flat, toFlatten) { return flat.concat( Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten ); }, []); } function getRoleAllocationsForUsers() { var promises = []; var i, j, temparray, chunk = 1000; for (i = 0, j = $scope.userIds.length; i < j; i += chunk) { temparray = $scope.userIds.slice(i, i + chunk); if (config.appCode == "MSA") promises.push( rolesAdminDataContext.getAllRoleAllocationsForManyUsers( "MS", temparray ) ); promises.push( rolesAdminDataContext.getAllRoleAllocationsForManyUsers( appCode, temparray ) ); } return $q.all(promises).then(function (data) { var roleAllocations = []; for (var i = 0; i < data.length; i++) { roleAllocations.push(data[i]); } roleAllocations = flatten(roleAllocations); var roleTemp = []; for (var i = 0; i < roleAllocations.length; i++) { if (!roleTemp[roleAllocations[i].userId]) roleTemp[roleAllocations[i].userId] = []; roleTemp[roleAllocations[i].userId].push(roleAllocations[i]); } roleAllocations = roleTemp; var allAllocations = roleTemp; var allRoles = []; // loop through all the admin allocations, check if the user id exists in the personal allocations, if not set it, otherwise merge the users allocations. for (var userId in roleAllocations) { if (!allAllocations[userId]) allAllocations[userId] = roleAllocations[userId]; else { roleAllocations[userId].forEach(function (allocation) { allAllocations[userId].push(allocation); }); } allAllocations[userId].forEach(function (role) { if (allRoles.indexOf(role.roleDisplayName) === -1) allRoles.push(role.roleDisplayName); }); } $scope.userAllocations = allAllocations; $scope.allRoles = allRoles; $timeout(function () { $(".selectpicker").selectpicker("refresh"); }); }); } function setUserRoleAllocations() { $scope.users.forEach(function (user) { user.roleAllocations = $scope.userAllocations[user.userId]; }); } $scope.managableUserCount = function (users, meId) { if (users) { var count = users.length; for (i in users) { if (users[i].id == meId) count = count - 1; if (users[i].cannotManage && users[i].id !== meId) count = count - 1; } return count; } }; $scope.includeChildOrgs = false; $scope.isOrgSelected = function (orgId) { return $scope.selectedOrgs .map(function (org) { return org.id; }) .includes(orgId); }; $scope.setAllUsers = function (value) { // if (value == null || value == '') { // if ($scope.visibleUserCount < 24) { // $scope.visibleUserCount = 24; // } else { // $scope.visibleUserCount = $scope.visibleUserCount; // } // } else { // $scope.visibleUserCount = $scope.users.length; // } }; $scope.selectOrg = function (org) { // Check if the selected org is already the primary selected org (the first one) if ($scope.selectedOrgs[0] && $scope.selectedOrgs[0].id == org.id) { $scope.selectedOrgs = []; return; } // Update the selected orgs updateSelectedOrgs(org); }; $scope.onIncludeChildOrgs = function () { if ($scope.selectedOrgs[0]) updateSelectedOrgs($scope.selectedOrgs[0]); }; function updateSelectedOrgs(org) { var selectedOrgs = []; if ($scope.includeChildOrgs) { selectChildOrgs(org, selectedOrgs); } else { selectedOrgs = [org]; } $scope.selectedOrgs = selectedOrgs; console.log($scope.selectedOrgs); } function selectChildOrgs(org, selectedOrgs) { selectedOrgs.push(org); org.children.forEach(function (org) { selectChildOrgs(org, selectedOrgs); }); } $scope.removeUsers = function (orgId, users) { return myUsersDataContext .removeUsers(orgId, users) .then(function () { //Remove roleallocations angular.forEach(users, function (userId) { rolesAdminDataContext.removeRoleAllocationsForUserInOrg( userId, orgId ); logSuccess("Successfully removed selected users"); $scope.selectedUsers = []; $rootScope.$broadcast("user-updated", { users: userId }); $scope.editMode = false; refreshUserListing(); }); }); }; function refreshUserListing() { getUsersAndOrgs().then(function() { $scope.editMode = false; $scope.selectedUsers = []; $scope.users.selectAll = false; }) .then(getRoleAllocationsForUsers) .then(setUserRoleAllocations); } $scope.selectedOrgs = []; $scope.bulkAction = function (actionType, orgId, users) { let nameCount = {}; // this checks if there are any organisations with the same name Object.keys($scope.organisations).forEach(key => { const org = $scope.organisations[key]; if (nameCount[org.name]) { nameCount[org.name]++; } else { nameCount[org.name] = 1; } }); // if the organisation appears more than once, differentiate between group or org Object.keys($scope.organisations).forEach(key => { const org = $scope.organisations[key]; if (nameCount[org.name] > 1) { if (org.type === 0) { org.name = `${org.name} - Organisation`; } else if (org.type === 2) { org.name = `${org.name} - Group`; } } }); $modal.open({ templateUrl: templatePath + "orgchooser.html", controller: orgSelectorController, size: "sm", backdrop: "static", resolve: { selectedOrg: function () { return $scope.selectedOrg; }, actionType: function () { return actionType; }, orgId: function () { return orgId; }, orgs: function () { return $scope.organisations; }, users: function () { return $scope.selectedUsers; }, refreshUserListing: function () { return refreshUserListing; }, }, }); }; var orgSelectorController = function ( common, $scope, $rootScope, $modalInstance, selectedOrg, actionType, orgId, orgs, users, refreshUserListing ) { $scope.organisations = []; for (i in orgs) { if (selectedOrg !== orgs[i].id) $scope.organisations.push(orgs[i]); } $scope.actionType = actionType; $scope.selectedOrg = null; $scope.users = users; $scope.saving = false; $scope.ok = function () { $scope.saving = true; OrganisationAdminService.getTopLevelOrg().then(function (data) { if ($scope.actionType == "add") { var model = { topLevelOrgId: data.id, appCode: config.appCode, toOrganisationIds: [$scope.selectedOrg.id], userIds: $scope.users, }; if (config.appCode == "MSA") { model.appCode = "MS"; } else { model.appCode = config.appCode; } usersAdminDataContext .addUsersToOrg(model) .then(function (data) { logSuccess( "Succesfully added " + $scope.users.length + " users to " + $scope.selectedOrg.name ); $rootScope.$broadcast("user-updated", { users: $scope.users, }); refreshUserListing(); $scope.saving = false; selectedOrg = $scope.selectedOrg.id; $modalInstance.dismiss("cancel"); }); } if ($scope.actionType == "move") { var model = { topLevelOrgId: data.id, fromOrganisationId: orgId, appCode: config.appCode, toOrganisationIds: [$scope.selectedOrg.id], userIds: $scope.users, }; usersAdminDataContext .moveUsersToOrg(model) .then(function (data) { logSuccess( "Succesfully added " + $scope.users.length + " users to " + $scope.selectedOrg.name ); $rootScope.$broadcast("user-updated", { users: $scope.users, }); refreshUserListing(); selectedOrg = $scope.selectedOrg.id; $modalInstance.dismiss("cancel"); $scope.saving = false; }); } if ($scope.actionType == "copy") { var model = { topLevelOrgId: data.id, fromOrganisationId: orgId, appCode: config.appCode, toOrganisationIds: [$scope.selectedOrg.id], userIds: $scope.users, }; usersAdminDataContext .copyUsersToOrg(model) .then(function (data) { logSuccess( "Succesfully added " + $scope.users.length + " users to " + $scope.selectedOrg.name ); $rootScope.$broadcast("user-updated", { users: $scope.users, }); refreshUserListing(); selectedOrg = $scope.selectedOrg.id; $modalInstance.dismiss("cancel"); $scope.saving = false; }); } }); }; //close the modal $scope.cancel = function () { $modalInstance.dismiss("cancel"); }; }; $scope.inviteUsers = function () { $modal.open({ templateUrl: templatePath + "invite.html", controller: inviteController, size: "sm", backdrop: "static", resolve: { terminology: function () { return $scope.terminology; }, meId: function () { return $scope.meId; }, selectedOrg: function () { return $scope.selectedOrg; }, refreshUserListing: function () { return refreshUserListing; }, users: function () { return $scope.users; }, organisationId: function () { return $scope.organisationId; }, userEmail: function () { return $scope.invite; }, topLevelOrgId: function () { return $scope.topLevelOrgId; }, }, }); }; var inviteController = function ( $rootScope, common, $scope, $modalInstance, selectedOrg, refreshUserListing, users, organisationId, userEmail, meId, topLevelOrgId, terminology ) { $scope.terminology = terminology; $scope.meId = meId; $scope.saving = false; $scope.userEmail = userEmail; $scope.selectedOrganisations = []; $scope.emailExists = false; $scope.topLevelOrgId = topLevelOrgId; $scope.organisationId = organisationId; getOrganisations(); getAvailableRoles(); function getOrganisations() { OrganisationAdminService.getTopLevelOrg().then(function (data) { $scope.topLevelOrgId = data.id; }); myUsersDataContext .getOrganisationsFullFlatSimple() .then(function (data) { $scope.groups = []; $scope.organisations = []; $scope.jobRoles = []; $scope.teams = []; $scope.employerGroups = []; $scope.mentorGroups = []; $scope.employerOrganisations = []; for (var i = 0; i < data.length; i++) { if (data[i].type === 0) { $scope.organisations.push(data[i]); } if (data[i].type === 2) { $scope.groups.push(data[i]); } if (data[i].type === 5) { $scope.jobRoles.push(data[i]); } if (data[i].type === 6) { $scope.teams.push(data[i]); } if (data[i].type === 8) { $scope.employerGroups.push(data[i]); } if (data[i].type === 7) { $scope.employerOrganisations.push(data[i]); } if (data[i].type === 9) { $scope.mentorGroups.push(data[i]); } } $scope.organisationsLoaded = true; $scope.groupsLoaded = true; $scope.jobRolesLoaded = true; $scope.teamsLoaded = true; $scope.employerGroupsLoaded = true; $scope.mentorGroupsLoaded = true; $scope.employerOrganisationsLoaded = true; }); } $scope.singleRoleLoaded = false; function getAvailableRoles() { $scope.availableRoles = []; if (config.appCode == "CUPPA") { var rls = []; var addedRls = []; rolesAdminDataContext .getAllRoleAllocations(config.appCode) .then(function (roles) { for (var r in roles) { rls.push(roles[r].name); } console.log(rls); rolesAdminDataContext .getAllRoles(config.appCode) .then(function (data) { for (i in data) { var d = data[i].name; console.log(d); if (d == "PlatformAdmin") { // are they a platform admin? if ( rls.indexOf("PlatformAdmin") != -1 && addedRls.indexOf(d) == -1 ) { $scope.availableRoles.push(data[i]); addedRls.push(d); } } else if (d == "CuppaAdmin") { // can they access this role? if ( (rls.indexOf("PlatformAdmin") != -1 || rls.indexOf("CuppaAdmin") != -1) && addedRls.indexOf(d) == -1 ) { $scope.availableRoles.push(data[i]); addedRls.push(d); } } else if (d == "OrgAdmin") { // can they access this role? if ( (rls.indexOf("PlatformAdmin") != -1 || rls.indexOf("CuppaAdmin") != -1 || rls.indexOf("OrgAdmin") != -1) && addedRls.indexOf(d) == -1 ) { $scope.availableRoles.push(data[i]); addedRls.push(d); } } else if (d == "SipManager") { // can they access this role? if ( (rls.indexOf("PlatformAdmin") != -1 || rls.indexOf("CuppaAdmin") != -1 || rls.indexOf("OrgAdmin") != -1 || rls.indexOf("SipManager") != -1) && addedRls.indexOf(d) == -1 ) { $scope.availableRoles.push(data[i]); addedRls.push(d); } } else if (d == "Learner") { if (addedRls.indexOf(d) == -1) { // can they access this role? $scope.availableRoles.push(data[i]); addedRls.push(d); } } } $scope.availableRolesLoaded = true; }); }); } else { // Get roles for MSA (Myshowcase.me Admin) rolesAdminDataContext .getAllRoles(config.appCode) .then(function (data) { for (i in data) { $scope.availableRoles.push(data[i]); } $scope.availableRolesLoaded = true; }); if (config.appCode == "MSA") { // Get roles for MS (Myshowcase.me) rolesAdminDataContext.getAllRoles("MS").then(function (data) { for (i in data) { $scope.availableRoles.push(data[i]); } }); } } } $scope.selectOrganisation = function (org) { if (org.selected) { $scope.orgHasBeenSelected = true; var orgAllocation = usersAdminService.createBlankOrganisationAllocation(); orgAllocation.organisationId = org.id; orgAllocation.isAdmin = false; for (i in $scope.selectedOrganisations) { if ($scope.selectedOrganisations[i].id == org.id) { $scope.selectedOrganisations.splice(i, 1); return; } } org.orgAllocation = orgAllocation; for (i in $scope.availableRoles) { if ( $scope.availableRoles[i].name == "User" || $scope.availableRoles[i].name == "Learner" ) { org.role = $scope.availableRoles[i]; $scope.setOrgRole(org.role, org); } } } else { for (i in $scope.selectedOrganisations) { if ($scope.selectedOrganisations[i].organisationId == org.id) { $scope.selectedOrganisations.splice(i, 1); if ($scope.selectedOrganisations.length == 0) { $scope.orgHasBeenSelected = false; } } } org.orgAllocation = null; } }; $scope.setOrgRole = function (role, org) { org.orgAllocation.myRolesId = role.id; if (role.isAdmin) { org.orgAllocation.isAdmin = true; } else { org.orgAllocation.isAdmin = false; } for (i in $scope.selectedOrganisations) { if ($scope.selectedOrganisations[i].organisationId == org.id) { $scope.selectedOrganisations.splice(i, 1); } } $scope.selectedOrganisations.push(org.orgAllocation); }; $scope.doesEmailExist = function (email) { $scope.userId = null; $scope.userAlreadyInOrg = false; $scope.emailExists = false; $scope.checking = true; //HTML encode the username so that e.g. '+' is handled correctly var email = encodeURIComponent(email); usersAdminDataContext.isEmailAvailable(email).then(function (data) { if (data === true) { usersAdminDataContext .getUserIdByEmail(email) .then(function (id) { $scope.userId = id; for (i in users) { if (users[i].id == $scope.userId) { $scope.userAlreadyInOrg = true; $scope.emailExists = true; $scope.checking = false; } } if (!$scope.userAlreadyInOrg) { $scope.emailExists = true; $scope.checking = false; } }); } $scope.checking = false; }); }; $scope.ok = function () { $scope.saving = true; var orgModels = []; for (i in $scope.organisations) { if ($scope.organisations[i].orgAllocation) { $scope.organisations[i].orgAllocation.userId = $scope.userId; orgModels.push($scope.organisations[i].orgAllocation); } } for (i in $scope.groups) { if ($scope.groups[i].orgAllocation) { $scope.groups[i].orgAllocation.userId = $scope.userId; orgModels.push($scope.groups[i].orgAllocation); } } for (i in $scope.jobRoles) { if ($scope.jobRoles[i].orgAllocation) { $scope.jobRoles[i].orgAllocation.userId = $scope.userId; orgModels.push($scope.jobRoles[i].orgAllocation); } } for (i in $scope.teams) { if ($scope.teams[i].orgAllocation) { $scope.teams[i].orgAllocation.userId = $scope.userId; orgModels.push($scope.teams[i].orgAllocation); } } for (i in $scope.employerGroups) { if ($scope.employerGroups[i].orgAllocation) { $scope.employerGroups[i].orgAllocation.userId = $scope.userId; orgModels.push($scope.employerGroups[i].orgAllocation); } } for (i in $scope.mentorGroups) { if ($scope.mentorGroups[i].orgAllocation) { $scope.mentorGroups[i].orgAllocation.userId = $scope.userId; orgModels.push($scope.mentorGroups[i].orgAllocation); } } for (i in $scope.employerOrganisations) { if ($scope.employerOrganisations[i].orgAllocation) { $scope.employerOrganisations[i].orgAllocation.userId = $scope.userId; orgModels.push($scope.employerOrganisations[i].orgAllocation); } } usersAdminDataContext.updateUsers(orgModels).then(function (data) { logSuccess("User successfully updated"); $scope.saving = false; $modalInstance.dismiss("cancel"); $location.url($location.path()); refreshUserListing(); }); }; $scope.editUser = function () { $location.url($location.path()); // Redirect to edit user if ($scope.organisationId) { $location.path( "/users/" + $scope.organisationId + "/" + $scope.userId + "/edit" ); } else { $location.path("/user/" + $scope.userId + "/edit"); } $modalInstance.dismiss("cancel"); }; $scope.hideAdministrator = function (orgId) { return function (value, index, array) { if ( $scope.topLevelOrgId == orgId && (value.name == "SystemAdministrator" || value.name == "SystemAdmin" || value.name == "CuppaAdmin") && $rootScope.isSystemAdmin ) { return true; } else if ( value.name == "SystemAdministrator" || value.name == "SystemAdmin" || value.name == "CuppaAdmin" ) { return false; } else { return true; } }; }; //close the modal $scope.cancel = function () { $modalInstance.dismiss("cancel"); }; if (userEmail) { $scope.doesEmailExist($scope.userEmail); } }; $scope.createUser = function () { usersAdminService.setUsers($scope.users); $location.path("/createuser"); }; $scope.importUsers = function () { $modal.open({ templateUrl: templatePath + 'importusers.html', controller: importUsersController, size: 'md', backdrop: 'static', resolve: { meId: function () { return $scope.meId; }, user: function () { return $scope.user; }, usersAdminService: function () { return $scope.usersAdminService; }, users: function () { return $scope.users; }, organisationId: function () { return $scope.organisationId; }, userEmail: function () { return $scope.invite; }, topLevelOrgId: function () { return $scope.topLevelOrgId; }, } }); } var importUsersController = function ($scope, $rootScope, user, meId, usersAdminService, $modalInstance, terminology, validation) { $scope.meId = meId; $scope.terminology = terminology; $scope.importDataLoaded = false; $scope.saving = false; $scope.selectedRole = {}; $scope.canDelete = false; $scope.validateReady = false; $scope.complete = false; $scope.errorResults = []; $scope.userTerm = "user"; $scope.appCode = config.appCode; $scope.csvDownloadUrl = templatePath + 'users.csv'; // console.log(user); // if (config.appCode === "CUPPA" || config.appCode === "OB" ) { // $scope.userTerm = "learner"; // user.getProfile().then(function (me) { // $scope.meId = me.userId; // }); // } $scope.onFileSelect = function ($files) { if (!$files[0]) return; $scope.file = $files[0]; $scope.fileName = $files[0].name; if (($files[0].type !== 'application/vnd.ms-excel' && $files[0].type !== 'text/csv') || $scope.fileName.slice($scope.fileName.length - 3, $scope.fileName.length) === 'xls') { $scope.fileIsBad = true; return; } else { $scope.usersToAdd = []; $scope.fileIsBad = false; $scope.csvValid = true; $scope.validateReady = true; $scope.errorResults = []; $scope.complete = false; } }; $scope.validate = function () { $scope.validateReady = false; $scope.importDataLoaded = true; $scope.fileName = $scope.file.name; $scope.usersToAdd = []; var emailRegex = validation.userValidationConfig().email.regex; var emailMaxCharacters = validation.userValidationConfig().email.maxCharacters; var firstnameRegex = validation.userValidationConfig().userFirstName.regex; var firstnameMaxCharacters = validation.userValidationConfig().userFirstName.maxCharacters; var surnameRegex = validation.userValidationConfig().userLastName.regex; var surnameMaxCharacters = validation.userValidationConfig().userLastName.maxCharacters; if ($scope.file) { var reader = new FileReader(); reader.readAsText($scope.file); reader.onload = function (e) { var rows = e.target.result.split("\n"); $scope.rowNumbers = rows.length + 1; var emailList = []; for (var i = 1; i < rows.length; i++) { var valid = true; var cells = rows[i].split(","); var uid1 = cells[0]; var uid2 = cells[1]; var email = cells[4]; var firstname = cells[2]; var surname = cells[3]; var role = cells[6] || ''; var group = cells[5] || ''; var uid = ''; if (email && firstname && surname) { // validate email var validEmail = emailRegex.test(String(email).toLowerCase()); if (!validEmail) { $scope.errorResults.push("Row " + (i) + " has an invalid email: " + email); valid = false; } else if (!email || email.length > emailMaxCharacters) { $scope.errorResults.push("Row " + (i) + " has a email with too many characters. Max length is " + emailMaxCharacters); valid = false; } if (validEmail) { if (emailList.indexOf(email.toLowerCase()) > -1) { $scope.errorResults.push("Row " + (i) + " has a duplicate email: " + email); valid = false; } else { emailList.push(email.toLowerCase()); } } // validate firstname var validFirstname = firstnameRegex.test(String(firstname).toLowerCase()); if (!validFirstname) { $scope.errorResults.push("Row " + (i) + " has an invalid firstname: " + firstname); valid = false; } else if (!firstname || firstname.length > firstnameMaxCharacters) { $scope.errorResults.push("Row " + (i) + " has a firstname with too many characters. Max length is " + firstnameMaxCharacters); valid = false; } // validate surname var validLastname = surnameRegex.test(String(surname).toLowerCase()); if (!validLastname) { $scope.errorResults.push("Row " + (i) + " has an invalid surname: " + surname); valid = false; } else if (!surname || surname.length > surnameMaxCharacters) { $scope.errorResults.push("Row " + (i) + " has a surname with too many characters. Max length is " + surnameMaxCharacters); valid = false; } // validate column number if (cells.length < 2) { $scope.errorResults.push("Row " + (i) + " has less than the required 3 columns."); valid = false; } if (valid) { var user = { 'email': email, 'firstname': firstname.trim(), 'lastname': surname.trim(), 'role': role.trim(), 'uniqueIdentifier': uid1.trim(), 'group': group.trim(), 'appCode': config.appCode, 'applicationId': config.applicationId, 'associatedUserId': $scope.meId }; console.log(user); $scope.usersToAdd.push(user); } } } if ($scope.usersToAdd.length === 0 && $scope.errorResults.length === 0) { $scope.errorResults.push("The file data looks invalid. Please check to ensure data is correctly formatted."); valid = false; } if ($scope.errorResults.length > 0) { $scope.$apply(function () { $scope.importDataLoaded = false; $scope.validateReady = true; $scope.complete = false; }); } else if ($scope.usersToAdd.length > 0 && $scope.errorResults.length === 0) { $scope.$apply(function () { $scope.importDataLoaded = false; $scope.validateReady = false; $scope.complete = true; }); } }; } }; $scope.validateV2 = function () { $scope.validateReady = false; $scope.importDataLoaded = false; $scope.fileName = $scope.file.name; $scope.usersToAdd = []; var emailRegex = validation.userValidationConfig().email.regex; var emailMaxCharacters = validation.userValidationConfig().email.maxCharacters; var firstnameRegex = validation.userValidationConfig().userFirstName.regex; var firstnameMaxCharacters = validation.userValidationConfig().userFirstName.maxCharacters; var surnameRegex = validation.userValidationConfig().userLastName.regex; var surnameMaxCharacters = validation.userValidationConfig().userLastName.maxCharacters; if ($scope.file) { var reader = new FileReader(); reader.readAsText($scope.file); reader.onload = function (e) { var rows = e.target.result.split("\n"); $scope.rowNumbers = rows.length + 1; var emailList = []; for (var i = 1; i < rows.length; i++) { var valid = true; var cells = rows[i].split(","); var uid1 = cells[0]; var uid2 = cells[1]; var email = cells[4]; var firstname = cells[2]; var surname = cells[3]; var role = cells[6] || ''; var groups = cells[5] || ''; if (email && firstname && surname) { // validate email var validEmail = emailRegex.test(String(email).toLowerCase()); if (!validEmail) { $scope.errorResults.push("Row " + (i) + " has an invalid email: " + email); valid = false; } else if (!email || email.length > emailMaxCharacters) { $scope.errorResults.push("Row " + (i) + " has a email with too many characters. Max length is " + emailMaxCharacters); valid = false; } if (validEmail) { if (emailList.indexOf(email.toLowerCase()) > -1) { $scope.errorResults.push("Row " + (i) + " has a duplicate email: " + email); valid = false; } else { emailList.push(email.toLowerCase()); } } // validate firstname var validFirstname = firstnameRegex.test(String(firstname).toLowerCase()); if (!validFirstname) { $scope.errorResults.push("Row " + (i) + " has an invalid firstname: " + firstname); valid = false; } else if (!firstname || firstname.length > firstnameMaxCharacters) { $scope.errorResults.push("Row " + (i) + " has a firstname with too many characters. Max length is " + firstnameMaxCharacters); valid = false; } // validate surname var validLastname = surnameRegex.test(String(surname).toLowerCase()); if (!validLastname) { $scope.errorResults.push("Row " + (i) + " has an invalid surname: " + surname); valid = false; } else if (!surname || surname.length > surnameMaxCharacters) { $scope.errorResults.push("Row " + (i) + " has a surname with too many characters. Max length is " + surnameMaxCharacters); valid = false; } // validate column number if (cells.length < 2) { $scope.errorResults.push("Row " + (i) + " has less than the required 3 columns."); valid = false; } if (valid) { var user = { 'email': email, 'firstname': firstname.trim(), 'lastname': surname.trim(), 'role': role.trim(','), 'groups': groups.split(','), 'uniqueIdentifier': uid1.trim(), 'applicationId' : config.applicationId }; $scope.usersToAdd.push(user); } } } if ($scope.usersToAdd.length === 0 && $scope.errorResults.length === 0) { $scope.errorResults.push("The file data looks invalid. Please check to ensure data is correctly formatted."); valid = false; } if ($scope.errorResults.length > 0) { $scope.validateReady = true; $scope.complete = false; } else if ($scope.usersToAdd.length > 0 && $scope.errorResults.length === 0) { $scope.validateReady = false; $scope.complete = true; } }; } $scope.importDataLoaded = true; }; $scope.pushImportedUsers = function () { if (config.appCode === 'CUPPA' || config.appCode === "OB" ) { $scope.importDataLoaded = true; OrganisationAdminService.getCurrentOrg().then(function (org) { usersAdminDataContext.createUsers($scope.usersToAdd, org.id).then(function (data) { $location.path('/users'); logSuccess($scope.usersToAdd.length + " users successfully imported."); $modalInstance.dismiss('cancel'); refreshUserListing(); }); }); } else { usersAdminDataContext.importUsers($scope.file).then(function (results) { $scope.importDataLoaded = true; $scope.errorResults = results; $scope.validateReady = false; $scope.usersToAdd = []; $scope.fileIsBad = false; $scope.file = null; if ($scope.errorResults && $scope.errorResults.problems.length === 0) { logSuccess($scope.usersToAdd.length + " users successfully imported."); refreshUserListing(); } }); } }; //close the modal $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; } $scope.selectAllUsers = function () { $scope.selectedUsers = []; var filteredUsers = $scope.users; if ($scope.selectedOrg || $scope.selectedGroup || $scope.searchQueryText || $scope.selectedRole || $scope.selectedUserStatus) { filteredUsers = $filter('usersSelectedOrgFilter')(filteredUsers, $scope.selectedOrg); filteredUsers = $filter('usersSelectedOrgFilter')(filteredUsers, $scope.selectedGroup); filteredUsers = $filter('filter')(filteredUsers, $scope.searchQueryText); filteredUsers = $filter('roleFilter')(filteredUsers, $scope.selectedRole, $scope.selectedOrg); filteredUsers = $filter('usersSelectedUserStatusFilter')(filteredUsers, $scope.selectedUserStatus); } if ($scope.users.selectAll) { angular.forEach(filteredUsers, function(user) { if (user.userId !== $scope.meId && !user.cannotManage) { $scope.selectedUsers.push(user.userId); } }); } }; $scope.deleteUsers = function (userIds) { usersAdminDataContext.deleteUsers(userIds).then(function (data) { logSuccess("Successfully removed " + userIds.length + " users"); $rootScope.$broadcast("user-updated", { users: userIds }); $scope.selectedUsers = []; $scope.editMode = false; refreshUserListing(); }); }; getUsersAndOrgs() .then(getRoleAllocationsForUsers) .then(setUserRoleAllocations); } }, ]); app.directive("userTableDisplay", [ "$modal", "$location", "usersAdminService", "user", "$rootScope", "terminology", function ( $modal, $location, usersAdminService, user, $rootScope, terminology ) { return { restrict: "E", templateUrl: templatePath + "usertabledisplay.html", link: link, scope: { users: "=", meId: "=", filteredUsers: "=", selectedOrg: "=", selectedGroup: "=", searchQueryText: "=", roleAllocations: "=", selectedRole: "=", selectedUserStatus: "=", orgTree: "=", orderByPredicate: "=", reverse: "=", ready: "=", selectedUsers: "=", editMode: "=", visibleUserCount: "=", organisation: "=", }, }; function link($scope, elem, attrs) { $scope.terminology = terminology; $scope.startFilter = function (query, org) { if (query === undefined) query = ""; }; $scope.showMoreUsers = function () { $scope.visibleUserCount = $scope.visibleUserCount + 4; }; $scope.isSystemAdmin = function (user) { for (i in user.roleAllocations) { if ( user.roleAllocations[i].roleName == "SystemAdministrator" || user.roleAllocations[i].roleName == "SystemAdmin" || user.roleAllocations[i].roleName == "CuppaAdmin" ) { if ($rootScope.isSystemAdmin) return false; else { user.cannotManage = true; return true; } } } return false; }; // Manage the selected user $scope.viewUser = function (user) { if ($scope.editMode || user.id == $scope.meId || user.cannotManage) { return; } // Redirect to the manage user view if ($scope.organisation) { usersAdminService.setOrganisation($scope.organisation); $location.path( "/users/" + $scope.organisation.id + "/" + user.id + "/profile" ); } else { $location.path("/user/" + user.id + "/profile"); } }; $scope.editUser = function (user) { if ($scope.editMode) { return; } usersAdminService.setManagingUser(user); // Redirect to edit user if ($scope.organisation) { usersAdminService.setOrganisation($scope.organisation); $location.path( "/users/" + $scope.organisation.id + "/" + user.id + "/edit" ); } else { $location.path("/user/" + user.id + "/edit"); } }; $scope.claculateGroupCount = function (orgs) { var count = 0; for (i in orgs) { if (orgs[i].type == 2) { count++; } } return count; }; $scope.claculateOrgCount = function (orgs) { var count = 0; for (i in orgs) { if (orgs[i].type == 0) { count++; } } return count; }; } }, ]); app.filter("usersSelectedOrgFilter", function () { return function (users, selectedOrg) { if (!selectedOrg) return users; var filterOrgIds = [selectedOrg]; return users.filter(function (user) { var match = false; if (user.organisations) { user.organisations .map(function (org) { return org.id; }) .forEach(function (id) { if (filterOrgIds.indexOf(id) > -1) match = true; }); return match; } }); }; }); app.filter("usersRoleSelectedOrgFilter", function () { return function (roles, selectedOrg) { if (!selectedOrg) return roles; var filterOrgIds = [selectedOrg]; if (roles) { return roles.filter(function (role) { if (filterOrgIds.indexOf(role.organisationId) > -1) return true; return false; }); } else { return true; } }; }); app.filter("selectedOrgFilter", function () { return function (users, selectedOrg) { if (!selectedOrg) return users; return users.filter(function (user) { var match = false; user.organisations .map(function (org) { return org; }) .forEach(function (org) { if (selectedOrg == org.id) match = true; }); return match; }); }; }); app.filter("usersSelectedUserStatusFilter", function () { return function (users, selectedUserStatus) { if (!selectedUserStatus) return users; if (selectedUserStatus === "") return users; return users.filter(function (user) { if(user.userStatus === selectedUserStatus) return true; return false; }); }; }); app.directive("createUser", [ "$rootScope", "config", "user", "usersAdminDataContext", "usersAdminService", "common", "$location", "$injector", "$routeParams", "rolesAdminDataContext", "datacontext", "userServiceDataContext", "$q", "rolesAdminService", "OrganisationAdminService", "validation", "usersAdminConfig", "fullScreenLoaderContext", "terminology", "myUsersDataContext", "tenantService", "skillsPassportsDataContext", function ( $rootScope, config, user, usersAdminDataContext, usersAdminService, common, $location, $injector, $routeParams, rolesAdminDataContext, datacontext, userServiceDataContext, $q, rolesAdminService, OrganisationAdminService, validation, usersAdminConfig, fsl, terminology, myUsersDataContext, tenantService, skillsPassportsDataContext ) { return { restrict: "E", templateUrl: templatePath + "createuser.html", scope: { singleRole: "=", singleRoleAdmins: "=", }, link: link, }; function link($scope, elem, attrs) { // Set the log notifiers up var getLogFn = common.logger.getLogFn; var logSuccess = getLogFn("rolesAdmin", "success"); var logError = getLogFn("rolesAdmin", "error"); $scope.terminology = terminology; $scope.validation = validation.userValidationConfig(); //get the relevant validation logic $scope.showUserExists = false; $scope.selectedOrganisations = []; $scope.saving = false; $scope.userCreated = true; // Get the currently selected user $scope.user = usersAdminService.createBlankUser(); $scope.user.sendVerificationEmail = true; $scope.selectedRole; $scope.showAssociatedUser = false; $scope.user.userStatus = ""; $scope.associatedUsers = []; $scope.selectedStatus = {}; $scope.availableUserStatuses = []; if (config.appCode === "MSA") { var relationshipsDataContext = $injector.get( "relationshipsDataContext" ); } if (config.appCode === "MSA") { $scope.showRelationships = true; } user.getProfile().then(function (me) { $scope.meId = me.userId; getAvailableRoles(); getAvailableUserStatuses(); }); $scope.appCode = config.appCode; $scope.organisationId = $routeParams.organisationId; if ($scope.organisationId) { $scope.organisation = usersAdminService.getOrganisation(); if (!$scope.organisation) { $location.path("/users/" + $scope.organisationId); } } function getAvailableUserStatuses() { OrganisationAdminService.getTopLevelOrg().then(function (data) { tenantService .getUserStatus(data.id) .then(function (d) { angular.forEach(d, function (v, key) { var ar = { "id": v.name, "name": v.name, "description": v.description, "roleId": v.roleId } $scope.availableUserStatuses.push(ar); }); }); }); } function getAssociatedUsers() { usersAdminDataContext.getAdminUsers().then(function (data) { $scope.associatedUsers = data; angular.forEach($scope.associatedUsers, function (value, key) { if (value.userId === $scope.meId) { $scope.associatedUserId = value; return; } }); }); } function getRelationships() { $scope.allRoleIds = $scope.availableRoles.map(function (role) { return role.id; }); usersAdminDataContext .getUsersInRoles({ roleIds: $scope.allRoleIds, orgIds: $scope.allOrgIds, }) .then(function (allUsers) { allUsers = allUsers.map(function (user) { return { id: user.id.toLowerCase(), name: user.firstName + " " + user.lastName + " - " + user.emailAddress, }; }); relationshipsDataContext .getRelationshipTypes() .then(function (types) { $scope.relationshipTypes = types; angular.forEach($scope.relationshipTypes, function (value) { value.relationship = { relationshipTypeId: value.id, }; if (value.secondActorRole) { usersAdminDataContext .getUsersInRoles({ roleIds: [value.secondActorRole], orgIds: $scope.allOrgIds, }) .then(function (users) { value.availableUsers = users.map(function (user) { return { id: user.id.toLowerCase(), name: user.firstName + " " + user.lastName + " - " + user.emailAddress, }; }); value.usersLoaded = true; }); } else { value.availableUsers = allUsers; value.usersLoaded = true; } }); $scope.relationshipsLoaded = true; }); }); } function getOrganisations() { OrganisationAdminService.getTopLevelOrg().then(function (data) { $scope.topLevelOrgId = data.id; }); myUsersDataContext .getOrganisationsFullFlatSimple() .then(function (data) { $scope.allOrgIds = data.map(function (org) { return org.id; }); if (config.appCode === "MSA") { getRelationships(); } $scope.groups = []; $scope.organisations = []; $scope.jobRoles = []; $scope.teams = []; $scope.employerGroups = []; $scope.mentorGroups = []; $scope.employerOrganisations = []; for (var i = 0; i < data.length; i++) { if (data[i].type === 0) { $scope.organisations.push(data[i]); } if (data[i].type === 2) { $scope.groups.push(data[i]); } if (data[i].type === 5) { $scope.jobRoles.push(data[i]); } if (data[i].type === 6) { $scope.teams.push(data[i]); } if (data[i].type === 8) { $scope.employerGroups.push(data[i]); } if (data[i].type === 7) { $scope.employerOrganisations.push(data[i]); } if (data[i].type === 9) { $scope.mentorGroups.push(data[i]); } } if (config.appCode == "CUPPA") { $scope.showAssociatedUser = true; $scope.organisations[0].selected = true; var lrole = $scope.availableRoles.filter(function (r) { return r.name == "Learner"; })[0]; var orgallocation = { organisationId: $scope.organisations[0].id, myrolesId: lrole.id, isAdmin: false, }; $scope.user.organisations.push(orgallocation); } setSelectedSingleUserRole(); $scope.organisationsLoaded = true; $scope.groupsLoaded = true; $scope.jobRolesLoaded = true; $scope.teamsLoaded = true; $scope.employerGroupsLoaded = true; $scope.mentorGroupsLoaded = true; $scope.employerOrganisationsLoaded = true; }); } function setSelectedSingleUserRole() { if (!$scope.selectedRole) { $scope.selectedRole = getDefaultAvailableUserRole(); } } function getDefaultAvailableUserRole() { var theUserRole = $scope.availableUserRoles.filter(function (a) { return a.name == "User"; })[0]; if (theUserRole) { return theUserRole; } return null; } $scope.setUserRole = function (roleId, isFromUserStatus) { if ($scope.singleRole) { return setUserRole(roleId, isFromUserStatus); } } function setUserRole(roleId, isFromUserStatus) { if ($scope.singleRole) { $scope.isUserStatusRole = roleId && isFromUserStatus; var theUserRole; if (!roleId && $scope.selectedRole == null) { theUserRole = $scope.availableUserRoles.filter(function (a) { return a.name == "User"; })[0]; roleId = theUserRole.id; } //Reset the roles list back to original if ($scope.availableRolesUnchanged.length > 0) { $scope.availableRoles = $scope.availableRolesUnchanged; } if (roleId) { $scope.selectedRole = $scope.availableUserRoles.filter( function (r) { return ( r.id === roleId ); } )[0]; if (!$scope.selectedRole) { $scope.selectedRole = theUserRole; } //Set this user role as the role on any existing org membership roles that are user role type for (var i in $scope.groups) { if ($scope.groups[i].role && !$scope.groups[i].role.isAdmin) { $scope.groups[i].role = $scope.selectedRole; setOrgRoles($scope.selectedRole, $scope.groups[i]) } } for (var i in $scope.organisations) { if ($scope.organisations[i].role && !$scope.organisations[i].role.isAdmin) { $scope.organisations[i].role = $scope.selectedRole; setOrgRoles($scope.selectedRole, $scope.organisations[i]) } } for (var i in $scope.jobRoles) { if ($scope.jobRoles[i].role && !$scope.jobRoles[i].role.isAdmin) { $scope.jobRoles[i].role = $scope.selectedRole; setOrgRoles($scope.selectedRole, $scope.jobRoles[i]) } } for (var i in $scope.employerOrganisations) { if ($scope.employerOrganisations[i].role && !$scope.employerOrganisations[i].role.isAdmin) { $scope.employerOrganisations[i].role = $scope.selectedRole; setOrgRoles($scope.selectedRole, $scope.employerOrganisations[i]) } } for (var i in $scope.employerGroups) { if ($scope.employerGroups[i].role && !$scope.employerGroups[i].role.isAdmin) { $scope.employerGroups[i].role = $scope.selectedRole; setOrgRoles($scope.selectedRole, $scope.employerGroups[i]) } } for (var i in $scope.mentorGroups) { if ($scope.mentorGroups[i].role && !$scope.mentorGroups[i].role.isAdmin) { $scope.mentorGroups[i].role = $scope.selectedRole; setOrgRoles($scope.selectedRole, $scope.mentorGroups[i]) } } setAdminAndSingleUserRoles(); } } } $scope.singleRoleLoaded = false; function getAvailableRoles() { $scope.availableRoles = []; $scope.availableUserRoles = []; $scope.availableRolesUnchanged = []; $scope.isCuppa = false; if (config.appCode == "CUPPA") { $scope.isCuppa = true; var rls = []; var addedRls = []; rolesAdminDataContext .getAllRoleAllocations(config.appCode) .then(function (roles) { for (var r in roles) { rls.push(roles[r].name); } rolesAdminDataContext .getAllRoles(config.appCode) .then(function (data) { for (i in data) { var d = data[i].name; console.log(d); if (d == "PlatformAdmin") { // are they a platform admin? if ( rls.indexOf("PlatformAdmin") != -1 && addedRls.indexOf(d) == -1 ) { $scope.availableRoles.push(data[i]); addedRls.push(d); } } else if (d == "CuppaAdmin") { // can they access this role? if ( (rls.indexOf("PlatformAdmin") != -1 || rls.indexOf("CuppaAdmin") != -1) && addedRls.indexOf(d) == -1 ) { $scope.availableRoles.push(data[i]); addedRls.push(d); } } else if (d == "OrgAdmin") { // can they access this role? if ( (rls.indexOf("PlatformAdmin") != -1 || rls.indexOf("CuppaAdmin") != -1 || rls.indexOf("OrgAdmin") != -1) && addedRls.indexOf(d) == -1 ) { $scope.availableRoles.push(data[i]); addedRls.push(d); } } else if (d == "SipManager") { // can they access this role? if ( (rls.indexOf("PlatformAdmin") != -1 || rls.indexOf("CuppaAdmin") != -1 || rls.indexOf("OrgAdmin") != -1 || rls.indexOf("SipManager") != -1) && addedRls.indexOf(d) == -1 ) { $scope.availableRoles.push(data[i]); addedRls.push(d); } } else if (d == "Learner") { if (addedRls.indexOf(d) == -1) { // can they access this role? $scope.availableRoles.push(data[i]); addedRls.push(d); } } } $scope.availableRolesUnchanged = $scope.availableRoles; //So that we can refer back to the original list if needed $scope.availableRolesLoaded = true; getOrganisations(); getAssociatedUsers(); }); }); } else { rolesAdminDataContext .getAllRoles(config.appCode) .then(function (data) { for (i in data) { $scope.availableRoles.push(data[i]); } $scope.availableRolesUnchanged = $scope.availableRoles; //So that we can refer back to the original list if needed $scope.availableRolesLoaded = true; if (config.appCode == "MSA") { // Get roles for MS (Myshowcase.me) rolesAdminDataContext.getAllRoles("MS").then(function (data) { for (i in data) { $scope.availableRoles.push(data[i]); $scope.availableUserRoles.push(data[i]); } getOrganisations(); }); } else { getOrganisations(); } }); } } function selectedOrganisation(org) { if (org.selected) { var orgAllocation = usersAdminService.createBlankOrganisationAllocation(); orgAllocation.organisationId = org.id; orgAllocation.isAdmin = false; for (i in $scope.user.organisations) { if ($scope.user.organisations[i].id == org.id) { $scope.user.organisations.splice(i, 1); return; } } org.orgAllocation = orgAllocation; for (i in $scope.availableRoles) { if ( ($scope.availableRoles[i] && $scope.availableRoles[i].name == "User" )|| ($scope.availableRoles[i] && $scope.availableRoles[i].name == "Learner") ) { org.role = $scope.availableRoles[i]; $scope.setOrgRole(org.role, org); } } if ($scope.singleRole) { setAdminAndSingleUserRoles(); } } else { for (i in $scope.user.organisations) { if ($scope.user.organisations[i].organisationId == org.id) { $scope.user.organisations.splice(i, 1); } } org.orgAllocation = null; } } $scope.selectOrganisation = function (org) { selectedOrganisation(org); }; function setAdminAndSingleUserRoles() { var theUserRole = $scope.availableRolesUnchanged.filter(function (a) { return a.name == "User"; })[0]; if (theUserRole == null) { $scope.availableUserRoles.filter(function (a) { return a.name == "User"; })[0]; } var allowedUserRole = $scope.selectedRole != null ? $scope.selectedRole.isAdmin ? theUserRole : $scope.selectedRole : theUserRole; $scope.availableRoles = $scope.availableRolesUnchanged.filter( function (r) { return ( (r.isAdmin //admin roles && r.makeAvailable //and available )); } ); //Add the single allowed user role if (allowedUserRole != null) { if (!allowedUserRole.displayName.startsWith('(User) ')) { allowedUserRole.displayName = "(User) " + allowedUserRole.displayName; } $scope.availableRoles.push(allowedUserRole); } } function setOrgRoles(role, org) { if (!role) { role = $scope.selectedRole; } if (org.orgAllocation == null) { org.orgAllocation = { myRolesId: "", organisationId: org.id, isAdmin: role.isAdmin } } org.orgAllocation.myRolesId = role.id; if (role.isAdmin) { org.orgAllocation.isAdmin = true; } else { org.orgAllocation.isAdmin = false; } for (i in $scope.user.organisations) { if ($scope.user.organisations[i].organisationId == org.id) { $scope.user.organisations.splice(i, 1); } } $scope.user.organisations.push(org.orgAllocation); if ($scope.singleRole) { setAdminAndSingleUserRoles(); } } $scope.setOrgRole = function (role, org) { setOrgRoles(role, org); }; $scope.saveUser = function () { fsl.show("Creating user"); $scope.saving = true; // Set the applications URL for B2C $scope.user.applicationUrl = config.siteUrl; for (i in $scope.user.organisations) { if ($scope.user.organisations[i].isAdmin) { $scope.user.isAdmin = true; } //if ($scope.singleRole) { // $scope.user.organisations[i].myRolesId = $scope.selectedRole.id; // if ($scope.selectedRole.isAdmin) { // $scope.user.isAdmin = true; // $scope.user.organisations[i].isAdmin = true; // } //} } if (!$scope.user.isAdmin) { if (config.appCode == "MSA") { //The email verification url needs to point to the personal site: $scope.user.applicationId = usersAdminConfig.msApplicationId; if (!$scope.user.isAdmin) { $scope.user.appCode = "MS"; $scope.user.applicationUrl = config.myShowcaseSiteUrl; } } if (config.appCode == "CUPPA") { //Cuppa end users shouldn't be sent a welcome email $scope.user.sendWelcomeEmail = false; $scope.user.managedAccount = true; } } if ($scope.showAssociatedUser && $scope.associatedUserId) { $scope.user.associatedUserId = $scope.associatedUserId.userId; } $scope.user.topLevelOrgId = $scope.topLevelOrgId; usersAdminDataContext.createUser($scope.user).then(function (data) { //data is the new userid //Do training requirements processing if necessary if ($scope.jobRoles.length) { $scope.jobRoleIds = []; for (i in $scope.jobRoles) { var orgAllocation = $scope.jobRoles[i].orgAllocation; if (orgAllocation) { $scope.jobRoleIds.push(orgAllocation.organisationId); } } if ($scope.jobRoleIds.length) { skillsPassportsDataContext.updateUserTrainingRequirements(data, $scope.jobRoleIds).then(function () { logSuccess("Successfully updated training requirements"); }, function () { logError("Problem updating training requirements"); }); } } logSuccess("User successfully created"); $rootScope.$broadcast("user-email-updated", { users: $scope.user.email, }); if ($scope.user.userStatus) { if (!$scope.user.newStatusReason) $scope.user.newStatusReason = ""; var userStatus = { "id": $scope.user.userStatus.id, "statusReason": $scope.user.newStatusReason, "status": $scope.user.userStatus.name, "roleId": $scope.user.userStatus.roleId, "firstName": $scope.user.firstName, "lastName": $scope.user.lastName, "userName": $scope.user.userName } console.log(data); // Update the user status to the default for the org usersAdminDataContext .saveCurrentUserStatus( $scope.topLevelOrgId, data, userStatus ) .then(function () { console.log("updated user status"); }); } if ($scope.showRelationships) { if ($scope.relationshipTypes.length > 0) { for (i in $scope.relationshipTypes) { if ($scope.relationshipTypes[i].relationship.secondActor) { $scope.relationshipTypes[i].relationship.firstActor = data; relationshipsDataContext .createRelationship( $scope.relationshipTypes[i].relationship ) .then(function () { console.log("Created relationship for user"); }); } } } } fsl.hide(); if ($scope.organisationId) { $location.path("/users/" + $scope.organisationId); } else { $location.path("/users"); } $scope.saving = false; $scope.userCreated = true; }); }; $scope.doesEmailExist = function (email) { $scope.emailExists = false; //HTML encode the username so that e.g. '+' is handled correctly var email = encodeURIComponent(email); usersAdminDataContext.isEmailAvailable(email).then(function (data) { //Decode the email back again email = decodeURIComponent(email); if (data === true) { $scope.emailExists = true; } }); }; $scope.doesUsernameExist = function (user) { user.userNameExists = false; //HTML encode the username so that e.g. '+' is handled correctly var username = encodeURIComponent(user.userName); usersAdminDataContext .isUsernameAvailable(username) .then(function (data) { //Decode the email back again username = decodeURIComponent(username); if (data === false && username !== $scope.originalUsername) { user.userNameExists = true; } }); }; $scope.inviteUser = function (email) { email = encodeURIComponent(email); window.location = "#!/users?invite=" + email; }; $scope.hideAdministrator = function (orgId) { return function (value, index, array) { if ( $scope.topLevelOrgId == orgId && (value.name == "SystemAdministrator" || value.name == "SystemAdmin" || value.name == "CuppaAdmin") && $rootScope.isSystemAdmin ) { return true; } else if ( value.name == "SystemAdministrator" || value.name == "SystemAdmin" || value.name == "CuppaAdmin" ) { return false; } else { return true; } }; }; $scope.adminAndSingleRoles = function () { return $scope.availableRoles.filter( function (r) { return ( (r.isAdmin || r.id === $scope.selectedRole.id) //admin roles and the single allowed user role && r.makeAvailable //and available ); } ); } } }, ]); app.directive("userProfile", [ "config", "user", "usersAdminService", "common", "$location", "$modal", "$injector", "$routeParams", "datacontext", "userServiceDataContext", "$filter", "OrganisationAdminService", "branding", "rolesAdminDataContext", "usersAdminDataContext", "terminology", "myUsersDataContext", function ( config, user, usersAdminService, common, $location, $modal, $injector, $routeParams, datacontext, userServiceDataContext, $filter, OrganisationAdminService, branding, rolesAdminDataContext, usersAdminDataContext, terminology, myUsersDataContext ) { return { restrict: "E", templateUrl: templatePath + "profile.html", scope: { userId: "=", organisationId: "=", dashboardType: "=", }, link: link, }; function link($scope, elem, attrs) { // Set the log notifiers up var getLogFn = common.logger.getLogFn; var logSuccess = getLogFn("rolesAdmin", "success"); var logError = getLogFn("rolesAdmin", "error"); $scope.roles = []; $scope.terminology = terminology; $scope.branding = branding; $scope.userStatus = "Active"; $scope.statusLoaded = false; getOrganisations(); if ($scope.dashboardType == "framework") { $scope.dashboardUrl = profileTemplatePath + "framework.html"; } if ($scope.dashboardType == "badges") { $scope.dashboardUrl = profileTemplatePath + "badges.html"; var myBadgesAdminDataContext = $injector.get( "myBadgesAdminDataContext" ); getBadgeData(); } if ($scope.dashboardType == "cuppa") { $scope.dashboardUrl = profileTemplatePath + "cuppa.html"; var microlearningAdminDataContext = $injector.get( "microlearningAdminDataContext" ); } $scope.appCode = config.appCode; if ($scope.organisationId) { $scope.organisation = usersAdminService.getOrganisation(); if (!$scope.organisation) { $location.path("/users/" + $scope.organisationId); } } function getOrganisations() { OrganisationAdminService.getTopLevelOrg().then(function (org) { myUsersDataContext .getOrganisationsForUser($scope.userId) .then(function (orgs) { usersAdminDataContext.getCurrentStatusByTenant(org.id, $scope.userId).then(function (data) { if (data) { $scope.userStatus = data.status; $scope.statusLoaded = true; } }); $scope.organisations = orgs; for (i in $scope.organisations) { rolesAdminDataContext .getAllRoleAllocationsForOrgForUser( config.appCode, $scope.organisations[i].id, $scope.userId ) .then(function (role) { if (role) { if ($scope.roles.indexOf(role.roleDisplayName) === -1) { $scope.roles.push(role.roleDisplayName); } } }); } }); }); } $scope.badgeOptions = { responsive: true, maintainAspectRatio: false, legend: { display: false }, scales: { yAxes: [ { ticks: { beginAtZero: true, max: 5, callback: function (value) { if (!(value % 1)) { return Number(value).toFixed(0); } }, }, scaleLabel: { display: false, labelString: "1k = 1000", }, }, ], }, }; $scope.badgeDatasets = [ { backgroundColor: [], borderColor: [], borderWidth: 2, }, ]; $scope.badgeSeriese = ["# of Badges"]; $scope.summaryOptions = { scale: { reverse: false, ticks: { beginAtZero: true, fontSize: 0, }, }, //legend: { display: true } }; $scope.chartOptionsRadar = { scaleLineColor: "transparent", scaleShowLabels: false, legend: { display: false, }, tooltips: { enabled: false, }, }; // Get the currently selected user myUsersDataContext.getUserProfile($scope.userId) .then(function (user) { $scope.user = user; $scope.gotUser = true; }); if ($scope.dashboardType == "framework") { user.getUserAccountSummary($scope.userId).then(function (summary) { var ids = []; ids.push($scope.userId); for (i in $scope.organisations) { ids.push($scope.organisations[i].id); } var queryString = ids.join("&ids="); console.log(queryString); usersAdminDataContext .getDeployments(queryString) .then(function (data) { console.log(data); summary.numActiveFrameworks = data.length; $scope.summary = summary; $scope.summaryLoaded = true; }); }); user .getAssignedTaskCountForUser($scope.userId) .then(function (taskCount) { $scope.taskCount = taskCount; $scope.taskCountLoaded = true; }); } if ($scope.dashboardType == "cuppa") { microlearningAdminDataContext .getMicroLearningAllocationByUser($scope.userId) .then(function (sips) { $scope.sips = sips; }); } function getBadgeData() { myBadgesAdminDataContext .getIssuedByUserForOrg($scope.userId, 2) .then(function (badges) { $scope.issuedBadges = badges; $scope.badgesLoaded = true; $scope.badgeData = []; $scope.badgeData.data = [[]]; $scope.badgeData.label = []; console.log(badges); var max = 5; var index = 30; var fixedStartDate = moment() .startOf("day") .add(1, "day") .toDate(); var fixedEndDate = moment().endOf("day").add(1, "day").toDate(); for (var j = 30; j > 0; j--) { var startDate = moment(fixedStartDate) .subtract(j, "day") .startOf("day") .toDate(); var endDate = moment(fixedEndDate) .subtract(j, "day") .endOf("day") .toDate(); var badgeTotal = 0; for (i in $scope.issuedBadges) { var compareDate = moment( $scope.issuedBadges[i].dateIssued ).toDate(); if (compareDate > startDate && compareDate < endDate) { badgeTotal++; } } if (max < badgeTotal) { max = badgeTotal; $scope.badgeOptions.scales.yAxes[0].ticks.max = badgeTotal; } if ($scope.branding) { $scope.badgeDatasets[0].backgroundColor.push( hexToRGB($scope.branding.secondaryColour, 0.5) ); $scope.badgeDatasets[0].borderColor.push( $scope.branding.secondaryColour ); } else if (config.appCode == "MSA") { $scope.badgeDatasets[0].backgroundColor.push( "rgba(76, 181, 72, 0.5)" ); $scope.badgeDatasets[0].borderColor.push( "rgba(76, 181, 72, 1)" ); } else if (config.appCode == "OB") { $scope.badgeDatasets[0].backgroundColor.push( "rgba(229, 40, 134, 0.5)" ); $scope.badgeDatasets[0].borderColor.push( "rgba(229, 40, 134, 1)" ); } $scope.badgeData.data[0].push(badgeTotal); $scope.badgeData.label.push( $filter("date")( moment(fixedStartDate) .subtract(j, "day") .startOf("day") .toDate(), "dd MMM" ) ); } }); } myUsersDataContext .getOrganisationsForUser($scope.userId) .then(function (orgs) { $scope.organisations = orgs; $scope.orgsLoaded = true; }); $scope.editUser = function (user) { // Set the currently selected user usersAdminService.setManagingUser(user); // Redirect to edit user if ($scope.organisation) { usersAdminService.setOrganisation($scope.organisation); $location.path( "/users/" + $scope.organisation.id + "/" + user.userId + "/edit" ); } else { $location.path("/user/" + user.userId + "/edit"); } }; // Convert the hex to an translucent rgba function hexToRGB(hex, alpha) { var r = parseInt(hex.slice(1, 3), 16), g = parseInt(hex.slice(3, 5), 16), b = parseInt(hex.slice(5, 7), 16); if (alpha) { return "rgba(" + r + ", " + g + ", " + b + ", " + alpha + ")"; } else { return "rgb(" + r + ", " + g + ", " + b + ")"; } } } }, ]); app.directive("editUser", [ "$rootScope", "config", "user", "usersAdminService", "common", "$location", "userServiceDataContext", "OrganisationAdminService", "rolesAdminDataContext", "usersAdminDataContext", "$q", "fullScreenLoaderContext", "usersAdminConfig", "terminology", "myUsersDataContext", "tenantService", "$injector", '$modal', 'skillsPassportsDataContext', function ( $rootScope, config, user, usersAdminService, common, $location, userServiceDataContext, OrganisationAdminService, rolesAdminDataContext, usersAdminDataContext, $q, fullScreenLoaderContext, usersAdminConfig, terminology, myUsersDataContext, tenantService, $injector, $modal, skillsPassportsDataContext ) { return { restrict: "E", templateUrl: templatePath + "edituser.html", scope: { userId: "=", organisationId: "=", singleRole: "=", singleRoleAdmins: "=", canEdit: "=", }, link: link, }; function link($scope, elem, attrs) { // Set the log notifiers up var getLogFn = common.logger.getLogFn; var logSuccess = getLogFn("rolesAdmin", "success"); var logError = getLogFn("rolesAdmin", "error"); $scope.saving = false; $scope.selectedRole = null; $scope.selectedStatus = ""; $scope.terminology = terminology; $scope.relationshipTypes = []; $scope.availableUserStatuses = []; user.getProfile().then(function (me) { $scope.meId = me.userId; getUserProfile(); }); if (config.appCode === "MSA") { var relationshipsDataContext = $injector.get( "relationshipsDataContext" ); } $scope.canDelete = false; $scope.showAssociatedUser = false; $scope.associatedUsers = []; $scope.topLevelOrgId = null; if (!$scope.userId) $location.path("/users"); if ($scope.organisationId) { myUsersDataContext .getOrganisationDetailsSimple($scope.organisationId) .then(function (org) { $scope.organisation = org; }); } function getAvailableUserStatuses() { OrganisationAdminService.getTopLevelOrg().then(function (data) { $scope.topLevelOrgId = data.id; tenantService .getUserStatus(data.id) .then(function (d) { angular.forEach(d, function (v, key) { var ar = { "id": v.name, "name": v.name, "description": v.description, "roleId": v.roleId } $scope.availableUserStatuses.push(ar); }); }); usersAdminDataContext.getCurrentStatusByTenant(data.id, $scope.userId).then(function (data) { if (data) { $scope.user.userStatus = { "id": data.id, "name": data.status, "roleId": data.roleId } $scope.user.selectedStatus = { "id": data.id, "name": data.status, "roleId": data.roleId }; $scope.user.statusReason = data.statusReason; } else { $scope.user.userStatus = { "id": "", "name": "" } $scope.user.selectedStatus = $scope.user.userStatus; } //We need the role id from the status var matchingStatuses = $scope.availableUserStatuses.filter(function (a) { return a.name == $scope.user.userStatus.name; }); if (matchingStatuses.length > 0) { var matchingStatus = matchingStatuses[0]; if (matchingStatus != null) { $scope.user.userStatus.roleId = matchingStatus.roleId; if ($scope.singleRole) { setUserRole($scope.user.userStatus.roleId); } } } }); }); } function getUserProfile() { myUsersDataContext .getUserProfile($scope.userId) .then(function (data) { $scope.user = data; $scope.user.organisations = []; getAvailableUserStatuses(); getAvailableRoles(); $scope.originalUsername = data.userName; $scope.appCode = config.appCode; if (config.appCode === "CUPPA") { $scope.canDelete = true; $scope.showAssociatedUser = true; getAssociatedUsers(data); } if (config.appCode === "MSA") { $scope.showRelationships = true; } }); } function getAssociatedUsers(asoc) { usersAdminDataContext.getAdminUsers().then(function (data) { $scope.associatedUsers = data; if (asoc.associatedUsers && asoc.associatedUsers.length > 0) { angular.forEach($scope.associatedUsers, function (value, key) { if (asoc.associatedUsers[0].associatedUserId == value.userId) { $scope.associatedUserId = value; return; } }); } else { angular.forEach($scope.associatedUsers, function (value, key) { if ($scope.meId == value.userId) { $scope.associatedUserId = value; return; } }); } }); } function getRelationships(userId) { $scope.allRoleIds = $scope.availableRoles.map(function (role) { return role.id; }); usersAdminDataContext .getUsersInRoles({ roleIds: $scope.allRoleIds, orgIds: $scope.allOrgIds, }) .then(function (allUsers) { allUsers = allUsers.map(function (user) { return { id: user.id.toLowerCase(), name: user.firstName + " " + user.lastName + " - " + user.emailAddress, }; }); relationshipsDataContext .getRelationshipTypes() .then(function (types) { $scope.relationshipTypes = types; relationshipsDataContext .getRelationshipsForUser(userId) .then(function (relationships) { angular.forEach( $scope.relationshipTypes, function (value) { var relationship = relationships.filter(function (r) { return ( r.relationshipTypeId === value.id && r.firstActor === userId ); })[0]; value.relationship = relationship ? relationship : { firstActor: userId, relationshipTypeId: value.id, }; if (value.secondActorRole) { usersAdminDataContext .getUsersInRoles({ roleIds: [value.secondActorRole], orgIds: $scope.allOrgIds, }) .then(function (users) { value.availableUsers = users.map(function ( user ) { return { id: user.id.toLowerCase(), name: user.firstName + " " + user.lastName + " - " + user.emailAddress, }; }); value.usersLoaded = true; }); } else { value.availableUsers = allUsers; value.usersLoaded = true; } } ); $scope.relationshipsLoaded = true; }); }); }); } function getOrganisations() { return myUsersDataContext .getOrganisationsForUser($scope.userId) .then(function (orgs) { $scope.currentOrganisations = orgs; var allPromises = []; return myUsersDataContext .getOrganisationsFullFlatSimple() .then(function (data) { $scope.allOrgIds = data.map(function (org) { return org.id; }); if (config.appCode === "MSA") { getRelationships($scope.user.userId); } $scope.groups = []; $scope.organisations = []; $scope.jobRoles = []; $scope.teams = []; $scope.employerGroups = []; $scope.mentorGroups = []; $scope.employerOrganisations = []; for (var i = 0; i < data.length; i++) { if (data[i].type === 0) { $scope.organisations.push(data[i]); } if (data[i].type === 2) { $scope.groups.push(data[i]); } if (data[i].type === 5) { $scope.jobRoles.push(data[i]); } if (data[i].type === 6) { $scope.teams.push(data[i]); } if (data[i].type === 8) { $scope.employerGroups.push(data[i]); } if (data[i].type === 7) { $scope.employerOrganisations.push(data[i]); } if (data[i].type === 9) { $scope.mentorGroups.push(data[i]); } } for (i in $scope.organisations) { var exists = $scope.currentOrganisations.filter(function ( fn ) { return fn.id == $scope.organisations[i].id; })[0]; if (exists) { (function (i) { $scope.organisations[i].selected = true; var promise = rolesAdminDataContext .getAllRoleAllocationsForOrgForUser( config.appCode, $scope.organisations[i].id, $scope.userId ) .then(function (role) { if (!role) { var subPromise = rolesAdminDataContext .getAllRoleAllocationsForOrgForUser( "MS", $scope.organisations[i].id, $scope.userId ) .then(function (role) { if (role) { $scope.organisations[i].orgAllocation = {}; $scope.organisations[ i ].orgAllocation.myRolesId = role.roleId; $scope.organisations[ i ].orgAllocation.userId = $scope.userId; $scope.organisations[ i ].orgAllocation.organisationId = $scope.organisations[i].id; $scope.organisations[ i ].orgAllocation.isAdmin = role.role.isAdmin; $scope.user.organisations.push( $scope.organisations[i].orgAllocation ); } return { orgs: $scope.user.organisations, promiser: 'organisations sub' }; }); allPromises.push(subPromise); } else { $scope.organisations[i].orgAllocation = {}; $scope.organisations[i].orgAllocation.myRolesId = role.roleId; $scope.organisations[i].orgAllocation.userId = $scope.userId; $scope.organisations[ i ].orgAllocation.organisationId = $scope.organisations[i].id; $scope.organisations[i].orgAllocation.isAdmin = role.role.isAdmin; if ( !$rootScope.isSystemAdmin && (role.roleName == "SystemAdministrator" || role.roleName == "SystemAdmin" || role.roleName == "CuppaAdmin") ) $scope.organisations[ i ].orgAllocation.disabled = true; $scope.user.organisations.push( $scope.organisations[i].orgAllocation ); } return { orgs: $scope.user.organisations, promiser: 'organisations' }; }); allPromises.push(promise); })(i); } } if ($scope.groups.length == 0) { $scope.groupsLoaded = true; } for (i in $scope.groups) { var exists = $scope.currentOrganisations.filter(function ( fn ) { return fn.id == $scope.groups[i].id; })[0]; if (exists) { (function (i) { $scope.groups[i].selected = true; var promise = rolesAdminDataContext .getAllRoleAllocationsForOrgForUser( config.appCode, $scope.groups[i].id, $scope.userId ) .then(function (role) { if (!role) { var subPromise = rolesAdminDataContext .getAllRoleAllocationsForOrgForUser( "MS", $scope.groups[i].id, $scope.userId ) .then(function (role) { if (role) { $scope.groups[i].orgAllocation = {}; $scope.groups[i].orgAllocation.myRolesId = role.roleId; $scope.groups[i].orgAllocation.userId = $scope.userId; $scope.groups[ i ].orgAllocation.organisationId = $scope.groups[i].id; $scope.groups[i].orgAllocation.isAdmin = role.role.isAdmin; $scope.user.organisations.push( $scope.groups[i].orgAllocation ); } return { orgs: $scope.user.organisations, promiser: 'groups sub' }; }); allPromises.push(subPromise); } else { $scope.groups[i].orgAllocation = {}; $scope.groups[i].orgAllocation.myRolesId = role.roleId; $scope.groups[i].orgAllocation.userId = $scope.userId; $scope.groups[i].orgAllocation.organisationId = $scope.groups[i].id; $scope.groups[i].orgAllocation.isAdmin = role.role.isAdmin; $scope.user.organisations.push( $scope.groups[i].orgAllocation ); } return { orgs: $scope.user.organisations, promiser: 'groups' }; }); allPromises.push(promise); })(i); } } if ($scope.jobRoles.length === 0) { $scope.jobRolesLoaded = true; } for (i in $scope.jobRoles) { var exists = $scope.currentOrganisations.filter(function ( fn ) { return fn.id === $scope.jobRoles[i].id; })[0]; if (exists) { (function (i) { $scope.jobRoles[i].selected = true; var promise = rolesAdminDataContext .getAllRoleAllocationsForOrgForUser( config.appCode, $scope.jobRoles[i].id, $scope.userId ) .then(function (role) { if (!role) { var subPromise = rolesAdminDataContext .getAllRoleAllocationsForOrgForUser( "MS", $scope.jobRoles[i].id, $scope.userId ) .then(function (role) { if (role) { $scope.jobRoles[i].orgAllocation = {}; $scope.jobRoles[i].orgAllocation.myRolesId = role.roleId; $scope.jobRoles[i].orgAllocation.userId = $scope.userId; $scope.jobRoles[ i ].orgAllocation.organisationId = $scope.jobRoles[i].id; $scope.jobRoles[i].orgAllocation.isAdmin = role.role.isAdmin; $scope.user.organisations.push( $scope.jobRoles[i].orgAllocation ); } return { orgs: $scope.user.organisations, promiser: 'jobRoles sub' }; }); allPromises.push(subPromise); } else { $scope.jobRoles[i].orgAllocation = {}; $scope.jobRoles[i].orgAllocation.myRolesId = role.roleId; $scope.jobRoles[i].orgAllocation.userId = $scope.userId; $scope.jobRoles[i].orgAllocation.organisationId = $scope.jobRoles[i].id; $scope.jobRoles[i].orgAllocation.isAdmin = role.role.isAdmin; $scope.user.organisations.push( $scope.jobRoles[i].orgAllocation ); } return { orgs: $scope.user.organisations, promiser: 'jobRoles' }; }); allPromises.push(promise); })(i); } } if ($scope.teams.length === 0) { $scope.teamsLoaded = true; } for (i in $scope.teams) { var exists = $scope.currentOrganisations.filter(function ( fn ) { return fn.id === $scope.teams[i].id; })[0]; if (exists) { (function (i) { $scope.teams[i].selected = true; var promise = rolesAdminDataContext .getAllRoleAllocationsForOrgForUser( config.appCode, $scope.teams[i].id, $scope.userId ) .then(function (role) { if (!role) { var subPromise = rolesAdminDataContext .getAllRoleAllocationsForOrgForUser( "MS", $scope.teams[i].id, $scope.userId ) .then(function (role) { if (role) { $scope.teams[i].orgAllocation = {}; $scope.teams[i].orgAllocation.myRolesId = role.roleId; $scope.teams[i].orgAllocation.userId = $scope.userId; $scope.teams[ i ].orgAllocation.organisationId = $scope.teams[i].id; $scope.teams[i].orgAllocation.isAdmin = role.role.isAdmin; $scope.user.organisations.push( $scope.teams[i].orgAllocation ); } return { orgs: $scope.user.organisations, promiser: 'teams sub' }; }); allPromises.push(subPromise); } else { $scope.teams[i].orgAllocation = {}; $scope.teams[i].orgAllocation.myRolesId = role.roleId; $scope.teams[i].orgAllocation.userId = $scope.userId; $scope.teams[i].orgAllocation.organisationId = $scope.teams[i].id; $scope.teams[i].orgAllocation.isAdmin = role.role.isAdmin; $scope.user.organisations.push( $scope.teams[i].orgAllocation ); } return { orgs: $scope.user.organisations, promiser: 'teams' }; }); allPromises.push(promise); })(i); } } if ($scope.employerGroups.length === 0) { $scope.employerGroupsLoaded = true; } for (i in $scope.employerGroups) { var exists = $scope.currentOrganisations.filter(function ( fn ) { return fn.id === $scope.employerGroups[i].id; })[0]; if (exists) { (function (i) { $scope.employerGroups[i].selected = true; var promise = rolesAdminDataContext .getAllRoleAllocationsForOrgForUser( config.appCode, $scope.employerGroups[i].id, $scope.userId ) .then(function (role) { if (!role) { var subPromise = rolesAdminDataContext .getAllRoleAllocationsForOrgForUser( "MS", $scope.employerGroups[i].id, $scope.userId ) .then(function (role) { if (role) { $scope.employerGroups[i].orgAllocation = {}; $scope.employerGroups[ i ].orgAllocation.myRolesId = role.roleId; $scope.employerGroups[ i ].orgAllocation.userId = $scope.userId; $scope.employerGroups[ i ].orgAllocation.organisationId = $scope.employerGroups[i].id; $scope.employerGroups[ i ].orgAllocation.isAdmin = role.role.isAdmin; $scope.user.organisations.push( $scope.employerGroups[i].orgAllocation ); } return { orgs: $scope.user.organisations, promiser: 'employerGroups sub' }; }); allPromises.push(subPromise); } else { $scope.employerGroups[i].orgAllocation = {}; $scope.employerGroups[i].orgAllocation.myRolesId = role.roleId; $scope.employerGroups[i].orgAllocation.userId = $scope.userId; $scope.employerGroups[ i ].orgAllocation.organisationId = $scope.employerGroups[i].id; $scope.employerGroups[i].orgAllocation.isAdmin = role.role.isAdmin; $scope.user.organisations.push( $scope.employerGroups[i].orgAllocation ); } return { orgs: $scope.user.organisations, promiser: 'employerGroups' }; }); allPromises.push(promise); })(i); } } if ($scope.mentorGroups.length === 0) { $scope.mentorGroupsLoaded = true; } for (i in $scope.mentorGroups) { var exists = $scope.currentOrganisations.filter(function ( fn ) { return fn.id === $scope.mentorGroups[i].id; })[0]; if (exists) { (function (i) { $scope.mentorGroups[i].selected = true; var promise = rolesAdminDataContext .getAllRoleAllocationsForOrgForUser( config.appCode, $scope.mentorGroups[i].id, $scope.userId ) .then(function (role) { if (!role) { var subPromise = rolesAdminDataContext .getAllRoleAllocationsForOrgForUser( "MS", $scope.mentorGroups[i].id, $scope.userId ) .then(function (role) { if (role) { $scope.mentorGroups[i].orgAllocation = {}; $scope.mentorGroups[ i ].orgAllocation.myRolesId = role.roleId; $scope.mentorGroups[ i ].orgAllocation.userId = $scope.userId; $scope.mentorGroups[ i ].orgAllocation.organisationId = $scope.mentorGroups[i].id; $scope.mentorGroups[ i ].orgAllocation.isAdmin = role.role.isAdmin; $scope.user.organisations.push( $scope.mentorGroups[i].orgAllocation ); } return { orgs: $scope.user.organisations, promiser: 'mentorGroups sub' }; }); allPromises.push(subPromise); } else { $scope.mentorGroups[i].orgAllocation = {}; $scope.mentorGroups[i].orgAllocation.myRolesId = role.roleId; $scope.mentorGroups[i].orgAllocation.userId = $scope.userId; $scope.mentorGroups[ i ].orgAllocation.organisationId = $scope.mentorGroups[i].id; $scope.mentorGroups[i].orgAllocation.isAdmin = role.role.isAdmin; $scope.user.organisations.push( $scope.mentorGroups[i].orgAllocation ); } return { orgs: $scope.user.organisations, promiser: 'mentorGroups' }; }); allPromises.push(promise); })(i); } } if ($scope.employerOrganisations.length === 0) { $scope.employerOrganisationsLoaded = true; } for (i in $scope.employerOrganisations) { var exists = $scope.currentOrganisations.filter(function ( fn ) { return fn.id === $scope.employerOrganisations[i].id; })[0]; if (exists) { (function (i) { $scope.employerOrganisations[i].selected = true; var promise = rolesAdminDataContext .getAllRoleAllocationsForOrgForUser( config.appCode, $scope.employerOrganisations[i].id, $scope.userId ) .then(function (role) { if (!role) { var subPromise = rolesAdminDataContext .getAllRoleAllocationsForOrgForUser( "MS", $scope.employerOrganisations[i].id, $scope.userId ) .then(function (role) { if (role) { $scope.employerOrganisations[ i ].orgAllocation = {}; $scope.employerOrganisations[ i ].orgAllocation.myRolesId = role.roleId; $scope.employerOrganisations[ i ].orgAllocation.userId = $scope.userId; $scope.employerOrganisations[ i ].orgAllocation.organisationId = $scope.employerOrganisations[i].id; $scope.employerOrganisations[ i ].orgAllocation.isAdmin = role.role.isAdmin; $scope.user.organisations.push( $scope.employerOrganisations[i] .orgAllocation ); } return { orgs: $scope.user.organisations, promiser: 'employerOrganisations sub' }; }); allPromises.push(subPromise); } else { $scope.employerOrganisations[i].orgAllocation = {}; $scope.employerOrganisations[ i ].orgAllocation.myRolesId = role.roleId; $scope.employerOrganisations[ i ].orgAllocation.userId = $scope.userId; $scope.employerOrganisations[ i ].orgAllocation.organisationId = $scope.employerOrganisations[i].id; $scope.employerOrganisations[ i ].orgAllocation.isAdmin = role.role.isAdmin; $scope.user.organisations.push( $scope.employerOrganisations[i].orgAllocation ); } return { orgs: $scope.user.organisations, promiser: 'employerOrganisations' }; }); allPromises.push(promise); })(i); } } /* --------------------------------------------- * Once all the orgs/groups processing is done * we can do other processing using that info * * We will have a promise result for each org * membership the user has * --------------------------------------------*/ return $q.all(allPromises).then(function (results) { $scope.organisationsLoaded = true; $scope.groupsLoaded = true; $scope.jobRolesLoaded = true; $scope.teamsLoaded = true; $scope.employerGroupsLoaded = true; $scope.mentorGroupsLoaded = true; $scope.employerOrganisationsLoaded = true; return results; }); }); OrganisationAdminService.getTopLevelOrg().then(function (data) { $scope.topLevelOrgId = data.id; }); }); } function setSelectedSingleUserRole(orgRoles) { /* ---------------------------------------------------------------- * Here we are ensuring there is a User role set in the * 'User Role' dropdown... * * This is complicated because we first want to check if the user * has any User role other than the default one * * So each time we hit this (after each org type list is loaded) * we potentially set and override the set value * * Eventually though we should either have a User role that is * not the default one, or just the default one (because the * user might have been set that or only have admin roles) ---------------------------------------------------------------- */ if (!orgRoles) { return; } //We are using the first User role we come across for the user //as they should only have one User role across the board var firstOrgUserMembership = orgRoles.filter( function (r) { return !r.isAdmin })[0]; //Store the user's org User role info here var orgUserRole = null; var orgUserRoleId = null; if (firstOrgUserMembership && firstOrgUserMembership.myRolesId) { orgUserRoleId = firstOrgUserMembership.myRolesId; } //if ($scope.user.userStatus.roleId) { // orgUserRoleId = $scope.user.userStatus.roleId //} //Set the 'User Role' dropdown option as the user's org user role //(if they have one) if (orgUserRoleId) { orgUserRole = $scope.availableUserRoles.filter( function (r) { return ( r.id === orgUserRoleId ); } )[0]; } //If it's found set it as the dropdown user role if (orgUserRole) { $scope.selectedRole = orgUserRole } var roleIsSet = false; //Check if it's a user role that's not the default one var defaultUserRole = getDefaultAvailableUserRole(); if ($scope.selectedRole != null && defaultUserRole != null && $scope.selectedRole.id != defaultUserRole.id) { //If so, stop processing roleIsSet = true; } //If nothing has been set in the dropdown, use the default user role else if ($scope.selectedRole == null && defaultUserRole != null) { $scope.selectedRole = defaultUserRole; } $scope.originalRole = orgUserRoleId; return roleIsSet; } $scope.setUserRole = function (roleId, isFromUserStatus) { if ($scope.singleRole) { return setUserRole(roleId, isFromUserStatus); } } function getDefaultAvailableUserRole() { var theUserRole = $scope.availableUserRoles.filter(function (a) { return a.name == "User"; })[0]; if (theUserRole) { return theUserRole; } return null; } function setUserRole(roleId, isFromUserStatus) { if ($scope.singleRole) { $scope.isUserStatusRole = roleId && isFromUserStatus; if (!roleId && $scope.selectedRole == null) { var role = getDefaultAvailableUserRole(); if (role) { roleId = role.id; } } //Reset the roles list back to original if ($scope.availableRolesUnchanged.length > 0) { $scope.availableRoles = $scope.availableRolesUnchanged; } if (roleId) { $scope.selectedRole = $scope.availableUserRoles.filter( function (r) { return ( r.id === roleId ); } )[0]; if (!$scope.selectedRole) { $scope.selectedRole = $scope.availableUserRoles.filter( function (r) { return ( r.id === $scope.originalRole ); } )[0]; } //Set this user role as the role on any existing org membership roles that are user role type for (var i in $scope.user.organisations) { if (!$scope.user.organisations[i].isAdmin) { $scope.user.organisations[i].myRolesId = roleId; if (!roleId && $scope.selectedRole) { $scope.user.organisations[i].myRolesId = $scope.selectedRole.id; } } } setAdminAndSingleUserRoles(); } } } $scope.singleRoleHasBeenSet = false; $scope.singleRoleLoaded = false; function getAvailableRoles() { $scope.availableRoles = []; $scope.availableUserRoles = []; $scope.availableRolesUnchanged = []; var orgRoles = []; if (config.appCode == "CUPPA") { var rls = []; var addedRls = []; rolesAdminDataContext .getAllRoleAllocations(config.appCode) .then(function (roles) { for (var r in roles) { rls.push(roles[r].name); } rolesAdminDataContext .getAllRoles(config.appCode) .then(function (data) { for (i in data) { var d = data[i].name; console.log(d); if (d == "PlatformAdmin") { // are they a platform admin? if ( rls.indexOf("PlatformAdmin") != -1 && addedRls.indexOf(d) == -1 ) { $scope.availableRoles.push(data[i]); addedRls.push(d); } } else if (d == "CuppaAdmin") { // can they access this role? if ( (rls.indexOf("PlatformAdmin") != -1 || rls.indexOf("CuppaAdmin") != -1) && addedRls.indexOf(d) == -1 ) { $scope.availableRoles.push(data[i]); addedRls.push(d); } } else if (d == "OrgAdmin") { // can they access this role? if ( (rls.indexOf("PlatformAdmin") != -1 || rls.indexOf("CuppaAdmin") != -1 || rls.indexOf("OrgAdmin") != -1) && addedRls.indexOf(d) == -1 ) { $scope.availableRoles.push(data[i]); addedRls.push(d); } } else if (d == "SipManager") { // can they access this role? if ( (rls.indexOf("PlatformAdmin") != -1 || rls.indexOf("CuppaAdmin") != -1 || rls.indexOf("OrgAdmin") != -1 || rls.indexOf("SipManager") != -1) && addedRls.indexOf(d) == -1 ) { $scope.availableRoles.push(data[i]); addedRls.push(d); } } else if (d == "Learner" && addedRls.indexOf(d) == -1) { // can they access this role? $scope.availableRoles.push(data[i]); addedRls.push(d); } } $scope.availableRolesLoaded = true; getOrganisations().then(function () { if ($scope.singleRole && !singleRoleHasBeenSet) { setSelectedSingleUserRole(''); } }); }); }); } else { // Get roles for MSA (Myshowcase.me Admin) rolesAdminDataContext .getAllRoles(config.appCode) .then(function (data) { for (i in data) { $scope.availableRoles.push(data[i]); } $scope.availableRolesUnchanged = $scope.availableRoles; //So that we can refer back to the original list if needed $scope.availableRolesLoaded = true; getOrganisations().then(function (promiseResults) { for (var i in promiseResults) { var result = promiseResults[i]; for (var j in result.orgs) { orgRoles.push(result.orgs[j]); } } if ($scope.singleRole && !$scope.singleRoleHasBeenSet) { $scope.singleRoleHasBeenSet = setSelectedSingleUserRole(orgRoles); } }).then(function () { // Get roles for MS (Myshowcase.me) rolesAdminDataContext.getAllRoles("MS").then(function (data) { for (i in data) { $scope.availableRoles.push(data[i]); $scope.availableUserRoles.push(data[i]); } getOrganisations().then(function (promiseResults) { for (var i in promiseResults) { var result = promiseResults[i]; for (var j in result.orgs) { orgRoles.push(result.orgs[j]); } } if ($scope.singleRole && !$scope.singleRoleHasBeenSet) { $scope.singleRoleHasBeenSet = setSelectedSingleUserRole(orgRoles); } setAdminAndSingleUserRoles(); $scope.singleRoleLoaded = true; }); }); }); }); } } $scope.selectOrganisation = function (org) { if (org.selected) { var orgAllocation = usersAdminService.createBlankOrganisationAllocation(); orgAllocation.organisationId = org.id; orgAllocation.userId = $scope.userId; orgAllocation.isAdmin = false; for (i in $scope.availableRoles) { if ( $scope.availableRoles[i].name == "User" || $scope.availableRoles[i].name == "Learner" ) { orgAllocation.myRolesId = $scope.availableRoles[i].id; orgAllocation.isAdminRole = $scope.availableRoles[i].isAdmin; } } org.orgAllocation = orgAllocation; $scope.user.organisations.push(orgAllocation); if ($scope.singleRole) { setAdminAndSingleUserRoles(); } } else { for (i in $scope.user.organisations) { if ($scope.user.organisations.length == 1) { org.selected = true; return; } if ($scope.user.organisations[i].organisationId == org.id) { $scope.user.organisations.splice(i, 1); } } org.orgAllocation = null; } }; function setAdminAndSingleUserRoles() { var theUserRole = $scope.availableRolesUnchanged.filter(function (a) { return a.name == "User"; })[0]; if (theUserRole == null) { $scope.availableUserRoles.filter(function (a) { return a.name == "User"; })[0]; } var allowedUserRole = $scope.selectedRole != null ? $scope.selectedRole.isAdmin ? theUserRole : $scope.selectedRole : theUserRole; $scope.availableRoles = $scope.availableRolesUnchanged.filter( function (r) { return ( (r.isAdmin //admin roles && r.makeAvailable //and available )); } ); //Add the single allowed user role if (allowedUserRole != null) { if (!allowedUserRole.displayName.startsWith('(User) ')) { allowedUserRole.displayName = "(User) " + allowedUserRole.displayName; } $scope.availableRoles.push(allowedUserRole); } } $scope.setOrgRole = function (org) { for (i in $scope.availableRoles) { if ($scope.availableRoles[i].id == org.orgAllocation.myRolesId) { if ($scope.availableRoles[i].isAdmin) { org.orgAllocation.isAdmin = true; } else { org.orgAllocation.isAdmin = false; } } } for (i in $scope.user.organisations) { if ($scope.user.organisations[i].organisationId == org.id) { $scope.user.organisations.splice(i, 1); } } $scope.user.organisations.push(org.orgAllocation); if ($scope.singleRole) { setAdminAndSingleUserRoles(); } }; $scope.deleteUser = function () { fullScreenLoaderContext.show("Deleting user"); var userIds = []; userIds.push($scope.userId); $scope.saving = true; usersAdminDataContext.deleteUsers(userIds).then(function (data) { $location.path("/users"); logSuccess("User successfully deleted"); fullScreenLoaderContext.hide(); }); }; $scope.sendVerificationLink = function () { $scope.sendingVerificationLink = true; $scope.user.applicationId = config.applicationId; $scope.user.appCode = config.appCode; for (i in $scope.user.organisations) { if ($scope.user.organisations[i].isAdmin) { $scope.user.isAdmin = true; } if ($scope.singleRole) { $scope.user.organisations[i].myRolesId = $scope.selectedRole.id; if ($scope.selectedRole.isAdmin) { $scope.user.isAdmin = true; $scope.user.organisations[i].isAdmin = true; } } } if (!$scope.user.isAdmin) { if (config.appCode == "MSA") { //The email verification url needs to point to the personal site: $scope.user.applicationId = usersAdminConfig.msApplicationId; $scope.user.appCode = "MS"; } } // Set the applications URL for B2C if (!$scope.user.isAdmin) { $scope.user.applicationUrl = config.myShowcaseSiteUrl; } else { $scope.user.applicationUrl = config.siteUrl; } usersAdminDataContext .sendVerificationLink( $scope.user.email.email, $scope.user.userId, $scope.user.applicationId, $scope.user.appCode, $scope.user.applicationUrl ) .then(function (data) { $rootScope.$broadcast("user-updated", { users: $scope.userId }); logSuccess("Verification email sent"); $scope.sendingVerificationLink = false; }); }; $scope.doesUsernameExist = function (user) { user.userNameExists = false; //HTML encode the username so that e.g. '+' is handled correctly var username = encodeURIComponent(user.userName); usersAdminDataContext .isUsernameAvailable(username) .then(function (data) { //Decode the email back again username = decodeURIComponent(username); if (data === false && username !== $scope.originalUsername) { user.userNameExists = true; $scope.saving = false; } }); }; $scope.saveUser = function () { if ($scope.originalUsername !== $scope.user.userName) { $scope.doesUsernameExist($scope.user); } if ($scope.showAssociatedUser && $scope.associatedUserId) { $scope.user.associatedUserId = $scope.associatedUserId.userId; } $scope.saving = true; for (i in $scope.user.organisations) { if ($scope.user.organisations[i].isAdmin) { $scope.user.isAdmin = true; } } var orgModels = []; for (i in $scope.organisations) { if ($scope.organisations[i].orgAllocation) { orgModels.push($scope.organisations[i].orgAllocation); } } for (i in $scope.groups) { if ($scope.groups[i].orgAllocation) { orgModels.push($scope.groups[i].orgAllocation); } } $scope.jobRoleIds = []; for (i in $scope.jobRoles) { var orgAllocation = $scope.jobRoles[i].orgAllocation; if (orgAllocation) { orgModels.push(orgAllocation); $scope.jobRoleIds.push(orgAllocation.organisationId); } } for (i in $scope.teams) { if ($scope.teams[i].orgAllocation) { orgModels.push($scope.teams[i].orgAllocation); } } for (i in $scope.employerGroups) { if ($scope.employerGroups[i].orgAllocation) { orgModels.push($scope.employerGroups[i].orgAllocation); } } for (i in $scope.mentorGroups) { if ($scope.mentorGroups[i].orgAllocation) { orgModels.push($scope.mentorGroups[i].orgAllocation); } } for (i in $scope.employerOrganisations) { if ($scope.employerOrganisations[i].orgAllocation) { orgModels.push($scope.employerOrganisations[i].orgAllocation); } } //Set the appcode on each model for (i in orgModels) { if (orgModels[i] != null) orgModels[i].appCode = config.appCode; //if ($scope.singleRole) { // orgModels[i].myRolesId = $scope.selectedRole.id; // if ($scope.selectedRole.isAdmin) { // $scope.user.isAdmin = true; // orgModels[i].isAdmin = true; // } //} } $scope.user.topLevelOrgId = $scope.topLevelOrgId; if (config.appCode == "MSA") { //The email verification url needs to point to the personal site: $scope.user.applicationId = usersAdminConfig.msApplicationId; $scope.user.applicationUrl = config.myShowcaseAdminSiteUrl; if (!$scope.user.isAdmin) { $scope.user.appCode = "MS"; $scope.user.applicationUrl = config.myShowcaseSiteUrl; } } $scope.userStatusChanged = false; if (//status changed from a value to empty ($scope.user.userStatus == null && ($scope.user.selectedStatus != null && $scope.user.selectedStatus.id != null)) || //status changed from one value to something else ($scope.user.userStatus && ($scope.user.userStatus.id != $scope.user.selectedStatus.id))) { $scope.userStatusChanged = true; $scope.saving = false; $modal.open({ templateUrl: templatePath + 'token.html', controller: tokenController, size: 'sm', backdrop: 'static', resolve: { message: function () { var statusChangeMessage = ""; if ($scope.user.userStatus) { statusChangeMessage = "change this user's status from " + $scope.user.selectedStatus.name + " to " + $scope.user.userStatus.name + ""; } else { statusChangeMessage = "remove this user's status"; } return "You are about to " + statusChangeMessage + ". Please confirm."; }, user: function () { return $scope.user; }, selectedStatus: function () { return $scope.user.selectedStatus; }, statusReason: function () { return $scope.user.newStatusReason; }, orgModels: function () { return orgModels; }, jobRoleIds: function () { return $scope.jobRoleIds; } } }); } else { fullScreenLoaderContext.show("Updating User") usersAdminDataContext.updateUsers(orgModels).then(function (data) { /*if ($scope.canEdit || $scope.user.managedUser) {*/ usersAdminDataContext.updateUser($scope.user).then(function (data) { $rootScope.$broadcast("user-updated", { users: $scope.userId }); logSuccess("User successfully updated"); if ($scope.organisationId) { $location.path("/users/" + $scope.organisationId); } else { $location.path("/users"); } $scope.saving = false; fullScreenLoaderContext.hide(); }); //} else { // $rootScope.$broadcast('user-updated', { users: $scope.userId }); // logSuccess("User successfully updated"); // if ($scope.organisationId) { // $location.path('/users/' + $scope.organisationId); // } else { // $location.path('/users'); // } // $scope.saving = false; //} }); } // Set the user status if ($scope.showRelationships) { if ($scope.relationshipTypes.length > 0) { for (i in $scope.relationshipTypes) { if ( $scope.relationshipTypes[i].relationship.secondActor && $scope.relationshipTypes[i].relationship.hasChanged ) { if ($scope.relationshipTypes[i].relationship.id) { relationshipsDataContext .updateRelationship( $scope.relationshipTypes[i].relationship ) .then(function () { console.log("Updated relationship for user"); }); } else { relationshipsDataContext .createRelationship( $scope.relationshipTypes[i].relationship ) .then(function () { console.log("Created relationship for user"); }); } } if ( !$scope.relationshipTypes[i].relationship.secondActor && $scope.relationshipTypes[i].relationship.id ) { relationshipsDataContext .deleteRelationship( $scope.relationshipTypes[i].relationship ) .then(function () { console.log("Deleted relationship for user"); }); } } } } //Do training requirements processing if necessary if (!$scope.userStatusChanged) { if ($scope.jobRoleIds && $scope.jobRoleIds.length) { skillsPassportsDataContext.updateUserTrainingRequirements($scope.userId, $scope.jobRoleIds).then(function () { logSuccess("Successfully updated training requirements"); }, function () { logError("Problem updating training requirements"); }); } else { skillsPassportsDataContext.updateUserTrainingRequirements($scope.userId, []).then(function () { //Training requirements were all removed (use has no job roles) }); } } if ($scope.user.verifyUser) { usersAdminDataContext.verifyUserEmail($scope.userId).then(function () { logSuccess("Successfully verified users email"); }, function () { logError("Failed to verify users email"); }); } }; var tokenController = function ($scope, common, $modalInstance, message, user, selectedStatus, statusReason, orgModels, fullScreenLoaderContext, jobRoleIds) { $scope.message = message; $scope.user = user; $scope.selectedStatus = selectedStatus; if (!statusReason) statusReason = ""; //cancel the modal, user doesn't want to chnage password $scope.cancelModel = function () { $scope.saving = false; $modalInstance.close(); }; $scope.confirm = function () { $modalInstance.close(); fullScreenLoaderContext.show("Updating user"); $scope.user.userStatusId = $scope.selectedStatus; var userStatus = { "id": null, "statusReason": statusReason, "status": "", "roleId": null }; if ($scope.user.userStatus) { userStatus = { "id": $scope.user.userStatus.id, "status": $scope.user.userStatus.name, "roleId": $scope.user.userStatus.roleId, "statusReason": $scope.user.newStatusReason, "roleId": $scope.user.userStatus.roleId, "firstName": $scope.user.firstName, "lastName": $scope.user.lastName, "userName": $scope.user.userName }; } OrganisationAdminService.getTopLevelOrg().then(function (data) { return usersAdminDataContext.updateUsers(orgModels) .then(function () { return usersAdminDataContext.updateUser($scope.user); }) .then(function () { if (userStatus.status != "") { return usersAdminDataContext.saveCurrentUserStatus(data.id, $scope.user.userId, userStatus); } else { //Status unselected, so delete their user status completely return usersAdminDataContext.deleteUserStatusesForUser($scope.user.userId); } }); }).then(function () { console.log("updated user status"); $rootScope.$broadcast("user-updated", { users: $scope.userId }); fullScreenLoaderContext.hide(); logSuccess("User successfully updated"); if (jobRoleIds && jobRoleIds.length) { skillsPassportsDataContext.updateUserTrainingRequirements($scope.userId, jobRoleIds).then(function () { logSuccess("Successfully updated training requirements"); }, function () { logError("Problem updating training requirements"); }); } else { skillsPassportsDataContext.updateUserTrainingRequirements($scope.userId, []).then(function () { //Training requirements were all removed (use has no job roles) }); } if ($scope.organisationId) { $location.path("/users/" + $scope.organisationId); } else { $location.path("/users"); } $scope.saving = false; }).catch(function (error) { console.error("An error occurred:", error); fullScreenLoaderContext.hide(); }); }; } $scope.hideAdministrator = function (orgId) { return function (value, index, array) { if ( $scope.topLevelOrgId == orgId && (value.name == "SystemAdministrator" || value.name == "SystemAdmin" || value.name == "PlatformAdmin" || value.name == "CuppaAdmin") && $rootScope.isSystemAdmin ) { return true; } else if ( value.name == "SystemAdministrator" || value.name == "SystemAdmin" || value.name == "PlatformAdmin" || value.name == "CuppaAdmin" ) { return false; } else { return true; } }; }; } }, ]); app.directive("userListDisplay", [ "$modal", "$location", "usersAdminService", "user", "$rootScope", "terminology", function ( $modal, $location, usersAdminService, user, $rootScope, terminology ) { return { restrict: "E", templateUrl: templatePath + "userlistdisplay.html", link: link, scope: { users: "=", meId: "=", filteredUsers: "=", selectedOrg: "=", selectedGroup: "=", searchQueryText: "=", roleAllocations: "=", selectedRole: "=", selectedUserStatus: "=", orgTree: "=", orderByPredicate: "=", reverse: "=", ready: "=", selectedUsers: "=", editMode: "=", visibleUserCount: "=", organisation: "=", }, }; function link($scope, elem, attrs) { $scope.terminology = terminology; $scope.filteredUsers = $scope.users; $scope.startFilter = function (query, org) { if (query === undefined) query = ""; }; $scope.searchFilter = function (obj) { var re = new RegExp($scope.searchQueryText, 'i'); return !$scope.searchQueryText || re.test(obj.firstName) || re.test(obj.lastName) || re.test(obj.email) || re.test(obj.firstname + ' ' + obj.lastName); }; $scope.showMoreUsers = function () { $scope.visibleUserCount = $scope.visibleUserCount + 4; }; $scope.isSystemAdmin = function (user) { for (i in user.roleAllocations) { if ( user.roleAllocations[i].roleName == "SystemAdministrator" || user.roleAllocations[i].roleName == "SystemAdmin" || user.roleAllocations[i].roleName == "CuppaAdmin" ) { if ($rootScope.isSystemAdmin) return false; else { user.cannotManage = true; return true; } } } return false; }; // Manage the selected user $scope.viewUser = function (user) { if ($scope.editMode || user.id == $scope.meId || user.cannotManage) { return; } // Redirect to the manage user view if ($scope.organisation) { usersAdminService.setOrganisation($scope.organisation); $location.path( "/users/" + $scope.organisation.id + "/" + user.id + "/profile" ); } else { $location.path("/user/" + user.id + "/profile"); } }; $scope.editUser = function (user) { if ($scope.editMode) { return; } usersAdminService.setManagingUser(user); // Redirect to edit user if ($scope.organisation) { usersAdminService.setOrganisation($scope.organisation); $location.path( "/users/" + $scope.organisation.id + "/" + user.id + "/edit" ); } else { $location.path("/user/" + user.id + "/edit"); } }; $scope.claculateGroupCount = function (orgs) { var count = 0; for (i in orgs) { if (orgs[i].type == 2) { count++; } } return count; }; $scope.claculateOrgCount = function (orgs) { var count = 0; for (i in orgs) { if (orgs[i].type == 0) { count++; } } return count; }; } }, ]); })();