angular.module('kalgudiApp.eCommerce').controller('storeChatController', ['$scope', '$state', '$rootScope', '$injector', 'kalgudiLiterals', 'eCommerceServices', function ($scope, $state, $rootScope, $injector, kalgudiLiterals, eCommerceServices) { /** * Message type constants */ $scope.msgTypes = { 'TEXT': 'TEXT', 'IMAGE': 'IMAGE' }; $scope.chatLiterals = kalgudiLiterals; $scope.attachmentImg = []; // Empty order id by default $scope.orderId = false; // Current selected chat thread Id, default to null $scope.activeThread = false; // Active chat thread $scope.chatThread = []; $scope.isBuyer = false; /** * Initializes controller. */ $scope.init = function () { // Get order Id from params $scope.orderId = $state.params.id; // try { // $scope.isBuyer = $scope.$parent.$parent.isBuyer; // console.log($scope.isBuyer); // } catch (e) { } $rootScope.$on('orderDetailsFetched', function (event, isBuyer){ $scope.isBuyer = isBuyer; }); // Get list of all participants $scope.getParticipants(); if (detectmob()) { $ionicModal = $injector.get("$ionicModal"); $ionicScrollDelegate = $injector.get('$ionicScrollDelegate'); } else { $uibModal = $injector.get('$uibModal'); } }; /** * Gets, the list of available participants for the current order. */ $scope.getParticipants = function () { $rootScope.spinerisActive = true; eCommerceServices.getOrderParticipants($scope.orderId).then( function (res) { $rootScope.spinerisActive = false; // Check for valid response if (res.code === 200) { res.data = JSON.parse(res.data); $scope.chatList = res.data; // If chat list contains list of participants. // Then set first user in the chat list as active user $scope.activeThread = typeof ($scope.chatList) === 'object' && Array.isArray($scope.chatList) ? $scope.chatList[0] : false; // Switch participant if(!detectmob()){ $scope.switchParticipant($scope.activeThread); } console.log($scope.chatList); } else { $scope.activeThread = false; $scope.chatList = []; } }, function (err) { $rootScope.spinerisActive = false; console.error('Unable to get participants list.'); // Empty chat participants list $scope.chatList = []; $scope.activeThread = false; } ); }; /** * Sends a message to the current the current selected active thread. * * @param {string} msg Text message to post * @param {any[]} attachment List of attachments */ $scope.postMessage = function (msg, attachment) { $scope.attachmentImg = []; // Attachment validation attachment = typeof(attachment) === 'object' && Array.isArray(attachment) ? attachment : false; // Validate message posting if (!msg && !attachment) { return false; } $rootScope.spinerisActive = true; // Prepare request object const requestPayload = { 'senderFirstName': $rootScope.loggedInUserBusinessProfile.firstName, 'senderProfileKey': $rootScope.loggedInUserBusinessProfile.profileKey, 'receiverProfileKey': $scope.activeThread.profileKey, 'threadId': $scope.activeThread.threadId, 'orderId': $scope.orderId, 'type': $scope.activeThread.chatType, 'text': msg || '', 'timestamp': new Date().toISOString(), 'msgType': attachment ? $scope.msgTypes.IMAGE : $scope.msgTypes.TEXT, 'attachments': attachment ? attachment : [] }; // Post message to service eCommerceServices.postMessage($scope.orderId, requestPayload).then( function (res) { $rootScope.spinerisActive = false; // Reset message fields $scope.resetChatWindow(); $scope.getMessages(true); console.log(res); }, function (err) { console.warn('Unable to post message.', err); $rootScope.spinerisActive = false; } ); if (detectmob()) { $ionicScrollDelegate.scrollBottom(true); } }; /** * Opens image attachment dialog window. The image attachment * dialog window handles image upload to s3 and returns an * object containing attachmentTO. */ $scope.postImage = function () { var obj = { uploadType: 'IMAGE' }; var modalInstance = $uibModal.open({ templateUrl: $rootScope.themebasepathvalue + 'shared/uploadMultimedia.html', controller: 'uploadMultimediaController', windowClass: 'app-modal-window', size: 'lg', resolve: { items: function () { return obj; } } }); // uploadedMedia will contain all uploaded objects as an array modalInstance.result.then(function (uploadedMedia) { // Delete name and size coming from image upload dialog for (i in uploadedMedia) { if (uploadedMedia.hasOwnProperty(i)) { uploadedMedia[i].url = env.secure + uploadedMedia[i].url; delete uploadedMedia[i].name; delete uploadedMedia[i].size; } } $scope.postMessage('', uploadedMedia); }); }; /** * Toggle display of answer attachments box. */ $scope.toggleAttachments = function () { // $scope.isAnsAttachmentsVisible = !$scope.isAnsAttachmentsVisible; // if ($scope.isAttachOpen) // $('.attach-toggle').closeFAB(); // else // $('.attach-toggle').openFAB(); $scope.isAttachOpen = !$scope.isAttachOpen; } // To hide attachment options on elsewhere click angular.element(document).on("click", function (e) { $scope.$apply(function () { if (e.toElement.className != 'material-icons') { if ($scope.isAttachOpen) { // $('.attach-toggle').closeFAB(); $scope.isAttachOpen = false; } } if (e.toElement.name !== 'quote-modal') $scope.isQuoteShown = false; }); }); /** -----------------------------upload Attachments Starts-----------------*/ if (IS_MOBILE_DEVICE) { $rootScope.$on("uploadedS3URL", function (event, objectS3URL) { $scope.attachmentImg.push(objectS3URL); for (i in $scope.attachmentImg) { if ($scope.attachmentImg.hasOwnProperty(i)) { $scope.attachmentImg[i].url = $scope.attachmentImg[i].url; delete $scope.attachmentImg[i].name; delete $scope.attachmentImg[i].size; } } $scope.postMessage('', $scope.attachmentImg); }); } /** -----------------------------upload Attachments ends-----------------*/ $scope.getImgUrl = function (url) { // console.log('url :',url); if (url && url.indexOf('http') > -1) { return url; } else { return env.secure + url; } } /** * Gets, list of all messages posted to a unique chat thread. */ $scope.getMessages = function (showSpinner) { $rootScope.spinerisActive = showSpinner; eCommerceServices.getChatMessages($scope.orderId, $scope.activeThread.threadId).then( function (res) { $scope.chatThread = []; // Check for valid service response if ((res.code === 200 || res.code === 204) && (typeof(res.data) === 'string' && res.data.length > 0)) { res.data = JSON.parse(res.data); $scope.chatThread = res.data; $scope.scrollToLastThread(); } $rootScope.spinerisActive = false; }, function (err) { console.warn('Unable to get chat message from service', err); $rootScope.spinerisActive = false; } ); } /** * Switches the active chat participant. * * @param {any} participant Chat participant object */ $scope.switchParticipant = function (participant) { // Change active participant $scope.activeThread = participant; // Reset chat window fields $scope.resetChatWindow(); // Get fresh messages $scope.getMessages(); if (detectmob()) { // Initialize add admin modal $scope.adminModal = $ionicModal.fromTemplateUrl($rootScope.themebasepathvalue + 'eCommerce/chat-fullview.html', { scope: $scope, animation: 'slide-in-up', }).then(function (modal) { $scope.adminModal = modal; $scope.adminModal.show(); }); //Model Close $scope.closeorderConfig = function () { $scope.adminModal.hide(); } } } /** * Scrolls to last chat item in the message thread. */ $scope.scrollToLastThread = function () { setTimeout(function() { var elem = document.querySelector("#chat-window .chat-window .thread"); if (elem) { elem = elem.children; var lastElem = elem[elem.length - 1]; if (lastElem) { lastElem.scrollIntoView(); } } }, 500); } /** * Resets chat window fields. */ $scope.resetChatWindow = function () { $scope.msg = ''; $scope.attachments = []; } /* --------------- NOTHING BEYOND --------------- */ $scope.init(); }]);