(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', 'myUsersDataContext', 'OrganisationAdminService', 'terminology', function (config, $rootScope, usersAdminDataContext, usersAdminService, common, $location, $modal, $filter, $timeout, $q, user, rolesAdminDataContext, $routeParams, myUsersDataContext, OrganisationAdminService, terminology) { 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.canImport = config.appCode === 'CUPPA'; $scope.selectedGroup = $scope.groupType[0]; if (config.appCode === 'CUPPA') { $scope.listdisplay = 2; } if ($scope.organisationId) { $scope.selectedOrg = $scope.organisationId; $scope.organisationUserView = true; } else { $scope.selectedOrg; $scope.selectedGroup; } 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.setGroupSelection = function () { $scope.selectedOrg = $scope.selectedGroup; } $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.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; } }); } function generateTypes() { for (i in $scope.organisations) { if ($scope.organisations[i].type === 0) { $scope.organisationType.push($scope.organisations[i]); } else { $scope.groupType.push($scope.organisations[i]); } } $scope.selectedGroup = ''; } 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; }); } 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; getUsersAndOrgs() .then(getRoleAllocationsForUsers) .then(setUserRoleAllocations); }); }); } function refreshUserListing() { $scope.editMode = false; $scope.selectedUsers = []; getUsersAndOrgs() .then(getRoleAllocationsForUsers) .then(setUserRoleAllocations); } $scope.selectedOrgs = []; $scope.bulkAction = function (actionType, orgId, users) { $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: { 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) { $scope.meId = meId; $scope.saving = false; $scope.userEmail = userEmail; $scope.selectedOrganisations = []; $scope.emailExists = false; $scope.topLevelOrgId = topLevelOrgId; $scope.organisationId = organisationId; getOrganisations(); getGroups(); getAvailableRoles(); function getOrganisations() { OrganisationAdminService.getTopLevelOrg().then(function (data) { $scope.topLevelOrgId = data.id; }); myUsersDataContext.getOrganisationsFullFlatSimple(0).then(function (data) { $scope.organisations = data; $scope.organisationsLoaded = true; }); } function getGroups() { myUsersDataContext.getOrganisationsFullFlatSimple(2).then(function (data) { $scope.groups = data; $scope.groupsLoaded = true; }); } 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); } } 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.importUser = function () { $location.path('/importusers'); } $scope.selectAllUsers = function (users, selectAll) { $scope.selectedUsers = []; if (selectAll) { for (i in users) { if (users[i].userId !== $scope.meId && !users[i].cannotManage) $scope.selectedUsers.push(users[i].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: '=', searchQueryText: '=', roleAllocations: '=', selectedRole: '=', 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.directive('createUser', ['$rootScope', 'config', 'user', 'usersAdminDataContext', 'usersAdminService', 'common', '$location', '$modal', '$routeParams', 'rolesAdminDataContext', 'datacontext', 'myUsersDataContext', '$q', 'rolesAdminService', 'OrganisationAdminService', 'validation', 'usersAdminConfig', 'fullScreenLoaderContext', 'terminology', function ($rootScope, config, user, usersAdminDataContext, usersAdminService, common, $location, $modal, $routeParams, rolesAdminDataContext, datacontext, myUsersDataContext, $q, rolesAdminService, OrganisationAdminService, validation, usersAdminConfig, fsl, terminology) { return { restrict: 'E', templateUrl: templatePath + 'createuser.html', scope: { singleRole: '=' }, 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.associatedUsers = []; user.getProfile().then(function (me) { $scope.meId = me.userId; getAvailableRoles(); }); $scope.appCode = config.appCode; if (config.appCode !== 'CUPPA') { getOrganisations(); } $scope.organisationId = $routeParams.organisationId; if ($scope.organisationId) { $scope.organisation = usersAdminService.getOrganisation(); if (!$scope.organisation) { $location.path('/users/' + $scope.organisationId); } } 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 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]) } } 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); } $scope.organisationsLoaded = true; $scope.groupsLoaded = true; $scope.jobRolesLoaded = true; $scope.teamsLoaded = true; $scope.employerGroupsLoaded = true; $scope.mentorGroupsLoaded = true; $scope.employerOrganisationsLoaded = true; }); } function getAvailableRoles() { $scope.availableRoles = []; $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); } 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; getOrganisations(); getAssociatedUsers(); }); }); } else { 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]); } }); } } } 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].name == 'User' || $scope.availableRoles[i].name == 'Learner') { org.role = $scope.availableRoles[i]; $scope.setOrgRole(org.role, org); } } } 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 setOrgRoles(role, org) { 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); } $scope.setOrgRole = function (role, org) { setOrgRoles(role, org); }; $scope.saveUser = function () { fsl.show('Creating user'); $scope.saving = true; 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'; } } 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) { logSuccess("User successfully created"); $rootScope.$broadcast('user-email-updated', { users: $scope.user.email }); 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; } } }; } }]); app.directive('userProfile', ['config', 'user', 'usersAdminService', 'common', '$location', '$modal', '$injector', '$routeParams', 'datacontext', 'myUsersDataContext', 'myBadgesAdminDataContext', '$filter', 'OrganisationAdminService', 'branding', 'rolesAdminDataContext', 'usersAdminDataContext', 'terminology', function (config, user, usersAdminService, common, $location, $modal, $injector, $routeParams, datacontext, myUsersDataContext, myBadgesAdminDataContext, $filter, OrganisationAdminService, branding, rolesAdminDataContext, usersAdminDataContext, terminology) { 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; getOrganisations(); if ($scope.dashboardType == 'framework') { $scope.dashboardUrl = profileTemplatePath + 'framework.html'; } if ($scope.dashboardType == 'badges') { $scope.dashboardUrl = profileTemplatePath + 'badges.html'; 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) { $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); } console.log($scope.roles); } }); } }); }); }; $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 user.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', '$modal', '$routeParams', 'datacontext', 'myUsersDataContext', 'OrganisationAdminService', 'rolesAdminDataContext', 'usersAdminDataContext', 'rolesAdminService', '$q', 'fullScreenLoaderContext', 'usersAdminConfig', 'terminology', function ($rootScope, config, user, usersAdminService, common, $location, $modal, $routeParams, datacontext, myUsersDataContext, OrganisationAdminService, rolesAdminDataContext, usersAdminDataContext, rolesAdminService, $q, fullScreenLoaderContext, usersAdminConfig, terminology) { return { restrict: 'E', templateUrl: templatePath + 'edituser.html', scope: { userId: '=', organisationId: '=', singleRole: '=', 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 = {}; $scope.terminology = terminology; user.getProfile().then(function (me) { $scope.meId = me.userId; getUserProfile(); }); $scope.canDelete = false; $scope.showAssociatedUser = false; $scope.associatedUsers = []; if (!$scope.userId) $location.path('/users'); if ($scope.organisationId) { myUsersDataContext.getOrganisationDetailsSimple($scope.organisationId).then(function (org) { $scope.organisation = org; }); } function getUserProfile() { user.getUserProfile($scope.userId).then(function (data) { $scope.user = data; $scope.user.organisations = []; getAvailableRoles(); $scope.appCode = config.appCode; if (config.appCode === 'CUPPA') { $scope.canDelete = true; $scope.showAssociatedUser = true; getAssociatedUsers(data); } }); } 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 getOrganisations() { myUsersDataContext.getOrganisationsForUser($scope.userId).then(function (orgs) { $scope.currentOrganisations = orgs; 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]) } } var orgRolePromises = []; var orgRoleSubPromises = []; var orgdeferer = $q.defer(); 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); } }); orgRolePromises.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); } }); orgRolePromises.push(promise); })(i); } } $q.all(orgRolePromises).then(function () { orgdeferer.resolve($scope.organisations); $scope.organisationsLoaded = true; if ($scope.singleRole && $scope.user.organisations && $scope.user.organisations.length > 0) { $scope.selectedRole = $scope.availableRoles.filter(function (r) { return r.id === $scope.user.organisations[0].myRolesId })[0]; } }); var groupRolePromises = []; var groupdeferer = $q.defer(); 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); } }); groupRolePromises.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); } }); groupRolePromises.push(promise); })(i); } } $q.all(groupRolePromises).then(function () { $scope.groupsLoaded = true; groupdeferer.resolve($scope.groups); if ($scope.singleRole && $scope.user.organisations && $scope.user.organisations.length > 0) { $scope.selectedRole = $scope.availableRoles.filter(function (r) { return r.id === $scope.user.organisations[0].myRolesId })[0]; } }); var jobRolePromises = []; var jobRoledeferer = $q.defer(); 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); } }); jobRolePromises.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); } }); jobRolePromises.push(promise); })(i); } } $q.all(jobRolePromises).then(function () { $scope.jobRolesLoaded = true; jobRoledeferer.resolve($scope.jobRoles); if ($scope.singleRole && $scope.user.organisations && $scope.user.organisations.length > 0) { $scope.selectedRole = $scope.availableRoles.filter(function (r) { return r.id === $scope.user.organisations[0].myRolesId })[0]; } }); var teamPromises = []; var teamdeferer = $q.defer(); 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); } }); teamPromises.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); } }); teamPromises.push(promise); })(i); } } $q.all(teamPromises).then(function () { $scope.teamsLoaded = true; teamdeferer.resolve($scope.teams); if ($scope.singleRole && $scope.user.organisations && $scope.user.organisations.length > 0) { $scope.selectedRole = $scope.availableRoles.filter(function (r) { return r.id === $scope.user.organisations[0].myRolesId })[0]; } }); var employerGroupPromises = []; var employerGroupdeferer = $q.defer(); 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); } }); employerGroupPromises.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); } }); employerGroupPromises.push(promise); })(i); } } $q.all(employerGroupPromises).then(function () { $scope.employerGroupsLoaded = true; employerGroupdeferer.resolve($scope.employerGroups); if ($scope.singleRole && $scope.user.organisations && $scope.user.organisations.length > 0) { $scope.selectedRole = $scope.availableRoles.filter(function (r) { return r.id === $scope.user.organisations[0].myRolesId })[0]; } }); var mentorGroupPromises = []; var mentorGroupdeferer = $q.defer(); 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); } }); mentorGroupPromises.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); } }); mentorGroupPromises.push(promise); })(i); } } $q.all(mentorGroupPromises).then(function () { $scope.mentorGroupsLoaded = true; mentorGroupdeferer.resolve($scope.mentorGroups); if ($scope.singleRole && $scope.user.organisations && $scope.user.organisations.length > 0) { $scope.selectedRole = $scope.availableRoles.filter(function (r) { return r.id === $scope.user.organisations[0].myRolesId })[0]; } }); var employerOrganisationPromises = []; var employerOrganisationdeferer = $q.defer(); 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); } }); employerOrganisationPromises.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); } }); employerOrganisationPromises.push(promise); })(i); } } $q.all(employerOrganisationPromises).then(function () { $scope.employerOrganisationsLoaded = true; employerOrganisationdeferer.resolve($scope.employerOrganisations); if ($scope.singleRole && $scope.user.organisations && $scope.user.organisations.length > 0) { $scope.selectedRole = $scope.availableRoles.filter(function (r) { return r.id === $scope.user.organisations[0].myRolesId })[0]; } }); }); OrganisationAdminService.getTopLevelOrg().then(function (data) { $scope.topLevelOrgId = data.id; }); } ) }; 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' && (addedRls.indexOf(d) == -1)) { // can they access this role? $scope.availableRoles.push(data[i]); addedRls.push(d); } } $scope.availableRolesLoaded = true; getOrganisations(); }); }); } 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; getOrganisations(); }); 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]); } getOrganisations(); }); } } } $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; } } org.orgAllocation = orgAllocation; $scope.user.organisations.push(orgAllocation); } 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; } } $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); } $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'; } } usersAdminDataContext.sendVerificationLink($scope.user.email.email, $scope.user.userId, $scope.user.applicationId, $scope.user.appCode) .then(function (data) { $rootScope.$broadcast('user-updated', { users: $scope.userId }); logSuccess("Verification email sent"); $scope.sendingVerificationLink = false; }); } $scope.saveUser = function () { 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); } } for (i in $scope.jobRoles) { if ($scope.jobRoles[i].orgAllocation) { orgModels.push($scope.jobRoles[i].orgAllocation); } } 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; } } } 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; }); } 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; } }); } $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('importUsers', ['$rootScope', 'config', 'user', 'usersAdminService', 'common', '$location', '$modal', '$routeParams', 'datacontext', 'myUsersDataContext', 'OrganisationAdminService', 'rolesAdminDataContext', 'usersAdminDataContext', 'rolesAdminService', '$q', 'fullScreenLoaderContext', 'validation', 'terminology', function ($rootScope, config, user, usersAdminService, common, $location, $modal, $routeParams, datacontext, myUsersDataContext, OrganisationAdminService, rolesAdminDataContext, usersAdminDataContext, rolesAdminService, $q, fullScreenLoaderContext, validation, terminology) { return { restrict: 'E', templateUrl: templatePath + 'importusers.html', scope: { organisationId: '=' }, 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.saving = false; $scope.selectedRole = {}; $scope.canDelete = false; $scope.validateReady = false; $scope.complete = false; $scope.errorResults = []; $scope.userTerm = "user"; if (config.appCode === "CUPPA") { $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; fullScreenLoaderContext.show('Validating file'); $scope.fileName = $scope.file.name; console.log($scope.fileName); $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 email = cells[0]; var firstname = cells[1]; var surname = cells[2]; var role = ''; var uid = ''; var group = ''; if (cells.length > 3) { role = cells[3]; } if (cells.length > 4) { uid = cells[4]; } if (cells.length > 5) { group = 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(), 'uniqueIdentifier': uid.trim(), 'group': group.trim(), 'appCode': config.appCode, 'applicationId': config.applicationId, 'associatedUserId': $scope.meId }; $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; } }; } fullScreenLoaderContext.hide(); }; $scope.pushImportedUsers = function () { fullScreenLoaderContext.show('Importing ' + $scope.usersToAdd.length + ' Users'); OrganisationAdminService.getCurrentOrg().then(function (org) { var orgId = org.id; console.log($scope.usersToAdd); console.log(orgId); usersAdminDataContext.createUsers($scope.usersToAdd, orgId).then(function (data) { fullScreenLoaderContext.hide(); $location.path('/users'); logSuccess($scope.usersToAdd.length + " users successfully imported."); }); }); }; } }]); 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: '=', searchQueryText: '=', roleAllocations: '=', selectedRole: '=', 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.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; } } }]); })();