(function() { "use strict"; angular .module("agora.plus.emailValidation", ["ngSanitize"]) .directive("emailValidation", emailValidation) // This required!!! Its being used to compile the return of some Translations // Check the function ttt. // The translations have angular code, ng-click, that needs to be compiled. .directive("compile",compiler); function emailValidation() { return { restrict: "E", controller: emailValidationController, scope:{}, controllerAs: "ctrl", bindToController: true, templateUrl: PCK_GLOBAL_VARIABLES.email_validation }; emailValidationController.$inject = ["$scope", "constant", "$sce", "$translate", "ApiService", "DashboardService", "NewCompModal", "$timeout", "$location"]; function emailValidationController($scope, constant, $sce, $translate, ApiService, DashboardService, NewCompModal, $timeout, $location) { var vm = this; vm.imgPath = constant.imgPath; vm.cleanStatus = true; vm.emailSent = false; vm.validate = false; vm.displayTroubleshoot = false; vm.emailAlreadyExists = false; vm.accountCreated = false; vm.accountCreateHasError = false; vm.showLoader = false; vm.accountVerificationHasError = false; vm.isContactUsVisible = false; vm.isPhotoUploadEnabled = false; vm.isNewCodeSent = false; vm.confirmTerms = 0; vm.login = login; vm.cancel = cancel; vm.newCode = newCode; vm.setIcon = setIcon; vm.sendEmail = sendEmail; vm.newProcess = newProcess; vm.setButtons = setButtons; vm.troubleshoot = troubleshoot; vm.validateCode = validateCode; vm.buttonHandler = buttonHandler; vm.createAccount = createAccount; vm.definePassword = definePassword; vm.generalConditionsDocument = sessionHandler.sessionStorage.get("initialConfig").configsList.generalConditionsDocument; // Max birth date var maxDate = new Date(); maxDate.setFullYear(maxDate.getFullYear() - 16); vm.maxDate = maxDate; /** * Return a safe and translated string * @param {String} translationKey The key to be translated * @return {String} Safe translated string */ vm.ttt = function (translationKey) { return $sce.trustAsHtml($translate.instant(translationKey)); }; vm.setButtons(); /** * newCode Send email with a new code */ function newCode() { if (vm.isContactUsVisible) { vm.isContactUsVisible = false; } vm.showLoader = true; vm.accountVerificationHasError = false; ApiService.verifyEmail(vm.form.email) .then(function(d){}) .finally(function() { vm.showLoader = false; if (!vm.accountVerificationHasError) { vm.isNewCodeSent = true; $timeout(function() { vm.isNewCodeSent = false; }, 2500); } }) .catch(function(e){ vm.accountVerificationHasError = true; console.error(e); // vm.showLoader = false; }); } /** * sendEmail If the form is valid send an email to the user, providing * a token so that he can continue the registration process * @return {[type]} [description] */ function sendEmail() { angular.element(document.querySelectorAll('.checkboxTerm')).removeClass('errorTerm'); angular.element(document.querySelectorAll('.mandatory-checkbox-message')).addClass('no-error-message'); if (vm.confirmTerms != 1 || !vm.confirmTerms){ angular.element(document.querySelectorAll('.checkboxTerm')).addClass('errorTerm'); angular.element(document.querySelectorAll('.mandatory-checkbox-message')).removeClass('no-error-message'); return; } var formValid = true; var mandatory = ["firstName", "lastName", "email", "birthDate"]; var mandatoryLength = mandatory.length; vm.accountVerificationHasError = false; for (var i = 0; i < mandatoryLength; i++) { if (vm.emailValidation[mandatory[i]].$invalid) { formValid = false; vm.emailValidation[mandatory[i]].$setTouched(); if (i === mandatoryLength - 1) { vm.emailValidation[mandatory[i]].$pristine = false; } } } if (formValid) { vm.showLoader = true; var payload = { "login": vm.form.email, "firstName": vm.form.firstName, "lastName": vm.form.lastName, "birthDate": (vm.form.birthDate) ? moment(vm.form.birthDate).format("DD/MM/YYYY") : "", }, resp = {}; ApiService.validateAccount(payload) .then(function(response) { resp = response; }) .catch(function(error) { vm.showLoader = false; }) .finally(function() { if (resp.data.DATA >= 1 && resp.data.DATA <= 3) { // NOTE - it was a rule to send an email... going to leave it for now /*if (resp.data.DATA === 2) { // var params = { "context": resp.data.DATA, "from": "", "to": vm.form.email, "subject": "EMAIL_ACCOUNT_NOTIFICATION", "body": "EMAIL_ACCOUNT_NOTIF_BODY", "showClose": false }; getModalsMapper(resp.data.DATA)(params); } else {*/ vm.showLoader = false; // cancel(); getModalsMapper(resp.data.DATA)({"context":resp.data.DATA, "showClose": resp.data.DATA === 1}); // } } else if (resp.data.DATA === 4) { ApiService.verifyEmail(vm.form.email) .then(function (data) { vm.buttons[1] = { label: "BUTTON_VALIDATE", func: vm.validateCode, primary: true, isVisible: true }; if (vm.form.code) { vm.form.code = undefined; vm.emailValidation.code.$setUntouched(); vm.emailValidation.code.$setPristine(); } vm.emailSent = true; vm.validate = true; }) .finally(function() { vm.showLoader = false; }) .catch(function (error) { vm.showLoader = false; vm.accountVerificationHasError = true; if (error.hasError) { vm.icon = vm.setIcon("error"); vm.cleanStatus = false; vm.buttons = [{ label: "BUTTON_OK", func: vm.cancel, primary: true, center: true, isVisible: true }]; } }); } else { vm.accountVerificationHasError = true; vm.showLoader = false; } }); } } /** * validateCode Validate the code provided to the user * and show errors if the code is invalid or redesign * the view by setting up new buttons and new flags. */ function validateCode() { vm.emailValidation.code.$setValidity("wrongCode", true); if (vm.emailValidation.code.$untouched) { vm.emailValidation.code.$setTouched(); } if (vm.emailValidation.code.$valid) { vm.showLoader = true; ApiService.validateCode(vm.form.code) .then(function (data) { if (data.data.success == "1") { vm.emailValidation.code.$setValidity("wrongCode", true); vm.emailValidated = true; vm.buttons[1] = { label: "BUTTON_LETS_GO", func: vm.definePassword, primary: true, isVisible: true }; } }) .catch(function (error) { if (error.data.success == "0") { vm.emailValidation.code.$setValidity("wrongCode", false); } }).finally(function() { vm.showLoader = false; }); } } /** * login Show login dialog */ function login() { var initialConfig = sessionHandler.sessionStorage.get("initialConfig"); NewCompModal.show("LoginDiagCtrl", PCK_GLOBAL_VARIABLES.home_login_diag_view, { parent: angular.element(document.body), disableClose: true, targetEvent: null, escapeToClose: false, controllerAs: "$ctrl", bindToController: true, locals: { "params": { "email": vm.form.email, "isLogin": true, "showLabel": false, "franceConnectLink": initialConfig.configsList.franceConnectLink, "isFranceConnectVisible": initialConfig.configsList.hasFranceConnect, "isGoogleConnectVisible": initialConfig.configsList.hasGoogleConnect, "googleConnectClientKey": initialConfig.configsList.googleConnectClientKey, "googleConnectScope": initialConfig.configsList.googleConnectScope } } }).then(function(response) {}) .catch(function(error) { if (error) { console.error("Error occured logging in"); } }).finally(function() {}); } /** * accountExists Show popup notification * @param {Object} params Parameters that this function receives */ function accountExists(params) { NewCompModal.show("NotificationDiagCtrl", PCK_GLOBAL_VARIABLES.notification_diag_view, { parent: angular.element(document.body), clickOutsideToClose: false, disableParentScroll: true, controllerAs: "$ctrl", bindToController: true, escapeToClose: false, locals: { "params": params } }).then(function(response) { }).catch(function(error) { if (error) { console.error(error); } }).finally(function() { login(); }); } /** * notification description * @param {Object} params Parameters that this function receives */ function notification(params, showClose) { // params.showClose = showClose || false; NewCompModal.show("NotificationDiagCtrl", PCK_GLOBAL_VARIABLES.notification_diag_view, { parent: angular.element(document.body), clickOutsideToClose: false, disableParentScroll: true, controllerAs: "$ctrl", bindToController: true, escapeToClose: false, locals: { "params": params } }).then(function(response) { }).catch(function(error) { if (error) { console.error(error); } }).finally(function() {}); } /** * triggerEmail Send an email * @param {Object} params Parameters that this function receives */ function triggerEmail(params) { DashboardService.sendEmail(params.from, params.to, params.subject, params.body) .then(function(response) { console.log(response); }) .catch(function(error) { vm.accountVerificationHasError = true; console.error(error); }) .finally(function() { vm.showLoader = false; if (!vm.accountVerificationHasError) { notification({"context": 2}); } }); } /** * getModalsMapper Return a function based * on the response from validateAccount service * @param {Integer} response One of 1,2,3 or 4 that corresponds * to different account status. * @return {Function} Returns a function reference */ function getModalsMapper(response) { var mapper = { "1": accountExists, // "2": triggerEmail, "2": notification, "3": notification }; if (!mapper.hasOwnProperty(response)) { throw("No mapper function found for the provided response."); } return mapper[response]; } /** * cancel when called emits an event to close a dialog */ function cancel() { $scope.$emit("closeDialog", {sender:"emailValidation"}); // window.location = PCK_GLOBAL_VARIABLES.dashboard_home_view; // window.location = PCK_GLOBAL_VARIABLES.pck_home_home_view; // test if $location works always!! $location.path("/"); } /** * newProcess Closes the current dialog * and performs an automatic login */ function newProcess() { $scope.$emit("closeDialog", { sender: "emailValidation", action: "login", data: { login: vm.form.email, password: vm.form.password } }); } /** * setButtons Sets an array of buttons to be added to the view */ function setButtons() { vm.buttons = [ { label: "BUTTON_CANCEL", func: vm.cancel, isVisible: true }, { label: "BUTTON_SEND", func: vm.sendEmail, enabled: true, primary: true, isVisible: true } ]; } /** * buttonHandler Generic button handler. * When this handler is called it executes the function provided. * @param {Function} f Some function */ function buttonHandler(f) { f.call(); } /** * setIcon Set dialog icon * @param {String} icon icon name to be added * @return {String} Server for the provided icon */ function setIcon(icon) { return vm.imgPath+"assets/img/"+icon+".svg"; } /** * definePassword When in password mode this function is executed * when submitting the data */ function definePassword() { vm.passwordMode = true; vm.buttons[1] = { label: "BUTTON_CREATE_ACCOUNT", func: vm.createAccount, primary: true, isVisible: true }; } /** * createAccount Create a new temporary account with the data * provided by the user. */ function createAccount() { // Reset error flag vm.accountCreateHasError = false; if (!vm.form.password) { $scope.$broadcast("setRequired"); } else { var payload = { "FIRST_NAME": vm.form.firstName, "LAST_NAME": vm.form.lastName, "EMAIL": vm.form.email, "BIRTH_DATE": (vm.form.birthDate) ? moment(vm.form.birthDate).format("DD/MM/YYYY") : "", "PASSWORD": vm.form.password, "ID_USER_TYPE": -1 }; vm.showLoader = true; DashboardService.createAccount(payload) .then(function (data) { if (parseInt(data.data.TYPE_RESULT, 10) === 1) { vm.accountCreated = true; } else { vm.accountCreateHasError = true; } }) .catch(function (error) { vm.accountCreated = false; vm.accountCreateHasError = true; }) .finally(function() { vm.showLoader = false; if (vm.accountCreated) { vm.newProcess(); } }); } } } } /** * compiler Compile some elements; in this this particular case * compile the tags p in the troubleshoot section. This is needed because * the translations returned contain angular code, ng-clicks.... * @param {Object} $compile AngularJs compile service * @param {Object} $parse AngularJs parse service */ function compiler($compile,$parse) { return { link: function(scope, element, attr){ var parsed = $parse(attr.ngBindHtml); function getStringValue() { return (parsed(scope) || "").toString(); } //Recompile if the template changes scope.$watch(getStringValue, function() { $compile(element, null, -9999)(scope); //The -9999 makes it skip directives so that we do not recompile ourselves }); } }; } }());