angular.module('kalgudiApp.surveys').controller('surveyAdminFullviewController', ['$scope', '$state', '$rootScope', '$injector', 'kalgudiLiterals', 'surveyServices', 'pageServices', function($scope, $state, $rootScope, $injector,kalgudiLiterals, surveyServices, pageServices) { $scope.surveyLiterals = kalgudiLiterals; if(!IS_MOBILE_DEVICE) { $uibModal = $injector.get('$uibModal'); } else { $ionicModal = $injector.get("$ionicModal"); /** * Modal for Questions Form */ $scope.questionModal = $ionicModal.fromTemplateUrl($rootScope.themebasepathvalue+'surveys/question-modal.html', { scope: $scope, animation: 'slide-in-up', }).then(function(modal) { $scope.questionModal = modal; }); /** * Modal for Questions to be Updated in Surveys. */ $scope.questionListModal = $ionicModal.fromTemplateUrl($rootScope.themebasepathvalue+'surveys/surveys-admin-fullview-questions-modal.html', { scope: $scope, animation: 'slide-in-up', }).then(function(modal) { $scope.questionListModal = modal; }); $scope.membersModal = $ionicModal.fromTemplateUrl($rootScope.themebasepathvalue+'surveys/surveys-admin-fullview-members-modal.html', { scope: $scope, animation: 'slide-in-up', }).then(function(modal) { $scope.membersModal = modal; }); } $scope.programpageLiterals = kalgudiLiterals; // activites $scope.selectedTab = "Activites"; $scope.tabs = ["Activites", "Details", "Settings", "Analytics"]; $scope.activites = new Array(); //settings $scope.reminderDescpritionFlag = false; $scope.disableSurveyDescriptionFlag = false; $scope.resubmittableSurveyDescriptionFlag = false; $scope.expiryDateFlag = false; $scope.surveyObj = new Object(); $scope.s3Url = ""; $scope.datepickerObject = { todayLabel : 'Today', closeLabel : 'Close', inputDate : '', step : "1", format : "12", callback : function (val) { datePickerCallback(val); } } $scope.programHeaderData = { icon:"md md-group-add", heading:$scope.connectsLiterals.searchByKey('PROGRAM_PROGRAM'), description: $scope.connectsLiterals.searchByKey('COMMON_LOAD_MORE_LOADING') } //analytics $scope.analyticsObj = new Object(); $scope.maxValue = 0; $scope.emailValidFlag = false; $scope.surveyReport = { email : '' } //details $scope.selectedDetailsTab = "Questions"; $scope.detailsTabs = ["Questions","Members"]; $scope.NoMembersFlag = false; $scope.filterSurveyMembers = []; $scope.tempList = []; $scope.pageLiterals = kalgudiLiterals; $scope.loadMore = { text: $scope.pageLiterals.searchByKey('COMMON_LOAD_MORE_MORE_MSG'), limit: 20, flag:true } $scope.membersData = { limit: $scope.loadMore.limit, offset: 0 } /*if(window.env.enviorment == "devkalgudi.vasudhaika.net") { $scope.s3Url = ""; } else { $scope.s3Url = ""; }*/ $scope.surveyObj.isResubmittable = true; $scope.surveyActivities = []; $scope.init = function () { surveyServices.getActivites($state.params.id).then( function(res) { res.data = JSON.parse(res.data); if (res.data && res.data.length > 0) { res.data.forEach(function(d){ $scope.surveyActivities.push({ profileKey: d.profileKey, name: d.firstName, profilePicUrl: d.profilePicUrl, activity: 'Responded to survey', }); }); } }); $scope.getSurveyDetails(); }; /** * Resets target member filters fields. */ $scope.resetTargetMemberFilters = function () { $scope.rangeData = []; $rootScope.rangeData = [] $rootScope.selectedProductList = []; $rootScope.selectedBusinessList = []; $rootScope.selectedBusinessArray = []; $rootScope.selectedLocationList = []; }; /** * Gets, survey details from service */ $scope.getSurveyDetails = function () { $scope.surveyActivities = []; $rootScope.spinerisActive = true; surveyServices.getSurvey($state.params.id).then( function(response) { $rootScope.spinerisActive = false; $scope.surveyObj = JSON.parse(response.data); $scope.datepickerObject.inputDate = new Date($scope.surveyObj.expiryDate); var createdSurvey = { profileKey : $scope.surveyObj.createdBy.id, name : $scope.surveyObj.createdBy.name, profilePicUrl : $scope.surveyObj.surveyPicURL, activity : 'Created survey', }; $scope.surveyActivities.unshift(createdSurvey); // If survey created under program if ($scope.surveyObj.entityId) { if (IS_MOBILE_DEVICE) { $scope.membersModal = $ionicModal.fromTemplateUrl($rootScope.themebasepathvalue + 'surveys/survey-add-program-member-dialog.html', { scope: $scope, animation: 'slide-in-up', }).then(function(modal) { $scope.membersModal = modal; }); } // Get members filters if not exists if (typeof $scope.surveyObj.filters === 'undefined') { $scope.getMemberTargetFilters(); $rootScope.selectedProductList = []; $rootScope.selectedBusinessList = []; $rootScope.selectedBusinessArray = []; $rootScope.selectedLocationList = []; } } console.log($scope.surveyObj); }, function (err) { $rootScope.spinerisActive = false; } ); }; $scope.selectTab = function(tab) { $scope.selectedTab = tab; if(tab == "Analytics") { $scope.loadGraph(); } } $scope.expandReminder = function() { $scope.reminderDescpritionFlag = !$scope.reminderDescpritionFlag; $scope.disableSurveyDescriptionFlag = false; $scope.resubmittableSurveyDescriptionFlag = false; $scope.expiryDateFlag = false; } $scope.expandDisable = function() { $scope.disableSurveyDescriptionFlag = !$scope.disableSurveyDescriptionFlag; $scope.reminderDescpritionFlag = false; $scope.resubmittableSurveyDescriptionFlag = false; $scope.expiryDateFlag = false; } $scope.changeAdmins = function() { $state.go("surveys.admins", {'id' : $state.params.id}); } $scope.openSurveyResponse = function (userId, index) { if(!index) { return false; } $scope.getAdmin(); $rootScope.goToState('surveys.response', {surveyId: $state.params.id, profileId: userId, adminFlag: $scope.isAdmin}); } $scope.changeExpirayDateFlag = function() { $scope.expiryDateFlag = !$scope.expiryDateFlag; $scope.reminderDescpritionFlag = false; $scope.disableSurveyDescriptionFlag = false; $scope.resubmittableSurveyDescriptionFlag = false; } var datePickerCallback = function (val) { if (typeof(val) !== 'undefined') { $scope.datepickerObject.inputDate = val; $scope.surveyObj.expiryDate = val; $scope.updateSurvey($state.params.id, 'EXPIRY_DATE', $scope.surveyObj); }; } $scope.reminder = function() { surveyServices.reminder($state.params.id).then( function(response) { if(response.code == 200){ if( IS_MOBILE_DEVICE) { var title = "Success"; var icon = "notifications_active"; var expires = "3000"; var message = response.info; $rootScope.showAlertBox (message, title, icon, expires); $scope.reminderDescpritionFlag = false; } else { $rootScope.showSuccessMessage('Success','Reminder sent successfully',4000); } } }); } $scope.disableSurvey = function() { surveyServices.disableSurvey($state.params.id).then( function(response) { if(response.code == 200) { var title = "Success"; var icon = "done"; var expires = "3000"; var message = response.info; $rootScope.showAlertBox (message, title, icon, expires); $scope.reminderDescpritionFlag = false; } }); } /** * This method calls when the admin toggles the Re-submit in setting's tab */ $scope.updateSurvey = function(surveyId, operation, surveyObj) { if(operation == "DISABLE") { surveyObj.isDisabled = true; } surveyServices.updateSurvey(surveyId, "EXPIRY_DATE", surveyObj).then( function(response) { if(IS_MOBILE_DEVICE && response.code == 201) { var title = "Success"; var icon = "done"; var expires = "3000"; var message = response.info; $rootScope.showAlertBox (message, title, icon, expires); $scope.reminderDescpritionFlag = false; } if(!IS_MOBILE_DEVICE && response.code == 201){ $rootScope.showSuccessMessage(' Success ', 'Survey updated successfully', 2500); } else { $rootScope.showErrorMessage('Error','Please try after some time', 2500); } }); } /*Analytics tab*/ $scope.getAnalytics = function() { surveyServices.getAnalytics($state.params.id).then( function(response) { if(response.data) { $scope.analyticsObj = JSON.parse(response.data); console.log($scope.analyticsObj); } }); } $scope.getAnalytics(); $scope.loadGraph = function() { for (var i = 0; i < $scope.analyticsObj.surveyAnalytics.length; i++) { $scope.maxValue = 0; var dataset = []; var analyticsObj = $scope.analyticsObj.surveyAnalytics[i].analytics; for (var j in analyticsObj) { if (analyticsObj[j] > $scope.maxValue) { $scope.maxValue = parseInt(analyticsObj[j]); } var data = { name : j, percent : parseInt(analyticsObj[j]) } dataset.push(data); } if ($scope.maxValue < 300) { $scope.maxValue = 300; } if (Object.values($scope.analyticsObj.surveyAnalytics[i].analytics).length <= 5) { if(Object.values($scope.analyticsObj.surveyAnalytics[i].analytics).length) { $scope.createPieChart(i, dataset); } else { $scope.analyticsObj.surveyAnalytics[i].noAnalytics = true; } } else { $scope.loadBarGraph(i, dataset); } } } $scope.createPieChart = function(id, dataset) { var id = "#pie" + id; $(id).empty(); var pie = d3.layout.pie() .value(function(d){return d.percent}) .sort(null) .padAngle(.03); var w = 280, h = 300; var outerRadius = w / 2; var innerRadius = 100; var color = d3.scale.category10(); var arc = d3.svg.arc() .outerRadius(outerRadius) .innerRadius(innerRadius); var svg = d3.select(id) .append("svg") .attr({ width : w, height : h, class : 'shadow' }).append('g') .attr({ transform : 'translate(' + w / 2 + ',' + h / 2 + ')' }); var path = svg.selectAll('path') .data(pie(dataset)) .enter() .append('path') .attr({ d : arc, fill : function(d, i) { return color(d.data.name); } }); path.transition() .duration(1000) .attrTween('d', function(d) { var interpolate = d3.interpolate({startAngle : 0, endAngle : 0}, d); return function(t) { return arc(interpolate(t)); }; }); var restOfTheData = function() { var text = svg.selectAll('text') .data(pie(dataset)) .enter() .append("text") .transition() .duration(200) .attr("transform", function (d) { return "translate(" + arc.centroid(d) + ")"; }) .attr("dy", ".4em") .attr("text-anchor", "middle") .text(function(d){ return d.data.percent; }) .style({ fill:'#fff', 'font-size':'10px' }); var legendRectSize = 20; var legendSpacing = 7; var legendHeight = legendRectSize + legendSpacing; var legend = svg.selectAll('.legend') .data(color.domain()) .enter() .append('g') .attr({ class : 'legend', transform : function(d,i) { //Just a calculation for x & y position return 'translate(-35,' + ((i * legendHeight) - 65) + ')'; } }); legend.append('rect') .attr({ width : legendRectSize, height : legendRectSize, rx : 20, ry : 20 }) .style({ fill : color, stroke : color }); legend.append('text') .attr({ x : 30, y : 15 }) .text( function(d) { return d; }).style({ fill : '#929DAF', 'font-size' : '12px' }); }; setTimeout(restOfTheData, 1000); } $scope.loadBarGraph = function(id, dataset) { var id = "#bar" + id; $(id).empty(); var margin = { top : 20, right : 15, bottom : 150, left : 60 }; var width = 280 - margin.left - margin.right; var height = ($scope.maxValue) - margin.top - margin.bottom; var x = d3.scale.ordinal().rangeRoundBands([0, width], .05); var y = d3.scale.linear().range([height, 0]); var xAxis = d3.svg.axis() .scale(x) .orient("bottom") .ticks(dataset.length); var yAxis = d3.svg.axis() .scale(y) .orient("left") .ticks(dataset.length); var svg = d3.select(id).append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); d3.csv("dummySurveyFile.csv", function(data) { dataset.forEach( function(d) { d.date = d.name; d.value = +d.percent; }); x.domain(dataset.map(function(d) { return d.date; })); y.domain([0, d3.max(dataset, function(d) { return d.value; })]); svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis) .selectAll("text") .style("text-anchor", "end") .attr("dx", "-.8em") .attr("dy", "-.55em") .attr("transform", "rotate(-90)" ); svg.append("g") .attr("class", "y axis") .call(yAxis) .append("text") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", ".71em") .style("text-anchor", "end") .text("Users"); svg.selectAll("bar") .data(dataset) .enter().append("rect") .style("fill", "steelblue") .attr("x", function(d) { return x(d.date); }) .attr("width", x.rangeBand()) .attr("y", function(d) { return y(d.value); }) .attr("height", function(d) { return height - y(d.value); }); }); } /** Email validation to send survey analytics */ $scope.validateEmail = function (email){ var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; if(reg.test(email)){ $scope.sendReportInEmail(); } else { $scope.emailValidFlag = true; } } $scope.sendReportInEmail = function () { // var email = $rootScope.loggedInUserBusinessProfile.lstOfUserBusinessDetailsInfo[0].emailId; $scope.emailValidFlag = false; var email = $scope.surveyReport.email; var surveyId = $state.params.id; console.log('email :',email); $rootScope.spinerisActive = true; surveyServices.sendSurveyReportInEmail(email, surveyId).then( function (response) { $scope.surveyReport.email = ''; $rootScope.spinerisActive = false; if(response.code == 200){ if(IS_MOBILE_DEVICE ) { $rootScope.showAlertBox('E-mail has been sent to ' + email, 'E-mail sent', 'done'); } else { $rootScope.showSuccessMessage('Success','E-mail has been sent to ' + email, 4000); } } else { if( response.code == 504) { if(!IS_MOBILE_DEVICE) { $rootScope.showSuccessMessage('Success','E-mail has been sent to ' + email, 4000); } else { $rootScope.showAlertBox('E-mail has been sent to ' + email, 'E-mail sent', 'done'); } } } }); } /*Details tabs*/ $scope.selectedDetailsTabs=function(tab) { $scope.selectedDetailsTab=tab; if(tab == "Questions") { } if(tab == "Members") { if($scope.tempList.length != 0) { $rootScope.spinerisActive = false; } else { $scope.filterSurveyMembers = []; $scope.NoMembersFlag = true; // $rootScope.spinerisActive = true; if ($scope.surveyObj.entityId) { // Survey created under program if (typeof $scope.surveyObj.filters !== 'undefined') { // Get targeted members list $scope.getMembersOfSurveyUnderProgram($scope.surveyObj.id); } else { $scope.NoMembersFlag = false; } } else { $scope.getMembers($scope.surveyObj.id); } // surveyServices.getMembers($state.params.id, $scope.membersData.offset).then( function(response) { // $rootScope.spinerisActive = false; // if((JSON.parse(response.data)).length==0) { // $scope.NoMembersFlag = false; // } // $scope.tempList = JSON.parse(response.data); // $scope.filterSurveyMembers = $scope.filterSurveyMembers.concat($scope.tempList); // $scope.membersListLoadMoreCount($scope.tempList); // $scope.tempList = []; // }); } } } $scope.membersListLoadMoreCount = function (result) { if(IS_MOBILE_DEVICE) { if(result.length >= $scope.loadMore.limit) { $scope.loadMore.text = $scope.contentLiterals.searchByKey('COMMON_LOAD_MORE_MORE_MSG'); $scope.loadMore.flag = true; }else{ $scope.loadMore.text = $scope.contentLiterals.searchByKey('COMMON_LOAD_MORE_NO_MORE_MSG'); $scope.loadMore.flag = false; } } } /*----------------------------- UPDATE SURVEY QUESTIONS & MEMBERS ---------------------*/ /* Fields */ $scope.questionList = { questions : [] } $scope.question = { id:'', questionType:'', questionText:'', options:[] } $scope.membersList = { newMembers : [] } var counter = 0; $scope.answers_template = []; $scope.hideFlag=0; $scope.typeList = []; $scope.question_count = 0; $scope.selectedValue = ''; $scope.typeOptions = [ {"name":"Yes/No", "val":"0", "type": "YES_NO"}, {"name":"Text", "val":"1", "type": "TEXT"}, {"name":"Rating", "val":"2", "type": "RATING"}, {"name":"Date", "val":"2", "type": "DATE"}, {"name":"Multiple Choice with 2","val":"3", "type": "MULTIPLE_CHOICE_QUESTION"}, {"name":"Multiple Choice with 3","val":"4", "type": "MULTIPLE_CHOICE_QUESTION"}, {"name":"Multiple Choice with 4","val":"5", "type": "MULTIPLE_CHOICE_QUESTION"}, {"name":"Multiple Choice with 5", "val":"6", "type": "MULTIPLE_CHOICE_QUESTION"}, {"name":"Multiple Choice with 6", "val":"7", "type": "MULTIPLE_CHOICE_QUESTION"}, {"name":"Multiple Choice with 8", "val":"9", "type": "MULTIPLE_CHOICE_QUESTION"}, ]; $scope.openAddQuestionModal = function() { $scope.isQuestionEmtpy = false; $scope.headerTitle = 'Add Question'; $scope.questionModal.show(); }; $scope.closeAddQuestionModal = function() { $scope.questionModal.hide(); }; /** * Show Surveys Questions List Modal */ $scope.openQuestionListModal = function() { $scope.isQuestionEmtpy = false; $scope.headerTitle = 'Questions'; $scope.questionListModal.show(); }; /** * Hides Surveys Questions List Modal */ $scope.closeQuestionListModal = function() { $scope.questionListModal.hide(); }; /** * Submit all added Surveys Questions */ $scope.submitQuestions = function () { $rootScope.spinerisActive = true; /* Service to update survey questions */ surveyServices.submitSurveyQuestions($state.params.id, $scope.questionList).then ( function (response) { $rootScope.spinerisActive = false; if(response.code == 200) { $scope.isQuestionsSubmitted = true; $scope.surveyActivities = []; $scope.questionList.questions = []; $scope.init(); if(IS_MOBILE_DEVICE) { $scope.questionListModal.hide(); var title = "Success"; var icon = "done"; var expires = "3000"; var message = "Questions Added Successfully" $rootScope.showAlertBox (message, title, icon, expires); } else { $rootScope.showSuccessMessage('Changes Accepted', 'Questions Added Sucessfully', 4000); } } else { if(IS_MOBILE_DEVICE) { $scope.questionListModal.hide(); var title = "Error"; var icon = "close"; var expires = "3000"; var message = "Please try after some time." $rootScope.showAlertBox (message, title, icon, expires); } else { $rootScope.showErrorMessage('Something went wrong', 'Please try again after some time', 4000); } } }, function (err) { if(IS_MOBILE_DEVICE) { $scope.questionListModal.hide(); if(response.code != 200) { var title = "Error"; var icon = "close"; var expires = "3000"; var message = "Please try after some time" $rootScope.showAlertBox (message, title, icon, expires); } } } ); } $scope.questionForm = false; /** * Generate Question form with selected option */ $scope.selectedType = function (selectedValue) { if(selectedValue != null) { $scope.selectedQuestionType = selectedValue.name; $scope.questionForm = true; if($scope.hideFlag>0) { counter = 0; } $scope.answers_menu = true; $scope.questionLabelFlag = true; $scope.question.options=[]; $scope.typeList.push(selectedValue.name); $scope.question_label = 'Enter the question'; if(selectedValue.val >= 3) { for (var i = 1; i < selectedValue.val; i++) { counter++; $scope.question.options.push(""); } $scope.hideFlag++; } } } /** * Web specific functions */ if (!IS_MOBILE_DEVICE) { /** * Uploads and attaches multiple images to a question. */ $scope.attachImageWeb = function(){ var tempObj = { uploadType: 'IMAGE', } // tempObj.uploadType = 'IMAGE'; var modalInstance = $uibModal.open({ templateUrl: $rootScope.themebasepathvalue + 'shared/uploadMultimedia.html', controller: 'uploadMultimediaController', windowClass: 'app-modal-window', size: 'lg', resolve: { items: function () { return tempObj; } } }); // uploadedMedia will contain all uploaded objects as an array modalInstance.result.then(function (uploadedMedia) { // if(!scope.uploadedImageList) { // scope.uploadedImageList = uploadedMedia; // } else { // } $scope.question.attachments = []; for(i in uploadedMedia){ try { // Delete unnecessary files delete uploadedMedia[i].name; delete uploadedMedia[i].size; // Append http/s if not exists if (!uploadedMedia[i].url.includes(env.secure)) { uploadedMedia[i].url = env.secure + uploadedMedia[i].url; } // Add geo tagging var lat = ""; var long = ""; if (Array.isArray(LATITUDELONGITUDEVALUES) && LATITUDELONGITUDEVALUES.length >= 2) { lat = LATITUDELONGITUDEVALUES[0]; long = LATITUDELONGITUDEVALUES[1]; } uploadedMedia[i].geoLocation = { latitude: lat, longitude: long }; } catch (e) { console.warn('Unable to attach images to survey question', e); } $scope.question.attachments.push(uploadedMedia[i]); } }); }; /** * Open video attachment url dialog and attaches video url. */ $scope.attachVideoUrlWeb = function(){ var modalInstance = $uibModal.open({ templateUrl: $rootScope.themebasepathvalue + 'shared/urlPicker.html', // This controller is defined below in this same file controller: 'urlController', size: 'md' }); modalInstance.result.then(function (url) { if(url) { $scope.question.attachments = []; $scope.question.attachments.push({ context: '', msgType: 'VIDEO', url: url, }); // scope.urlSpinner = true; // scope.web.url = url; // scope.uploadedImageList = []; // scope.shareUrl(url); } }); }; /** * Opens question image attachments fullview. * * @param {any} question Question object */ $scope.openAttachmentFullview = function (question) { const message = { lstOfAttachments: question.attachments, }; var modalInstance = $uibModal.open({ templateUrl: 'webapp/themes/html/newsFeed/shareAthoughtFullview.html', controller: 'sharefullviewController', size: 'md', windowClass:'share-full', resolve: { items: function () { return message; } } }); modalInstance.result.then(function (selectedItem) { //$scope.selected = selectedItem; }, function () { //$log.info('Modal dismissed at: ' + new Date()); }); }; } else { /** * Mobile specific functions */ $scope.showAttachments = { value: false }; $scope.showUrlAttachment = { value: false, disabled: false, }; $rootScope.$on("uploadedS3URL", function (event, objectS3URL) { if ($scope.question) { $scope.question.attachments = $scope.question.attachments || []; delete objectS3URL.localFile; delete objectS3URL.size; delete objectS3URL.name; // Add geo tagging var lat = ""; var long = ""; if (Array.isArray(LATITUDELONGITUDEVALUES) && LATITUDELONGITUDEVALUES.length >= 2) { lat = LATITUDELONGITUDEVALUES[0]; long = LATITUDELONGITUDEVALUES[1]; } objectS3URL.geoLocation = { latitude: lat, longitude: long }; $scope.question.attachments.push(objectS3URL); console.log($scope.question); } $scope.showAttachments.value = false; console.log($scope.showAttachments); }); $rootScope.$on("activateShareURL", function (event, data) { $scope.showUrlAttachment.value = !$scope.showUrlAttachment.value; $scope.showAttachments.value = false; }); $scope.attachVideoUrl = function (url) { if ($scope.question) { $scope.question.attachments = $scope.question.attachments || []; // Add geo tagging var lat = ""; var long = ""; if (Array.isArray(LATITUDELONGITUDEVALUES) && LATITUDELONGITUDEVALUES.length >= 2) { lat = LATITUDELONGITUDEVALUES[0]; long = LATITUDELONGITUDEVALUES[1]; } $scope.question.attachments.push({ context: '', url: url, msgType: 'VIDEO', geoLocation: { latitude: lat, longitude: long } }); $scope.showUrlAttachment.disabled = true; } } } /** * Removes attachment from current question. * * @param {number} index */ $scope.removeQuestionAttachment = function (index) { // Param and attachments validation if ($scope.question && Array.isArray($scope.question.attachments) && $scope.question.attachments.length >= index) { $scope.question.attachments.splice(index, 1); } }; /** * Add Question & Answers to Survey Questions List */ $scope.saveQuestion = function (question) { if(!$scope.isQuestionValid(question)) { $scope.isQuestionsSubmitted = false; return; } if(IS_MOBILE_DEVICE) { $scope.closeAddQuestionModal(); } $scope.question.questionType = question.questionType.type; $scope.headerTitle = 'Questions'; $scope.question_count++; $scope.questionLabelFlag = false; $scope.isQuestion_Template = false; $scope.answers_menu = false; question.id = $scope.surveyObj.questions.length == 0 ? $scope.questionList.questions.length : $scope.surveyObj.questions.length + $scope.questionList.questions.length; $scope.questionList.questions.push(question); $scope.question_form = false; console.log($scope.question); $scope.question = {}; $scope.selectedValue = 0; $scope.questionForm = false; $scope.questionField = false; } /** * Question & Answers Form Validation */ $scope.isQuestionValid = function (question) { switch($scope.question.questionType.type) { case 'YES_NO': case 'TEXT': case 'RATING': if(!question.questionText){ $scope.isQuestionEmtpy = true; return false; } break; case 'MULTIPLE_CHOICE_QUESTION': case 'MULTIPLE_CHOICE_QUESTION': case 'MULTIPLE_CHOICE_QUESTION': if(!question.questionText) { $scope.isQuestionEmtpy = true; return false; } if (question.options) { for (var i = 0; i < question.options.length; i++) { if(!question.options[i]) { return false; } } } break; } return true; } /** * Remove Question & Answers from Survey Questions List */ $scope.removeQuestion = function (questionToRemove, index) { $scope.questionList.questions.splice(index, 1); } /*------------------------ Update Members to Survey --------------------*/ /* Mobile survey target members filter */ /** * Get, program target members filters. */ $scope.getMemberTargetFilters = function () { $rootScope.spinerisActive = true; pageServices.getRangeToFilterSubscribers($scope.surveyObj.entityId).then( function(res){ $scope.rangeData = JSON.parse(res.data); $rootScope.spinerisActive = false; }, function (err) { $rootScope.spinerisActive = false; } ); }; $scope.membersLoadMore = { loadMore: true, offset: 0, limit: 20, }; /** * Gets, survey targeted members list for the survey created under program. */ $scope.getMembersOfSurveyUnderProgram = function (surveyId) { $rootScope.spinerisActive = true; $scope.loadMore.text = $scope.pageLiterals.searchByKey('COMMON_LOAD_MORE_LOADING'); // limit: 20, // flag:true // } surveyServices.getMembersOfSurveyUnderProgram(surveyId, $scope.membersLoadMore.offset).then( function (res) { $rootScope.spinerisActive = false; if (res.code === 200) { res.data = JSON.parse(res.data); if (res.data.length <= 0) { $scope.NoMembersFlag = false; } $scope.filterSurveyMembers = $scope.filterSurveyMembers.concat(res.data); // Nothing more to load if (res.data.length < $scope.membersLoadMore.limit) { $scope.membersLoadMore.loadMore = false; $scope.loadMore.flag = false; $scope.loadMore.text = $scope.pageLiterals.searchByKey('COMMON_LOAD_MORE_NO_MORE'); } else { $scope.membersLoadMore.offset = $scope.membersLoadMore.limit; } } }, function (err) { $rootScope.spinerisActive = false; } ); }; /** * Gets, survey members list from service. * * @param {string} surveyId Survey Id */ $scope.getMembers = function(surveyId) { $rootScope.spinerisActive = true; surveyServices.getMembers(surveyId, $scope.membersData.offset).then( function(response) { $rootScope.spinerisActive = false; if((JSON.parse(response.data)).length==0) { $scope.NoMembersFlag = false; } $scope.tempList = JSON.parse(response.data); $scope.filterSurveyMembers = $scope.filterSurveyMembers.concat($scope.tempList); $scope.membersListLoadMoreCount($scope.tempList); $scope.tempList = []; }, function (err) { console.error('Unable to get survey members list.', err); $rootScope.spinerisActive = false; } ); }; $scope.showsharefilter = function(type) { if(type=="product"){ $scope.previewResult = ""; $scope.resultFlag = false; $scope.items= $scope.rangeData.products; $scope.items.pickerType="product"; }else if(type=="location"){ $scope.previewResult = ""; $scope.resultFlag = false; $scope.items={ countries: $scope.rangeData.countries, statesOrRegions: $scope.rangeData.statesOrRegions, districts: $scope.rangeData.districts, pickerType: "location" }; }else if(type=="business"){ $scope.items=$scope.rangeData.businessTypes; $scope.items.pickerType="business"; } $scope.pickerType=type; $ionicModal.fromTemplateUrl('app/programs/sharefilter-directive.html', { scope: $scope, animation: 'slide-in-up' }).then(function(modal){ $scope.sharefilterModal = modal; $scope.sharefilterModal.show(); }); } $scope.closesharefilter=function(){ $scope.pickerType=""; $scope.sharefilterModal.hide(); } /* Mobile survey target members filter */ /* Web survey target members filter */ if (!IS_MOBILE_DEVICE) { // Will open businss type picker $scope.filterByBusinessTypes = function(){ $scope.previewResult = ""; $scope.resultFlag = false; var tempObj = $scope.rangeData.businessTypes; tempObj.pickerType="business"; var modalInstance = $uibModal.open({ templateUrl: $rootScope.themebasepathvalue + 'shared/filterPicker.html', // controller is defined below in this same file controller: 'filterPickerController', size: 'md', resolve: { items: function () { return tempObj; } } }); } // Will open product picker with multiple selection option $scope.filterByProducts = function(){ $scope.previewResult = ""; $scope.resultFlag = false; var tempObj = $scope.rangeData.products; tempObj.pickerType="product"; var modalInstance = $uibModal.open({ templateUrl: $rootScope.themebasepathvalue+'shared/filterPicker.html', // controller is defined below in this same file controller: 'filterPickerController', size: 'md', resolve: { items: function () { return tempObj; } } }); } // Will open location picker with multiple selection option $scope.filterByLocations =function(){ $scope.previewResult = ""; $scope.resultFlag = false; var tempObj = { countries: $scope.rangeData.countries, statesOrRegions: $scope.rangeData.statesOrRegions, districts: $scope.rangeData.districts, pickerType: "location" }; var modalInstance = $uibModal.open({ templateUrl: $rootScope.themebasepathvalue+'shared/filterPicker.html', // controller is defined below in this same file controller: 'filterPickerController', size: 'md', resolve: { items: function () { return tempObj; } } }); } } /* Web survey target members filter */ $scope.openAddMembersModal = function() { if ($scope.surveyObj.entityId) { $scope.headerTitle = 'Target Members'; } else { $scope.headerTitle = 'Add Members'; } $scope.membersModal.show(); }; $scope.closeAddMembersModal = function() { $scope.membersModal.hide(); console.log($scope.membersList.members) }; $scope.onMembersSelect = function (users) { // Push all selected elements to selected participants for (i in users) { $scope.membersList.newMembers.push ( { name : users[i].firstName, id : users[i].profileKey, profilePicUrl : users[i].profilePicUrl, bizId : users[i].lstOfUserBusinessDetailsInfo[0].businessKey, location : users[i].lstOfUserBusinessDetailsInfo[0].locationTo.locationLong, bizTypeName : users[i].lstOfUserBusinessDetailsInfo[0].businessTypeName } ); } // Filter our profile keys of selected users. $scope.selectedAudienceProfileKey = $scope.membersList.newMembers.map(function (e) { return e.profileKey; }); $scope.isUserPickerShown = false; console.log($scope.membersList.members) } $scope.removeMember = function (user, index) { $scope.membersList.newMembers.splice(index, 1); } $scope.submitMembers = function () { $rootScope.spinerisActive = true; /* Service to update survey members */ surveyServices.submitSurveyMembers($state.params.id, $scope.membersList).then ( function (response) { $rootScope.spinerisActive = false; /* $scope.membersList.newMembers = []; $scope.toggleTabs($scope.parentTab.MEMBERS, $scope.childTab.MEMBERS_LIST);*/ $scope.membersList.newMembers = []; if(response.code == 200) { if(IS_MOBILE_DEVICE) { $scope.membersModal.hide(); var title = "Success"; var icon = "done"; var expires = "3000"; var message = "Members Added Successfully" $rootScope.showAlertBox (message, title, icon, expires); /* Re-calling Service Again for upadted Members*/ $scope.selectedDetailsTabs("Members"); $scope.filterSurveyMembers = []; } else { $rootScope.showSuccessMessage('Changes Accepted', 'Member(s) Added Sucessfully', 4000); } } else { if(IS_MOBILE_DEVICE) { $scope.membersModal.hide(); var title = "Error"; var icon = "close"; var expires = "3000"; var message = "Please try after some time." $rootScope.showAlertBox (message, title, icon, expires); } else { $rootScope.showErrorMessage('Something went wrong', 'Please try again after some time', 4000); } } }, function (err) { $rootScope.spinerisActive = false; if(IS_MOBILE_DEVICE) { $scope.membersModal.hide(); if(response.code != 200) { var title = "Error"; var icon = "close"; var expires = "3000"; var message = "Please try after some time" $rootScope.showAlertBox (message, title, icon, expires); } } } ); } $scope.submitTargetedMembers = function () { $scope.selectedData = {}; if (!IS_MOBILE_DEVICE) { $rootScope.selectedBusinessList = $rootScope.selectedBusinessArray; } if($rootScope.selectedBusinessList && $rootScope.selectedBusinessList.length > 0){ var bizList = []; for(var bizz in $rootScope.selectedBusinessList){ bizList.push($rootScope.selectedBusinessList[bizz].id); } $scope.selectedData.businessTypes = bizList; } if($rootScope.selectedLocationList && $rootScope.selectedLocationList.length > 0){ if($rootScope.rangeData){ $scope.filter = { countries : [] } for(i in $rootScope.rangeData){ for(j in $rootScope.rangeData[i].states){ if(!$scope.filter.states){ $scope.filter.states = []; } if($scope.filter.states.indexOf($rootScope.rangeData[i].states[j]) == -1){ $scope.filter.states.push($rootScope.rangeData[i].states[j]); } } for(j in $rootScope.rangeData[i].districts){ if(!$scope.filter.districts){ $scope.filter.districts = []; } if($scope.filter.districts.indexOf($rootScope.rangeData[i].districts[j]) == -1){ $scope.filter.districts.push($rootScope.rangeData[i].districts[j]); } } for(j in $rootScope.rangeData[i].regions){ if(!$scope.filter.regions){ $scope.filter.regions = []; } if($scope.filter.regions.indexOf($rootScope.rangeData[i].regions[j]) == -1){ $scope.filter.regions.push($rootScope.rangeData[i].regions[j]); } } if($scope.filter.countries.indexOf($rootScope.rangeData[i].countries.id) == -1){ $scope.filter.countries.push($rootScope.rangeData[i].countries.id); } } } else { var locList = []; for(var loc in $rootScope.selectedLocationList){ locList.push($rootScope.selectedLocationList[loc].id); } $scope.selectedData.locations = locList; } } if($rootScope.selectedProductList && $rootScope.selectedProductList.length > 0){ var proList = []; for(var pro in $rootScope.selectedProductList){ proList.push($rootScope.selectedProductList[pro].id); } $scope.selectedData.products = proList; } if($scope.selectedData.hasOwnProperty("products") || $scope.selectedData.hasOwnProperty("businessTypes") || $scope.selectedData.hasOwnProperty("locations")){ if(!$scope.filter){ $scope.filter = $scope.selectedData; } else { $scope.filter.businessTypes = $scope.selectedData.businessTypes; $scope.filter.products = $scope.selectedData.products; } } // Add pageId and pageName to filters $scope.filter.pageId = $scope.surveyObj.entityId; $scope.filter.pageTitle = $scope.surveyObj.entityName; const payload = { filters: $scope.filter, } $rootScope.spinerisActive = true; /* Service to update survey members */ surveyServices.submitSurveyMembers($state.params.id, payload).then ( function (response) { $rootScope.spinerisActive = false; $scope.membersList.newMembers = []; if(response.code == 200) { if(IS_MOBILE_DEVICE) { $scope.membersModal.hide(); var title = "Success"; var icon = "done"; var expires = "3000"; var message = "Members Added Successfully" $rootScope.showAlertBox (message, title, icon, expires); /* Re-calling Service Again for upadted Members*/ $scope.selectedDetailsTabs("Members"); $scope.NoMembersFlag = true; } else { $rootScope.showSuccessMessage('Changes Accepted', 'Member(s) Added Successfully', 4000); } $scope.resetTargetMemberFilters(); // Fetch survey details again to update the members list $scope.getSurveyDetails(); } else { if(IS_MOBILE_DEVICE) { $scope.membersModal.hide(); var title = "Error"; var icon = "close"; var expires = "3000"; var message = "Please try after some time." $rootScope.showAlertBox (message, title, icon, expires); } else { $rootScope.showErrorMessage('Something went wrong', 'Please try again after some time', 4000); } } }, function (err) { $rootScope.spinerisActive = false; if(IS_MOBILE_DEVICE) { $scope.membersModal.hide(); if(response.code != 200) { var title = "Error"; var icon = "close"; var expires = "3000"; var message = "Please try after some time" $rootScope.showAlertBox (message, title, icon, expires); } } } ); } /* ------------------------ TARGET AUDIENCE ----------------------- */ $scope.audienceCount = 0; $scope.selectedAudience = []; $scope.selectedAudienceProfileKey = []; $scope.isUserPickerShown = false; $scope.onAudienceSelect = function (users) { // Push all selected elements to selected audience for (i in users) { $scope.selectedAudience.push(users[i]); } // Filter our profile keys of selected users. $scope.selectedAudienceProfileKey = $scope.selectedAudience.map(function (e) { return e.profileKey; }); $scope.isUserPickerShown = false; // Update audience count $scope.audienceCount = $scope.selectedAudience.length; } $scope.showUserPicker = function() { title = "Select Target Members"; $rootScope.$broadcast("changeHeaderTitle", title); $scope.isUserPickerShown = true; } $scope.userPickerClosed = function() { title = "Create Survey"; $rootScope.$broadcast("changeHeaderTitle", title); $scope.isUserPickerShown = false; } /* -----------------------------------Surveys Web App ------------------------------*/ $scope.openContactSearch = function (size,assignnTo) { var modalInstance = $uibModal.open ({ templateUrl: 'webapp/themes/html/shared/connects.html', controller: 'kalgudiSearchContacts', size: 'md', resolve: { filterData: {} } }); modalInstance.result.then(function (selectedConnects) { for (i in selectedConnects) { $scope.membersList.newMembers.push ( { name : selectedConnects[i].firstName, id : selectedConnects[i].profileKey, profilePicUrl : selectedConnects[i].profilePicURL, bizId : selectedConnects[i].businessKey, location : selectedConnects[i].location, bizTypeName : selectedConnects[i].businessName, } ); } console.log($scope.membersList.newMembers) }, function () { }); } $scope.addQuestion = function () { $scope.questionField = true; } $scope.cancelQuestion = function () { $scope.questionField = false; $scope.questionForm = false; } $scope.searchTabForm = true; $scope.tabs.searchTab=true; $scope.verifyUsers = function () { $scope.tableForm = true; } $scope.closeUserTable = function () { /** * Clearing the entered Users id's in textarea */ $scope.multipleMembersData = {}; $scope.tableForm = false; } /* Date Picker (Expiry Date)*/ var today = new Date(); $scope.datevar = { fromDate :new Date(), toDate : new Date() } $scope.AvailableDate = ''; $scope.ExpireDate = new Date(); $scope.dateFormat = 'dd-MMM-yy'; $scope.availableDateOptions = { formatYear: 'yy', startingDay: 1, minDate: new Date(), maxDate: new Date(2030, 5, 22) }; $scope.expireDateOptions = { formatYear: 'yy', startingDay: 1, minDate: today, maxDate: new Date(2030, 5, 22) }; $scope.availableDatePopup = { opened: false, fromOpened: false, toOpened: false }; $scope.expireDatePopup = { opened: false }; $scope.ChangeExpiryMinDate = function(availableDate) { if (availableDate != null) { var expiryMinDate = new Date(availableDate); $scope.expireDateOptions.minDate = expiryMinDate; $scope.ExpireDate = expiryMinDate; } }; $scope.ChangeExpiryMinDate(); $scope.OpenAvailableDate = function(indexDate) { $scope.availableDatePopup.opened = !$scope.availableDatePopup.opened; $scope.postMessageFormData = $scope.AvailableDate; $scope.datepickerObject.inputDate = $scope.postMessageFormData.AvailableDate; }; // $scope.ChangeDate = function(indexChangeDate) { // $scope.postMessageFormData.date = indexChangeDate; // $scope.surveyObject.expiryDate = indexChangeDate; // }; $scope.OpenExpireDate = function() { $scope.expireDatePopup.opened = !$scope.expireDatePopup.opened; }; /* Date Picker (Expiry Date) Ends*/ $scope.multipleMembersData = { ids : "" } $scope.surveyMultipleMembers = []; $scope.addMultipleMembers = function () { console.log($scope.multipleMembersData) $scope.tableForm = true; $rootScope.spinerisActive = true; /* Service to update survey members */ surveyServices.addMultipleMembers($state.params.id, $scope.multipleMembersData).then ( function (response) { $rootScope.spinerisActive = false; $scope.surveyMultipleMembers = JSON.parse(response.data); if(!IS_MOBILE_DEVICE && response.code == 200) { $rootScope.showSuccessMessage('Success', 'Member(s) added successfully', 4000); } }, function (err) { if(!IS_MOBILE_DEVICE){ $rootScope.showErrorMessage('Something went wrong', 'Please try again after some time', 4000); } } ); console.log($scope.surveyMultipleMembers) } $scope.parentTab = { ACTIVITY : 0, QUESTIONS : 1, MEMBERS : 2, ANALYTICS : 3, SETTINGS : 4 } $scope.childTab = { SEARCH_ADD : 0, USER_ID : 1, MEMBERS_LIST : 2 } $scope.selectedParentTab = 0; $scope.selectedChildTab = 0; $scope.toggleTabs = function (parentTab, childTab) { $scope.selectedParentTab = parentTab; $scope.selectedChildTab = childTab; $scope.membersLoadMore.offset = 0; } $scope.admins = []; $scope.changeSurveyAdmin = function (size,assignnTo) { var modalInstance = $uibModal.open ({ templateUrl: 'webapp/themes/html/surveys/survey-admin-modal.html', size: 'md', controller: 'surveyAdminsController', resolve: { filterData: {} } }); } /*$scope.filterAdminProfileKeys = function () { $scope.adminProfileKeys = $scope.admins.map(function (admin) { return admin.id; }); };*/ /** To know the admin of a particular survey */ $scope.isAdmin = false; $scope.getAdmin = function () { for(var i in $scope.surveyObj.admins) { if($scope.surveyObj.admins[i].id === $rootScope.loggedInUserBusinessProfile.profileKey){ $scope.isAdmin = true; } } console.log('adminFlag:',$scope.isAdmin); } $scope.init(); } ]);