(function () { "use strict"; var app = angular.module("organisationManager"); var templatePath = modulesSharedResourcesUrl + "Modules/OrganisationManager/Views/"; app.directive("organisationManager", [ "config", "myUsersDataContext", "common", "$location", "$modal", "$q", "$upload", "OrganisationAdminService", "fileUpload", "organisationManagerDataContext", "datacontext", "$rootScope", "$routeParams", "licencingAdminDataContext", "$filter", "$route", "rolesAdminDataContext", "frameworks", "features", "$injector", function ( config, userServiceDataContext, common, $location, $modal, $q, $upload, OrganisationAdminService, fileUpload, organisationManagerDataContext, datacontext, $rootScope, $routeParams, licContext, $filter, $route, rolesAdminDataContext, frameworks, features, $injector ) { return { restrict: "E", templateUrl: templatePath + "manage.html", scope: { includeGroups: "=", manageDiscovery: "=", manageFrameworks: "=", manageUsers: "=", manageDetails: "=", createGroups: "=", createOrganisations: "=", createMentors: "=", organisationLogos: "=", disableTopLevelEdit: "=", hideTitle: "=", manageReference: "=", groupTerm: "=", groupIconClass: "=", organisationTerm: "=", organisationIconClass: "=", userTerm: "=", groupTypeId: "=", organisationTypeId: "=", createRootOrgs: "=", manageApiKey: "=", }, link: link, }; function link($scope, elem, attrs) { var getLogFn = common.logger.getLogFn; var log = getLogFn("branding"); var logSuccess = getLogFn("branding", "success"); var logWarning = getLogFn("branding", "warning"); var initial = true; $scope.twoWeeksForward = '20160313T00:00:00'; console.log($scope.twoWeeksForward); $scope.organisationTerm = $scope.organisationTerm ? $scope.organisationTerm : "Organisation"; $scope.organisationIconClass = $scope.organisationIconClass ? $scope.organisationIconClass : "far fa-building"; $scope.groupTerm = $scope.groupTerm ? $scope.groupTerm : "Group"; $scope.groupIconClass = $scope.groupIconClass ? $scope.groupIconClass : "fa fa-users"; $scope.otherGroupIconClass = "fa fa-users"; $scope.userTerm = $scope.userTerm ? $scope.userTerm : "User"; $scope.groupTypeId = $scope.groupTypeId ? $scope.groupTypeId : config.groupTypeId; $scope.organisationTypeId = $scope.organisationTypeId ? $scope.organisationTypeId : config.organisationTypeId; $scope.isHelpOpen = false; $scope.orderByPredicate = "name"; $scope.meId = config.userId; $scope.groups = []; $scope.topLevelOrg = ""; $scope.organisationId = $routeParams.organisationId; $scope.orgsLoaded = false; $scope.orgNotFound = false; $scope.appCode = config.appCode; $scope.searchResults = []; $scope.othertype = $scope.organisationTypeId === 7 ? 9 : 2; activate(); function activate() { $scope.orderByChoice = "Order by name"; $q.all([ getGroups(), //licContext.getCurrentLicense() ]).then(function (data) { $scope.licence = data[1]; log("Activated Groups View"); NProgress.done(); }); if ($location.search().showHelp) { $scope.isHelpOpen = true; } } function flatten(arr, flatArr) { for (i in arr) { flatArr.push(arr[i]); if (arr[i].children) { flatten(arr[i].children, flatArr); } } if (arr.children) { flatten(arr.children, flatArr); } return flatArr; } //get the group details function getGroups(newOrg) { $scope.orgsLoaded = false; return userServiceDataContext .getOrganisationsFullSimpleMulti( $scope.organisationTypeId, $scope.groupTypeId, $scope.othertype ) .then(function (organisations) { log("Got Groups"); var orgs = []; var groups = []; for (var i = 0; i < organisations.length; i++) { if (organisations[i].type === $scope.groupTypeId) { groups.push(organisations[i]); } else if (organisations[i].type === $scope.othertype) { groups.push(organisations[i]); } else if ( organisations[i].type === $scope.organisationTypeId ) { orgs.push(organisations[i]); } } $scope.groups = groups; return getOrganisations(orgs, organisations, newOrg); }); } function findParentOrg(org, orgs) { var found = org; if (found && found.parentId) found = $filter("filter")(orgs, { id: org.parentId }, true)[0]; if (found && found.parentId) found = findParentOrg(found, orgs) ? findParentOrg(found, orgs) : found; return found; } function getOrganisations(data, organisations, newOrg) { if (data.length > 0) { if (data[0].id === "c255c828-8de5-e311-8cfe-78e3b597545b") { data.splice(0, 1); } if (newOrg && data.length > 1) { $scope.setTopLevelOrg(newOrg); } else { $scope.topLevelOrg = data[0].id; } if (data.length > 1) { $scope.topLevelOrgs = data; } if (initial && !$scope.organisationId) { initial = false; } if ($scope.organisationId) { var flatArray = []; flatten(data, flatArray); var filteredOrg = $filter("filter")( flatArray, { id: $scope.organisationId }, true )[0]; if (!filteredOrg) { filteredOrg = $filter("filter")( $scope.groups, { id: $scope.organisationId }, true )[0]; } var parentOrg = findParentOrg( filteredOrg, flatArray.concat($scope.groups) ); if (parentOrg) { $scope.setTopLevelOrg(parentOrg.id); } } var orgIds = []; for (i in data) { orgIds.push(data[i].id); } log("Got Toplevel org"); organisations.topLevel = true; $scope.orgsInTree = []; $scope.organisations = sortOrgGroups(organisations[0]); for (var i = 0; i < $scope.groups.length; i++) { for (var j = 0; j < $scope.orgsInTree.length; j++) { if ($scope.orgsInTree[j].id === $scope.groups[i].id) { $scope.groups[i].hide = true; } } } $scope.organisations.otherGroups = $scope.groups; $scope.organisations = [$scope.organisations]; $scope.orgsLoaded = true; } else { // User must only be an admin for group return userServiceDataContext .getOrganisationsFullSimple($scope.groupTypeId) .then(function (groups) { groups.sort(function (a, b) { if (a.name < b.name) return -1; if (a.name > b.name) return 1; return 0; }); if (groups.length > 0) { $scope.topLevelOrg = groups[0].id; $scope.organisations = groups; return datacontext .getOrgUsers($scope.topLevelOrg) .then(function (data) { if ($scope.orgLicences) { if ($scope.orgLicences[$scope.topLevelOrg]) { $scope.orgLicences[$scope.topLevelOrg].users = data; $scope.selectedNode.users = data; if ( data.totalUsers >= $scope.orgLicences[$scope.topLevelOrg] .numberOfLicences ) { $scope.noLicences = true; } } } $scope.groupAdmin = true; $scope.orgsLoaded = true; log("Got org users"); }); } else { $scope.orgsLoaded = true; } }); } } $scope.setTopLevelOrg = function (orgId) { $scope.orgsLoaded = false; $scope.topLevelOrg = orgId; userServiceDataContext .getOrganisationDetailsSimpleOther( orgId, $scope.organisationTypeId, $scope.groupTypeId, $scope.othertype ) .then(function (data) { log("Got Toplevel org"); data.topLevel = true; $scope.organisations = []; $scope.orgsInTree = []; $scope.organisations = sortOrgGroups(data[0]); for (var i = 0; i < $scope.groups.length; i++) { for (var j = 0; j < $scope.orgsInTree.length; j++) { if ($scope.orgsInTree[j].id == $scope.groups[i].id) { $scope.groups[i].hide = true; } } } $scope.organisations.otherGroups = $scope.groups; $scope.organisations = [$scope.organisations]; $scope.orgsLoaded = true; }); }; $scope.getOrgUsers = function (org) { datacontext.getOrgUsers(org.id).then(function (data) { org.users = data; }); }; $scope.getOrgFrameworks = function (org) { getFrameworks(org.id); }; $scope.backToGroups = function () { adminService.setGroupIsDefault(true); $location.path("/organisations"); }; function sortOrgGroups(data) { if (!data) return; data.groups = []; for (i in data.children) { if ( data.children[i].type === $scope.groupTypeId || data.children[i].type === $scope.othertype ) { data.groups.push(data.children[i]); $scope.orgsInTree.push(data.children[i]); } if (data.children[i]) { sortOrgGroups(data.children[i]); } } return data; } $scope.addGroup = function (orgId, type) { showCreateUpdateUi(null, orgId, null, type); }; $scope.getEmails = function (val) { return datacontext.getEmails(val); }; $scope.onDeleteOrg = function (orgId) { $rootScope.$broadcast("UpdateGroups"); $scope.changeMenu("Hide", true); }; $scope.onEditOrg = function (org) { $rootScope.$broadcast("UpdateGroups"); $scope.changeMenu("Hide", true); }; $scope.onAddUsersToOrg = function (org, users) { log("Users added to organisation " + org.Name); datacontext.sendNotification({ userIds: users, description: "You have been added to the " + org.name + " Organisation", }); }; $scope.onMakeUsersAdminInOrg = function (org, users) { log("Users made admins for organisation " + org.name); datacontext.sendNotification({ userIds: users, description: "You have been made an administrator of the " + org.name + " Organisation", }); }; $scope.onRemoveUsersAdminFromOrg = function (org, users) { log("Users removed as admins for organisation " + org.name); datacontext.sendNotification({ userIds: users, description: "You have been removed as an administrator of the " + org.name + " Organisation", }); }; $scope.onRemoveUsersFromOrg = function (org, users) { log("Users removed from for organisation " + org.name); datacontext.sendNotification({ userIds: users, description: "You have been removed from the " + org.name + " Organisation", }); }; $scope.manageGroup = function (group) { $scope.showUsers = false; $scope.manageShow = true; $scope.theOrg = group; //$scope.meId = $rootScope.currentUser.id; $scope.getUsersForOrganisation(group.id); $scope.getInvitedUsersForOrganisation(group.id); $scope.getPossibleUsersForOrganisation(group.id); $scope.showUsers = true; }; $scope.changeMenu = function (active, showMain) { // $scope.selectedNode = angular.copy($scope.originalNode); $scope.rightPaneSubDetails = false; $scope.rightPaneSubMembers = false; $scope.rightPaneSubInvites = false; $scope.rightPaneSubFrameworks = false; $scope.rightPaneSubDiscovery = false; if (active == "Details") { getorganisationsflat(); $scope.rightPaneSubDetails = true; } if (active == "Members") { $scope.rightPaneSubMembers = true; } if (active == "Frameworks") { $scope.rightPaneSubFrameworks = true; } if (active == "Invites") { $scope.rightPaneSubInvites = true; } if (active == "Discovery") { $scope.rightPaneSubDiscovery = true; } if (active == "Hide" && !showMain) { $scope.manageShow = !$scope.manageShow; } }; $scope.searchOrganisations = function(search) { var orgsCopy = angular.copy($scope.organisations); return searchRecursion(orgsCopy, search.trim().toLowerCase()); }; function searchRecursion(organisations, search, results) { if (!search) return []; if (!organisations) return []; if (!results) results = []; organisations.forEach(org => { let hasMatchingChildren = false; if (org.children && org.children.length > 0) { const filteredChildren = searchRecursion(org.children, search); if (filteredChildren.length > 0) { hasMatchingChildren = true; org.children = filteredChildren; } else { org.children = []; } } const matchesSearch = org.name.toLowerCase().includes(search) || org.description.toLowerCase().includes(search) || hasMatchingChildren; if (matchesSearch) { org.isSearchResult = true; results.push(org); } }); return results; } function showCreateUpdateUi(group, parentId, notOriginal, type) { $modal.open({ templateUrl: templatePath + "createupdate.html", controller: createGroupController, size: "sm", backdrop: "static", resolve: { group: function () { return group; }, datacontext: function () { return datacontext; }, orgId: function () { return $scope.organisationId; }, parentId: function () { return parentId; }, config: function () { return config; }, topLevelOrg: function () { return $scope.topLevelOrg; }, notOriginal: function () { return notOriginal; }, selected: function () { return $scope.selectedNode; }, organisationLogos: function () { return $scope.organisationLogos; }, manageReference: function () { return $scope.manageReference; }, groupTerm: function () { return $scope.groupTerm; }, organisationTerm: function () { return $scope.organisationTerm; }, mentorTerm: function () { return $scope.mentorTerm; }, groupTypeId: function () { return $scope.groupTypeId; }, organisationTypeId: function () { return $scope.organisationTypeId; }, type: function () { return type; }, manageApiKey: function () { return $scope.manageApiKey; }, }, }); } $scope.editGroup = function (group, orgId, notOriginal) { showCreateUpdateUi(group, orgId, notOriginal); }; $scope.deleteGroup = function (group) { userServiceDataContext .deleteOrganisation(group.id) .then(function (result) { getGroups(); }); }; $scope.$on("UpdateGroups", function () { $rootScope.$broadcast("refreshRoleToken"); getGroups($scope.topLevelOrg); }); $scope.cancelChanges = function () { getGroups(); $scope.changeMenu("Hide", true); }; function getorganisationsflat() { userServiceDataContext .getOrganisationDetails( $scope.topLevelOrg, $scope.organisationTypeId, $scope.groupTypeId ) .then(function (data) { $scope.organisationsAvailable = []; $scope.organisationsAvailable.push(data); treeToList(data.children); }); } function treeToList(org) { if (!org) { return; } for (i in org) { if (org[i].type === $scope.organisationTypeId) { $scope.organisationsAvailable.push(org[i]); } if (org[i].children) { treeToList(org[i].children); } } return org; } $scope.updateOrg = function (node) { $scope.toUpdate = node; if ($scope.file) { fileUpload.uploadImage( $scope.file, $scope.file, fileUploadSuccess, UploadProgress, UploadError, cloudinaryUploadPath ); return; } doTheUpdate($scope.toUpdate); }; function doTheUpdate(node) { userServiceDataContext .editOrganisation(node.id, node) .then(function (result) { logSuccess("Successfully updated"); if ($scope.orgSet) { userServiceDataContext .reAssociateGroupWithOrg( [{ id: node.id }], $scope.organisationId ) .then(function (data) { $scope.orgSet = false; if ($scope.parentOrganisationId) { var model = { parentId: $scope.parentOrganisationId, order: 0, }; userServiceDataContext .moveOrg(node.id, model) .then(function (data) { //broadcast the event so the groups list refreshes $rootScope.$broadcast("UpdateGroups"); }); } else { //broadcast the event so the groups list refreshes $rootScope.$broadcast("UpdateGroups"); } }); } else { //broadcast the event so the groups list refreshes $rootScope.$broadcast("UpdateGroups"); } $scope.changeMenu("Hide", true); }); } //controller to handle the create group modal view var createGroupController = function ( $scope, $modalInstance, group, datacontext, config, topLevelOrg, notOriginal, selected, parentId, organisationLogos, manageReference, groupTerm, organisationTerm, groupTypeId, organisationTypeId, $injector, type, manageApiKey ) { $scope.organisationLogos = organisationLogos; $scope.parentOrganisationId = angular.copy(parentId); $scope.topLevelOrg = topLevelOrg; $scope.manageReference = manageReference; $scope.groupTerm = groupTerm; $scope.organisationTerm = organisationTerm; $scope.groupTypeId = type ? type : groupTypeId; $scope.organisationTypeId = organisationTypeId; $scope.manageApiKey = manageApiKey; if (group) { //must be updating $scope.group = $.extend({}, group); $scope.isEdit = true; userServiceDataContext .getOrganisationExternalId($scope.group.id) .then(function (externalId) { if (externalId) { $scope.group.externalId = externalId; } }); if (manageApiKey) { userServiceDataContext .getOrganisationApiDetails($scope.group.id) .then(function (apiDetails) { if (apiDetails) { angular.forEach(apiDetails, function (apiDetail) { if (apiDetail) { if (apiDetail.connectionType != 17) { return; } //!This is only setting 'connectionId' if the connection type is 17 $scope.group.connectionId = apiDetail.id; if (apiDetail.properties) { $scope.group.apiKey = apiDetail.properties.apiKey; $scope.group.apiUrl = apiDetail.properties.systemUrl; } } }); } }); } } else { //must be adding a new group $scope.group = {}; $scope.isEdit = false; $scope.group.enabled = true; } function getorganisations() { userServiceDataContext .getOrganisationsFullFlat($scope.organisationTypeId) .then(function (data) { $scope.organisations = data; }); } if ($scope.isEdit) { getorganisations(); } $scope.setOrg = function (orgId) { $scope.organisationId = orgId; }; //ok clicked - save the new group $scope.ok = function () { if ($scope.file) { fileUpload.uploadImage( $scope.file, $scope.file, fileUploadSuccess, UploadProgress, UploadError, cloudinaryUploadPath ); return; } else { if ($scope.group.startDate && $scope.group.endDate) { if (new Date($scope.group.startDate) > new Date($scope.group.endDate)) { logWarning("Please ensure start date is before end date."); return; } } saveGroup(); } }; function saveGroup() { $scope.saving = true; if ($scope.group.startDate) { var start = new Date($scope.group.startDate).setHours(new Date($scope.group.startDate).getHours() + 1); $scope.group.startDate = new Date(start); } if ($scope.group.endDate) { var end = new Date($scope.group.endDate).setHours(new Date($scope.group.startDate).getHours() + 1); $scope.group.endDate = new Date(end); } $scope.group.type = $scope.groupTypeId; $scope.group.parentId = $scope.group.parentId ? $scope.group.parentId : parentId; if ($scope.group.id && !notOriginal) { userServiceDataContext .editOrganisation($scope.group.id, $scope.group) .then(function (result) { logSuccess("Successfully updated"); if ($scope.parentOrganisationId !== $scope.group.parentId) { var model = { parentId: $scope.parentOrganisationId, order: 0, }; userServiceDataContext .moveOrg($scope.group.id, model) .then(function (data) { //broadcast the event so the groups list refreshes $rootScope.$broadcast("UpdateGroups"); }); } else { //broadcast the event so the groups list refreshes $rootScope.$broadcast("UpdateGroups"); } updateExternalId($scope.group.id); updateApiDetails($scope.group.id); //close the modal $scope.saving = false; $modalInstance.close(); }); } // This if statement can be removed once the migration of groups to orgs has been completed else if (notOriginal) { userServiceDataContext .associateGroupWithOrg( [{ id: $scope.group.id }], $scope.group.parentId ) .then(function (data) { //close the modal $modalInstance.close(); //broadcast the event so the groups list refreshes $rootScope.$broadcast("UpdateGroups"); }); } else { $scope.group.type = $scope.groupTypeId; userServiceDataContext .createGroup($scope.group) .then(function (result) { logSuccess("Successfully created"); selected = result; userServiceDataContext .associateGroupWithOrg( [{ id: result }], $scope.group.parentId ) .then(function (data) { updateExternalId(result); updateApiDetails($scope.group.id); //close the modal $modalInstance.close(); //broadcast the event so the groups list refreshesupdateOrg $rootScope.$broadcast("UpdateGroups"); }); }); } } function updateExternalId(groupId) { if ($scope.group.externalId) { var externalModel = { externalId: $scope.group.externalId }; userServiceDataContext .saveOrganisationExternalId(groupId, externalModel) .then(function (apiDetailsUpdated) { }); } else { var externalModel = { externalId: "" }; userServiceDataContext .saveOrganisationExternalId(groupId, externalModel) .then(function (apiDetailsUpdated) { }); } } function updateApiDetails(groupId) { if (manageApiKey) userServiceDataContext .editOrganisationApiDetails({ id: $scope.group.connectionId, organisationId: groupId, systemUrl: $scope.group.apiUrl, connectionName: $scope.group.apiUrl, connectionType: 17, properties: { ApiKey: $scope.group.apiKey, SystemUrl: $scope.group.apiUrl, }, }) .then(function (apiDetailsUpdated) { logSuccess("Api details saved"); }); } // Called when image file has been selected $scope.onFileSelect = function (files) { if (files) { $scope.errorMessage = null; $scope.file = files[0]; $scope.file.fileName = $scope.file.name; if ($scope.file.size > 20000000) { $scope.errorMessage = "File size is too large, max 20MB"; return; } var reader = new FileReader(); reader.onload = function (e) { $scope.$apply(function () { // get loaded data and render preview. $scope.imagePreview = e.target.result; }); }; // Generate base 64 image for preview reader.readAsDataURL($scope.file); } }; //called when a logo is uploaded function fileUploadSuccess(files, data) { handleUploadResponse(files, data); return; } function handleUploadResponse(files, data) { data.url = data.url.replace(/^http:\/\//i, "https://"); data.url = data.url.replace( /upload\//i, "upload/w_200,h_200,c_pad/" ); $scope.group.logoPath = data.url; saveGroup(); } // Generate the image upload process percentage function UploadProgress(percentComplete) { $scope.progress = percentComplete; $scope.uploadStatus = "Uploading... " + percentComplete + "%"; } function UploadError() { // Throw an error } //cancel the modal, user doesn't want to create a new showcase after all $scope.cancel = function () { $modalInstance.dismiss("cancel"); }; }; //remove an organisation $scope.removeOrg = function (org) { $modal.open({ templateUrl: config.modulesSharedResourcesUrl + "Modules/OrganisationBrowser/orgremoval.html", controller: removeOrgController, size: "sm", backdrop: "static", resolve: { theOrg: function () { return org; }, fullOrgDetails: function () { return [org]; }, onDeleteOrg: function () { return $scope.onDeleteOrg; }, }, }); }; //chnage to a new top level org $scope.changeOrganisation = function () { setOrganisationDetails($scope.currentOrg.id); }; //edit an existing org $scope.editOrganisation = function (org) { openAddEditModal(org, true, false); }; $scope.deleteOrgIssuer = function (orgId) { userServiceDataContext .deleteOrganisationIssuer(orgId) .then(function (data) { logSuccess("Badge issuer successfully deleted"); return data; }); }; $scope.updateOrgIssuer = function (issuer) { if (issuer.id == null) userServiceDataContext .createOrganisationIssuer(issuer) .then(function (data) { $rootScope.containsValidIssuer = true; logSuccess("Badge issuer successfully updated"); return data; }); else { userServiceDataContext .updateOrganisationIssuer(issuer) .then(function (data) { $rootScope.containsValidIssuer = true; logSuccess("Badge issuer successfully updated"); return data; }); } }; $scope.clearModal = true; $scope.$on("UpdateOrganisationDetails", function (event, args) { getGroups(args); }); $scope.$on("UpdateOrganisations", function (event, args) { getGroups(args); }); function openAddEditModal(parentOrg, isEdit, isTopLevel) { $modal.open({ templateUrl: config.modulesSharedResourcesUrl + "Modules/OrganisationBrowser/addeditorg.html", controller: addEditOrgController, size: "sm", backdrop: "static", resolve: { parentOrg: function () { return parentOrg; }, isEdit: function () { return isEdit; }, isTopLevel: function () { return isTopLevel; }, organisationLogos: function () { return $scope.organisationLogos; }, manageReference: function () { return $scope.manageReference; }, groupTerm: function () { return $scope.groupTerm; }, organisationTerm: function () { return $scope.organisationTerm; }, organisationTypeId: function () { return $scope.organisationTypeId; }, manageApiKey: function () { return $scope.manageApiKey; }, }, }); } $scope.newSubOrg = function (org) { var parentOrg = org; if (!parentOrg) { OrganisationAdminService.getTopLevelOrg().then(function (org) { openAddEditModal(org, false, false); }); } else { openAddEditModal(parentOrg, false, false); } }; var addEditOrgController = function ( common, $scope, $modalInstance, $injector, parentOrg, isEdit, isTopLevel, organisationLogos, manageReference, groupTerm, organisationTerm, organisationTypeId, config, manageApiKey ) { var controllerId = "organisations"; var getLogFn = common.logger.getLogFn; var logSuccess = getLogFn(controllerId, "success"); var logWarning = getLogFn(controllerId, "warning"); $scope.saving = false; $scope.parentOrg = parentOrg; $scope.isTopLevel = isTopLevel; $scope.isEdit = isEdit; $scope.organisationLogos = organisationLogos; $scope.manageReference = manageReference; $scope.groupTerm = groupTerm; $scope.organisationTerm = organisationTerm; $scope.author = config.appCode === "CUPPA" && $rootScope.currentRole.name === "CuppaAdmin"; $scope.organisationTypeId = organisationTypeId; $scope.manageApiKey = manageApiKey; if ($scope.author) { var microlearningAdminDataContext = $injector.get( "microlearningAdminDataContext" ); if (isEdit) { microlearningAdminDataContext .getAuthoringEnabled(parentOrg.id) .then(function (data) { $scope.organisation = { id: parentOrg.id, name: parentOrg.name, description: parentOrg.description, children: parentOrg.children, order: parentOrg.order, selfRegistration: parentOrg.selfRegistration, logoPath: parentOrg.logoPath, reference: parentOrg.reference, author: data.enabled, parentId: parentOrg.parentId, externalId: parentOrg.externalId, }; }); } else { $scope.organisation = {}; $scope.organisation.enabled = true; } } else { if (isEdit) { $scope.organisation = { id: parentOrg.id, name: parentOrg.name, description: parentOrg.description, children: parentOrg.children, order: parentOrg.order, selfRegistration: parentOrg.selfRegistration, logoPath: parentOrg.logoPath, reference: parentOrg.reference, parentId: parentOrg.parentId, apiKey: parentOrg.apiKey, apiUrl: parentOrg.apiUrl, startDate: parentOrg.startDate, endDate: parentOrg.endDate, enabled: parentOrg.enabled, externalId: "", }; userServiceDataContext .getOrganisationExternalId($scope.organisation.id) .then(function (externalId) { if (externalId) { $scope.organisation.externalId = externalId; } }); if (manageApiKey) { userServiceDataContext .getOrganisationApiDetails($scope.organisation.id) .then(function (apiDetails) { if (apiDetails) { angular.forEach(apiDetails, function (apiDetail) { if (apiDetail) { if (apiDetail.connectionType != 17) { return; } //!This is only setting 'connectionId' if the connection type is 17 $scope.organisation.connectionId = apiDetail.id; if (apiDetail.properties) { $scope.organisation.apiKey = apiDetail.properties.apiKey; $scope.organisation.apiUrl = apiDetail.properties.systemUrl; } } }); } }); } } else $scope.organisation = {enabled:true}; } //close the modal $scope.cancel = function () { $modalInstance.dismiss("cancel"); }; $("#description").keypress(function (e) { if (e.keyCode != 13) return; var msg = $("#description").val().replace(/\n/g, ""); if (!util.isBlank(msg)) { send(msg); $("#description").val(""); } return false; }); $scope.ok = function () { $scope.saving = true; if ($scope.file) { fileUpload.uploadImage( $scope.file, $scope.file, fileUploadSuccess, UploadProgress, UploadError, cloudinaryUploadPath ); return; } else { if ($scope.organisation.startDate && $scope.organisation.endDate) { if (new Date($scope.organisation.startDate) > new Date($scope.organisation.endDate)) { logWarning("Please ensure start date is before end date."); $scope.saving = false; return; } } saveOrg(); } }; function saveOrg() { if ($scope.organisation.startDate) { var start = new Date($scope.organisation.startDate).setHours(new Date($scope.organisation.startDate).getHours() + 1); $scope.organisation.startDate = new Date(start); } if ($scope.organisation.endDate) { var end = new Date($scope.organisation.endDate).setHours(new Date($scope.organisation.startDate).getHours() + 1); $scope.organisation.endDate = new Date(end); } $scope.organisation.selfRegistration = true; //TODO - maybe take this out $scope.organisation.type = $scope.organisationTypeId; if ($scope.isTopLevel) { userServiceDataContext .createNewParentOrg($scope.parentOrg.id, $scope.organisation) .then(function (newOrg) { updateApiDetails(); completeUpdate(newOrg); $scope.organisation.id = newOrg; updateExternalId(); LogOrgOperation("created"); $rootScope.$broadcast("UpdateGroups"); if ($scope.author) { microlearningAdminDataContext .setAuthoringEnabled( $scope.organisation.id, $scope.organisation.author ) .then(function (data) {}); } }); } else { if ($scope.isEdit) { userServiceDataContext .editOrganisation($scope.organisation.id, $scope.organisation) .then(function () { updateApiDetails(); updateExternalId(); completeUpdate(); LogOrgOperation("updated"); $rootScope.$broadcast("UpdateGroups"); if ($scope.author) { microlearningAdminDataContext .setAuthoringEnabled( $scope.organisation.id, $scope.organisation.author ) .then(function (data) {}); } }); } else { userServiceDataContext .addChildOrganisation( $scope.parentOrg.id, $scope.organisation ) .then(function (newOrg) { updateApiDetails(); completeUpdate(newOrg); $scope.organisation.id = newOrg; updateExternalId(); LogOrgOperation("created"); $rootScope.$broadcast("UpdateGroups"); if ($scope.author) { microlearningAdminDataContext .setAuthoringEnabled(newOrg, $scope.organisation.author) .then(function (data) {}); } }); } } } function updateExternalId() { if ($scope.organisation.externalId) { var externalModel = { externalId: $scope.organisation.externalId, }; userServiceDataContext .saveOrganisationExternalId( $scope.organisation.id, externalModel ) .then(function (apiDetailsUpdated) { }); } else { var externalModel = { externalId: "" }; userServiceDataContext .saveOrganisationExternalId( $scope.organisation.id, externalModel ) .then(function (apiDetailsUpdated) {}); } } function updateApiDetails() { if (manageApiKey) userServiceDataContext .editOrganisationApiDetails({ id: $scope.organisation.connectionId, organisationId: $scope.organisation.id, systemUrl: $scope.organisation.apiUrl, connectionName: $scope.organisation.apiUrl, connectionType: 17, properties: { ApiKey: $scope.organisation.apiKey, SystemUrl: $scope.organisation.apiUrl, }, }) .then(function (apiDetailsUpdated) { logSuccess("Api details saved"); }); } function LogOrgOperation(operation) { switch ($scope.organisation.type) { default: case 0: logSuccess("Organisation successfully " + operation); break; case 2: logSuccess("Group successfully " + operation); break; case 7: logSuccess("Employer successfully " + operation); break; case 8: logSuccess("Contact Group successfully " + operation); break; } } // Called when image file has been selected $scope.onFileSelect = function (files) { if (files) { $scope.errorMessage = null; $scope.file = files[0]; $scope.file.fileName = $scope.file.name; if ($scope.file.size > 20000000) { $scope.errorMessage = "File size is too large, max 20MB"; return; } var reader = new FileReader(); reader.onload = function (e) { $scope.$apply(function () { // get loaded data and render preview. $scope.imagePreview = e.target.result; }); }; // Generate base 64 image for preview reader.readAsDataURL($scope.file); } }; //called when a logo is uploaded function fileUploadSuccess(files, data) { handleUploadResponse(files, data); return; } function handleUploadResponse(files, data) { data.url = data.url.replace(/^http:\/\//i, "https://"); data.url = data.url.replace( /upload\//i, "upload/w_200,h_200,c_pad/" ); $scope.organisation.logoPath = data.url; saveOrg(); } // Generate the image upload process percentage function UploadProgress(percentComplete) { $scope.progress = percentComplete; $scope.uploadStatus = "Uploading... " + percentComplete + "%"; } function UploadError() { // Throw an error } function completeUpdate(newOrg) { if (isTopLevel) $rootScope.$broadcast("UpdateOrganisations", newOrg); else $rootScope.$broadcast("UpdateOrganisationDetails", newOrg); $modalInstance.close(); } }; //close the modal $scope.cancel = function () { $modalInstance.dismiss("cancel"); }; $scope.getUsersForOrganisation = function (orgId) { $scope.users = []; return userServiceDataContext.getUsers(orgId).then(function (data) { var users = data; var userIds = users.map(function (user) { return user.id; }); if (userIds.length > 0) { var roles$ = rolesAdminDataContext.getAllocationsForOrgForManyUsers( "MSA", orgId, userIds ); return roles$.then(function (userRoleAllocations) { $scope.users = users.map(function (user) { user.roleAllocation = userRoleAllocations[user.id]; return user; }); console.log($scope.users); return $scope.users; }); } else { return; } }); }; $scope.getPossibleUsersForOrganisation = function () { return userServiceDataContext.getUsers(noOrgId).then(function (data) { return ($scope.possibleUsers = data); }); }; $scope.getAdministratorsForOrganisation = function (orgId) { return userServiceDataContext .getAdministratorsForOrganisation(orgId) .then(function (data) { return data; }); }; $scope.getInvitedUsersForOrganisation = function (orgId) { return userServiceDataContext .getInvitedUsers(orgId) .then(function (invitedUsers) { for (var i = 0; i < invitedUsers.length; i++) { invitedUsers[i].email = invitedUsers[i].emailAddress; } $scope.invitedUsers = invitedUsers; }); }; $scope.invite = function (orgId, emails, orgName) { return userServiceDataContext .addInvitedUsers(orgId, emails) .then(function (data) { if (data) return userServiceDataContext.sendInviteEmails({ IndividualOrganisationInvites: data, organisation: { id: orgId, name: orgName, }, isOrg: true, }); }); }; $scope.addUsersToOrganisation = function (orgId, addedUsers) { return userServiceDataContext .addUsers(orgId, addedUsers) .then(function () { if ($scope.onAddUsersToOrg) { var fullAddedUsers = []; for (var i = 0; i < $scope.possibleUsers.length; i++) { if (addedUsers.length === fullAddedUsers.length) break; for (var j = 0; j < addedUsers.length; j++) { if ($scope.possibleUsers[i].id === addedUsers[j]) { fullAddedUsers.push($scope.possibleUsers[i]); break; } } } $scope.onAddUsersToOrg(orgId, fullAddedUsers); } }); }; var removeOrgController = function ( $scope, $modalInstance, theOrg, fullOrgDetails, onDeleteOrg ) { $scope.theOrg = theOrg; $scope.fullOrgDetails = fullOrgDetails; $scope.rootOrgId = fullOrgDetails[0].id; $scope.onDeleteOrg = onDeleteOrg; $scope.orgsLoaded = false; //close the modal $scope.cancel = function () { $modalInstance.dismiss("cancel"); }; $scope.getUsersForOrganisation = function () { return userServiceDataContext .getUsers($scope.theOrg.id) .then(function (data) { return ($scope.users = data); }); }; $scope.confirmDelete = function () { deleteOrg($scope.theOrg.id); }; function deleteOrg(orgId) { userServiceDataContext.deleteOrganisation(orgId).then(function () { $scope.onDeleteOrg(); $rootScope.$broadcast("UpdateOrganisationDetails"); $modalInstance.dismiss(); }); } function getOrganisationDetails(orgId) { userServiceDataContext .getOrganisationDetails( orgId, $scope.organisationTypeId, $scope.groupTypeId ) .then(function (data) { //remove the'no org' org $scope.hasChildOrgs = data.children.length > 0; var index = -1; for (var i = 0; i < data.children.length; i++) { if (data.children[i].id === noOrgId) { index = i; break; } } if (index > -1) data.children.splice(index, 1); $scope.organisationDetails = [data]; $scope.orgsLoaded = true; $scope.childrenLoaded = true; }); } function getUserIds(users) { var userIds = []; for (var i = 0; i < users.length; i++) { userIds.push(users[i].id); } return userIds; } $scope.manageUsers = function () { $location.path("/users/" + theOrg.id); $modalInstance.dismiss(); }; $scope.removeUsers = function () { return userServiceDataContext .removeUsers($scope.theOrg.id, getUserIds($scope.users)) .then(function () { deleteOrg($scope.theOrg.id); }); }; $scope.reassignUsersToRoot = function () { var userIds = getUserIds($scope.users); return userServiceDataContext .removeUsers($scope.theOrg.id, userIds) .then(function () { userServiceDataContext .addUsers($scope.rootOrgId, userIds) .then(function () { deleteOrg($scope.theOrg.id); }); }); }; $scope.addUsersToOrganisation = function (orgId, users) { return userServiceDataContext.addUsers(orgId, users); }; $scope.getUsersForOrganisation($scope.theOrg.id); getOrganisationDetails($scope.theOrg.id); }; //remove an organisation $scope.manageFrameworksForOrg = function (org) { $modal.open({ templateUrl: config.modulesSharedResourcesUrl + "Modules/OrganisationManager/Views/frameworks.html", controller: manageFrameworksController, size: "lg", backdrop: "static", resolve: { theOrg: function () { return org; }, }, }); }; var manageFrameworksController = function ( $scope, $modalInstance, theOrg ) { $scope.org = theOrg; $scope.frameworks = []; $scope.saveFrameworks = function (id) { var ids = []; for (var i = 0; i < $scope.frameworks.length; i++) { ids.push($scope.frameworks[i].id); } userServiceDataContext .editFrameworksForOrg(id, ids) .then(function () { logSuccess("Frameworks updated"); $modalInstance.dismiss("cancel"); }); }; function getFrameworks(id) { userServiceDataContext .getFrameworksForOrg(id) .then(function (theFrameworks) { if (theFrameworks.length > 0) { frameworks .getFrameworkList(theFrameworks) .then(function (data) { for (var i = 0; i < data.length; i++) { data[i].deactivated = false; data[i].groupAllocated = false; } $scope.frameworks = data; }); } else $scope.frameworks = []; }); } //close the modal $scope.cancel = function () { $modalInstance.dismiss("cancel"); }; getFrameworks($scope.org.id); }; } }, ]); app.directive("jobRolesManager", [ "config", "myUsersDataContext", "common", "$modal", "OrganisationAdminService", "$rootScope", "terminology", function ( config, userServiceDataContext, common, $modal, OrganisationAdminService, $rootScope, terminology ) { return { restrict: "E", templateUrl: templatePath + "jobroles.html", link: link, }; function link($scope, elem, attrs) { var getLogFn = common.logger.getLogFn; var log = getLogFn("branding"); var logSuccess = getLogFn("branding", "success"); $scope.topLevelOrg = ""; activate(); function activate() { getJobRoles(); } function getJobRoles() { OrganisationAdminService.getTopLevelOrg().then(function (data) { $scope.topLevelOrg = data.id; userServiceDataContext .getOrganisationsFullFlat(config.jobRoleTypeId) .then(function (jobRoles) { log("Got job roles"); $scope.jobRoles = jobRoles; userServiceDataContext .getOrganisationsFullFlat(0) .then(function (orgs) { for (var i = 0; i < $scope.jobRoles.length; i++) { for (var j = 0; j < orgs.length; j++) { if ($scope.jobRoles[i].parentId === orgs[j].id) $scope.jobRoles[i].organisation = orgs[j]; } } }); }); }); } $scope.addJobRole = function () { showCreateUpdateUi(null); }; $scope.editJobRole = function (jobRole) { showCreateUpdateUi(jobRole); }; $scope.deleteJobRole = function (jobRole) { userServiceDataContext .deleteOrganisation(jobRole.id) .then(function (result) { getJobRoles(); }); }; function showCreateUpdateUi(jobRole, parentId, notOriginal) { $modal.open({ templateUrl: templatePath + "createupdatejobrole.html", controller: createJobRoleController, size: "sm", backdrop: "static", resolve: { jobRole: function () { return jobRole; }, orgId: function () { return $scope.organisationId; }, topLevelOrg: function () { return $scope.topLevelOrg; }, notOriginal: function () { return notOriginal; }, terminology: function () { return terminology; }, }, }); } //controller to handle the create job role modal view var createJobRoleController = function ( $scope, $modalInstance, jobRole, orgId, topLevelOrg, notOriginal, terminology ) { $scope.organisationId = orgId; $scope.topLevelOrg = topLevelOrg; $scope.parentOrganisationId = ""; $scope.terminology = terminology; if (jobRole) { //must be updating userServiceDataContext .getOrganisationDetails(jobRole.id) .then(function (data) { $scope.jobRole = data; $scope.parentOrganisationId = data.parentId; $scope.loaded = true; }); $scope.isEdit = true; } else { //must be adding a new job role $scope.jobRole = {}; $scope.isEdit = false; $scope.loaded = true; } function getorganisations() { userServiceDataContext .getOrganisationsFullFlat(0) .then(function (data) { $scope.organisations = data; }); } getorganisations(); //ok clicked - save the new group $scope.ok = function () { saveJobRole(); }; function saveJobRole() { $scope.saving = true; $scope.jobRole.ordinal = 0; if ($scope.jobRole.id) { userServiceDataContext .editOrganisation($scope.jobRole.id, $scope.jobRole) .then(function (result) { logSuccess("Successfully updated"); userServiceDataContext .associateGroupWithOrg( [{ id: $scope.jobRole.id }], $scope.parentOrganisationId ) .then(function (data) { //close the modal $modalInstance.close(); //broadcast the event so the job roles list refreshesupdateOrg $rootScope.$broadcast("UpdateJobRoles"); }); }); } else { userServiceDataContext .createJobRole($scope.jobRole) .then(function (result) { logSuccess("Successfully created"); userServiceDataContext .associateGroupWithOrg( [{ id: result }], $scope.parentOrganisationId ) .then(function (data) { //close the modal $modalInstance.close(); //broadcast the event so the job roles list refreshesupdateOrg $rootScope.$broadcast("UpdateJobRoles"); }); }); } } $scope.cancel = function () { $modalInstance.dismiss("cancel"); }; }; $scope.$on("UpdateJobRoles", function () { activate(); }); } }, ]); app.directive("teamsManager", [ "config", "myUsersDataContext", "common", "$modal", "OrganisationAdminService", "$rootScope", function ( config, userServiceDataContext, common, $modal, OrganisationAdminService, $rootScope ) { return { restrict: "E", templateUrl: templatePath + "teams.html", link: link, }; function link($scope, elem, attrs) { var getLogFn = common.logger.getLogFn; var log = getLogFn("branding"); var logSuccess = getLogFn("branding", "success"); $scope.topLevelOrg = ""; activate(); function activate() { getTeams(); } function getTeams() { OrganisationAdminService.getTopLevelOrg().then(function (data) { $scope.topLevelOrg = data.id; return userServiceDataContext .getOrganisationsFullFlat(config.teamTypeId) .then(function (teams) { log("Got job roles"); $scope.teams = teams; console.log(teams); }); }); } $scope.getOrgDetails = function (team) { userServiceDataContext .getOrganisationDetails(team.parentId) .then(function (org) { team.organisation = org; return team; }); }; $scope.addTeam = function () { showCreateUpdateUi(null); }; $scope.editTeam = function (team) { showCreateUpdateUi(team); }; $scope.deleteTeam = function (team) { userServiceDataContext .deleteOrganisation(team.id) .then(function (result) { getTeams(); }); }; function showCreateUpdateUi(team, parentId, notOriginal) { $modal.open({ templateUrl: templatePath + "createupdateteam.html", controller: createTeamController, size: "sm", backdrop: "static", resolve: { team: function () { return team; }, orgId: function () { return $scope.organisationId; }, topLevelOrg: function () { return $scope.topLevelOrg; }, notOriginal: function () { return notOriginal; }, }, }); } //controller to handle the create job role modal view var createTeamController = function ( $scope, $modalInstance, team, orgId, topLevelOrg, notOriginal ) { $scope.organisationId = orgId; $scope.topLevelOrg = topLevelOrg; $scope.parentOrganisationId = ""; if (team) { //must be updating userServiceDataContext .getOrganisationDetails(team.id) .then(function (data) { $scope.team = data; $scope.parentOrganisationId = data.parentId; $scope.loaded = true; }); $scope.isEdit = true; } else { //must be adding a new job role $scope.team = {}; $scope.isEdit = false; $scope.loaded = true; } function getorganisations() { userServiceDataContext .getOrganisationsFullFlat(0) .then(function (data) { $scope.organisations = data; }); } getorganisations(); //ok clicked - save the new group $scope.ok = function () { saveTeam(); }; function saveTeam() { $scope.saving = true; $scope.team.ordinal = 0; if ($scope.team.id) { userServiceDataContext .editOrganisation($scope.team.id, $scope.team) .then(function (result) { logSuccess("Successfully updated"); userServiceDataContext .associateGroupWithOrg( [{ id: $scope.team.id }], $scope.parentOrganisationId ) .then(function (data) { //close the modal $modalInstance.close(); //broadcast the event so the job roles list refreshesupdateOrg $rootScope.$broadcast("UpdateTeams"); }); }); } else { userServiceDataContext .createTeam($scope.team) .then(function (result) { logSuccess("Successfully created"); userServiceDataContext .associateGroupWithOrg( [{ id: result }], $scope.parentOrganisationId ) .then(function (data) { //close the modal $modalInstance.close(); //broadcast the event so the job roles list refreshesupdateOrg $rootScope.$broadcast("UpdateTeams"); }); }); } } $scope.cancel = function () { $modalInstance.dismiss("cancel"); }; }; $scope.$on("UpdateTeams", function () { activate(); }); } }, ]); })();