/** * Survey program stream inbox handler controller. */ angular.module('kalgudiApp.surveys').controller('programSurveyStreamController', ['$scope', '$state', '$rootScope', 'surveyServices', 'loadingS3UrlServices', function ($scope, $state, $rootScope, surveyServices, loadingS3UrlServices) { $scope.programId = ''; // Load more object $scope.loadMore = { offset: 0, limit: 20, count: -1, }; // Survey stream object $scope.surveyStream = []; /** * Initializes survey program inbox stream controller. */ $scope.init = function() { // Reset stream $scope.resetStream(); try { // Get program id from state $scope.programId = $state.params.programId || $state.params.entityId; // Get survey stream $scope.getSurveyStream(); } catch (e) { console.log('Unable to initialize survey response submission page.', e); } // Inject a new survey to the stream whenever its newly created $rootScope.$on('newSurveyStreamObject', function(event, survey) { $scope.injectNewSurvey(survey); }); }; /* ------------------------- DECLARE FUNCTIONS BELOW ------------------------- */ /** * Resets survey stream objects. */ $scope.resetStream = function () { $scope.loadMore.offset = 0; $scope.loadMore.limit = 20; $scope.loadMore.count = -1; $scope.surveyStream = []; }; /** * Gets, survey stream created under a program. */ $scope.getSurveyStream = function () { $rootScope.spinerisActive = true; surveyServices.getProgramSurveyStream($scope.programId, $scope.loadMore.offset).then( function (res) { $rootScope.spinerisActive = false; // Successful response if (res.code === 200) { res.data = JSON.parse(res.data); $scope.loadMore.count = res.data.totalSurveys; // Get survey complete object from s3 url if (typeof res.data.surveys === 'object' && Array.isArray(res.data.surveys)) { res.data.surveys.forEach(function (s3Url) { $scope.getSurveyFromS3(s3Url); }); } } }, function (err) { $rootScope.spinerisActive = false; console.error('Unable to get program survey stream.', err); } ); }; /** * Gets, survey object stored in s3. */ $scope.getSurveyFromS3 = function (s3Url) { loadingS3UrlServices.callS3RespectiveUrls(s3Url, 0).then( function (res) { // Got response from s3, inject it to survey stream if (res.data) { $scope.injectNewSurvey(res.data); } }, function (err) { console.error('Unable to get survey object from s3.', err); } ) }; /** * Injects a new survey to the survey stream object * @param {any} survey Survey object */ $scope.injectNewSurvey = function (survey) { const d = survey.createdTS.split(' '); survey.TS = new Date(d[0] + ' ' + d[1]); $scope.surveyStream.unshift(survey); } // Initialize survey response page. $scope.init(); } ]);