Built xcally-motion-dialpad from commit 141221b.|1.0.96
[dialpad.git] / js / controllers / classic.controller.js
diff --git a/js/controllers/classic.controller.js b/js/controllers/classic.controller.js
new file mode 100644 (file)
index 0000000..d9af647
--- /dev/null
@@ -0,0 +1,575 @@
+'use strict';
+
+angular
+    .module('motion')
+    .controller('classicController', classicController);
+
+function classicController($scope, $window, $interval, $location, angularLoad, $http) {
+
+    var vm = this;
+
+    // Integration
+    var agentCallbacks = {};
+    var callsCallbacks = {};
+
+    // Socket object
+    var socket = null;
+
+    // Data
+    vm.timer = '';
+    vm.phone = '';
+    vm.inCall = false;
+
+    // task
+    var _task = {}; // global 
+    var _xml = {};
+
+    // Methods
+    vm.compose = compose;
+    vm.remove = remove;
+    vm.hangup = hangup;
+    vm.dial = dial;
+
+    var dialCount = 0;
+
+    //********************************************* */
+
+    var scriptTag = angular.element(document.createElement('base'));
+    scriptTag.href = window.location.pathname;
+
+    //*****************************************//
+    // LOADING
+    //********************************************* */
+
+    angularLoad
+        .loadScript(window.location.pathname.substring(0,window.location.pathname.lastIndexOf('/'))  + '/js/salesforce/interaction.js') //
+        //.loadScript(window.location.origin  + '/js/salesforce/interaction.js') //
+        .then(function () {
+
+            console.log('Salesforce Classic');
+            sforce.interaction.cti.getCallCenterSettings(getCallCenterSettingsCallback);
+            sforce.interaction.cti.enableClickToDial(enableClickToDialCallback);
+
+        }).catch(function (err) {
+            console.error(err);
+        });
+
+    function enableClickToDialCallback(response) {
+        if (response.result) { // boolean
+            sforce.interaction.cti.onClickToDial(onClickToDialListener);
+        } else {
+            console.error('Something went wrong! Errors:', response.errors);
+        }
+    }
+
+    //*****************************************//
+    // getCallCenterSettingsCallback
+    //*****************************************//
+    function getCallCenterSettingsCallback(response) {
+
+        var _parsedXml = {};
+
+        if (response.result) {
+
+            _parsedXml = JSON.parse(response.result);
+            vm.host = _parsedXml['/Motion/Host'];
+            //_xml.host = _parsedXml['/Motion/Host'];
+
+            _xml.createTask = _parsedXml['/ManageTask/createTask'];
+            _xml.createTask = _xml.createTask ? _xml.createTask : 'false';
+
+            _xml.createOnAnswer = _parsedXml['/ManageTask/createOnAnswer'];
+            _xml.createOnAnswer = _xml.createOnAnswer ? _xml.createOnAnswer : 'false';
+
+            _xml.updateOnHangup = _parsedXml['/ManageTask/updateOnHangup'];
+            _xml.updateOnHangup = _xml.updateOnHangup ? _xml.updateOnHangup : 'false';
+
+            _xml.refreshOnHangup = _parsedXml['/ManageTask/refreshOnHangup'];
+            _xml.refreshOnHangup = _xml.refreshOnHangup ? _xml.refreshOnHangup : 'false';
+
+            _xml.defaultCreateStatus = _parsedXml['/ManageTask/defaultCreateStatus'];
+            _xml.defaultCreateStatus = _xml.defaultCreateStatus ? _xml.defaultCreateStatus : 'In Progress';
+
+            _xml.defaultUpdateStatus = _parsedXml['/ManageTask/defaultUpdateStatus'];
+            _xml.defaultUpdateStatus = _xml.defaultUpdateStatus ? _xml.defaultUpdateStatus : 'Completed';
+
+            _xml.uniqueid = _parsedXml['/FieldMapping/uniqueid'];
+            _xml.uniqueid = _xml.uniqueid ? _xml.uniqueid : null;
+            _xml.agent = _parsedXml['/FieldMapping/agent'];
+            _xml.agent = _xml.agent ? _xml.agent : null;
+            _xml.callerid = _parsedXml['/FieldMapping/callerid'];
+            _xml.callerid = _xml.callerid ? _xml.callerid : null;
+            _xml.date = _parsedXml['/FieldMapping/date'];
+            _xml.date = _xml.date ? _xml.date : null;
+            _xml.time = _parsedXml['/FieldMapping/time'];
+            _xml.time = _xml.time ? _xml.time : null;
+            _xml.starttime = _parsedXml['/FieldMapping/starttime'];
+            _xml.starttime = _xml.starttime ? _xml.starttime : null;
+            _xml.endtime = _parsedXml['/FieldMapping/endtime'];
+            _xml.endtime = _xml.endtime ? _xml.endtime : null;
+            _xml.answertime = _parsedXml['/FieldMapping/answertime'];
+            _xml.answertime = _xml.answertime ? _xml.answertime : null;
+            _xml.holdtime = _parsedXml['/FieldMapping/holdtime'];
+            _xml.holdtime = _xml.holdtime ? _xml.holdtime : null;
+            _xml.duration = _parsedXml['/FieldMapping/duration'];
+            _xml.duration = _xml.duration ? _xml.duration : null;
+            _xml.billsec = _parsedXml['/FieldMapping/billsec'];
+            _xml.billsec = _xml.billsec ? _xml.billsec : null;
+
+        } else {
+            console.error('Something went wrong! Errors:', response.errors);
+        }
+    }
+
+    //*****************************************//
+    // onClickToDialListener
+    //*****************************************//
+    function onClickToDialListener(response) {
+
+        var result = JSON.parse(response.result);
+
+        if (dialCount < 1) {
+
+            if (vm.online && result.number) {
+
+                vm.phone = result.number;
+
+                _task.endUserPhone = angular.copy(result.number);
+                _task.endUserObjectType = result.object;
+                _task.endUserId = result.objectId;
+                _task.endUserName = result.objectName;
+
+                vm.dial();
+
+                dialCount++;
+            }
+        }
+    }
+
+    //*****************************************//
+    // display
+    //*****************************************//
+
+    function display(task) {
+        console.log('Display', task);
+        sforce.interaction.screenPop(task.recordId, true, screenPopCallback);
+    }
+
+    //****************************************************** */
+    // compose
+    //****************************************************** */
+    function compose(value) {
+        vm.phone = vm.phone.concat(value);
+    }
+
+    //****************************************************** */
+    // remove
+    //****************************************************** */
+    function remove() {
+        vm.phone = vm.phone.substring(0, vm.phone.length - 1);
+    }
+
+     //****************************************************** */
+    //  KEEPALIVE
+    //****************************************************** */
+    function keepalive() {
+
+        var uniqueid = Date.now();
+
+        $http.get('http://localhost:9888/api/agent')
+            .then(agentCallbacks[uniqueid] = function (result) {
+                if (result && result.status >= 200 && result.status < 300) {
+                    var message = result.data;
+                    vm.id = message.id;
+                    vm.name = message.name;
+                    vm.fullname = message.fullname;
+                    vm.internal = String(message.internal);
+                    vm.online = true;
+
+                    //****************************************************** */
+                    if (!socket) {
+                        if (vm.host && vm.id) {
+                            socket = io(vm.host, {
+                                query: {
+                                    id: vm.id
+                                },
+                                autoConnect: false,
+                                transports: ['websocket', 'polling']
+                            });
+
+                            // NOTE: RIVEDERE CON ANDREA
+                            socket.on('trigger:salesforce:display', display);
+
+                            //****************************************************** */
+                            // connessione socket OUTBOUND CHANNEL
+
+                            // socket.on to launch saveLog()
+
+                            socket.on('voice_outbound_channel:save', function (evt) {
+                                // evento
+                                if (evt.destexten && evt.destexten === String(_task.endUserPhone) &&
+                                    !evt.dialstatus) { // simple ring
+                                    if (_xml.createTask === 'true' && _xml.createOnAnswer === 'false') { // creazione task
+                                        saveLog(evt);
+                                    }
+                                }
+
+                                // evento
+                                if (evt.destexten && evt.destexten === String(_task.endUserPhone) &&
+                                    evt.dialstatus && evt.dialstatus === 'ANSWER') { // on answer
+                                    if (_xml.createTask === 'true' && _xml.createOnAnswer === 'true') { // creazione task
+                                        saveLog(evt);
+                                    }
+                                }
+                            });
+
+                            // socket.on to launch updateLog()
+
+                            socket.on('voice_outbound_channel:remove', function (evt) {
+
+                                vm.phone = '';
+
+                                if (evt.destexten && evt.destexten === String(_task.endUserPhone)) {
+                                    if (_xml.createTask === 'true' && _xml.updateOnHangup === 'true') { // 
+                                        updateLog(evt);
+                                    } else {
+                                        _task = {};
+                                    }
+                                }
+                            });
+                        }
+                    }
+                    //****************************************************** */
+                    if (socket && socket.disconnected) {
+                        socket.connect();
+                    }
+                } else {
+                    vm.online = false;
+                }
+            })
+            .catch(function(err){
+                console.error(err);
+            });
+    }
+
+//****************************************************** */
+    //  getCalls (checking status)
+    //****************************************************** */
+
+    function getCalls() {
+        var uniqueid = Date.now();
+
+        $http.get('http://localhost:9888/api/calls')
+        .then(
+            callsCallbacks[uniqueid] = function (result) {
+                if (result && result.status >= 200 && result.status < 300) {
+                    var message = result.data;
+                    if (_.isArray(message) && _.find(message, {
+                            stateId: 8
+                        })) {
+                        //******************************** */
+                        // activeDuration exists
+                        vm.timer = parseTime(message[0].callingNumber, message[0].activeDuration);
+                        //******************************** */
+                        vm.inCall = true;
+                    } else {
+                        // activeDuration undefined
+                        vm.inCall = false;
+                        vm.timer = '';
+                    }
+                } else {
+                    vm.inCall = false;
+                    vm.timer = '';
+                }
+            }
+
+        )
+        .catch(function(err){
+            console.error(err);
+        });
+
+        //postExtMessage('http://localhost:9888/api/calls', uniqueid);
+    }
+
+    function parseTime(cl_n, aD) {
+        var parsedTime = cl_n + ' ACTIVE  (';
+        parsedTime += aD.hours < 10 ? '0' : '';
+        parsedTime += aD.hours;
+        parsedTime += ':';
+        parsedTime += aD.minutes < 10 ? '0' : '';
+        parsedTime += aD.minutes;
+        parsedTime += ':';
+        parsedTime += aD.seconds < 10 ? '0' : '';
+        parsedTime += aD.seconds;
+        parsedTime += ')';
+
+        return parsedTime;
+    }
+
+    //******************************** */
+    //  DIAL
+    //******************************** */
+    function dial() {
+        $http.get('http://localhost:9888/api/originate/' + vm.phone);
+        $http.get('http://localhost:9888/api/answer');
+        getUser_Apex(); // logged user UserId
+    }
+
+    function getUser_Apex() {
+        sforce.interaction.runApex('UserInfo', 'getUserId', null, getUser_ApexCallback);
+    }
+
+    function getUser_ApexCallback(response) {
+        if (response.result) {
+            _task.userId = String(response.result);
+            //saveLog(); // ora gestito da evento socket.on in keepalive
+        } else {
+            console.error('Something went wrong! Errors:', response.errors);
+        }
+    }
+
+    //******************************** */
+    //  SAVELOG
+    //******************************** */
+
+    function saveLog(evt) {
+
+        _task.activityDate = moment().utc(); //
+
+        // 00Q means a lead.. adding this to support logging on leads as well as contacts.
+
+        var endUserIdSubstr = _task.endUserId.substr(0, 3);
+        var description = '';
+        description += '*** Call Info ***\n';
+        description += 'Called Number: ' + _task.endUserPhone + '\n';
+        description += 'Member Name: ' + evt.membername + '\n';
+        description += 'UniqueId: ' + evt.uniqueid + '\n';
+        description += 'Date: ' + evt.starttime + '\n'; // creato alla chiamata
+        // if(evt.evt.answertime) {
+        //   description += 'Date: ' + evt.answertime + '\n'; // creato alla risposta
+        // }
+        description += '*** Time Info ***\n';
+        if (evt.answertime) {
+            description += 'Answer Time: ' + evt.answertime + '\n'; // creato alla risposta
+        }
+
+        var saveParams = 'Subject=' + 'Outbound Call [xCALLY Ticket] '  + _task.endUserPhone;
+        saveParams += '&Activitydate=' + _task.activityDate;
+        saveParams += '&Phone=' + _task.endUserPhone;
+        saveParams += '&Description=' + description;
+        saveParams += '&OwnerId=' + _task.userId; // different from ProfileId [ERROR: invalid field input type]
+        if (endUserIdSubstr === '003' || endUserIdSubstr === '00Q') {
+            saveParams += '&whoId=' + _task.endUserId;
+        } else {
+            saveParams += '&whatId=' + _task.endUserId;
+        }
+        saveParams += '&Priority=Normal';
+        //saveParams += '&Status=In Progress'; // or '&Status=Not Started';
+        saveParams += '&Status=' + _xml.defaultCreateStatus; // or '&Status=Not Started';
+        saveParams += '&Type=Call';
+        //saveParams += '&CallType=' + SP.calltype;  //should change this to reflect actual inbound or outbound
+        //
+
+        if (_xml.uniqueid && evt.uniqueid) {
+            saveParams += '&' + _xml.uniqueid + '=' + String(evt.uniqueid);
+        }
+        //   if(_xml.agent && evt.membername) {
+        //     saveParams += '&' + _xml.agent + '=' + evt.membername;
+        //   }
+        if (_xml.agent && vm.fullname) {
+            saveParams += '&' + _xml.agent + '=' + vm.fullname;
+        }
+        if (_xml.callerid && evt.calleridnum) {
+            saveParams += '&' + _xml.callerid + '=' + evt.calleridnum;
+        }
+        if (_xml.date && evt.starttime) {
+            var _date = String(evt.starttime).split(' ')[0];
+            saveParams += '&' + _xml.date + '=' + _date;
+        }
+        if (_xml.time && evt.starttime) {
+            var _time = String(evt.starttime).split(' ')[1];
+            saveParams += '&' + _xml.time + '=' + _time;
+        }
+        if (_xml.starttime && evt.starttime) {
+            saveParams += '&' + _xml.starttime + '=' + evt.starttime;
+        }
+        if (_xml.answertime && evt.answertime) {
+            saveParams += '&' + _xml.answertime + '=' + evt.answertime;
+        }
+
+        sforce.interaction.saveLog('Task', encodeURI(saveParams), saveLogCallback);
+
+        description = '';
+    }
+
+    function saveLogCallback(response) {
+
+        if (response.result) { // boolean
+            _task.Id = response.result; // differente dalla documentazione
+            dialCount = 0; // reset click count to 0 (new dial possible)
+            
+            //sforce.interaction.cti.enableClickToDial(enableClickToDialCallback);
+            
+            saveScreenPop();
+        } else {
+            console.error('Something went wrong! Errors:', response.errors);
+        }
+    }
+
+    function saveScreenPop() {
+        sforce.interaction.screenPop('/' + _task.Id, true, screenPopCallback);
+    }
+
+    function screenPopCallback(response) {
+        if (response.result) { // boolean
+            console.log('API screenPop executed successfully!');
+        } else {
+            console.error('Something went wrong! Errors:', response.errors);
+        }
+    }
+
+    //***************************************** */
+    // HANGUP
+    //***************************************** */
+
+    function hangup() {
+
+        vm.phone = '';
+        $http.get('http://localhost:9888/api/hangup');
+
+        // hangup comunicato alla phonebar
+        // phonebar comunica a asterisk* che invia evt relativo all'hangup
+        // intercettiamo hangup via socket - verifichiamo il numero della chiamata
+    }
+
+    //***************************************** */
+    // UPDATELOG
+    //***************************************** */
+
+    // keepalive lancia la funzione updateLog
+
+    function updateLog(evt) {
+
+        _task.activityDate = moment().utc(); // 
+
+        var description = '';
+        description += '*** Call Info ***\n';
+        description += 'Called Number: ' + _task.endUserPhone + '\n';
+        description += 'Member Name: ' + evt.membername + '\n';
+        description += 'UniqueId: ' + evt.uniqueid + '\n';
+        description += 'Date: ' + evt.endtime + '\n'; // creato alla chiusura
+        description += '*** Time Info ***\n';
+        if (evt.answertime) {
+            description += 'Answer Time: ' + evt.answertime + '\n';
+        }
+        description += 'End Time: ' + evt.endtime + '\n';
+        if (evt.holdtime) {
+            description += 'Hold Time: ' + evt.holdtime + '\n';
+        }
+        description += 'Duration: ' + evt.duration + '\n';
+        if (evt.billableseconds) {
+            description += 'Billable Seconds: ' + evt.billableseconds + '\n';
+        }
+
+        var updateParams = 'Id=' + _task.Id; // on UPDATE
+        updateParams += '&Activitydate=' + _task.activityDate;
+        //updateParams += '&Status=Completed'; // '&Status=In Progress';
+        updateParams += '&Status=' + _xml.defaultUpdateStatus;
+        updateParams += '&Description=' + description;
+        //
+        // if(_xml.uniqueid && evt.uniqueid) {
+        //   updateParams += '&' + _xml.uniqueid + '=' + String(evt.uniqueid);
+        // }
+        // if(_xml.agent && evt.membername) {
+        //   updateParams += '&' + _xml.agent + '=' + evt.membername;
+        // }
+        // if(_xml.agent && vm.fullname) {
+        //   updateParams += '&' + _xml.agent + '=' + vm.fullname;
+        // }
+        // if(_xml.callerid && evt.calleridnum) {
+        //   updateParams += '&' + _xml.callerid + '=' + evt.calleridnum;
+        // }
+        if (_xml.date && evt.endtime) {
+            var _date = String(evt.endtime).split(' ')[0];
+            updateParams += '&' + _xml.date + '=' + _date;
+        }
+        if (_xml.time && evt.endtime) {
+            var _time = String(evt.endtime).split(' ')[1];
+            updateParams += '&' + _xml.time + '=' + _time;
+        }
+        // if(_xml.starttime && evt.starttime) {
+        //   updateParams += '&' + _xml.starttime + '=' +evt.starttime;
+        // }
+        if (_xml.endtime && evt.endtime) {
+            updateParams += '&' + _xml.endtime + '=' + evt.endtime;
+        }
+        if (_xml.answertime && evt.answertime) {
+            updateParams += '&' + _xml.answertime + '=' + evt.answertime;
+        }
+        if (_xml.holdtime && evt.holdtime) {
+            updateParams += '&' + _xml.holdtime + '=' + evt.holdtime;
+        }
+        if (_xml.duration && evt.duration) {
+            updateParams += '&' + _xml.duration + '=' + String(evt.duration);
+        }
+        if (_xml.billsec && evt.billableseconds) {
+            updateParams += '&' + _xml.billsec + '=' + String(evt.billableseconds);
+        }
+
+        sforce.interaction.saveLog('Task', encodeURI(updateParams), updateLogCallback); // 'Task' is mandatory also on update
+
+        description = '';
+
+    }
+
+    //***************************************** */
+
+    function updateLogCallback(response) {
+
+        if (_xml.createTask === 'true' && _xml.updateOnHangup === 'true' && _xml.refreshOnHangup === 'true') { // 
+
+            if (response.result) { // boolean
+                _task = {}; // reset _task object
+                sforce.interaction.refreshPage(refreshViewCallback); // it refreshes the current active tab
+
+            } else {
+                console.error('Something went wrong! Errors:', response.errors);
+            }
+        } else {
+            // nessun refresh
+            // resetta _task = {}
+            _task = {}; 
+        }
+    }
+
+    function refreshViewCallback(response) {
+        if (response.result) { // boolean
+            console.log('API refreshView classic executed successfully! returnValue:', response.result);
+        } else {
+            console.error('Something went wrong! Errors:', response.errors);
+        }
+    }
+
+    //***************************************** */
+    // receiveMessage
+    //***************************************** */
+    function receiveMessage(message) {
+        var data = message.data;
+
+        if (agentCallbacks[data.uniqueid]) {
+            agentCallbacks[data.uniqueid](data);
+            delete agentCallbacks[data.uniqueid];
+        } else if (callsCallbacks[data.uniqueid]) {
+            callsCallbacks[data.uniqueid](data);
+            delete callsCallbacks[data.uniqueid];
+        }
+
+        $scope.$apply();
+    }
+
+    $interval(keepalive, 2000);
+    $interval(getCalls, 1000);
+
+    $window.addEventListener('message', receiveMessage, false);
+
+}
\ No newline at end of file