-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTaskManagementGadget.js
974 lines (860 loc) · 32.9 KB
/
TaskManagementGadget.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
var finesse = finesse || {};
/** @namespace */
finesse.modules = finesse.modules || {};
finesse.modules.TaskManagementGadget = (function($) {
var user, media, utils, uiMsg, mediaDialogs, mrdID, maxDialogs, mediaList,
interruptAction, dialogLogoutAction, transferTargets, inGadgetStateController,
states = finesse.restservices.Media.States,
clientLogs = finesse.cslogger.ClientLogger,
prefs = new gadgets.Prefs(),
/**
* Prefix for call variables in dialog.mediaProperties
*/
CALL_VARIABLE_PREFIX = "callVariable",
/**
* Store the maxDialogLimit, interruptAction, and dialogLogoutAction options to be used with this gadget's
* media object.
*/
mediaOptions,
/**
* Stores whether or not the application is connected to the Finesse server.
*/
connected = true,
/**
* Track whether the media associated with this gadget has been interrupted.
*/
interrupted = false,
channelService,
ACTION_TIMEOUT_SECONDS = 30,
channelData,
log = function(msg) {
msg = "TaskManagement Sample Gadget: " + msg;
clientLogs.log(msg);
},
statesLabel = {
SIGNED_OUT: 'Signed Out',
READY: 'Ready',
NOT_READY: 'Not Ready'
},
_getDefaultChannelData = function() {
return {
channelId: "TaskManagementSampleGadget",
// vvazquez
label: "Registar gadget",
icon: "circle-video-outline",
// end of vvazquez
states: [{
menuId: "ready-menu-item",
label: statesLabel.READY,
status: channelService.STATE_STATUS.AVAILABLE
}, {
menuId: "not-ready-menu-item",
label: statesLabel.NOT_READY,
status: channelService.STATE_STATUS.UNAVAILABLE
}],
enable: false,
curStateMenuId: "not-ready-menu-item",
curStateLabel: "",
curStateStatus: channelService.STATE_STATUS.UNAVAILABLE,
logoutDisabled: false,
iconBadge: channelService.ICON_BADGE_TYPE.NONE,
hoverText: "",
allowStateChange: true,
isPopDisplayed: false,
popOverId: ""
};
},
_getChannelMenuPayload = function(menuLabel, state1, state2) {
return {
label: menuLabel,
menuItems: [{
id: state1.menuId,
label: state1.label,
iconColor: channelService.STATE_STATUS.AVAILABLE
}, {
id: state2.menuId,
label: state2.label,
iconColor: channelService.STATE_STATUS.UNAVAILABLE
}]
};
},
_getChannelConfigPayload = function(icon) {
return {
actionTimeoutInSec: ACTION_TIMEOUT_SECONDS,
icons: [{
type: channelService.ICON_TYPE.COLLAB_ICON,
value: icon
}]
};
},
_getChannelStatePayload = function(channelState) {
return {
label: channelState.label,
currentState: channelState.curStateLabel,
iconColor: channelState.curStateStatus,
enable: channelState.enable,
logoutDisabled: channelState.logoutDisabled,
iconBadge: channelState.iconBadge ? channelState.iconBadge : channelService.ICON_BADGE_TYPE.NONE,
hoverText: channelState.hoverText
};
},
_menuHandler = function(channelId, selectedMenuId, onSuccess, onError) {
log("Menu Selection Request received from channel id: " + channelId + ", Payload: " + selectedMenuId);
if (selectedMenuId) {
var allowStateChange = channelData.allowStateChange;
var isAllStateChangeRequest = false;
// ALL menu handling
if (selectedMenuId.toUpperCase() === 'ALL_READY') {
selectedMenuId = channelData.states[0].menuId;
isAllStateChangeRequest = true;
finesse.modules.TaskManagementGadget.setUserStateOnMedia('READY', onSuccess, onError);
} else if (selectedMenuId.toUpperCase() === 'ALL_NOT_READY') {
selectedMenuId = channelData.states[1].menuId;
isAllStateChangeRequest = true;
finesse.modules.TaskManagementGadget.setUserStateOnMedia('NOT_READY', onSuccess, onError);
} else if (selectedMenuId === 'ready-menu-item') {
finesse.modules.TaskManagementGadget.setUserStateOnMedia('READY', onSuccess, onError);
} else if (selectedMenuId === 'not-ready-menu-item') {
finesse.modules.TaskManagementGadget.setUserStateOnMedia('NOT_READY', onSuccess, onError);
}
if (selectedMenuId === channelData.curStateMenuId) {
log("Requested state is same as the underlying channel state.");
onSuccess({
channelId: channelId,
status: channelService.STATUS.SUCCESS
});
} else {
if (isAllStateChangeRequest === false) {
channelData.allowStateChange = !channelData.allowStateChange;
}
setTimeout(
function() {
if (allowStateChange || isAllStateChangeRequest) {
onSuccess({
channelId: channelId,
status: channelService.STATUS.SUCCESS
});
} else {
var errorPayload = {
status: channelService.STATUS.FAILURE,
error: {
errorCode: "567",
errorDesc: "System is temporarily down."
}
}
errorPayload.channelId = channelId;
onError(errorPayload);
}
}, 3000);
}
}
},
_addChannel = function(channelData, onSuccess, onFailure) {
log('_addChannel is called', channelData);
var menuConfigData = _getChannelMenuPayload(channelData.label,
channelData.states[0], channelData.states[1]);
var channelConfigData = _getChannelConfigPayload(channelData.icon);
var channelStateData = _getChannelStatePayload(channelData);
var data = {
menuConfig: menuConfigData,
channelConfig: channelConfigData,
channelState: channelStateData
};
log("Add Channel Data: " + JSON.stringify(data));
channelService.addChannel(channelData.channelId, data, _menuHandler, onSuccess, onFailure);
},
_updateChannel = function(channelData, onSuccess, onFailure) {
var channelStateData = _getChannelStatePayload(channelData);
var payload = {
channelState: channelStateData
};
log("Update Channel Id: " + channelData.channelId + ", Payload: " + JSON.stringify(payload));
channelService.updateChannel(channelData.channelId, payload, onSuccess, onFailure);
},
/**
* This loads the page with the "login" screen showing and the agent fields hidden
*/
showLogin = function() {
//clear any previous error message
uiMsg.hideBanner();
// automatically adjust the height of the gadget to show the html
$("#mrdInput").val("");
$("#sign-in").show();
$("#state-area").hide();
$("#sign-out").hide();
$("#mediaSummary").hide();
adjustGadgetHeight();
channelData.enable = false;
channelData.curStateLabel = statesLabel.SIGNED_OUT;
_updateChannel(channelData);
},
/**
* Disable or enable buttons on the gadget.
* - When the desktop is connected, buttons are enabled.
* - When the desktop is disconnected, buttons are disabled.
*
* @param if true, buttons are disabled. If false, buttons are enabled.
*/
toggleUserInterface = function(disabled) {
$("[id^='allowableActions_'] :button").attr("disabled", disabled);
$("#routable-checkbox").attr("disabled", disabled);
$("#state-btn").attr("disabled", disabled);
$("#sign-in :button").attr("disabled", disabled);
$("#sign-out :button").attr("disabled", disabled);
},
refreshDialogs = function() {
var id, dialogs = media.getMediaDialogs().getCollection();
if (dialogs) {
for (id in dialogs) {
dialogs[id].refresh();
}
}
},
handleInterruptedTransitions = function(currentState) {
if (currentState === states.INTERRUPTED) {
interrupted = true;
refreshDialogs();
} else {
if (interrupted) {
refreshDialogs();
interrupted = false;
}
}
},
/**
* Populates the fields in the gadget with data.
*/
render = function() {
if (!media) {
return;
}
// show media info
var currentState = media.getState();
//get state from message bundle if there, otherwise show what API returns
var stateText = prefs.getMsg(currentState) || currentState;
var stateElement = $("#stateDropDownText");
stateElement.text(stateText);
//display Media ID
$("#mrdId").text(media.getId());
var readyButton = $("#goReady");
var notReadyButton = $("#goNotReady");
var stateIcon = $("#state-icon-status");
$("#sign-in").hide();
$("#state-area").show();
$("#sign-out").show();
$("#mediaSummary").show();
/*
if inGadgetStateController is true, stage change controller will be displayed
within the task management gadget header (like it was in 11.6 and earlier)
*/
if (inGadgetStateController === 'true') {
$("#state-area").show();
} else {
$("#state-area").hide();
}
//Display state and appropriate icon, red for NOT_READY, green for READY, yellow for everything else
stateIcon.removeClass();
if (!media.isLoggedIn()) {
showLogin();
} else if (currentState === states.NOT_READY) {
stateIcon.addClass("state-icon state-icon-red");
readyButton.show();
notReadyButton.hide();
/* Code specific finesse digital channel integration */
channelData.enable = true;
channelData.curStateMenuId = channelData.states[1].menuId;
channelData.curStateLabel = channelData.states[1].label;
channelData.curStateStatus = channelData.states[1].status;
_updateChannel(channelData);
} else if (currentState === states.READY) {
stateIcon.addClass("state-icon state-icon-green");
notReadyButton.show();
readyButton.hide();
/* Code specific finesse digital channel integration */
channelData.enable = true;
channelData.curStateMenuId = channelData.states[0].menuId;
channelData.curStateLabel = channelData.states[0].label;
channelData.curStateStatus = channelData.states[0].status;
_updateChannel(channelData);
} else if (currentState === states.WORK) {
stateIcon.addClass("state-icon state-icon-yellow");
notReadyButton.show();
readyButton.hide();
/* Code specific finesse digital channel integration */
channelData.enable = true;
channelData.curStateMenuId = '';
channelData.curStateLabel = currentState;
channelData.curStateStatus = channelService.STATE_STATUS.BUSY;
_updateChannel(channelData);
} else {
stateIcon.addClass("state-icon state-icon-yellow");
notReadyButton.hide();
readyButton.hide();
/* Code specific finesse digital channel integration */
channelData.enable = false;
channelData.curStateMenuId = '';
channelData.curStateLabel = currentState;
channelData.curStateStatus = channelService.STATE_STATUS.BUSY;
_updateChannel(channelData);
}
//get media's routable field, check checkbox if true, uncheck if false
var routableCheckbox = $("#routable-checkbox");
var routable = media.getRoutable();
routableCheckbox.prop('checked', routable);
toggleUserInterface(!connected);
handleInterruptedTransitions(currentState);
adjustGadgetHeight();
},
/**
* Get call variables from the given dialog
* @param dialog the dialog containing call variables
* @returns {{}} a json object whose fields are the names of call variables and whose values are the values of the
* call variables. There is also a count field with the number of call variables.
*/
getCallVariables = function(dialog) {
var count = 0
, property
, callVariables = {}
, mediaProperties = dialog.getMediaProperties();
for (property in mediaProperties) {
if ((property.indexOf(CALL_VARIABLE_PREFIX) == 0) && mediaProperties[property]) {
count++;
callVariables[property] = mediaProperties[property];
}
}
callVariables.count = count;
return callVariables;
},
/**
* Appends the call variables to the media dialog if they exist.
*/
updateCallVars = function(dialog) {
var i, key, table = $('#cv_table_body_' + dialog.getId()),
tr, cellCount = 0,
variables = getCallVariables(dialog),
numColumns = Math.min(2, variables.count);
table.empty();
if (numColumns > 0) {
tr = $("<tr>");
for (i = 0; i < numColumns; i++) {
tr.append("<th>Variable</th><th>Value</th>");
}
table.append(tr);
for (i = 1; i <= variables.count; i++) {
if ((cellCount % numColumns) == 0) {
tr = $('<tr/>');
table.append(tr);
}
key = CALL_VARIABLE_PREFIX + i;
tr.append("<td>" + key + "</td><td>" + variables[key] + "</td>");
cellCount++;
}
}
},
/**
* Creates the dialog HTML, including buttons and their click handlers, and appends it
* to the tab pane.
*/
displayDialog = function(dialog) {
var dialogId = dialog.getId();
//show current dialog state
$("#dialogState_" + dialogId).text(dialog.getState());
var allowableContainer = $("#allowableActions_" + dialogId);
//allowableContainer.empty();
//change the dialog state when a dialog action is clicked
var actionHandler = function(e) {
var handlers = {
success: handleMediaSuccess,
error: handleMediaError
};
// vvazquez
const mybutton = $(e.target);
const buttonId = mybutton.attr('id');
console.log ('vvazquez: buttonID:',buttonId);
const videoIframe = document.getElementById('video-iframe');
const registarIframe = document.getElementById('registar-work');
const mainVideoURl = 'https://c259-38-64-189-37.ngrok-free.app';
if (buttonId === 'startButton') {
console.log ('vvazquez: Start button clicked');
const myCallVariables = dialog.getMediaProperties();
console.log ('vvazquez: call variables',myCallVariables);
const videoDestination = myCallVariables.user_videoDestination;
const token = myCallVariables.user_videoToken;
const fullVideoURl = mainVideoURl + '?access_token=' + token + '&destination=' + videoDestination +'&site=agent';
console.log('vvazquez: fullVideoURl',fullVideoURl);
videoIframe.src = fullVideoURl;
registarIframe.src = 'https://socketeer.glitch.me/';
}
// end of vvazquez
dialog.setTaskState(e.target.value, handlers);
};
//hide all buttons and add click handler, except for transfer
allowableContainer.children('button').each(function() {
var element = $(this);
element.off('click');
element.on("click", actionHandler);
element.hide();
});
$("#transferButton_" + dialogId).hide();
var participants = dialog.getParticipants();
for (var i = 0; i < participants.length; i++) {
var actions = participants[i].actions;
if (!actions) {
return;
}
actions = actions.action;
if (!actions) {
return;
}
//convert to array if its not
if (typeof actions === 'string') {
actions = [actions];
}
//draw action buttons
for (var j = 0; j < actions.length; j++) {
var value = actions[j];
allowableContainer.find('button').each(function() {
var buttonValue = $(this).val();
if (value === buttonValue) {
$(this).show();
}
});
}
}
updateCallVars(dialog);
},
/**
* Parse script-selectors.txt and return array or script selectors for transfer
* @param file
* @returns {Array}
*/
getScriptSelectorsFromFile = function(file) {
var scriptSelectors = [];
var scriptSelectorFile = new XMLHttpRequest();
scriptSelectorFile.open("GET", file, false);
scriptSelectorFile.onreadystatechange = function() {
if (scriptSelectorFile.readyState === 4) {
if (scriptSelectorFile.status === 200 || scriptSelectorFile.status == 0) {
var fileText = scriptSelectorFile.responseText;
scriptSelectors = fileText.split(',');
}
}
};
scriptSelectorFile.send(null);
return scriptSelectors;
},
/**
* For each dialog, add the transfer button with the dropdown of targets to pick from
* @param dialog
*/
addTransferAction = function(dialog) {
var dialogId = dialog.getId();
var allowableContainer = $("#allowableActions_" + dialogId);
//click handler for transfer button
var transferHandler = function(event) {
dialog.transfer(event.data.target);
};
//create transfer button from template and append to allowableContainer
var template = $('#transfer-button-template').html();
allowableContainer.append(template);
//give each button and dropdown a unique id
var transferDropdown = $("#transferDropdown");
transferDropdown.attr("id", "transferDropdown_" + dialogId);
var transferButton = $("#transferButton");
transferButton.attr("id", "transferButton_" + dialogId);
//transferTargets gets set in init when gadget loads
//append each target to the trasfer dropdown
for (var i in transferTargets) {
var target = transferTargets[i];
var element = $("<li><a class='dropdown-item' href='#'>" + target + "</a></li>");
transferDropdown.append(element);
element.on("click", {
target: target
}, transferHandler);
}
},
/**
* Callback used upon the load of a media object. This should be used for anything that only needs to be
* executed once during initialization.
*/
handleMediaLoad = function(_media) {
// Display media name from the desktop layout if there is no name from the API.
// $("#mediaName").text(_media.getName() ? _media.getName() : mrdName);
$("#mediaName").text('Video Channel');
loadMediaDialogs(_media);
//if user signed out of this media or state is unknown, show the sign in button
if (_media.getState() === states.LOGOUT || _media.getState() === undefined) {
showLogin();
} else {
_media.refresh();
}
},
/**
* Callback used when a media is changed. This is misleading because it will be triggered when any
* media changes, not just the one associated with this instance of the gadget.
*/
handleMediaChange = function(_media) {
//only update if the notification is for this gadgets's specific media
//since there could be multiple media gadgets corresponding to a different media id
if (mrdID === _media._data.id) {
render();
}
},
/**
* Handler used upon a successful action being performed on the media.
*/
handleMediaSuccess = function(obj) {
//clear any previous error message
uiMsg.hideBanner();
},
/**
* Handler called upon a failed action on the media.
*/
handleMediaError = function(rsp) {
var errorMessage = rsp.object.ApiErrors.ApiError.ErrorMessage;
var msg = prefs.getMsg(errorMessage) || errorMessage;
if (errorMessage == "E_ARM_STAT_AGENT_ALREADY_LOGGED_IN") {
loadMediaDialogs(media);
return;
}
showError("Operation Failed: " + msg);
},
/** shows error banner with dismissable error msg
* make the "hide msg" button displayed with the dismissable error msgs was added
*/
showError = function(error) {
uiMsg.showBannerError(error);
adjustGadgetHeight();
},
/**
* Load the current user's dialogs.
* @return {undefined}
*/
loadMediaDialogs = function(_media) {
mediaDialogs = _media.getMediaDialogs({
onCollectionAdd: handleMediaDialogsAdd,
onCollectionDelete: handleMediaDialogsDelete,
onLoad: handleMediaDialogsLoad
});
},
handleMediaDialogsLoad = function() {
//not getting here
var dialogCollection = mediaDialogs.getCollection(), id;
for (id in dialogCollection) {
var dialog = dialogCollection[id];
handleMediaDialogsAdd(dialog);
}
},
/**
* If the given dialog contains a media property named POD.ID, instruct the context gadget to display the pod with
* the given ID.
*/
displayPodInContextGadget = function(dialog) {
var podId, mediaProperties = dialog.getMediaProperties();
for (var property in mediaProperties) {
if (property === "POD.ID") {
podId = mediaProperties[property];
break;
}
}
if (podId) {
clientLogs.log("Displaying POD with id " + podId);
ContextServiceGadgetControl.showPodById(podId);
}
},
/**
* Handler that is called anytime a dialog is added for the user on all media.
*/
handleMediaDialogsAdd = function(dialog) {
$(".tabbable").css("display", "block");
//this gets called whenever there's a dialog change for all media
//only update if the notification is for this gadgets's specific media
//since there could be multiple media gadgets corresponding to a different media id
if (mrdID === dialog._data.mediaProperties.mediaId) {
createNewTab(dialog.getId());
addTransferAction(dialog);
displayDialog(dialog);
dialog.addHandler("change", displayDialog);
adjustGadgetHeight();
displayPodInContextGadget(dialog);
}
},
/**
* Handler called anytime a dialog is ended
*/
handleMediaDialogsDelete = function(dialog) {
if (mrdID === dialog._data.mediaProperties.mediaId) {
// vvazquez
console.log ('vvazquez: Ending Meeting');
// send end meeting request
const myCallVariables = dialog.getMediaProperties();
const videoDestination = myCallVariables.user_videoDestination;
const accessToken = myCallVariables.user_videoToken;
const mainVideoURl = 'https://c259-38-64-189-37.ngrok-free.app';
console.log ('vvazquez: ', accessToken, videoDestination);
let myHeaders = {
"Content-Type": "application/json"
}
let myBody = JSON.stringify({
"accessToken": accessToken,
"destination": videoDestination
});
const requestOptions = {
method: "POST",
headers: myHeaders,
body: myBody
};
fetch(mainVideoURl+'/end-meeting', requestOptions)
.then((response) => response.text())
.then((result) => console.log('vvazquez: ', result))
.catch((error) => console.error('vvazquez error: ', error));
// end of vvazquez
displayDialog(dialog);
removeCurrentTab(dialog.getId());
adjustGadgetHeight();
}
},
/**
* Handler for the onLoad of a User object. This occurs when the User object is initially read
* from the Finesse server. Any once only initialization should be done within this function.
*/
handleUserLoad = function(_user) {
mediaList = user.getMediaList({
onLoad: handleMediaListLoad
});
},
/**
* Handler for the onLoad of a MediaList object. This occurs when the MediaList object is initially read
* from the Finesse server.
*/
handleMediaListLoad = function(_mediaList) {
try {
//get the media with the specified id
media = _mediaList.getMedia({
id: mrdID,
onLoad: handleMediaLoad,
onError: handleMediaError,
onChange: handleMediaChange,
mediaOptions: mediaOptions
});
} catch (error) {
showError(prefs.getMsg("gadget.taskManagementGadget.message.mediaChannelNotFound") + " " + mrdID);
}
},
/**
* Adjusts the height of the gadget to account for the tab pane which contains dialogs.
*/
adjustGadgetHeight = function() {
setTimeout(function() {
var bScrollHeight = $("body").height();
var height = bScrollHeight + 20;
if (height < 125) {
height = 125;
}
gadgets.window.adjustHeight(height);
}, 100);
},
/**
* Handler for a failed logout request.
* @private
*/
failedSignout = function(user) {
return function(rsp) {
var errCode = utils.getErrCode(rsp),
errTxt = prefs.getMsg("gadget.taskManagementGadget.message.signOutError"),
errMsg = (errCode) ? errTxt + ": " + errCode : errTxt;
clientLogs.log("failedSignout(" + user.getId() + "): " + errMsg);
showError(errMsg);
};
},
/**
* Utility function that returns an array of key-value pairs
* for the query parameters in a given URL.
*/
getUrlVars = function(url) {
var vars = {};
var parts = url.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m, key, value) {
vars[key] = value;
});
return vars;
},
/**
* Validates that the gadget is configured with the correct query params from the desktop layout.
* MRD ID is required for the gadget to work. For the MRD name and max dialogs we default to 'Media'
* and 5 dialogs respectively if they are not configured or misconfigured.
*/
checkGadgetQueryParams = function() {
//First get just the URI for this gadget out of the full finesse URI and decode it.
var gadgetURI = decodeURIComponent(getUrlVars(location.search)["url"]);
//Now get the individual query params from the gadget URI
var decodedGadgetURI = getUrlVars(gadgetURI);
mrdID = decodedGadgetURI["mrdid"];
mrdName = decodedGadgetURI["mrdname"];
maxDialogs = decodedGadgetURI["maxdialogs"];
interruptAction = decodedGadgetURI["interruptAction"];
dialogLogoutAction = decodedGadgetURI["dialogLogoutAction"];
inGadgetStateController = decodedGadgetURI["inGadgetStateController"];
//If no MRD ID is configured or it's not a number we want to throw an error during init.
if (!mrdID || isNaN(mrdID)) {
return false;
}
//If there's no max dialogs configured or the value is not a number then default it to 5.
if (!maxDialogs || isNaN(maxDialogs)) {
maxDialogs = "5";
}
//If there's no interruptAction configured or the value is not valid, default to "ACCEPT".
if (!finesse.restservices.InterruptActions.isValidAction(interruptAction)) {
interruptAction = finesse.restservices.InterruptActions.ACCEPT;
}
//If there's no dialogLogoutAction configured or the value is not valid, default to "CLOSE".
if (!finesse.restservices.DialogLogoutActions.isValidAction(dialogLogoutAction)) {
dialogLogoutAction = finesse.restservices.DialogLogoutActions.CLOSE;
}
//If there's no dialogLogoutAction configured or the value is not valid, default to "CLOSE".
if (!dialogLogoutAction || dialogLogoutAction.toUpperCase() !== "CLOSE" && dialogLogoutAction.toUpperCase() !== "TRANSFER") {
dialogLogoutAction = "CLOSE";
}
return true;
};
/** @scope finesse.modules.TaskManagementGadget */
return {
/**
* Sets the user state on the media that this gadget is configured for.
*/
setUserStateOnMedia: function(state, onSuccess, onError) {
//clear any previous error message
uiMsg.hideBanner();
//state change will trigger media change notification, which will call handleMediaChange and then re-render
if (state === 'READY') {
media.setState(states.READY);
} else if (state === 'NOT_READY') {
//hardcoding for now until we do UX for how to do this
var reasonCode = null; //{id:2};
media.setState(states.NOT_READY, reasonCode);
}
/* Code specific finesse digital channel integration */
if (onSuccess) {
onSuccess({
channelId: channelData.channelId,
status: channelService.STATUS.SUCCESS
});
}
},
/**
* Logs out the agent out of the MRD that this gadget is configured for.
*/
logoutFromMrd: function() {
var params = {
handlers: {
error: failedSignout(user)
}
};
//hardcoding for now until we do UX for how to do this
var reasonCode = null; //{id:1};
media.logout(reasonCode, params);
},
/**
* Login an agent to the MRD that this gadget is configured for.
* If the agent is successfully logged in to the media it will load
* the dialogs for the agent on that media, otherwise an error will be thrown.
*/
loginToMrd: function() {
var params = {
maxDialogLimit: mediaOptions.maxDialogLimit,
interruptAction: mediaOptions.interruptAction,
dialogLogoutAction: mediaOptions.dialogLogoutAction,
handlers: {
error: handleMediaError
}
};
media.login(params);
},
/**
* Set agent to routable or not routable based on checkbox.
*
* Call media API whenever checkbox is checked or unchecked (called from onClick handler in TaskManagementGadget.xml).
*/
setRoutability: function() {
var routableCheckbox = $("#routable-checkbox");
var isRoutable = routableCheckbox.is(":checked");
var params = {
routable: isRoutable,
handlers: {
error: handleMediaError
}
};
media.setRoutable(params);
},
/**
* Performs all initialization for this gadget
*/
init: function() {
clientLogs = finesse.cslogger.ClientLogger; // declare clientLogs
/** Initialize private references */
utils = finesse.utilities.Utilities;
msgs = finesse.utilities.I18n.getString;
uiMsg = finesse.utilities.MessageDisplay;
var config = finesse.gadget.Config;
log('taskManagementGadget init is called');
gadgets.window.setTitle(prefs.getMsg('gadget.taskManagementGadget.message.title'));
adjustGadgetHeight();
if (!checkGadgetQueryParams()) {
var err = prefs.getMsg("gadget.taskManagementGadget.message.missingMrdIdParam");
showError(err);
$("#sign-in").hide();
$("#state-area").show();
$("#sign-out").show();
$("#mediaSummary").hide();
gadgets.loadingindicator.dismiss();
return;
}
mediaOptions = {
maxDialogLimit: maxDialogs,
interruptAction: interruptAction.toUpperCase(),
dialogLogoutAction: dialogLogoutAction.toUpperCase()
};
//initialize bootstrap tooltips
// $('[data-toggle="tooltip"]').tooltip();
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
return new bootstrap.Tooltip(tooltipTriggerEl)
});
// Initiate the ClientServices and load the user object. ClientServices are
// initialized with a reference to the current configuration.
finesse.clientservices.ClientServices.init(config);
// Hookup connect and disconnect handlers so that buttons can be disabled while failing over.
//
finesse.clientservices.ClientServices.registerOnConnectHandler(function() {
connected = true;
render();
});
finesse.clientservices.ClientServices.registerOnDisconnectHandler(function() {
connected = false;
render();
});
clientLogs.init(gadgets.Hub, "TaskManagementGadget"); //this gadget id will be logged as a part of the message
user = new finesse.restservices.User({
id: config.id,
onLoad: handleUserLoad
});
// Initiate the ContainerServices and add a handler for when the tab is visible
// to adjust the height of this gadget in case the tab was not visible
// when the html was rendered (adjustHeight only works when tab is visible)
containerServices = finesse.containerservices.ContainerServices.init();
/* Code specific finesse digital channel integration */
/* to gain access to finesse digital channel services, it must be initiated */
channelService = finesse.digital.ChannelService.init(containerServices);
containerServices.addHandler(finesse.containerservices.ContainerServices.Topics.ACTIVE_TAB, function() {
clientLogs.log("Gadget is now visible"); // log to Finesse logger
});
containerServices.makeActiveTabReq();
transferTargets = getScriptSelectorsFromFile('/3rdpartygadget/files/script-selectors.txt');
//now that the gadget has loaded, remove the loading indicator
gadgets.loadingindicator.dismiss();
/* Code specific finesse digital channel integration */
channelData = _getDefaultChannelData();
_addChannel(channelData);
}
};
}(jQuery));