5 .controller('lightningController', lightningController);
7 function lightningController($scope, $window, $interval, $location, angularLoad, $http) {
10 var agentCallbacks = {};
11 var callsCallbacks = {};
16 vm.phone = ''; // used inside DOM
17 vm.inCall = false; // used inside DOM
19 var _task = {}; // global
28 //********************************************* */
29 var scriptTag = angular.element(document.createElement('base'));
30 scriptTag.href = window.location.pathname;
32 //*****************************************//
34 //********************************************* */
37 .loadScript(window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/')) + '/js/salesforce/lightning.js') //
39 console.log('Salesforce Lightning');
40 sforce.opencti.getCallCenterSettings({
41 callback: getCallCenterSettingsCallback
43 sforce.opencti.enableClickToDial({
44 callback: enableClickToDialCallback
46 }).catch(function (err) {
50 function enableClickToDialCallback(response) {
51 console.log('enableClickToDialCallback', response);
52 if (response.success) {
53 sforce.opencti.onClickToDial({
54 listener: onClickToDialListener_lightning
57 console.error('Something went wrong! Errors:', response.errors);
61 //*****************************************//
62 // getCallCenterSettingsCallback
63 //*****************************************//
64 function getCallCenterSettingsCallback(response) {
66 if (response.success) {
68 vm.host = response.returnValue['/Motion/Host'];
69 //_xml.host = _parsedXml['/Motion/Host'];
71 _xml.createTask = response.returnValue['/ManageTask/createTask'];
72 _xml.createTask = _xml.createTask ? _xml.createTask : 'false';
74 _xml.createOnAnswer = response.returnValue['/ManageTask/createOnAnswer'];
75 _xml.createOnAnswer = _xml.createOnAnswer ? _xml.createOnAnswer : 'false';
77 _xml.updateOnHangup = response.returnValue['/ManageTask/updateOnHangup'];
78 _xml.updateOnHangup = _xml.updateOnHangup ? _xml.updateOnHangup : 'false';
80 _xml.refreshOnHangup = response.returnValue['/ManageTask/refreshOnHangup'];
81 _xml.refreshOnHangup = _xml.refreshOnHangup ? _xml.refreshOnHangup : 'false';
83 _xml.defaultCreateStatus = response.returnValue['/ManageTask/defaultCreateStatus'];
84 _xml.defaultCreateStatus = _xml.defaultCreateStatus ? _xml.defaultCreateStatus : 'In Progress';
86 _xml.defaultUpdateStatus = response.returnValue['/ManageTask/defaultUpdateStatus'];
87 _xml.defaultUpdateStatus = _xml.defaultUpdateStatus ? _xml.defaultUpdateStatus : 'Completed';
89 _xml.uniqueid = response.returnValue['/FieldMapping/uniqueid'];
90 _xml.uniqueid = _xml.uniqueid ? _xml.uniqueid : null;
91 _xml.agent = response.returnValue['/FieldMapping/agent'];
92 _xml.agent = _xml.agent ? _xml.agent : null;
93 _xml.callerid = response.returnValue['/FieldMapping/callerid'];
94 _xml.callerid = _xml.callerid ? _xml.callerid : null;
95 _xml.date = response.returnValue['/FieldMapping/date'];
96 _xml.date = _xml.date ? _xml.date : null;
97 _xml.time = response.returnValue['/FieldMapping/time'];
98 _xml.time = _xml.time ? _xml.time : null;
99 _xml.starttime = response.returnValue['/FieldMapping/starttime'];
100 _xml.starttime = _xml.starttime ? _xml.starttime : null;
101 _xml.endtime = response.returnValue['/FieldMapping/endtime'];
102 _xml.endtime = _xml.endtime ? _xml.endtime : null;
103 _xml.answertime = response.returnValue['/FieldMapping/answertime'];
104 _xml.answertime = _xml.answertime ? _xml.answertime : null;
105 _xml.holdtime = response.returnValue['/FieldMapping/holdtime'];
106 _xml.holdtime = _xml.holdtime ? _xml.holdtime : null;
107 _xml.duration = response.returnValue['/FieldMapping/duration'];
108 _xml.duration = _xml.duration ? _xml.duration : null;
109 _xml.billsec = response.returnValue['/FieldMapping/billsec'];
110 _xml.billsec = _xml.billsec ? _xml.billsec : null;
113 console.error('Something went wrong! Errors:', response.errors);
117 //*****************************************//
118 // onClickToDialListener LIGHTNING
119 //*****************************************//
120 function onClickToDialListener_lightning(data) {
123 if (vm.online && data.number) {
124 vm.phone = data.number;
126 _task.endUserPhone = angular.copy(data.number);
127 // _task.endUserPhone is now indipendent from both vm.phone & data.phone
128 _task.endUserObjectType = data.objectType;
129 _task.endUserId = data.recordId;
130 _task.endUserName = data.recordName;
133 dialCount++; // impedisce di creare eventi dial() dopo il primo click
138 //*****************************************//
140 //*****************************************//
142 function display(task) {
143 sforce.opencti.screenPop({
144 type: sforce.opencti.SCREENPOP_TYPE.SOBJECT, //Review the arguments section.
146 recordId: task.recordId
151 //****************************************************** */
153 //****************************************************** */
154 function compose(value) {
155 vm.phone = vm.phone.concat(value);
158 //****************************************************** */
160 //****************************************************** */
162 vm.phone = vm.phone.substring(0, vm.phone.length - 1);
165 //****************************************************** */
167 //****************************************************** */
168 function keepalive() {
170 var uniqueid = Date.now();
172 $http.get('http://localhost:9888/api/agent')
173 .then(agentCallbacks[uniqueid] = function (result) {
174 if (result && result.status >= 200 && result.status < 300) {
175 var message = result.data;
177 vm.name = message.name;
178 vm.fullname = message.fullname;
179 vm.internal = String(message.internal);
182 //****************************************************** */
184 if (vm.host && vm.id) {
185 socket = io(vm.host, {
190 transports: ['websocket', 'polling']
193 // NOTE: RIVEDERE CON ANDREA
194 socket.on('trigger:salesforce:display', display);
196 //****************************************************** */
197 // connessione socket OUTBOUND CHANNEL
199 // socket.on to launch saveLog()
201 socket.on('voice_outbound_channel:save', function (evt) {
203 if (evt.destexten && evt.destexten === String(_task.endUserPhone) &&
204 !evt.dialstatus) { // simple ring
205 if (_xml.createTask === 'true' && _xml.createOnAnswer === 'false') { // creazione task
211 if (evt.destexten && evt.destexten === String(_task.endUserPhone) &&
212 evt.dialstatus && evt.dialstatus === 'ANSWER') { // on answer
213 if (_xml.createTask === 'true' && _xml.createOnAnswer === 'true') { // creazione task
219 // socket.on to launch updateLog()
221 socket.on('voice_outbound_channel:remove', function (evt) {
225 if (evt.destexten && evt.destexten === String(_task.endUserPhone)) {
226 // attende evento hangup prima di farlo
227 // controlla che riguardi la nostra telefonata
228 if (_xml.createTask === 'true' && _xml.updateOnHangup === 'true') { //
229 // esegue solo se updateOnHungup = true
232 // si incarica di resettare _task = {}
239 //****************************************************** */
240 if (socket && socket.disconnected) {
247 .catch(function(err){
252 //****************************************************** */
253 // getCalls (checking status)
254 //****************************************************** */
256 function getCalls() {
257 var uniqueid = Date.now();
259 $http.get('http://localhost:9888/api/calls')
261 callsCallbacks[uniqueid] = function (result) {
262 if (result && result.status >= 200 && result.status < 300) {
263 var message = result.data;
264 if (_.isArray(message) && _.find(message, {
267 //******************************** */
268 // activeDuration exists
269 vm.timer = parseTime(message[0].callingNumber, message[0].activeDuration);
270 //******************************** */
273 // activeDuration undefined
283 .catch(function(err){
288 function parseTime(cl_n, aD) {
289 var parsedTime = cl_n + ' ACTIVE (';
290 parsedTime += aD.hours < 10 ? '0' : '';
291 parsedTime += aD.hours;
293 parsedTime += aD.minutes < 10 ? '0' : '';
294 parsedTime += aD.minutes;
296 parsedTime += aD.seconds < 10 ? '0' : '';
297 parsedTime += aD.seconds;
303 //******************************** */
305 //******************************** */
308 //var uniqueid = Date.now();
310 $http.get('http://localhost:9888/api/originate/' + vm.phone);
312 $http.get('http://localhost:9888/api/answer');
314 getUser_Apex(); // logged user UserId
317 function getUser_Apex() {
320 apexClass: 'UserInfo',
321 methodName: 'getUserId',
322 callback: getUser_ApexCallback
324 sforce.opencti.runApex(objectParams);
327 function getUser_ApexCallback(response) {
329 if (response.success) {
330 _task.userId = String(response.returnValue.runApex);
331 //saveLog(); // ora gestito da evento socket.on in keepalive
333 console.error('Something went wrong! Errors:', response.errors);
337 //******************************** */
339 //******************************** */
341 function saveLog(evt) {
343 _task.activityDate = moment().utc(); //
345 // 00Q means a lead.. adding this to support logging on leads as well as contacts.
347 var endUserIdSubstr = _task.endUserId.substr(0, 3);
348 var description = '';
349 description += '*** Call Info ***\n';
350 description += 'Called Number: ' + _task.endUserPhone + '\n';
351 description += 'Member Name: ' + evt.membername + '\n';
352 description += 'UniqueId: ' + evt.uniqueid + '\n';
353 description += 'Date: ' + evt.starttime + '\n'; // creato alla chiamata
354 // if(evt.evt.answertime) {
355 // description += 'Date: ' + evt.answertime + '\n'; // creato alla risposta
357 description += '*** Time Info ***\n';
358 if (evt.answertime) {
359 description += 'Answer Time: ' + evt.answertime + '\n'; // creato alla risposta
361 var obj_saveLog = { //
362 //entityApiName: 'Task', //Optional, on CREATE
363 //Id: string, //Optional, on UPDATE
364 OwnerId: _task.userId, // different from ProfileId [ERROR: invalid field input type]
365 //WhoId: _task.endUserId,
366 ActivityDate: _task.activityDate, //
367 IsReminderSet: false,
369 Subject: 'Outbound Call [xCALLY Ticket] ' + _task.endUserPhone,
370 Description: description,
373 //Status: 'In Progress' // or Status: 'Not Started'
374 Status: _xml.defaultCreateStatus
377 obj_saveLog.entityApiName = 'Task'; // CREATE
378 if (endUserIdSubstr === '003' || endUserIdSubstr === '00Q') {
379 obj_saveLog.WhoId = _task.endUserId;
381 obj_saveLog.WhatId = _task.endUserId;
384 if (_xml.uniqueid && evt.uniqueid) {
385 obj_saveLog[_xml.uniqueid] = String(evt.uniqueid);
387 // if (_xml.agent && evt.membername) {
388 // obj_saveLog[_xml.agent] = evt.membername;
390 if (_xml.agent && vm.fullname) {
391 obj_saveLog[_xml.agent] = vm.fullname;
393 if (_xml.callerid && evt.calleridnum) {
394 obj_saveLog[_xml.callerid] = evt.calleridnum;
396 if (_xml.date && evt.starttime) {
397 var date = String(evt.starttime).split(' ')[0];
398 obj_saveLog[_xml.date] = date;
400 if (_xml.time && evt.starttime) {
401 var time = String(evt.starttime).split(' ')[1];
402 obj_saveLog[_xml.time] = time;
404 if (_xml.starttime && evt.starttime) {
405 obj_saveLog[_xml.starttime] = evt.starttime;
407 if (_xml.answertime && evt.answertime) {
408 obj_saveLog[_xml.answertime] = evt.answertime;
411 sforce.opencti.saveLog({
412 value: JSON.parse(JSON.stringify(obj_saveLog)),
413 callback: saveLogCallback //Optional
418 function saveLogCallback(response) {
420 if (response.success) { // boolean
421 _task.Id = response.returnValue.recordId; //
422 dialCount = 0; // reset click count to 0 (new dial possible)
427 console.error('Something went wrong! Errors:', response.errors);
431 function saveScreenPop() {
432 sforce.opencti.screenPop({
433 type: sforce.opencti.SCREENPOP_TYPE.SOBJECT, //Review the arguments section.
436 }, //Depends on the SCREENPOP_TYPE. Review the arguments section.
437 callback: screenPopCallback
442 function screenPopCallback(response) {
443 if (response.success) {
444 console.log('API screenPop executed successfully!');
446 console.error('Something went wrong! Errors:', response.errors);
450 //***************************************** */
452 //***************************************** */
456 $http.get('http://localhost:9888/api/hangup');
458 // hangup comunicato alla phonebar
459 // phonebar comunica a asterisk* che invia evt relativo all'hangup
460 // intercettiamo hangup via socket - verifichiamo il numero della chiamata
463 //***************************************** */
465 //***************************************** */
467 // keepalive lancia la funzione updateLog
469 function updateLog(evt) {
470 _task.activityDate = moment().utc(); //
471 var description = '';
472 description += '*** Call Info ***\n';
473 description += 'Called Number: ' + _task.endUserPhone + '\n';
474 description += 'Member Name: ' + evt.membername + '\n';
475 description += 'UniqueId: ' + evt.uniqueid + '\n';
476 description += 'Date: ' + evt.endtime + '\n'; // creato alla chiusura
477 description += '*** Time Info ***\n';
478 if (evt.answertime) {
479 description += 'Answer Time: ' + evt.answertime + '\n';
482 description += 'End Time: ' + evt.endtime + '\n';
485 description += 'Hold Time: ' + evt.holdtime + '\n';
488 description += 'Duration: ' + evt.duration + '\n';
490 if (evt.billableseconds) {
491 description += 'Billable Seconds: ' + evt.billableseconds + '\n';
493 //var endUserIdSubstr = _task.endUserId.substr(0, 3);
494 var obj_updateLog = { //
495 Id: _task.Id, // on UPDATE
496 ActivityDate: _task.activityDate, // update
497 Status: _xml.defaultUpdateStatus,
498 Description: description
501 // if(_xml.uniqueid && evt.uniqueid) {
502 // obj_updateLog[_xml.uniqueid] = String(evt.uniqueid);
504 // if(_xml.agent && evt.membername) {
505 // obj_updateLog[_xml.agent] = evt.membername;
507 // if (_xml.agent && vm.fullname) {
508 // obj_updateLog[_xml.agent] = vm.fullname;
510 // if(_xml.callerid && evt.calleridnum) {
511 // obj_updateLog[_xml.callerid] = evt.calleridnum;
513 if (_xml.date && evt.endtime) {
514 var date = String(evt.endtime).split(' ')[0];
515 console.log("TCL: updateLog -> date", date);
516 obj_updateLog[_xml.date] = date;
518 if (_xml.time && evt.endtime) {
519 var time = String(evt.endtime).split(' ')[1];
520 console.log("TCL: updateLog -> time", time);
521 obj_updateLog[_xml.time] = time;
523 // if(_xml.starttime && evt.starttime) {
524 // obj_updateLog[_xml.starttime] = evt.starttime;
526 if (_xml.endtime && evt.endtime) {
527 obj_updateLog[_xml.endtime] = evt.endtime;
529 if (_xml.answertime && evt.answertime) {
530 obj_updateLog[_xml.answertime] = evt.answertime;
532 if (_xml.holdtime && evt.holdtime) {
533 obj_updateLog[_xml.holdtime] = String(evt.holdtime);
535 if (_xml.duration && evt.duration) {
536 obj_updateLog[_xml.duration] = String(evt.duration);
538 if (_xml.billsec && evt.billableseconds) {
539 obj_updateLog[_xml.billsec] = String(evt.billableseconds);
542 console.log(obj_updateLog);
543 sforce.opencti.saveLog({
544 value: JSON.parse(JSON.stringify(obj_updateLog)),
545 callback: updateLogCallback //Optional
551 //***************************************** */
553 function updateLogCallback(response) {
555 if (_xml.createTask === 'true' && _xml.updateOnHangup === 'true' && _xml.refreshOnHangup === 'true') { //
557 if (response.success) {
559 sforce.opencti.refreshView({
560 callback: refreshViewCallback
563 console.error('Something went wrong! Errors:', response.errors);
570 function refreshViewCallback(response) {
571 console.log('API refreshView classic executed successfully! returnValue:', response);
573 if (response.success) { // boolean
574 console.log('API refreshView lightning executed successfully!');
576 console.error('Something went wrong! Errors:', response.errors);
581 //***************************************** */
583 //***************************************** */
585 function receiveMessage(message) {
586 var data = message.data;
588 if (agentCallbacks[data.uniqueid]) {
589 agentCallbacks[data.uniqueid](data);
590 delete agentCallbacks[data.uniqueid];
591 } else if (callsCallbacks[data.uniqueid]) {
592 callsCallbacks[data.uniqueid](data);
593 delete callsCallbacks[data.uniqueid];
599 $interval(keepalive, 2000);
600 $interval(getCalls, 1000);
602 $window.addEventListener('message', receiveMessage, false);