(function () { var modalCreateLoginService = function ($modal) { this.show = function (person) { return $modal.open({ templateUrl: '/Person/ModalCreateLoginView', controller: 'modalCreateLoginController', resolve: { person: function () { return person; } } }).result; }; }; modalCreateLoginService.$inject = ['$modal']; angular.module('rubicApp').service('ModalCreateLoginService', modalCreateLoginService); }());; (function () { var modalCreateLoginController = function ($scope, $http, $modalInstance, WebApiUrlService, person, callApi, ServerValues) { $scope.person = person; $scope.emailPrefilled = person.contact.contactEmail != null && person.contact.contactEmail.length > 0; $scope.login = { personID: person.personID, username: person.contact.contactEmail, password: '', confirmPassword: '', organizationID: ServerValues.organizationID }; $scope.submitted = false; $scope.createLogin = function () { console.log($scope.createLoginFrm) $scope.hasError = false; $scope.error = ''; $scope.saving = true; $scope.submitted = true; if ($scope.createLoginFrm.$valid) { callApi(function () { return $http.post("/api/PersonsApi/CreateLogin/email", $scope.login); }) .then(function (person) { $scope.saving = false; $scope.person = person; $modalInstance.close($scope); }, function (error) { $scope.saving = false; $scope.error = error.toString(); $scope.hasError = true; }); } $scope.saving = false; }; $scope.removeLogin = function () { $scope.hasError = false; $scope.error = ''; $scope.saving = true; callApi(function () { return $http.post("/api/PersonsApi/DeleteLogin/" + $scope.person.personID) }) .then(function (person) { $scope.saving = false; $scope.person = person; $modalInstance.close($scope); }, function (error) { $scope.hasError = true; $scope.error = error.toString(); $scope.saving = false; }) }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; }; modalCreateLoginController.$inject = ['$scope', '$http', '$modalInstance', 'WebApiUrlService', 'person', 'CallApiService', 'ServerValues']; angular.module('rubicApp') .controller('modalCreateLoginController', modalCreateLoginController) .directive('equals', function () { return { restrict: 'A', // only activate on element attribute require: '?ngModel', // get a hold of NgModelController link: function (scope, elem, attrs, ngModel) { if (!ngModel) return; // do nothing if no ng-model // watch own value and re-validate on change scope.$watch(attrs.ngModel, function () { validate(); }); // observe the other value and re-validate on change attrs.$observe('equals', function (val) { validate(); }); var validate = function () { // values var val1 = ngModel.$viewValue; var val2 = attrs.equals; // set validity ngModel.$setValidity('equals', !val1 || !val2 || val1 === val2); }; } }; }) .directive('pwd', function () { return { restrict: 'A', // only activate on element attribute require: '?ngModel', // get a hold of NgModelController link: function (scope, elem, attrs, ctrl) { ctrl.$parsers.unshift(function (viewValue) { var pwdValidLength, pwdHasUpperLetter, pwdHasLowerLetter, pwdHasNumber; pwdValidLength = (viewValue && viewValue.length >= 7 ? true : false); pwdHasUpperLetter = (viewValue && /[A-Z]/.test(viewValue)) ? true : false; pwdHasLowerLetter = (viewValue && /[a-z]/.test(viewValue)) ? true : false; pwdHasNumber = (viewValue && /\d/.test(viewValue)) ? true : false; if (pwdValidLength && pwdHasUpperLetter && pwdHasLowerLetter && pwdHasNumber) { ctrl.$setValidity('pwd', true); } else { ctrl.$setValidity('pwd', false); } return viewValue; }); } }; }) .directive('username', function ($q, $timeout, $http) { return { require: 'ngModel', link: function (scope, elm, attrs, ctrl) { ctrl.$asyncValidators.username = function (modelValue, viewValue) { if (ctrl.$isEmpty(modelValue)) { // consider empty model valid return $q.resolve(); } var def = $q.defer(); $http.get("/rest/accounts/userexists?username=" + modelValue) .then(function (response) { if (response.data.result) { def.reject(); } else { def.resolve(); } }); return def.promise; }; } }; }); }());; (function () { function pad(number, length) { var str = '' + number; while (str.length < length) { str = '0' + str; } return str; } function formatDate(dt) { if (!dt || dt == "" || dt == null) { return ""; } var str = dt.toString(); var parts = str.substring(0, 10).split('-'); return pad(parts[2], 2) + "." + pad(parts[1], 2) + "." + pad(parts[0], 4); } function parseDate(dt) { if (typeof dt == undefined || dt == "" || dt == null) { return ""; } var parts = dt.toString().split('.'); var date = new Date(Date.UTC(parts[2], parts[1] - 1, parts[0], 0, 0, 0, 0)); return date; } var personEditController = function ($scope, $http, $rootScope, $upload, $timeout, $q, $modal, WebApiUrlService, ServerValues, ModalCreateLoginService, ModalActivateUserService, $window, ModalConfirmService, ModalChangePasswordService, ModalChangeUsernameService, ModalPaymentCardsService, CallApi) { $scope.loading = true; $scope.person = null; $scope.userAllowed = true; $scope.isGuardian = false; $scope.saving = false; $scope.countries = []; $scope.fileReaderSupported = window.FileReader != null; $scope.organizationID = ServerValues.organizationID; $scope.isPublic = (typeof ServerValues.isPublic == 'undefined' || !ServerValues.isPublic) ? false : true; $scope.isAurdalPublic = ($scope.isPublic && $scope.organizationID == 9509) ? true : false; $scope.isOrganizationAdmin = false; guardianCheck(); $scope.init = function () { $http.get(WebApiUrlService.BasicDataApi.GetCountries) .success(function (data, status, headers, config) { $scope.countries = data.data; }) .error(function (data, status, headers, config) { } ); $http.get(WebApiUrlService.PersonsApi.GetContactInfo + '/' + ServerValues.personID) .success(function (data, status, headers, config) { $scope.loading = false; $scope.person = data.data[0]; $rootScope.person = $scope.person; $scope.resetPicture(); $scope.birthDate = formatDate($scope.person.birthDate); $scope.checkIfOrgAdmin(); $scope.validateSocialnumber(); if ($scope.person.address != null) saveAddressToServerValues($scope.person.address.streetAddress1); }) .error(function (data, status, headers, config) { $scope.userAllowed = false; } ); }; $scope.countryChanged = function (country) { $person.address.country = country; }; $scope.checkIfOrgAdmin = function () { if ($scope.isPublic) { $scope.isOrganizationAdmin = false; } else { if (ServerValues.isOrganizationAdmin) { $scope.isOrganizationAdmin = true; } else { $scope.isOrganizationAdmin = false; } } } $scope.validateSocialnumber = function () { var nr = $scope.person.socialSecurityNumber; if (nr) { $scope.isValidSocialnumber = $scope.checkValidSocialnumber(nr); if ($scope.isValidSocialnumber) { $scope.personalInfo.socialSecurityNumber.$setValidity("socialSecurityNumber", true); } else { $scope.personalInfo.socialSecurityNumber.$setValidity("socialSecurityNumber", false); } } else { $scope.personalInfo.socialSecurityNumber.$setValidity("socialSecurityNumber", true); } } $scope.addMember = function () { $scope.saving = true; var subOrganizationIDs = []; ModalConfirmService.confirm("Innmelding", "Ønsker du å melde inn " + $scope.person.firstName + " " + $scope.person.lastName + "?", "Meld inn", "Avbryt") .then(function () { CallApi(function () { return $http.put('/api/Members/' + $scope.organizationID + '/admin/AddPersonAsMember/' + $scope.person.personID + '?roleID=0&memberCategory=1', subOrganizationIDs); }) .then(function (member) { location.reload(); }, function (error) { ModalConfirmService.confirm("Feil", error.toString(), "OK"); }); }, function () { $scope.saving = false; // cancel }) .finally(function () { member.saving = false; }); } $scope.checkValidSocialnumber = function (nr) { if (nr.length != 11) { return false; } var day = nr.substr(0, 2); var month = nr.substr(2, 2); var year = nr.substr(4, 2); var ind = nr.substr(6, 3); var c1 = nr.substr(9, 1); var c2 = nr.substr(10, 1); var yearno = parseInt(year); if (ind > 0 && ind < 500) { yearno += 1900; } else if (ind > 499 && ind < 750 && year > 55 && year < 100) { yearno += 1800; } else if (ind > 499 && ind <= 999 && year >= 00 && year < 40) { yearno += 2000; } else if (ind > 899 && ind <= 999 && year > 39 && year < 100) { yearno += 1900; } else { return false; } var d1 = parseInt(day.substr(0, 1)); var d2 = parseInt(day.substr(1, 1)); var m1 = parseInt(month.substr(0, 1)); var m2 = parseInt(month.substr(1, 1)); var a1 = parseInt(year.substr(0, 1)); var a2 = parseInt(year.substr(1, 1)); var i1 = parseInt(ind.substr(0, 1)); var i2 = parseInt(ind.substr(1, 1)); var i3 = parseInt(ind.substr(2, 1)); // Calculate control check c1 var c1calc = 11 - (((3 * d1) + (7 * d2) + (6 * m1) + m2 + (8 * a1) + (9 * a2) + (4 * i1) + (5 * i2) + (2 * i3)) % 11); if (c1calc == 11) c1calc = 0; if (c1calc == 10) { return false; } if (c1 != c1calc) { return false; } // Calculate control check c2 var c2calc = 11 - (((5 * d1) + (4 * d2) + (3 * m1) + (2 * m2) + (7 * a1) + (6 * a2) + (5 * i1) + (4 * i2) + (3 * i3) + (2 * c1calc)) % 11); if (c2calc == 11) c2calc = 0; if (c2calc == 10) { return false; } if (c2 != c2calc) { return false; } // If all checks are okay we can update birthdate and gender if (i3 % 2 == 0) { // if odd number the user is female $scope.person.gender = 'F'; } else { $scope.person.gender = 'M'; } //$scope.birthDate.day = parseInt(day); //$scope.birthDate.month = parseInt(month - 1); //$scope.birthDate.year = yearno; $scope.birthDate = day + '.' + month + '.' + yearno; return true; } $scope.readImageFiles = function (files) { var asyncOps = []; if (files && files.length > 0) { for (var i = 0; i < files.length; i++) { var file = files[i]; if (file != null) { if ($scope.fileReaderSupported && file.type.indexOf('image') > -1) { var deferred = $q.defer(); asyncOps.push(deferred.promise); $timeout(function () { var fileReader = new FileReader(); fileReader.readAsDataURL(file); fileReader.onload = function (e) { $timeout(function () { file.imageData = e.target.result; deferred.resolve(); }); }; }); } } } } return asyncOps; }; $scope.profileImageChange = function (files) { if (files && files.length > 0) { $q.all($scope.readImageFiles(files)). then(function () { var file = files[0]; $scope.selectedPicture = file.imageData; $scope.selectedPictureFileName = file.name; }); } } $scope.upload = function (files) { var asyncOps = []; if (files && files.length > 0) { for (var i = 0; i < files.length; i++) { var file = files[i]; var file = $scope.profileImageFile[i]; var url = WebApiUrlService.UploadApi.UploadPersonImage + '/' + $scope.person.personID; var promise = $upload.upload({ url: url, method: 'POST', file: file, fileFormDataName: file.name }); asyncOps.push(promise); } } return asyncOps; }; $scope.updatePerson = function () { $scope.contactForm.$submitted = true; $scope.personalInfo.$submitted = true; if ($scope.contactForm.$invalid || $scope.personalInfo.$invalid) { return; } console.log("error: " + $scope.contactForm.$submitted + ", " + $scope.contactForm.$error + ", " + $scope.personalInfo.$submitted + ", " + $scope.personalInfo.$error) var asyncOps = []; var asyncFileUploads = $scope.upload($scope.profileImageFile); $q.all(asyncFileUploads).then(function () { $scope.updatePersonInner(); }); }; $scope.updatePersonInner = function () { $scope.saving = true; var personCopy = angular.copy($scope.person); personCopy.birthDate = parseDate($scope.birthDate); if (personCopy.address && personCopy.address.country) personCopy.address.countryID = personCopy.address.country.countryID; CallApi(function () { return $http.post(WebApiUrlService.PersonsApi.UpdatePerson + '/' + personCopy.personID, personCopy) }) .then(function (person) { $scope.saving = false; $scope.person = person; $rootScope.person = $scope.person; $scope.resetPicture(); if ($scope.person.address != null) saveAddressToServerValues($scope.person.address.streetAddress1); $scope.birthDate = formatDate($scope.person.birthDate); ModalConfirmService.confirm('Lagring', 'Dine endringer ble lagret OK.'); $scope.contactForm.$submitted = false; if (typeof $scope.close == 'function') { $scope.close(); } }, function (error) { $scope.saving = false; ModalConfirmService.confirm("Feil", error.toString(), "OK"); }) }; $scope.resetPicture = function () { $scope.selectedPicture = $scope.person.picture; $scope.selectedPictureFileName = $scope.person.pictureFileName; }; $scope.openCreateLogin = function () { ModalCreateLoginService.show($scope.person).then(function (modalScope) { $scope.person = modalScope.person; $scope.hasChanges = true; }, function () { // cancel action }); }; $scope.openRemoveLogin = function () { var modalInstance = $modal.open({ templateUrl: 'removeLogin.html', controller: 'modalCreateLoginController', resolve: { person: function () { return $scope.person; } } }).result.then(function (modalScope) { $scope.person = modalScope.person; $scope.hasChanges = true; }); }; $scope.openChangePassword = function () { ModalChangePasswordService.show($scope.person).then(function (modalScope) { }, function () { // cancel action }); }; $scope.openChangeUsername = function () { ModalChangeUsernameService.show($scope.person).then(function (modalScope) { }, function () { }); }; $scope.openActivateUser = function () { ModalActivateUserService.show($scope.person, $scope.organizationID).then(function (modalScope) { $scope.person = modalScope.person; $scope.hasChanges = true; }, function () { // cancel action }); }; $scope.openPaymentCards = function () { ModalPaymentCardsService.show($scope.person).then(function (modalScope) { }, function () { // cancel action }); }; function guardianCheck() { if (angular.isUndefined(ServerValues.guardianID)) { CallApi(function () { return $http.get('/api/PersonsApi/GetOnlyGuardian/' + ServerValues.personID) }) .then(function (validateObj) { if (validateObj.isSuccess === true) { $scope.guardianID = validateObj.foundItem.personID; if ($scope.guardianID === ServerValues.personID) { $scope.isGuardian = true; } } }, function () { }); } else { if (ServerValues.guardianID === ServerValues.personID) { $scope.isGuardian = true; } } } $scope.gotoGuardianWard = function (isModal) { var link = "/Person/GuardianWard?personID=" + ServerValues.personID; if (isModal) { $window.open(link); } else { $window.location.href = link; } } $scope.gotoConcent = function (isModal) { var link = "/Person/Concent/" + ServerValues.personID; if (isModal) { $window.open(link); } else { $window.location.href = link; } } $scope.gotoPersondata = function (isModal) { var link = "/Person/Persondata/" + ServerValues.personID; if (isModal) { $window.open(link); } else { $window.location.href = link; } } $scope.getPersonIDForMessageForm = function () { return [ServerValues.personID]; } var saveAddressToServerValues = function (address) { ServerValues.address = address; }; }; personEditController.$inject = ['$scope', '$http', '$rootScope', '$upload', '$timeout', '$q', '$modal', 'WebApiUrlService', 'ServerValues', 'ModalCreateLoginService', 'ModalActivateUserService', '$window', 'ModalConfirmService', 'ModalChangePasswordService', 'ModalChangeUsernameService', 'ModalPaymentCardsService', 'CallApiService']; angular.module("rubicApp").controller("personEditController", personEditController) }()); ; (function () { var personMembershipsController = function ($scope, $http, $window, WebApiUrlService, ServerValues, ModalPersonOrgEditService, ModalConfirmService) { $scope.organizations = []; $scope.init = function () { $http.get('/api/Members/GetPersonMemberships/' + ServerValues.personID) .success(function (data, status, headers, config) { $scope.personOrgs = data.data; }) .error(function (data, status, headers, config) { $scope.userAllowed = false; } ); $http.get('/rest/organizations') .success(function (data, status, headers, config) { $scope.organizations = data.result; }) .error(function (data, status, headers, config) { } ); }; $scope.editPersonMembership = function (personOrg, index) { for (i = 0; i < personOrg.attributes; i++) { } ModalPersonOrgEditService.show(personOrg).then(function (result) { $scope.personOrgs[index] = result; }); }; $scope.goToOrg = function (personOrg) { $window.location.href = '/Organization/Public?organizationID='+ personOrg.organizationID; } $scope.addMember = function () { if ($scope.addToOrganization) { var organizationID = $scope.addToOrganization.id; $http.put('/api/Members/' + organizationID + '/AddPersonAsMember/' + ServerValues.personID) .success(function (data, status, headers, config) { $window.location.reload(); }) .error(function (data, status, headers, config) { } ); } else { ModalConfirmService.confirm("Velg organisasjon","Du må velge en organisasjon du skal melde personen inn i", "OK"); } } $scope.personOrgs = null; $scope.userAllowed = true; $scope.showEditButton = function (personOrg) { if (personOrg.editFieldsAllowed) return true; if (ServerValues.isApplicationAdmin == 'True') return true; return false; } }; personMembershipsController.$inject = ['$scope', '$http', '$window', 'WebApiUrlService', 'ServerValues', 'ModalPersonOrgEditService', 'ModalConfirmService']; angular.module('rubicApp').controller('personMembershipsController', personMembershipsController); }()); ; (function () { var personGuardianListController = function ($scope, $http, WebApiUrl, ServerValues, $window) { $scope.userAllowed = true; $scope.getParents = function () { $http.get(WebApiUrl.PersonsApi.GetParents + '/' + ServerValues.personID) .success(function (data, status, headers, config) { $scope.parents = data.data; }) .error(function (data, status, headers, config) { $scope.userAllowed = false; }); } $scope.getChildren = function () { $http.get(WebApiUrl.PersonsApi.GetChildren + '/' + ServerValues.personID) .success(function (data, status, headers, config) { $scope.children = filterWards(data.data); }) .error(function (data, status, headers, config) { $scope.userAllowed = false; } ); } $scope.getOtherFam = function () { $http.get(WebApiUrl.PersonsApi.GetOtherFam + '/' + ServerValues.personID) .success(function (data, status, headers, config) { $scope.otherFam = filterWards(data.data); }) .error(function (data, status, headers, config) { $scope.userAllowed = false; } ); } $scope.getParents(); $scope.getChildren(); $scope.getOtherFam(); function filterWards(wards) { var filteredWards = []; for (i = 0; i < wards.length; i++) { var ward = wards[i]; if (ward.personID != ServerValues.personID) { filteredWards.push(ward); } } return filteredWards; } $scope.goToPerson = function (p,isModal) { if (typeof $scope.$parent.dismiss == 'function') { $scope.dismiss(); } if (isModal == '') isModal = false; var link = "/Person/Edit/" + p.personID+'/'+ServerValues.organizationID; if (isModal) { $window.open(link); } else { $window.location.href = link; } }; }; personGuardianListController.$inject = ['$scope', '$http', 'WebApiUrlService', 'ServerValues','$window']; angular.module('rubicApp').controller('personGuardianListController', personGuardianListController); }());; (function () { var personOrgEditController = function ($scope, $http, $window, $q, WebApiUrlService, ServerValues, ModalConfirmService, CallApi) { $scope.personOrg = { membershipPayerID: null }; $scope.regionMember = null; $scope.attributes = null; $scope.customAttrSuggestions = null; $scope.userAllowed = true; $scope.saving = false; $scope.memberships = []; $scope.membershipPayers = null; $scope.errorGettingMemberships = false; $scope.dateOptions = { formatYear: 'yyyy', initDate: moment().utc().hour(0).minute(0).second(0).millisecond(0).toDate(), // new Date(), startingDay: 1 }; $scope.dateCal = { opened: false }; $scope.getMemberships = function () { var url = '/api/OrganizationsApi/GetMemberships/' + ServerValues.rootOrganizationID; CallApi(function () { return $http.get(url) }) .then(function (memberships) { $scope.memberships = memberships; }, function (error) { $scope.errorGettingMemberships = true; }); }; $scope.getPersonOrg = function () { $http.get('/api/Members/GetPersonOrg/' + ServerValues.personID + '/' + ServerValues.rootOrganizationID) .success(function (data, status, headers, config) { $scope.personOrg = data.data[0]; formatAttrValsFromServer(); }) .error(function (data, status, headers, config) { $scope.userAllowed = false; } ); }; $scope.getRegionOrgMemberNo = function () { $http.get('/api/Members/GetPersonOrg/' + ServerValues.personID + '/' + ServerValues.rootOrganizationID + '/RegionMember') .success(function (data, status, headers, config) { $scope.regionMember = data.data[0]; }) .error(function (data, status, headers, config) { $scope.userAllowed = false; } ); }; $scope.getMembershipPayers = function () { $http.get('/api/Members/GetMembershipPayers/' + ServerValues.personID + '/' + ServerValues.rootOrganizationID) .success(function (data, status, headers, config) { $scope.membershipPayers = data.data[0]; //$scope.membershipPayers.splice(0,0,{ personOrganizationID: null, fullName: "Medlemmet betaler selv" }); }) .error(function (data, status, headers, config) { $scope.userAllowed = false; } ); }; $scope.getAttributes = function () { $http.get('/api/OrganizationsApi/GetAttributes/' + ServerValues.rootOrganizationID) .success(function (data, status, headers, config) { $scope.attributes = data.data[0]; formatAttrValsFromServer(); }).error(function (data, status, headers, config) { $scope.userAllowed = false; }) } var formatAttrValsFromServer = function () { if ($scope.attributes && $scope.personOrg) { $scope.attributes.forEach(function (attr) { var attrType = attr.attributeProps.controlType; if (attrType == 'Checkbox' || attrType == 'Dropdown') { if (typeof $scope.personOrg[attr.attributePropertyName] == "string") { $scope.personOrg[attr.attributePropertyName] = $scope.personOrg[attr.attributePropertyName].split(","); $scope.personOrg[attr.attributePropertyName] = $scope.personOrg[attr.attributePropertyName].filter(item => item); } } else if (attrType == 'Date' && $scope.personOrg[attr.attributePropertyName]) { var momentObj = moment($scope.personOrg[attr.attributePropertyName], 'dd.MM.yyyy'); var dateValid = momentObj.isValid(); if (dateValid) { var parts = $scope.personOrg[attr.attributePropertyName].split('.'); var date = new Date(Date.UTC(parts[2], parts[1] - 1, parts[0], 0, 0, 0, 0)); $scope.personOrg[attr.attributePropertyName] = date; } else { $scope.personOrg[attr.attributePropertyName] = null; } } }); } } var formatAttrValsForUpdate = function () { $scope.attributes.forEach(function (attr) { var attrType = attr.attributeProps.controlType; if (attrType == 'Checkbox' || attrType == 'Dropdown') { if (typeof $scope.personOrg[attr.attributePropertyName] == "object" && $scope.personOrg[attr.attributePropertyName] != null) { $scope.personOrg[attr.attributePropertyName] = $scope.personOrg[attr.attributePropertyName].join(","); } } if (attrType == 'Date' && $scope.personOrg[attr.attributePropertyName]) { var options = { day: "2-digit", month: "2-digit", year: "numeric" }; $scope.personOrg[attr.attributePropertyName] = $scope.personOrg[attr.attributePropertyName].toLocaleDateString("no-NO", options); } }); } $scope.getAttrSuggestions = function (searchExpression, attr) { if (attr.allowSuggestions) { return $http.get('/api/OrganizationsApi/GetCustomAttributeSuggestions/' + ServerValues.rootOrganizationID + '/' + attr.attributeProperty + '/' + searchExpression) .then(function (response) { return response.data.data; }); } return []; } $scope.getDistrictSuggestions = function (searchExpression) { return $http.get('/api/OrganizationsApi/GetDistrictSuggestions/' + ServerValues.rootOrganizationID + '/' + searchExpression) .then(function (response) { return response.data.data; }); } $scope.init = function () { if (ServerValues.organizationID) { $scope.getPersonOrg(); $scope.getRegionOrgMemberNo(); $scope.getAttributes(); $scope.getMemberships(); $scope.getMembershipPayers(); } } $scope.memberNoCheck = function () { CallApi(function () { return $http.get('/api/OrganizationsApi/' + ServerValues.organizationID + '/Persons/' + ServerValues.personID + '/isMemberNoAvailable/' + $scope.personOrg.memberNo) }) .then(function (memberNoAvailable) { if (memberNoAvailable) { $scope.memberNotAvailable = false; } else { $scope.memberNotAvailable = true; } }, function () { }); } $scope.updatePersonOrg = function () { formatAttrValsForUpdate(); $scope.saving = true; CallApi(function () { return $http.post('/api/Members/UpdatePersonOrg/' + $scope.personOrg.personID + '/' + ServerValues.rootOrganizationID, $scope.personOrg) }) .then(function (personOrg) { $scope.personOrg = personOrg; $scope.$parent.updatePerson(); }, function (error) { ModalConfirmService.confirm("Feil", error.toString(), "OK"); $scope.saving = false; }); } $scope.selectSuggestion = function (attr, suggestion) { $scope.personOrg[attr.attributePropertyName] = suggestion; } $scope.$parent.$watch('saving', function (newValue, oldValue) { $scope.saving = newValue; }); $scope.setDateOpen = function ($event, attrName) { $scope.personOrg[attrName] = new Date(); $event.preventDefault(); $event.stopPropagation(); $scope.dateCal.opened = true; }; $scope.isDate = function (attrValue) { return attrValue instanceof Date; } }; personOrgEditController.$inject = ['$scope', '$http', '$window', '$q', 'WebApiUrlService', 'ServerValues', 'ModalConfirmService', 'CallApiService']; angular.module('rubicApp').controller('personOrgEditController', personOrgEditController); angular.module('rubicApp').filter("membershipFilter", function () { return function (membershipID, memberships) { if (membershipID && memberships) { var results = $.grep(memberships, function (m) { return m.membershipID == membershipID }); if (results.length > 0) return results[0].membershipName; } return ""; } }); angular.module('rubicApp').filter("payerFilter", function () { return function (membershipPayerID, membershipPayers) { if (membershipPayerID && membershipPayers) { var results = $.grep(membershipPayers, function (m) { return m.personOrganizationID == membershipPayerID }); if (results.length > 0) return results[0].fullName; } return ""; } }); angular.module('rubicApp').filter("isDateOrNull", function () { return function (attrValue) { return !attrValue || attrValue instanceof Date; } }); }()); ; // The function wrapper keeps global scope clear and avoids global naming collisions (function () { // define your controller and its logic in a local function variable var phoneVerificationController = function ($scope, $http, ServerValues,ModalConfirmService, CallApi) { $scope.verificationCode = ""; $scope.saving = false; $scope.sendPhoneVerificationCode = function () { CallApi(function () { return $http.post('/api/PersonsApi/SendPhoneVerificationCode/' + ServerValues.personID) }) .then(function (result) { ModalConfirmService.confirm("Sendt", "Verifiseringskode er sendt", "OK"); }, function (error) { ModalConfirmService.confirm("Error", error.toString(), "OK"); }); } $scope.verifyPhoneNumber = function () { CallApi(function () { return $http.post('/api/PersonsApi/VerifyPhoneNumber/' + ServerValues.personID + '/' + $scope.verificationCode) }) .then(function () { ModalConfirmService.confirm("Verifisert", "Mobilnummeret ble verifisert.", "OK"); }, function (error) { ModalConfirmService.confirm("Error", "Feil verifiseringskode.", "OK"); }); } }; // Set up dependecy injections for dependencies used by controller function phoneVerificationController.$inject = ['$scope', '$http', 'ServerValues', 'ModalConfirmService', 'CallApiService']; // Register the controller angular.module('rubicApp').controller('phoneVerificationController', phoneVerificationController); }());; (function () { var modalConfirmService = function ($modal) { this.confirm = function (title, body, confirmLabel, cancelLabel, backDrop) { if (typeof backDrop == "undefined") { backDrop = true; } var modalInst = $modal.open({ templateUrl: '/app/templates/ModalConfirm-2.html', controller: 'modalConfirmController', backdrop: backDrop, resolve: { title: function() { return title; }, body: function() { return body; }, confirmLabel: function () { return confirmLabel; }, cancelLabel: function () { return cancelLabel; } } }); if (typeof(confirmLabel) == 'undefined' && typeof(cancelLabel) == 'undefined') { setTimeout(function () { modalInst.dismiss(); }, 1500); } return modalInst.result; }; }; modalConfirmService.$inject = ['$modal']; angular.module('rubicApp').service('ModalConfirmService', modalConfirmService); }());; (function () { var modalConfirmController = function ($scope, $http, $modalInstance, title, body, confirmLabel, cancelLabel,$sce) { $scope.title = title; $scope.body = body; $scope.confirmLabel = confirmLabel; $scope.cancelLabel = cancelLabel; $scope.showConfirm = (typeof confirmLabel != 'undefined') && confirmLabel != ""; $scope.showCancel = (typeof cancelLabel != 'undefined') && cancelLabel != ""; $scope.confirm = function () { $modalInstance.close('confirm'); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; $scope.to_trusted = function (html_code) { return $sce.trustAsHtml(html_code); } }; modalConfirmController.$inject = ['$scope', '$http', '$modalInstance', 'title', 'body', 'confirmLabel', 'cancelLabel','$sce']; angular.module('rubicApp').controller('modalConfirmController', modalConfirmController); angular.module('rubicApp').filter('safe', function ($sce) { return function (val) { return $sce.trustAsHtml(val); //return $sce.trustAsUrl(val); //return $sce.trustAsResourceUrl(val); }; }); }());; (function () { angular.module('rubicApp').directive('sendmessageform', function () { return { restrict: 'AE', scope: { organizationId: "=", recievers: "&", recieverType: "@", projectId: "=" }, templateUrl: "/app/templates/SendMessageForm.html", link: function (scope, element, attrs) { }, controller: ['$scope', '$element', '$attrs', '$http', 'CallApiService', 'ModalAwaiterService', 'ModalConfirmService', 'FileTypesService', 'ModalMessageStatusService', function ($scope, $element, $attrs, $http, CallApiService, ModalAwaiterService, ModalConfirmService, FileTypesService, ModalMessageStatusService) { $scope.isEmail = false; $scope.isSMS = false; $scope.notificationType = ""; $scope.formError = false; $scope.sending = false; $scope.formData = new FormData(); $scope.files = []; $scope.filesTooBig = false; $scope.totalFileSize = 0; $scope.remainder = 0; $scope.smsCount = 0; $scope.showSMSForm = function(){ $scope.showEmail = false; $scope.showSms = true; } $scope.showEmailForm = function(){ $scope.showEmail = true; $scope.showSms = false; } $scope.isGSM7 = function () { gsm = "@£$¥èéùìòÇØøÅåΔ_ΦΓΛΩΠΨΣΘΞ^{}\[~]|€ÆæßÉ!\"#¤%&'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà"; var anyNonGSM7 = false; if ($scope.smsMessage != null) { var i = $scope.smsMessage.length; while (i--) { if (gsm.indexOf($scope.smsMessage.charAt(i)) == -1 && $scope.smsMessage.charAt(i) != " ") { anyNonGSM7 = true; break; } } } return !anyNonGSM7; } $scope.updateCount = function () { $scope.msgLength = typeof $scope.smsMessage == "undefined" || $scope.smsMessage == "" ? 0 : $scope.smsMessage.length; $scope.msgSpecialChars = !$scope.isGSM7(); var msgChunkLength = $scope.msgSpecialChars ? 70 : 160; if ($scope.msgLength <= msgChunkLength) { $scope.remainder = msgChunkLength - $scope.msgLength; $scope.smsCount = 1; } else { $scope.remainder = $scope.msgLength % (msgChunkLength - 7); $scope.smsCount = Math.ceil($scope.msgLength / (msgChunkLength - 7)); } } $scope.sendSmsMessage = function (self) { var smsMessage = createSmsMessage(self); var orgId = $scope.organizationId ? '' + $scope.organizationId : ''; var projId = $scope.projectId ? '' + $scope.projectId : ''; var receiverCnt = 0; if (angular.isDefined(self) && self === true) { receiverCnt = 1; } else if (angular.isDefined(smsMessage.personIDs) && smsMessage.personIDs.length > 0) { receiverCnt = smsMessage.personIDs.length; } else if (angular.isDefined(smsMessage.companyIDs) && smsMessage.companyIDs.length > 0) { receiverCnt = smsMessage.companyIDs.length; } if (receiverCnt === 0) { ModalConfirmService.confirm("Mottakere må velges", "Mottakere må velges fra listen", "OK"); } else { CallApiService(function () { return $http.post("/api/Message/Sms?organizationID=" + orgId + "&projectID=" + projId, smsMessage); }) .then(function (messageJobRequest) { $scope.sending = false; $scope.errormessage = null; ModalMessageStatusService.show($scope.organizationId, messageJobRequest.messageJobRequestID); }, function (error) { $scope.sending = false; $scope.successmessage = null; ModalConfirmService.confirm("Feil ved sending", error.toString(), "OK"); }); } } $scope.sendEmailMessage = function (self) { var emailMessage = createEmailMessage(self); var orgId = $scope.organizationId ? '' + $scope.organizationId : ''; var projId = $scope.projectId ? '' + $scope.projectId : ''; if ((!angular.isDefined(self) || (angular.isDefined(self) && self !== true)) && (!angular.isDefined(emailMessage.personIDs) || (angular.isDefined(emailMessage.personIDs) && emailMessage.personIDs.length === 0)) && (!angular.isDefined(emailMessage.companyIDs) || (angular.isDefined(emailMessage.companyIDs) && emailMessage.companyIDs.length === 0))) { ModalConfirmService.confirm("Mottakere må velges", "Mottakere må velges fra listen", "OK"); } else { CallApiService( function () { return $http({ method: 'POST', url: '/api/Message/Email?organizationID=' + orgId + "&projectID=" + projId, headers: { 'Content-Type': undefined }, transformRequest: function (data) { var formData = new FormData(); formData.append('model', JSON.stringify(data.model)); for (i = 0; i < data.files.length; i++) { formData.append('file' + i, data.files[i]); } return formData; }, data: { model: emailMessage, files: $scope.files } }); }) .then(function (messageJobRequest) { $scope.sending = false; $scope.errormessage = null; ModalMessageStatusService.show($scope.organizationId, messageJobRequest.messageJobRequestID); }, function (error) { $scope.sending = false; $scope.successmessage = null; ModalConfirmService.confirm("Feil ved sending", error.toString(), "OK"); }); } } $scope.SendToSelf = function () { if ($scope.notificationType == 'SMS') { if (!$scope.smsForm.smsMessage.$valid) { $scope.formError = true; return; } $scope.formError = false; $scope.sendSmsMessage(true); } else if ($scope.notificationType == 'EMail') { if (!$scope.emailForm.emailSubject.$valid || !$scope.emailBody || $scope.emailBody == "") { $scope.formError = true; return; } $scope.formError = false; $scope.sendEmailMessage(true); } }; $scope.SendMessage = function () { if ($scope.notificationType == 'SMS') { if (!$scope.smsForm.smsMessage.$valid) { $scope.formError = true; return; } $scope.formError = false; $scope.sendSmsMessage(); } else if ($scope.notificationType == 'EMail') { if (!$scope.emailForm.emailSubject.$valid || !$scope.emailBody || $scope.emailBody == "") { $scope.formError = true; return; } $scope.formError = false; $scope.sendEmailMessage(); } } $scope.AddFiles = function (selectedFiles) { if (selectedFiles[0]) { for (i = 0; i < selectedFiles.length; i++) { $scope.totalFileSize += selectedFiles[i].size; if ($scope.totalFileSize >= 10000000) { $scope.filesTooBig = true; return; } if (!FileTypesService.allowedFileType(selectedFiles[i])) { $scope.notSupportedFileName = selectedFiles[i].name; $scope.fileNotSupported = true; return; } } for (i = 0; i < selectedFiles.length; i++) { $scope.files.push(selectedFiles[i]); } $scope.filesTooBig = false; $scope.fileNotSupported = false; } } $scope.RemoveFile = function (index) { $scope.files.splice(index, 1); } var createSmsMessage = function (self) { if ($scope.recieverType === 'company') { return createCompanySmsMessage(self); } if ($scope.recieverType === 'person') { return createPersonSmsMessage(self); } return {}; } var createEmailMessage = function (self) { if ($scope.recieverType === 'company') { return createCompanyEmailMessage(self); } if ($scope.recieverType === 'person') { return createPersonEmailMessage(self); } return {}; } var createCompanySmsMessage = function (self) { var smsMessage = { message: $scope.smsMessage, companyIDs: self ? [] : $scope.recievers() } return smsMessage; } var createCompanyEmailMessage = function (self) { var emailMessage = { subject: $scope.emailSubject, body: encodeURIComponent($scope.emailBody), companyIDs: self ? [] : $scope.recievers() } return emailMessage; } var createPersonSmsMessage = function (self) { var smsMessage = { message: $scope.smsMessage, personIDs: self ? [] : $scope.recievers() } return smsMessage; } var createPersonEmailMessage = function (self) { var emailMessage = { subject: $scope.emailSubject, body: encodeURIComponent($scope.emailBody), personIDs: self ? [] : $scope.recievers() } return emailMessage; } }] } }); })();; (function () { var modalPersonOrgEditService = function ($modal) { this.show = function (personOrg) { return $modal.open({ templateUrl: '/app/templates/ModalPersonOrgEdit.html', controller: 'modalPersonOrgEditController', resolve: { personOrg: function () { return personOrg; } } }).result; }; }; modalPersonOrgEditService.$inject = ['$modal']; angular.module('rubicApp').service('ModalPersonOrgEditService', modalPersonOrgEditService); }());; (function () { var modalPersonOrgEditController = function ($scope, $http, $modalInstance, WebApiUrlService, personOrg) { $scope.personOrg = angular.copy(personOrg); $scope.attributes = null; $scope.getAttrSuggestions = function (searchExpression, attr) { if (attr.allowSuggestions) { return $http.get('/api/OrganizationsApi/GetCustomAttributeSuggestionsForPerson/' + $scope.personOrg.personID + '/' + $scope.personOrg.organizationID + '/' + attr.attributeProperty + '/' + searchExpression) .then(function (response) { return response.data.data; }); } return []; } $scope.getDistrictSuggestions = function (searchExpression) { return $http.get('/api/OrganizationsApi/GetDistrictSuggestionsForPerson/' + $scope.personOrg.personID + '/' + $scope.personOrg.organizationID + '/' + searchExpression) .then(function (response) { if (response.data.data) { return response.data.data; } return []; }); } var getAttributes = function () { $http.get('/api/OrganizationsApi/GetAttributesForPerson/' + $scope.personOrg.personID + '/' + $scope.personOrg.organizationID) .success(function (data, status, headers, config) { $scope.attributes = data.data; formatAttrValsFromServer(); }).error(function (data, status, headers, config) { $scope.userAllowed = false; }) } getAttributes(); var formatAttrValsFromServer = function () { $scope.attributes.forEach(function (attr) { var attrType = attr.attributeProps.controlType; if (attrType == 'Checkbox' || attrType == 'Dropdown') { if (typeof $scope.personOrg[attr.attributePropertyName] == "string") { $scope.personOrg[attr.attributePropertyName] = $scope.personOrg[attr.attributePropertyName].split(","); $scope.personOrg[attr.attributePropertyName] = $scope.personOrg[attr.attributePropertyName].filter(item => item); } } if (attrType == 'Date' && $scope.personOrg[attr.attributePropertyName]) { var momentObj = moment($scope.personOrg[attr.attributePropertyName], 'dd.MM.yyyy'); var dateValid = momentObj.isValid(); if (dateValid) { var parts = $scope.personOrg[attr.attributePropertyName].split('.'); var date = new Date(Date.UTC(parts[2], parts[1] - 1, parts[0], 0, 0, 0, 0)); $scope.personOrg[attr.attributePropertyName] = date; } else { $scope.personOrg[attr.attributePropertyName] = null; } } }); } var formatAttrValsForUpdate = function () { $scope.attributes.forEach(function (attr) { var attrType = attr.attributeProps.controlType; if (attrType == 'Checkbox' || attrType == 'Dropdown') { if (typeof $scope.personOrg[attr.attributePropertyName] == "object" && $scope.personOrg[attr.attributePropertyName]) { $scope.personOrg[attr.attributePropertyName] = $scope.personOrg[attr.attributePropertyName].join(","); } } else if (attrType == 'Date' && $scope.personOrg[attr.attributePropertyName]) { var options = { day: "2-digit", month: "2-digit", year: "numeric" }; $scope.personOrg[attr.attributePropertyName] = $scope.personOrg[attr.attributePropertyName].toLocaleDateString("no-NO", options); } }); } $scope.save = function () { $scope.saving = true; formatAttrValsForUpdate(); $http.post('/api/Members/UpdatePersonMembership/' + $scope.personOrg.personID, $scope.personOrg) .success(function (data, status, headers, config) { $scope.saving = false; var data1 = data.data; $modalInstance.close(data.data[0]); }) .error(function (data, status, headers, config) { $scope.saving = false; ModalConfirmService.confirm("Feil", "Det oppstod en feil ved lagring.", "OK") }); } $scope.cancel = function () { $modalInstance.dismiss(); } }; modalPersonOrgEditController.$inject = ['$scope', '$http', '$modalInstance', 'WebApiUrlService', 'personOrg']; angular.module('rubicApp').controller('modalPersonOrgEditController', modalPersonOrgEditController); }());; (function () { angular.module('rubicApp').factory('ModalAwaiterService', ['$modal', function ($modal) { return { awaitApiCall: function (title, body, type, apiFunc, calcElements, PredictedCalcTimeInSecPrElement, PredictedTotalTimeInSec) { var modalInst = $modal.open({ templateUrl: '/app/templates/ModalAwaiter.html', controller: 'modalAwaiterController', backdrop: 'static', keyboard: false, resolve: { title: function () { return title; }, body: function () { return body; }, apiFunc: function () { return apiFunc; }, type: function () { return type; }, calcElements: function () { return calcElements; }, calcSecElement: function () { return PredictedCalcTimeInSecPrElement; }, totalSec: function () { return PredictedTotalTimeInSec; } } }); return modalInst.result; }, typeEnum: { progressBar: 1, loadingSpinner: 2 } } }]); angular.module('rubicApp').controller('modalAwaiterController', ['$scope', '$http', '$modalInstance', '$q', '$timeout', 'CallApiService', 'title', 'body', 'apiFunc', 'type', 'calcElements', 'calcSecElement', 'totalSec', function ($scope, $http, $modalInstance, $q, $timeout, callApi, title, body, apiFunc, type, calcElements, calcSecElement, totalSec) { $scope.title = title; $scope.body = body; $scope.internalTypes = { progressBarDynamic: 1, progressBarStatic: 2, loadingSpinner: 3 }; callApi(apiFunc) .then(function (response) { if (angular.isDefined($scope.timeoutPromise)) { $timeout.cancel($scope.timeoutPromise); $scope.elapsedTimeMS = $scope.totalTimeMS; } $modalInstance.close(response); }, function (error) { if (angular.isDefined($scope.timeoutPromise)) { $timeout.cancel($scope.timeoutPromise); } $modalInstance.dismiss(error); }); if (type === 2) { $scope.internalType = $scope.internalTypes.loadingSpinner; } else if (type === 1 && ((angular.isDefined(calcElements) && angular.isDefined(calcSecElement)) || angular.isDefined(totalSec))) { $scope.internalType = $scope.internalTypes.progressBarDynamic; showProgress(); } else { $scope.internalType = $scope.internalTypes.progressBarStatic; $scope.dynamicProgressBar = false; } function showProgress() { var updateIntervallMS = 100; if (angular.isDefined(totalSec)) { $scope.totalTimeMS = totalSec * 1000; } else { var calcTimeElementMS = calcSecElement * 1000; $scope.totalTimeMS = calcElements * calcTimeElementMS; } $scope.elapsedTimeMS = 1; $scope.timeoutPromise = $timeout(updateProgressBar, updateIntervallMS); function updateProgressBar() { $scope.elapsedTimeMS += updateIntervallMS; $scope.timeoutPromise = $timeout(updateProgressBar, updateIntervallMS); } } }]); }());; (function () { // define service function with its logic var fileTypesService = function ($http) { var service = {}; var unacceptedFileTypes = [ "application/x-msdownload", "application/octet-stream", "application/javascript", "application/java-archive" ] var unacceptedFileExtensionRegex = /^[^.]+$|\.(?!(js|exe|dll|pif|msi|msp|com|scr|scf|inf|lnk|hta|cpl|msc|jar|bat|cmd|vb|vbs|vbe|jse|ps1|ps1xml|ps2|ps2xmlL|psc1|psc2|msh|msh1|msh2|mshxml|msh1xml|msh2xml)$)([^.]+$)/; service.allowedFileType = function (file) { if (unacceptedFileTypes.indexOf(file.type) > -1) { return false; } if (unacceptedFileExtensionRegex.test(file.name)) { return true; } else { return false; } } return service; } // add dependency injected services fileTypesService.$inject = ['$http']; // register factory angular.module('rubicApp').factory('FileTypesService', fileTypesService); }());; (function () { var modalActivateUserService = function ($modal) { this.show = function (person, organizationID) { return $modal.open({ templateUrl: '/app/viewapps/PersonActivateUser/ModalActivateUser.html', controller: 'ModalActivateUserController', size: "lg", resolve: { person: function () { return person; }, organizationID: function () { return organizationID; } } }).result; }; }; modalActivateUserService.$inject = ['$modal']; angular.module('rubicApp').service('ModalActivateUserService', modalActivateUserService); }());; (function () { var modalActivateUserController = function ($scope, $http, $modalInstance, WebApiUrlService, person, organizationID, callApi, ServerValues) { $scope.person = person; $scope.organizationID = (typeof organizationID == 'undefined' || organizationID == null || organizationID == '') ? 0 : organizationID; $scope.enableEmail = (person.contact.contactEmail != null && person.contact.contactEmail.length > 0) ? true : false; $scope.enableSMS = (person.contact.contactPhoneMobile != null && person.contact.contactPhoneMobile.length > 0) ? true : false; $scope.sendActivationMessage = function (method) { $scope.saving = true; callApi(function () { return $http.get("/api/PersonsApi/SendActivationMessage/" + $scope.person.personID + "?method=" + method + "&organizationID=" + $scope.organizationID) }) .then(function (person) { $scope.saving = false; $modalInstance.close($scope); }, function (error) { $scope.hasError = true; $scope.error = error.toString(); $scope.saving = false; }) } $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; }; // Set up dependecy injections for dependencies used by controller function modalActivateUserController.$inject = ['$scope', '$http', '$modalInstance', 'WebApiUrlService', 'person', 'organizationID', 'CallApiService', 'ServerValues']; // Register the controller angular.module('rubicApp').controller('ModalActivateUserController', modalActivateUserController); }());; (function () { var modalChangePasswordService = function ($modal) { this.show = function (person) { return $modal.open({ templateUrl: '/app/viewapps/ChangePassword/ModalChangePassword.html', controller: 'ModalChangePasswordController', size: "md", resolve: { person: function () { return person; } } }).result; }; }; modalChangePasswordService.$inject = ['$modal']; angular.module('rubicApp').service('ModalChangePasswordService', modalChangePasswordService); }());; (function () { var modalChangePasswordController = function ($scope, $http, $modalInstance, WebApiUrlService, person, CallRestApi, ServerValues, ModalConfirmService) { $scope.person = person; $scope.saving = false; $scope.login = { personID: person.personID, username: 'brukernavn', oldPassword: '', newPassword: '', confirmPassword: '', }; $scope.getUserName = function () { $scope.login.username = "Søker etter brukernavn..."; CallRestApi(function () { return $http.get("/rest/accounts/username/bypersonid/" + $scope.person.personID); }) .then( function (response) { $scope.login.username = response; }, function (error) { $scope.hasError = true; $scope.errorMessage = error.toString(); $scope.login.username = ""; }); } $scope.submit = function () { $scope.saving = true; CallRestApi(function(){ return $http.post("/rest/persons/" + $scope.person.personID + "/changePassword", $scope.login); }) .then( function (response) { if (response == "") { $scope.saving = false; $modalInstance.close($scope); } else { $scope.saving = false; $scope.wrongExistingPwdMessage = response; } }, function(error){ $scope.hasError = true; $scope.errorMessage = error.toString(); $scope.saving = false; }); }; $scope.sendResetPassword = function () { ModalConfirmService.confirm("Glemt passord", "Er du sikker på at du ønsker å sende epost til denne personen med link for å sette nytt passord?", "Ja", "Avbryt").then(function () { $scope.saving = true; CallRestApi(function () { return $http.post("/rest/persons/" + $scope.person.personID + "/sendForgottenPasswordLink", {}); }) .then( function (response) { $scope.saving = false; ModalConfirmService.confirm("Glemt passord", response, "OK"); }, function (error) { $scope.hasError = true; $scope.errorMessage = error.toString(); $scope.saving = false; }); }); } $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; $scope.getUserName(); }; // Set up dependecy injections for dependencies used by controller function modalChangePasswordController.$inject = ['$scope', '$http', '$modalInstance', 'WebApiUrlService', 'person', 'CallRestApiService', 'ServerValues', 'ModalConfirmService']; // Register the controller angular.module('rubicApp') .controller('ModalChangePasswordController', modalChangePasswordController) .directive('equals', function () { return { restrict: 'A', // only activate on element attribute require: '?ngModel', // get a hold of NgModelController link: function (scope, elem, attrs, ngModel) { if (!ngModel) return; // do nothing if no ng-model // watch own value and re-validate on change scope.$watch(attrs.ngModel, function () { validate(); }); // observe the other value and re-validate on change attrs.$observe('equals', function (val) { validate(); }); var validate = function () { // values var val1 = ngModel.$viewValue; var val2 = attrs.equals; // set validity ngModel.$setValidity('equals', !val1 || !val2 || val1 === val2); }; } }; }) .directive('pwd', function () { return { restrict: 'A', // only activate on element attribute require: '?ngModel', // get a hold of NgModelController link: function (scope, elem, attrs, ctrl) { ctrl.$parsers.unshift(function (viewValue) { var pwdValidLength, pwdHasUpperLetter, pwdHasLowerLetter, pwdHasNumber; pwdValidLength = (viewValue && viewValue.length >= 7 ? true : false); pwdHasUpperLetter = (viewValue && /[A-Z]/.test(viewValue)) ? true : false; pwdHasLowerLetter = (viewValue && /[a-z]/.test(viewValue)) ? true : false; pwdHasNumber = (viewValue && /\d/.test(viewValue)) ? true : false; if (pwdValidLength && pwdHasUpperLetter && pwdHasLowerLetter && pwdHasNumber) { ctrl.$setValidity('pwd', true); } else { ctrl.$setValidity('pwd', false); } return viewValue; }); } }; }); }());; (function () { var modalChangeUsernameService = function ($modal) { this.show = function (person) { return $modal.open({ templateUrl: '/app/viewapps/ChangeUsername/ModalChangeUsername.html', controller: 'ModalChangeUsernameController', size: "md", resolve: { person: function () { return person; } } }).result; }; }; modalChangeUsernameService.$inject = ['$modal']; angular.module('rubicApp').service('ModalChangeUsernameService', modalChangeUsernameService); }());; (function () { var modalChangeUsernameController = function ($scope, $http, $modalInstance, WebApiUrlService, person, CallRestApi, ServerValues) { $scope.person = person; $scope.saving = false; $scope.login = { personID: person.personID, username: '', newUsername: '', }; $scope.getUserName = function () { $scope.login.username = "Søker etter brukernavn..."; CallRestApi(function () { return $http.get("/rest/accounts/username/bypersonid/" + $scope.person.personID); }) .then( function (response) { $scope.login.username = response; }, function (error) { $scope.hasError = true; $scope.errorMessage = error.toString(); $scope.login.username = ""; }); } $scope.submit = function () { $scope.saving = true; $scope.usernameForm.$submitted = true; if ($scope.usernameForm.$valid) { console.log("save"); // ToDO: API kall CallRestApi(function () { return $http.post("/rest/persons/" + $scope.person.personID + "/changeUsername", $scope.login); }) .then( function (response) { if (response == "") { $scope.saving = false; $modalInstance.close($scope); } else { $scope.saving = false; $scope.responseMessage = response; } }, function (error) { $scope.hasError = true; $scope.errorMessage = error.toString(); $scope.saving = false; }); } /* CallRestApi(function () { return $http.post("/rest/persons/" + $scope.person.personID + "/changePassword", $scope.login); }) .then( function (response) { if (response == "") { $scope.saving = false; $modalInstance.close($scope); } else { $scope.saving = false; $scope.wrongExistingPwdMessage = response; } }, function (error) { $scope.hasError = true; $scope.errorMessage = error.toString(); $scope.saving = false; }); */ $scope.saving = false; }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; $scope.getUserName(); }; // Set up dependecy injections for dependencies used by controller function modalChangeUsernameController.$inject = ['$scope', '$http', '$modalInstance', 'WebApiUrlService', 'person', 'CallRestApiService', 'ServerValues']; // Register the controller angular.module('rubicApp').controller('ModalChangeUsernameController', modalChangeUsernameController); }());; (function () { var modalPaymentCardsService = function ($modal) { this.show = function (person, editCard) { return $modal.open({ templateUrl: '/app/viewapps/PaymentCards/ModalPaymentCards.html', size: 'lg', resolve: { person: function () { return person; }, editCard: function () { return editCard; } }, backdrop : 'static', keyboard : false, controller: function ($scope, $http, $filter, $modalInstance, CallRestApiService, ModalConfirmService, person, $window, editCard) { $scope.person = person; $scope.paymentCards = []; $scope.editCard = editCard; $scope.saveBtnText = ""; $scope.cancelBtnText = "Avbryt"; $scope.stripePublishableKey = null; $scope.cardType = ""; $scope.issuedTo = person.issuedTo; $scope.updating = false; $scope.deleting = false; $scope.saving = false; $scope.editMode = false; $scope.editExisting = false; $scope.onlyAddMode = false; $scope.init = function () { CallRestApiService(function () { return $http.get("/rest/persons/" + $scope.person.personID + "/paymentcards") }) .then(function (data) { $scope.paymentCards = data; $scope.saving = false; }, function (error) { ModalConfirmService.confirm("Error", error.toString(), "OK"); $scope.saving = false; }); CallRestApiService(function () { return $http.get("/rest/persons/" + $scope.person.personID + "/paymentcards/getpublishablekey") }) .then(function (data) { $scope.stripePublishableKey = data; $scope.saving = false; }, function (error) { ModalConfirmService.confirm("Error", error.toString(), "OK"); $scope.saving = false; }); // Dialog opened with card data if ($scope.editCard != null) { $scope.editMode = "Nytt betalingskort"; $scope.saveBtnText = "Lagre og betal"; $scope.cancelBtnText = "Avbryt, betal uten å lagre kortet"; $scope.editExisting = false; $scope.onlyAddMode = true; $scope.editCard.availableToChildren = true; } } $scope.createCard = function () { if ($scope.editCard.paymentMethodId) { // Add card from payment-screen CallRestApiService(function () { return $http.post("/rest/persons/" + $scope.person.personID + "/paymentcards", $scope.editCard) }) .then(function (data) { $scope.paymentCards.push(data); $scope.saving = false; $scope.editMode = false; if ($scope.onlyAddMode) $modalInstance.close(data); }, function (error) { ModalConfirmService.confirm("Error", error.toString(), "OK"); $scope.saving = false; }); } else { // Add new one from dialog CallRestApiService(function () { return $http.post("/rest/payments/organizations/0/stripe/setupintent", {}); }) .then( function (intent) { $window.Stripe.handleCardSetup(intent.client_secret, $scope.cardElement, { payment_method_data: { billing_details: { name: $scope.issuedTo } } }).then(function (result) { $scope.editCard.paymentMethodId = result.setupIntent.payment_method; // Add new card CallRestApiService(function () { return $http.post("/rest/persons/" + $scope.person.personID + "/paymentcards", $scope.editCard) }) .then(function (data) { $scope.paymentCards.push(data); $scope.saving = false; $scope.editMode = false; if ($scope.onlyAddMode) $modalInstance.close(data); }, function (error) { ModalConfirmService.confirm("Error", error.toString(), "OK"); $scope.saving = false; }); }); }, function (error) { }); } } $scope.addNewCard = function () { $scope.editCard = {}; if (person.contact != null) $scope.editCard.email = person.contact.contactEmail; $scope.editCard.fullName = person.issuedTo; $scope.editCard.paymentMethod = 3; // 3 = Stripe, 5 = RubicPay $scope.editCard.availableToChildren = true; $scope.editMode = "Nytt betalingskort"; $scope.saveBtnText = "Registrer"; $scope.editExisting = false; $window.Stripe = Stripe($scope.stripePublishableKey); var elements = $window.Stripe.elements({ locale: 'no' }); $scope.cardElement = elements.create('card'); $scope.cardElement.mount('#card-element'); $scope.cardElement.addEventListener('change', function (event) { if (event.error) { console.log(event.error.message); } else { console.log(""); } }); } $scope.registerCard = function () { $scope.saving = true; $scope.editCard.personID = $scope.person.personID; $scope.autoPaymentCheck(); if ($scope.editCard.personPaymentCardID == null) { $scope.createCard(); } else { // Update existing card CallRestApiService(function () { return $http.patch("/rest/persons/" + $scope.person.personID + "/paymentcards/" + $scope.editCard.personPaymentCardID, $scope.editCard) }) .then(function (data) { $scope.editCard = data; $scope.saving = false; $scope.editMode = false; }, function (error) { ModalConfirmService.confirm("Error", error.toString(), "OK"); $scope.saving = false; $scope.editMode = false; }); } } $scope.cancelEditCard = function () { $scope.editMode = false; if ($scope.onlyAddMode) $scope.close(); } $scope.editExistingCard = function (paymentCard) { $scope.editCard = paymentCard; $scope.editMode = "Oppdater betalingskort"; $scope.saveBtnText = "Oppdater"; $scope.editExisting = true; } $scope.deleteCard = function (paymentCard) { $scope.saving = true; // Update existing card CallRestApiService(function () { return $http.delete("/rest/persons/" + $scope.person.personID + "/paymentcards/" + paymentCard.personPaymentCardID) }) .then(function (data) { var i = $scope.paymentCards.length - 1; while (i >= 0) { if ($scope.paymentCards[i].personPaymentCardID == paymentCard.personPaymentCardID) { $scope.paymentCards.splice(i, 1); } i--; } $scope.saving = false; }, function (error) { ModalConfirmService.confirm("Error", error.toString(), "OK"); $scope.saving = false; }); } $scope.autoPaymentCheck = function () { if ($scope.editCard.autoPayAllPayments) { $scope.editCard.autoPayTrainingFee = true; $scope.editCard.autoPayMembership = true; } if (!$scope.editCard.autoPayAllPayments && !$scope.editCard.autoPayTrainingFee && !$scope.editCard.autoPayMembership) { $scope.editCard.autoPayChildren = false; } } $scope.close = function () { $modalInstance.close(); } $scope.init(); }// End controller }).result; }; }; modalPaymentCardsService.$inject = ['$modal']; angular.module('rubicApp').service('ModalPaymentCardsService', modalPaymentCardsService); }());; /** * Checklist-model * AngularJS directive for list of checkboxes * https://github.com/vitalets/checklist-model * License: MIT http://opensource.org/licenses/MIT */ //angular.module('checklist-model', []) angular.module('rubicApp') .directive('checklistModel', ['$parse', '$compile', function($parse, $compile) { // contains function contains(arr, item, comparator) { if (angular.isArray(arr)) { for (var i = arr.length; i--;) { if (comparator(arr[i], item)) { return true; } } } return false; } // add function add(arr, item, comparator) { arr = angular.isArray(arr) ? arr : []; if(!contains(arr, item, comparator)) { arr.push(item); } return arr; } // remove function remove(arr, item, comparator) { if (angular.isArray(arr)) { for (var i = arr.length; i--;) { if (comparator(arr[i], item)) { arr.splice(i, 1); break; } } } return arr; } // http://stackoverflow.com/a/19228302/1458162 function postLinkFn(scope, elem, attrs) { // exclude recursion, but still keep the model var checklistModel = attrs.checklistModel; attrs.$set("checklistModel", null); // compile with `ng-model` pointing to `checked` $compile(elem)(scope); attrs.$set("checklistModel", checklistModel); // getter / setter for original model var getter = $parse(checklistModel); var setter = getter.assign; var checklistChange = $parse(attrs.checklistChange); var checklistBeforeChange = $parse(attrs.checklistBeforeChange); // value added to list var value = attrs.checklistValue ? $parse(attrs.checklistValue)(scope.$parent) : attrs.value; var comparator = angular.equals; if (attrs.hasOwnProperty('checklistComparator')){ if (attrs.checklistComparator[0] == '.') { var comparatorExpression = attrs.checklistComparator.substring(1); comparator = function (a, b) { return a[comparatorExpression] === b[comparatorExpression]; }; } else { comparator = $parse(attrs.checklistComparator)(scope.$parent); } } // watch UI checked change scope.$watch(attrs.ngModel, function(newValue, oldValue) { if (newValue === oldValue) { return; } if (checklistBeforeChange && (checklistBeforeChange(scope) === false)) { scope[attrs.ngModel] = contains(getter(scope.$parent), value, comparator); return; } setValueInChecklistModel(value, newValue); if (checklistChange) { checklistChange(scope); } }); function setValueInChecklistModel(value, checked) { var current = getter(scope.$parent); if (angular.isFunction(setter)) { if (checked === true) { setter(scope.$parent, add(current, value, comparator)); } else { setter(scope.$parent, remove(current, value, comparator)); } } } // declare one function to be used for both $watch functions function setChecked(newArr, oldArr) { if (checklistBeforeChange && (checklistBeforeChange(scope) === false)) { setValueInChecklistModel(value, scope[attrs.ngModel]); return; } scope[attrs.ngModel] = contains(newArr, value, comparator); } // watch original model change // use the faster $watchCollection method if it's available if (angular.isFunction(scope.$parent.$watchCollection)) { scope.$parent.$watchCollection(checklistModel, setChecked); } else { scope.$parent.$watch(checklistModel, setChecked, true); } } return { restrict: 'A', priority: 1000, terminal: true, scope: true, compile: function(tElement, tAttrs) { if ((tElement[0].tagName !== 'INPUT' || tAttrs.type !== 'checkbox') && (tElement[0].tagName !== 'MD-CHECKBOX') && (!tAttrs.btnCheckbox)) { throw 'checklist-model should be applied to `input[type="checkbox"]` or `md-checkbox`.'; } if (!tAttrs.checklistValue && !tAttrs.value) { throw 'You should provide `value` or `checklist-value`.'; } // by default ngModel is 'checked', so we set it if not specified if (!tAttrs.ngModel) { // local scope var storing individual checkbox model tAttrs.$set("ngModel", "checked"); } return postLinkFn; } }; }]); ;