Free javascript Hosting


djiintaskmanagement.js

Uploaded on Feb 11 2022 05:03 by w95.nazih

/**
* Script supporting features provided by the task management interface
*/


/**
* Localisation registration.
*/
djiinUtil.localizedValues.registerAll({
'" à la nouvelle valeur "' : {'en' : '" to the new value "'},
' : Modification de la catégorisation "' : {'en' : ': Changing the category "'},
'Emetteur inconnu' : {'en' : 'Unknown sender'},
' : Réouverture du ticket "' : {'en' : ' : Reopening the ticket "'},
'Archivé' : {'en' : 'Archived'},
'Important' : {'en' : 'Important'},
'Détail de la campagne' : {'en' : 'Campaign details'},
'Détail du ticket' : {'en' : 'Ticket details'},
'Nombre de tickets' : {'en' : 'Ticket count'},
'Exporter' : {'en' : 'Export'},
'Exportation des tickets de la campagne' : {'en' : 'Exporting campaign tickets'}
});

/**
* the name space of this lib.
*/
const djiinTaskManagement = {
setupParametersDefinition: [
{name: 'parameters.setup.plugin.onTreatmentWindowClosed', description: 'A function called when the treatment window is closed. function(targetOptions). Just define the function body.'},
{name: 'parameters.setup.plugin.renderTicketListItem', description: 'A function called to render a single ticket in the ticket list. function(ticketLocation, ticket, isNewSwitchListener). Just define the function body.'},
{name: 'parameters.setup.plugin.renderTicketInDetail', description: 'A function called to render the ticket in the detail panel (right side). function(request). Just define the function body.'},
{name: 'parameters.setup.plugin.renderActionsInDetail', description: 'A function called to render the actions in the detail panel (right side). function(request). Just define the function body.'},
{name: 'parameters.setup.plugin.buildTicketSearchExtension', description: 'A function called to build the search extension when a search is issued. function(). Just define the function body.'},
{name: 'parameters.setup.plugin.buildTicketCustomSqlRequestSearchExtension', description: 'A function called to build the search extension for the custom SQL request when a search is issued. function(). Just define the function body.'},
{name: 'parameters.setup.plugin.checkTicketVisibility', description: 'A function called to determine whether a ticket should be displayed in lists. function(ticket, userGroups). Just define the function body.'},
{name: 'parameters.setup.environment', description: 'The name of the environment in which are stored the tickets.'},
{name: 'parameters.setup.displayMode', description: 'The category list display mode "CAMPAIGN" or "CATEGORY". campaign being the default.'},
{name: 'parameters.setup.showUnavailableAppointmentsMode', description: 'When set to "true" value, activates the display of a third category in each campaign, aside Pending and My files. This new category is named Unavailable and shows all tickets that are associated with appointments for which a user, other then the current one, is currently assigned.'},
{name: 'parameters.setup.dashboardName', description: 'The name of the dashboard which appointments are displayed in this task management UI.'},
{name: 'parameters.setup.treatmentKHAppName', description: 'The name of the KHApp used to start or resume the processing of tickets.'},
{name: 'parameters.setup.portalName', description: 'The portal name associated with this task management UI.'},
{name: 'parameters.setup.showNewButton', description: 'When set to the "true" value, allows the display of a ticket creation button. Defaults to true.'},
{name: 'parameters.setup.showTicketInDetail', description: 'When set to "true", allows the display of the ticket part of the request. Default to true.'},
{name: 'parameters.setup.showActionsInDetail', description: 'When set to "true", allows the display of the actions part of the request. Default to false.'},
{name: 'parameters.setup.filters', description: 'JSON Array defining the filters.'},
{name: 'parameters.setup.searchCriteria', description: 'JSON Array defining the search criteria.'},
{name: 'parameters.setup.searchRequest', description: 'JSON object describing a request used by search UI using the custom request API. When absent, default behavior is to search tickets using the ticket search api.'}
],



displayCampaigns : [],
archiveCategorySources : [],
plugins: {},
filters: [],
searchCriteria: [],
searchRequest : {status : 'UNDEFINED'},


//////////////// INITIAL SETUP ////////////////
//////////////// INITIAL SETUP ////////////////
//////////////// INITIAL SETUP ////////////////
//////////////// INITIAL SETUP ////////////////
//////////////// INITIAL SETUP ////////////////
//////////////// INITIAL SETUP ////////////////

/**
* Defines the filters.
*/
setFilters: function(filters)
{
this.filters = filters;
},

/**
* Defines the search criteria.
*/
setSearchCriteria: function(searchCriteria)
{
this.searchCriteria = searchCriteria;
},

/**
* Defines the search request to send to the custom request api.
*/
setSearchRequest: function(searchRequest)
{
this.searchRequest = searchRequest;
},

/**
* Defines the plugins.
*/
setPlugins: function(plugins)
{
if (plugins != undefined)
{
this.plugins = plugins;
}
},


/**
* Show admin help UI
*/
showAdminHelpUI: function() {
let bodyHTML = '';
for (parameterIndex in djiinTaskManagement.setupParametersDefinition)
{
let parameterDefinition = djiinTaskManagement.setupParametersDefinition[parameterIndex];
bodyHTML +=
'<div class="row form-horizontal">'+
' <div class="form-group side-margin">' +
' <div class="col-sm-3" style="font-weight: bold">' + parameterDefinition.name + ' </div>' +
' <div class="col-sm-9">' + searchCriterion.description + ' </div>' +
' </div>' +
'</div>';
}

djiinUtil.createModal('admin-help-popup', false, 'Admin Help',
'<div class="row form-horizontal">' +
' <h3 class="side-margin">Admin Help</h3>' +
'</div>'+
bodyHTML);
},




////////////////// CAMPAIGN MANAGEMENT //////////////////
////////////////// CAMPAIGN MANAGEMENT //////////////////
////////////////// CAMPAIGN MANAGEMENT //////////////////
////////////////// CAMPAIGN MANAGEMENT //////////////////
////////////////// CAMPAIGN MANAGEMENT //////////////////


/**
* Adds a campaign to the list. Analyses the contents.
*/
addDisplayCampaign : function(displayCampaign)
{
if (displayCampaign.hasOwnProperty('extension') && displayCampaign.extension.hasOwnProperty('categorisation') && displayCampaign.extension.categorisation.hasOwnProperty('source'))
{
let source = displayCampaign.extension.categorisation.source;
if (this.archiveCategorySources.indexOf(source) == -1) this.archiveCategorySources.push(source);
}
this.displayCampaigns.push(displayCampaign);
},
/**
* Retrieves the campaign by its index.
*/
getCampaign : function (campaignIndex)
{
return this.displayCampaigns[campaignIndex];
},
/**
* Retrieves the campaign category by its indices.
*/
getCategoryInCampaign : function (campaignIndex, categoryIndex)
{
return this.getCampaign(campaignIndex).categories[categoryIndex];
},
/**
* Shows a campaign export dialog.
*/
openCampaignExportModal : function(element)
{
let targetOptions = $(element).attr('data-target-options');
targetOptions = JSON.parse(targetOptions);
let category = this.getCategoryInCampaign(targetOptions.campaignIndex, targetOptions.categoryIndex);
let idList = '[';
for (ticketIndex in category.tickets)
{
idList += (ticketIndex > 0 ? ', ' : '') + category.tickets[ticketIndex].id;
}
idList += ']';
djiinUtil.createModal('campaign-export', false, djiinUtil.localize('Exportation des tickets de la campagne'),
'<div>' + idList + '</div>');
},
/**
* Shows a campaign export dialog.
*/
openCampaignInfoModal : function(element)
{
let targetOptions = $(element).attr('data-target-options');
targetOptions = JSON.parse(targetOptions);
let displayCampaign = this.getCampaign(targetOptions.campaignIndex);
let category = this.getCategoryInCampaign(targetOptions.campaignIndex, targetOptions.categoryIndex);
djiinUtil.createModal('campaign-info', false, djiinUtil.localize('Détail de la campagne'),
'<div><b>' + displayCampaign.libelle + ' > '+ category.name + '</b><br/>' +
'<b>' + djiinUtil.localize('Nombre de tickets') + '</b> ' + category.ticketCount + '/' + category.tickets.length +
'</div>');
},


//////////////////// TICKET MANAGEMENT ///////////////////////
//////////////////// TICKET MANAGEMENT ///////////////////////
//////////////////// TICKET MANAGEMENT ///////////////////////
//////////////////// TICKET MANAGEMENT ///////////////////////
//////////////////// TICKET MANAGEMENT ///////////////////////
//////////////////// TICKET MANAGEMENT ///////////////////////



/**
* checks whether this ticket has the archive category source set or not for all known sources.
* If one is found the isArchive property of the ticket is set to true, otherwise is false.
*/
checkIfTicketIsArchive : function(ticket)
{
let isArchive = false;
for (source of this.archiveCategorySources)
{
if (ticket.hasOwnProperty('extension') && ticket.extension.hasOwnProperty(source))
{
isArchive = true;
}
}
ticket.isArchive = isArchive;
},

/**
* checks whether this ticket matches the filters criteria or not.
*/
checkIfTicketMatchesFilters : function(ticket)
{
let matchesFilters = true; // defaults to "kept"
for (filterIndex in this.filters)
{
let filter = this.filters[filterIndex];
let value = djiinUtil.getPropertyInTree(ticket.extension, filter.extensionName);
if (filter.userCriterion != undefined && filter.userCriterion != null && filter.userCriterion.trim() != '' &&
(value == undefined || ! value.toLowerCase().includes(filter.userCriterion.toLowerCase())))
{
matchesFilters = false;
}
}
ticket.matchesFilters = matchesFilters;
},

/**
* Show ticket info dialog
*/
openTicketInfoModal : function(element)
{
let targetOptions = $(element).attr('data-target-options');
targetOptions = JSON.parse(targetOptions);
djiinUtil.createModal('ticket-info', false, djiinUtil.localize('Détail du ticket'),
'<div>' +
'<b>Ticket</b> #' + targetOptions.ticketId +
'</div>');
},

/**
* Loads all tickets registered in the given archive category.
*/
callGetTicketListByArchiveCategory : async function (archiveCategoryPropertyName, archiveCategory, pageIndex, pageSize, showErrorDialog)
{
let ticketSearchObject = {
searchExtension : [
{
fieldName: archiveCategoryPropertyName,
fieldValue: archiveCategory
}
],
sort: {
orderType: 'desc',
fieldName: 'extension.contact.lastEmailReceptionDate'
},
pagination: {
resultCountPerPage: pageSize,
pageIndex: pageIndex
}
};
let returnValue = await this.callGetTicketList(ticketSearchObject, showErrorDialog);
//djiinUtil.log("load ticket list with campaign", ticketSearchObject, returnValue);
return returnValue;
},
/**
* Loads all tickets with the given ids.
*/
callGetTicketListByIds : async function(ticketIdArray, pageIndex, pageSize, showErrorDialog)
{
let ticketSearchObject = {
name : "recherche-ticket-ids",
parameters : [
{
name:"requestIds",
value:[]
},
{
name:"resultCountPerPage",
value:pageSize
},
{
name:"pageIndex",
value:pageIndex
}
]
};
if (ticketIdArray == null || ticketIdArray.length == 0)
{
return {
tickets : [],
status : 'OK',
errorCode : null
};
}
let requestIdsParameterIndex;
for (parameterIndex in ticketSearchObject.parameters)
{
if (ticketSearchObject.parameters[parameterIndex].name == "requestIds")
{
requestIdsParameterIndex = parameterIndex;
}
}
for (idIndex in ticketIdArray)
{
if (ticketIdArray[idIndex] != undefined && ticketIdArray[idIndex] != null && !isNaN(ticketIdArray[idIndex]))
{
ticketSearchObject.parameters[requestIdsParameterIndex].value.push(ticketIdArray[idIndex]);
}
}
let returnValue = await this.callCustomSqlRequestGetTicketList(ticketSearchObject, showErrorDialog);
djiinUtil.log("load ticket list by ids", ticketSearchObject, returnValue);
return returnValue;
},
/**
* Loads all tickets with the given request.
*/
callCustomSqlRequestGetTicketList : async function(request, showErrorDialog)
{
// add all search extensions to the request parameters
Array.prototype.push.apply(request.parameters, this.buildTicketCustomSqlRequestSearchExtension());

let result = {
tickets : [],
status : 'OK',
errorCode : null
};
let tickets = await djiinUtil.callServiceAsync(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"intraneon.administration.customSQLRequest.execute.v1",
request,
false);
//djiinUtil.log("load ticket list with request", request, tickets);
if (tickets == undefined) {
if (showErrorDialog)
{
djiinUtil.createModal('error-display-popup', false, 'Error', (djiinUtil.info.language == 'fr' ? '<h4>Erreur de chargement de la campagne, veuillez réessayer. En cas d\'échec répété, vérifiez que vous êtes toujours connecté et rafraichissez la page. Si cela ne rétablit pas le chargement, contactez votre administrateur.</h4>' :
'<h4>Campaign loading error, please retry. In case of persistent failure, please check that you are still connected and refresh the page. If it does not restore the loading, contact your administrator.</h4>'));
}
result.status = "ERROR";
}
else if (tickets.code != 200) {
if (showErrorDialog)
{
djiinUtil.createModal('error-display-popup', false, 'Error', (djiinUtil.info.language == 'fr' ? '<h4>Erreur ' + appointments.code + ' de chargement de la campagne, veuillez réessayer. En cas d\'échec répété, vérifiez que vous êtes toujours connecté et rafraichissez la page. Si cela ne rétablit pas le chargement, contactez votre administrateur.</h4>' :
'<h4>Campaign loading error ' + appointments.code + ', please retry. In case of persistent failure, please check that you are still connected and refresh the page. If it does not restore the loading, contact your administrator.</h4>'));
}
result.status = "ERROR";
result.errorCode = tickets.code;
}
else
{
result.tickets = tickets.response.results;
}
return result;
},
/**
* Loads all tickets with the given request.
*/
callGetTicketList : async function(request, showErrorDialog)
{
if (request.searchExtension == undefined)
{
request.searchExtension = [];
}
request.searchExtension = request.searchExtension.concat(this.buildTicketSearchExtension());

let result = {
tickets : [],
status : 'OK',
errorCode : null
};
let tickets = await djiinUtil.callServiceAsync(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"intraneon.ticket.request.getList.v1",
request,
false);
//djiinUtil.log("load ticket list with request", request, tickets);
if (tickets == undefined) {
if (showErrorDialog)
{
djiinUtil.createModal('error-display-popup', false, 'Error', (djiinUtil.info.language == 'fr' ? '<h4>Erreur de chargement de la campagne, veuillez réessayer. En cas d\'échec répété, vérifiez que vous êtes toujours connecté et rafraichissez la page. Si cela ne rétablit pas le chargement, contactez votre administrateur.</h4>' :
'<h4>Campaign loading error, please retry. In case of persistent failure, please check that you are still connected and refresh the page. If it does not restore the loading, contact your administrator.</h4>'));
}
result.status = "ERROR";
}
else if (tickets.code != 200) {
if (showErrorDialog)
{
djiinUtil.createModal('error-display-popup', false, 'Error', (djiinUtil.info.language == 'fr' ? '<h4>Erreur ' + appointments.code + ' de chargement de la campagne, veuillez réessayer. En cas d\'échec répété, vérifiez que vous êtes toujours connecté et rafraichissez la page. Si cela ne rétablit pas le chargement, contactez votre administrateur.</h4>' :
'<h4>Campaign loading error ' + appointments.code + ', please retry. In case of persistent failure, please check that you are still connected and refresh the page. If it does not restore the loading, contact your administrator.</h4>'));
}
result.status = "ERROR";
result.errorCode = tickets.code;
}
else
{
result.tickets = tickets.response;
}
return result;
},


/**
* builds the search extension to load tickets
* relies on plugins to extend this behavior
*/
buildTicketSearchExtension: function()
{
let pluginSearchExtension = this.plugins.buildTicketSearchExtension();
if (pluginSearchExtension != undefined)
{
return pluginSearchExtension;
}
return [
{
fieldName: "contact.environnement",
fieldValue: djiinUtil.info.environment
}
];
},


/**
* builds the search extension to load tickets
* relies on plugins to extend this behavior
*/
buildTicketCustomSqlRequestSearchExtension: function()
{
let pluginSearchExtension = this.plugins.buildTicketCustomSqlRequestSearchExtension();
if (pluginSearchExtension != undefined)
{
return pluginSearchExtension;
}
return [
{
name: "environnement",
value: djiinUtil.info.environment
}
];
},



/**
* Show search tickets UI
*/
showSearchUI: function() {
let formHTML = '';
for (criterionIndex in djiinTaskManagement.searchCriteria)
{
let searchCriterion = djiinTaskManagement.searchCriteria[criterionIndex];
formHTML +=
'<div class="row form-horizontal">'+
' <div class="form-group side-margin">' +
' <div class="col-sm-3" style="font-weight: bold">' + (djiinUtil.info.language == 'fr' ? searchCriterion.label+' :' : searchCriterion["label-en"]+' :') + ' </div>' +
' <div class="col-sm-9">' +
(searchCriterion.type == 'boolean' ?
'<INPUT type="checkbox" id="ticketSearch' + searchCriterion.name + '" name="ticketSearch' + searchCriterion.name + '" ' + (searchCriterion.hasOwnProperty("userValue") && searchCriterion.userValue == 'true' ? 'checked' : '') + ' class="form-control">' :
'<INPUT id="ticketSearch' + searchCriterion.name + '" name="ticketSearch' + searchCriterion.name + '" value="' + (searchCriterion.hasOwnProperty("userValue") ? searchCriterion.userValue : '') + '" class="form-control">'
) +
' </div>' +
' </div>' +
'</div>';
}

djiinUtil.createModal('ticket-search-popup', false, (djiinUtil.info.language == 'fr' ? 'Critères de recherche' : 'Search criteria'),
'<div class="row form-horizontal">' +
' <h3 class="side-margin">' + (djiinUtil.info.language == 'fr' ? 'Recherche de ticket' : 'Ticket search') + '</h3>' +
' <h4 class="side-margin bottom-space">' + (djiinUtil.info.language == 'fr' ? 'Saisie des critères' : 'Criteria input') + '</h4>' +
' <p class="side-margin bottom-space">' +
(djiinUtil.info.language == 'fr' ? 'Veuillez saisir des critères de recherche les plus précis possible pour identifier le ticket à rechercher. Les résultats s\'afficheront dans la catégorie "Recherche" sur la gauche de l\'écran (au plus 100 résultats peuvent être remontés en même temps).' :
'Please type in search criteria that are as accurate as possible to identify the right ticket to find. The results will be displayed in the "Search" category on the left side of the screen (100 results at most will be returned at a time).') +
'</p>' +
'</div>'+
formHTML,
(djiinUtil.info.language == 'fr' ? 'Annuler' : 'Cancel'),
(djiinUtil.info.language == 'fr' ? 'Rechercher' : 'Search'),
loadTicketSearchResults);
}
}

/**
* Retrieves the ticket object given the assignedTickets
*/
function getTicketInCampaign(campaignIndex, categoryIndex, ticketId)
{
let category = djiinTaskManagement.getCategoryInCampaign(campaignIndex, categoryIndex);
let tickets = category.tickets;
if (tickets == undefined) tickets = [];
for (ticketIndex in tickets)
{
if (tickets[ticketIndex].id == ticketId)
{
return tickets[ticketIndex];
}
}
}

/**
* Toggle filtering for tickets
*/
function filteringToggle(elem){
isFilteringActivated = !isFilteringActivated;
sessionStorage.setItem('isFilteringActivated', isFilteringActivated);
if(isFilteringActivated){
elem.children[0].classList.replace( 'bi-toggle-off', 'bi-toggle-on' )
}else{
elem.children[0].classList.replace( 'bi-toggle-on', 'bi-toggle-off' )
}
asyncReloadAllDisplayCampaigns();
}

/**
* Checks if there is another user already processing the appointment
*/

function checkIfAppointmentHasAffectedUser(sessionId){
let appointmentSearchObject = {
objectId: sessionId
};
let appointments = djiinUtil.callService(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.calendar.appointment.getList.v1",
appointmentSearchObject,
false);
appointment = appointments.response[0];
if(appointment.hasOwnProperty('affectedUserId')){
if(appointment.affectedUserId == currentUserId){
return false;
}else{
return true;
}
}else{
return false;
}
}

/**
* Checks if there is another user already processing the appointment
* before opening the treatment modal.
*/
function openTreatmentModal(buttonElement){
let target = $$(buttonElement).attr('data-target');
let targetOptions = $$(buttonElement).attr('data-target-options');
targetOptions = JSON.parse(targetOptions);

let isProcessing = checkIfAppointmentHasAffectedUser(targetOptions.sessionId);
if(isProcessing){
djiinUtil.createModal('treatment-error-popup', true, (djiinUtil.info.language == 'fr' ? 'Erreur de traitement' : 'Treatment Error'),
(djiinUtil.info.language == 'fr' ? '<h4>Le traitement est déjà en cours par un autre utilisateur.</h4>' : '<h4>The treatment is already in progress by another user.</h4>'));
$$("#ticketTreatmentButton").addClass("hidden");
}else{
openKHAppModal(buttonElement);
}
}

/**
* Selects this ticket and shows it.
*/
function switchTicketIsNewForCategory(element, declarationId, qualificationId, declarationKey, qualificationKey, ticketId)
{
let currentTicketIndex;
for (ticketIndex in declarationsAndQualifications[declarationKey][qualificationKey])
{
if (declarationsAndQualifications[declarationKey][qualificationKey][ticketIndex].id == ticketId)
{
currentTicketIndex = ticketIndex;
}
}
let ticket = declarationsAndQualifications[declarationKey][qualificationKey][currentTicketIndex];
if (ticket != undefined)
{
let item = $$(element);
if (item.hasClass('isNewMail'))
{
if (ticket.extension.contact.hasNewMail == true)
{
ticket.extension.contact.hasNewMail = false;
let ticketUpdate = djiinUtil.callService(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.ticket.request.update.v3",
ticket,
false);
}
item.removeClass('isNewMail');
item.addClass('isNotNewMail');
}
else
{
if (ticket.extension.contact.hasNewMail == false)
{
ticket.extension.contact.hasNewMail = true;
let ticketUpdate = djiinUtil.callService(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.ticket.request.update.v3",
ticket,
false);
}
item.addClass('isNewMail');
item.removeClass('isNotNewMail');
}
updateCategoryBadges(declarationId, qualificationId, declarationKey, qualificationKey);
}
}
/**
* Selects this ticket and shows it.
*/
function switchTicketIsNew(element, campaignIndex, categoryIndex, ticketId)
{
let ticket = getTicketInCampaign(campaignIndex, categoryIndex, ticketId);
let item = $$(element);
if (item.hasClass('isNewMail'))
{
if (ticket.extension.contact.hasNewMail == true)
{
ticket.extension.contact.hasNewMail = false;
let ticketUpdate = djiinUtil.callService(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.ticket.request.update.v3",
ticket,
false);
}
item.removeClass('isNewMail');
item.addClass('isNotNewMail');
}
else
{
if (ticket.extension.contact.hasNewMail == false)
{
ticket.extension.contact.hasNewMail = true;
let ticketUpdate = djiinUtil.callService(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.ticket.request.update.v3",
ticket,
false);
}
item.addClass('isNewMail');
item.removeClass('isNotNewMail');
}
updateDisplayCampaignBadges(campaignIndex);
}

/**
* Tries to select the ticket corresponding to the given element.
* Returns the top level element if selection succeeds and null otherwise
* (succeeds and needs to be done, meaning that it returns null if already selected)
*/
function tryToSelectTicketInList(element)
{
// select item and unselect others
let item = $$(element);
if (! item.hasClass('list-group-item')) item = item.parents('.list-group-item');
if (item.hasClass("active"))
{
// already selected, exit
return null;
}
$$(".displayCategoryTasks .list-group-item").removeClass("active");
$$(".displayCampaignTasks .list-group-item").removeClass("active");
item.addClass("active");
return item;
}

/**
* Selects this ticket and shows it.
*/
function showTicketDetailForCategory(element, declarationId, qualificationId, declarationKey, qualificationKey, ticketId)
{
element = tryToSelectTicketInList(element);
if (element == null) return; // already done, nothing to do
// let displayCampaign = this.getCampaign(campaignIndex);
// let category = this.getCategoryInCampaign(campaignIndex, categoryIndex);
djiinSpinner.start($$("#ticketDetailPanel"), 0);
setTimeout(function(){
let request = {
ticket: callGetTicketById(ticketId),
actions: callGetActionsByTicketId(ticketId)
};
djiinTaskManagement.checkIfTicketIsArchive(request.ticket);

var currentTicketIndex;
for (ticketIndex in declarationsAndQualifications[declarationKey][qualificationKey])
{
if (declarationsAndQualifications[declarationKey][qualificationKey][ticketIndex].id = ticketId)
{
if (displayMode == "CATEGORY")
{
request.ticket.categoryAnalyser = declarationsAndQualifications[declarationKey][qualificationKey][ticketIndex].categoryAnalyser;
}
declarationsAndQualifications[declarationKey][qualificationKey][ticketIndex] = request.ticket;
currentTicketIndex = ticketIndex;
break;
}
}

if (request.ticket != null && request.actions != null)
{
if (declarationsAndQualifications[declarationKey][qualificationKey][currentTicketIndex].extension.contact.hasNewMail == true)
{
declarationsAndQualifications[declarationKey][qualificationKey][currentTicketIndex].extension.contact.hasNewMail = false;
let ticketUpdate = djiinUtil.callService(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.ticket.request.update.v3",
declarationsAndQualifications[declarationKey][qualificationKey][currentTicketIndex],
false);
let dotItem = element.find('.dotNew');
dotItem.removeClass('isNewMail');
dotItem.addClass('isNotNewMail');
updateCategoryBadges(declarationId, qualificationId, declarationKey, qualificationKey);
}

// set title text
if (request.ticket.extension.contact.firstEmailSubject !== undefined)
{
$$("#sessionSelectionTitle").text(request.ticket.extension.contact.firstEmailSubject);
}
else
{
$$("#sessionSelectionTitle").text("");
}
$$("#sessionSelectionTitle").append(' <span class="ticketId">#' + request.ticket.id + '</span>');

let requestDisplay = '';
let currentAction;
let emailBodies = {};
let currentMailId;
//console.log(request.actions);
for (actionIndex in request.actions) {
currentAction = request.actions[actionIndex];
if (currentAction.typeActionId == communicationActionTypeId && currentAction.extension != undefined && currentAction.extension.sender != undefined)
{
let attachmentAction = null;
for (attachmentActionIndex in request.actions)
{
if (request.actions[attachmentActionIndex].typeActionId == communicationDetailActionTypeId &&
request.actions[attachmentActionIndex].hasOwnProperty('extension') &&
request.actions[attachmentActionIndex].extension.hasOwnProperty('communicationActionId') &&
request.actions[attachmentActionIndex].extension.communicationActionId == currentAction.id)
{
attachmentAction = request.actions[attachmentActionIndex];
break;
}
}
requestDisplay += createEmailDiv(currentAction.extension, attachmentAction, '_mail' + actionIndex, 0, 0, emailBodies);
//console.log(currentAction);
}
if (currentAction.typeActionId == categorizationActionTypeId)
{
requestDisplay +=
'<div class="panel panel-default action-categorisation">\n'+
'<div class="panel-body">\n' +
currentAction.creationDate +
djiinUtil.localize(' : Modification de la catégorisation "') +
djiinUtil.htmlEncode(currentAction.extension.categorisation.type) +
djiinUtil.localize('" à la nouvelle valeur "') +
djiinUtil.htmlEncode(djiinUtil.localize(currentAction.extension.categorisation, 'valeur')) + '"' +
'</div>\n' +
'</div>';
}
if (currentAction.typeActionId == historisationActionTypeId)
{
requestDisplay +=
'<div class="panel panel-default action-historisation">\n'+
'<div class="panel-body">\n' +
currentAction.creationDate +
djiinUtil.localize(' : Réouverture du ticket "') +
djiinUtil.htmlEncode(currentAction.extension.reopeningReason) + '"' +
'</div>\n' +
'</div>';
}
}
//console.log(request);

$$("#ticketDetailPanel").html(requestDisplay);
let shadowContainer;
for (currentMailId in emailBodies)
{
shadowContainer = $$('#shadowBody_' + currentMailId).get(0).attachShadow({mode: 'open'});
let mailContent = $$.parseHTML(emailBodies[currentMailId]);
for (subElement in mailContent) shadowContainer.appendChild(mailContent[subElement]);
}



}
else {
$$("#ticketDetailPanel").html(djiinUtil.info.language == 'fr' ? '<p> Erreur de chargement du fil de discussion. Veuillez contacter votre administrateur</p>' : '<p> Error while loading the discussion thread. Please contact your administrator</p>');
// set title text
$$("#sessionSelectionTitle").text("");
}
// activation des boutons khapp-traitement
if (isArchived)
{
$$("#ticketReopenButton").removeClass("hidden");
$$("#ticketTreatmentButton").addClass("hidden");
$$("#ticketDeleteButton").addClass("hidden");
$$("#ticketReleaseButton").addClass("hidden");
$$("#ticketReopenButton").attr('data-target', '/'+treatmentKHAppName+'.kha?contact.canal=Email&contact.email.action=REOPEN&contact.email.ticketToReopenId='+request.ticket.id);
$$("#ticketReopenButton").attr('data-target-options', JSON.stringify({declarationId: declarationId, qualificationId: qualificationId, declarationKey: declarationKey, qualificationKey: qualificationKey, ticketId: request.ticket.id}));
$$('#ticketInfoButton').attr('data-target-options', JSON.stringify({declarationId: declarationId, qualificationId: qualificationId, declarationKey: declarationKey, qualificationKey: qualificationKey, ticketId: request.ticket.id}));
}
else
{
$$("#ticketReopenButton").addClass("hidden");
// if (category.ticketHasToBeAssigned && ! category.ticketHasToBeAssignedToSelf)
// {
// $$("#ticketTreatmentButton").addClass("hidden");
// }
// else
// {
$$("#ticketTreatmentButton").removeClass("hidden");
// }
if(userRights.rightToUnassign && appointment.hasOwnProperty('affectedUserId')){
$$("#ticketReleaseButton").removeClass("hidden");
$$("#ticketReleaseButton").attr('data-target-options', JSON.stringify({declarationId: declarationId, qualificationId: qualificationId, declarationKey: declarationKey, qualificationKey: qualificationKey, ticketId: request.ticket.id}));
}else{
$$("#ticketReleaseButton").addClass("hidden");
}

if(userRights.rightToDelete){
$$("#ticketDeleteButton").removeClass("hidden");
$$("#ticketDeleteButton").attr('data-target-options', JSON.stringify({declarationId: declarationId, qualificationId: qualificationId, declarationKey: declarationKey, qualificationKey: qualificationKey, ticketId: request.ticket.id}));

}else{
$$("#ticketDeleteButton").addClass("hidden");
}
$$("#ticketTreatmentButton").attr('data-target', '/'+treatmentKHAppName+'.kha?ACTION_MODE=REPRISE&khmCtx_com.sereneo.session='+sessionId);
$$("#ticketTreatmentButton").attr('data-target-options', JSON.stringify({declarationId: declarationId, qualificationId: qualificationId, declarationKey: declarationKey, qualificationKey: qualificationKey, ticketId: request.ticket.id, sessionId: sessionId}));
$$('#ticketInfoButton').attr('data-target-options', JSON.stringify({declarationId: declarationId, qualificationId: qualificationId, declarationKey: declarationKey, qualificationKey: qualificationKey, ticketId: request.ticket.id}));
}
//'/TraitementClient.kha?REPLAY_MODE=true&REPLAY_MODE_CURRENT_SESSION_ID='+sessionId+'&ticketConsultation=true');
djiinSpinner.stop();
},100);
}

/**
* Get user rights
*/

function getUserRights(){
let proId = djiinUtil.info.currentUser.profile.id;
let profileSearchObject = {
id: proId
};
let profileInfo = djiinUtil.callService(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"intraneon.administration.profil.get.v1",
profileSearchObject,
false);
profileInfo = profileInfo.response;
let droits = profileInfo["droits"];
return droits;
}
/**
* Check to see if the user has the right to unassign and delete
*/

function checkUserRightsForUnassignOrDelete(action){
let droits = getUserRights();
let unassignAppointmentControllerId = "KHM_CAMPAIGN_RENDEZ_VOUS_UNASSIGN_LIST";
let deleteAppointmentControllerId = "KHM_CAMPAIGN_RENDEZ_VOUS_DELETE_LIST";
let rightToUnassign = false;
let rightToDelete = false;

for(var i=0; i < droits.length; i++){
if(droits[i].privilege == "FULL_ACCESS"){
rightToUnassign = true;
rightToDelete = true;
break;
}else if(droits[i].privilege == unassignAppointmentControllerId){
rightToUnassign = true;
}else if(droits[i].privilege == deleteAppointmentControllerId){
rightToDelete = true;
}
}
return {rightToUnassign, rightToDelete};
}

/**
* Selects this ticket and shows it.
*/
function showTicketDetail(element, campaignIndex, categoryIndex, ticketId)
{
if(element != null){
// select item and unselect others
element = tryToSelectTicketInList(element);
if (element == null) return; // already done, nothing to do
}
let displayCampaign = djiinTaskManagement.getCampaign(campaignIndex);
let category = djiinTaskManagement.getCategoryInCampaign(campaignIndex, categoryIndex);
document.getElementById("ticketDetailPanel").innerHTML = '';
djiinSpinner.start($$("#ticketDetailPanel"), 0);
setTimeout(async function(){
let request = {
status: "OK",
ticket: callGetTicketById(ticketId),
//actions: callGetActionsByTicketId(ticketId)
};
djiinTaskManagement.checkIfTicketIsArchive(request.ticket);

if (request.ticket != null)
{

if (request.ticket.extension.contact.hasNewMail == true)
{
request.ticket.extension.contact.hasNewMail = false;
let ticketUpdate = djiinUtil.callService(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.ticket.request.update.v3",
request.ticket,
false);
let dotItem = element.find('.dotNew');
dotItem.removeClass('isNewMail');
dotItem.addClass('isNotNewMail');
updateDisplayCampaignBadges(campaignIndex);
}

// set title text
if (request.ticket.extension.contact.firstEmailSubject !== undefined)
{
$$("#sessionSelectionTitle").text(request.ticket.extension.contact.firstEmailSubject);
}
else
{
$$("#sessionSelectionTitle").text("");
}
$$("#sessionSelectionTitle").append(' <span class="ticketId">#' + request.ticket.id + '</span>');
$$("#sessionSelectionTitle").append(' <span id="ticketLoadingBadge" style="font-size: 0.6em">'+(djiinUtil.info.language == 'fr' ? '<strong>En cours de chargement...</strong>' : '<strong>Loading...</strong>')+'</span>');

let requestDisplay = '';
let currentAction;
let emailBodies = {};
let currentMailId;
djiinUtil.log('Display Ticket', request);
if (showTicketInDetail)
{
djiinUtil.log('Display Ticket header');
let pluginRendering = djiinTaskManagement.plugins.renderTicketInDetail(request);
if (pluginRendering != undefined)
{
requestDisplay += '<!--Ticket Header-->' + pluginRendering;
}
else
{
requestDisplay += '<div>Ticket empty header</div>';
}
}
if (showActionsInDetail)
{
djiinUtil.log('Display Ticket actions');
// Retrieve all actions
let ticketActionsSearchObject = {
requestId: request.ticket.id,
searchExtension:[
],
pagination: {
resultCountPerPage: 2000,
pageIndex: 0
},
retrieveExtension: false
};

var allActions = [];

//console.log(ticketActionsSearchObject);
let ticketActions = djiinUtil.callService(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.ticket.action.getList.v2",
ticketActionsSearchObject,
false);
if (ticketActions == undefined) {
request.status = 'Actions KO -1/' + sessionId + '/'+djiinUtil.info.ncfiId;
}
if (ticketActions.code != 200) {
request.status = 'Actions KO c' + ticketActions.code + '/' + sessionId + '/'+djiinUtil.info.ncfiId;
}

allActions = ticketActions.response;

request.actions = new Map();


// Get all but communication or communication detail actions and retrieve extensions

let ticketActionsSearchObjectWithIds = {
id : [
],
searchExtension:[
],
requestId: request.ticket.id,
pagination: {
resultCountPerPage: 2000,
pageIndex: 0
},
retrieveExtension: true
};

allActions.forEach(function(item) {
request.actions.set(item.id, item);
if (ticketActionsSearchObjectWithIds.id.indexOf(item.id) == -1 && item.typeActionId != communicationDetailActionTypeId && item.typeActionId != communicationActionTypeId)
{
ticketActionsSearchObjectWithIds.id.push({value: item.id});
}
});

let ticketActionsByIds = djiinUtil.callServiceAsync(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.ticket.action.getList.v2",
ticketActionsSearchObjectWithIds,
false);
ticketActionsByIds.done((response) => {
let actions = response.response;
actions.forEach((item) => {
request.actions.set(item.id, item);
})
displayTicketActions(request);
})

let promisesList = [];

// Get Communication Actions By Id
getAllActionsOfType(communicationActionTypeId, request, promisesList);

// Get Communication Detail Actions By Id
getAllActionsOfType(communicationDetailActionTypeId, request, promisesList);
Promise.all(promisesList).then(() => {
var elem = document.getElementById("ticketLoadingBadge");
if(elem != null && elem.parentElement != undefined){
elem.parentElement.removeChild(elem);
}
document.getElementById("ticketSortButton").setAttribute("onClick", "javascript:sortActionDivs('DESC');");
document.getElementById("ticketSortButton").parentElement.classList.remove("disabled");
});
}
$$("#ticketDetailPanel").append(requestDisplay);
var elem = document.getElementById("ticketLoadingBadge");
if(elem != null && elem.parentElement != undefined){
elem.parentElement.removeChild(elem);
}
}
// activation des boutons khapp-traitement
if (request.ticket.isArchive)
{
$$("#ticketReopenButton").removeClass("hidden");
$$("#ticketTreatmentButton").addClass("hidden");
$$("#ticketDeleteButton").addClass("hidden");
$$("#ticketReleaseButton").addClass("hidden");
$$("#ticketReopenButton").attr('data-target', '/'+treatmentKHAppName+'.kha?contact.canal=Email&contact.email.action=REOPEN&contact.email.ticketToReopenId='+request.ticket.id);
$$("#ticketReopenButton").attr('data-target-options', JSON.stringify({campaignIndex: campaignIndex, categoryIndex: categoryIndex, ticketId: request.ticket.id}));
$$('#ticketInfoButton').attr('data-target-options', JSON.stringify({campaignIndex: campaignIndex, categoryIndex: categoryIndex, ticketId: request.ticket.id}));
}
else
{
$$("#ticketReopenButton").addClass("hidden");
let isProcessing = checkIfAppointmentHasAffectedUser(request.ticket.extension.contact.sessionId);
if ((category.ticketHasToBeAssigned && ! category.ticketHasToBeAssignedToSelf) || isProcessing)
{
$$("#ticketTreatmentButton").addClass("hidden");
}
else
{
$$("#ticketTreatmentButton").removeClass("hidden");
}

if(userRights.rightToUnassign && appointment.hasOwnProperty('affectedUserId')){
$$("#ticketReleaseButton").removeClass("hidden");
$$("#ticketReleaseButton").attr('data-target-options', JSON.stringify({campaignIndex: campaignIndex, categoryIndex: categoryIndex, ticketId: request.ticket.id}));
}else{
$$("#ticketReleaseButton").addClass("hidden");
}

if(userRights.rightToDelete){
$$("#ticketDeleteButton").removeClass("hidden");
$$("#ticketDeleteButton").attr('data-target-options', JSON.stringify({campaignIndex: campaignIndex, categoryIndex: categoryIndex, ticketId: request.ticket.id}));

}else{
$$("#ticketDeleteButton").addClass("hidden");
}
$$("#ticketTreatmentButton").attr('data-target', '/'+treatmentKHAppName+'.kha?ACTION_MODE=REPRISE&khmCtx_com.sereneo.session=' + request.ticket.extension.contact.sessionId);
$$("#ticketTreatmentButton").attr('data-target-options', JSON.stringify({campaignIndex: campaignIndex, categoryIndex: categoryIndex, ticketId: request.ticket.id, sessionId: request.ticket.extension.contact.sessionId}));
$$('#ticketInfoButton').attr('data-target-options', JSON.stringify({campaignIndex: campaignIndex, categoryIndex: categoryIndex, ticketId: request.ticket.id}));
}
djiinSpinner.stop();
},100);
}

function getAllActionsOfType(typeId, request, promisesList = null){
for(actionId of request.actions.keys()) {
let item = request.actions.get(actionId);
if (item.typeActionId == typeId)
{
let searchObject = {
id: item.id,
retrieveExtension: true
};
let promise = new Promise((resolve, reject) => {
let serviceCall = djiinUtil.callServiceAsync(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.ticket.action.get.v2",
searchObject,
false);
serviceCall.then((response) => {
let status;

if (response == undefined) {
status = 'Actions KO -1/'+djiinUtil.info.ncfiId;
djiinUtil.log('Status', status);
reject(status);
}
if (response.code != 200) {
status = 'Actions KO c' + response.code + '/' +djiinUtil.info.ncfiId;
djiinUtil.log('Status', status);
reject(status);
}
let action = response.response;
request.actions.set(item.id, action);
displayTicketActions(request);
resolve(response.response);
}).catch((error) => {
reject(error);
});
});
if(promisesList != null){
promisesList.push(promise);
}
}
}
}

async function displayTicketActions(request){
if (request.status == 'OK') {

let requestDisplay = '';
let currentAction;
let emailBodies = {};
let currentMailId;
djiinUtil.log('Display Ticket', request);
let actionIndex = 0;
for(actionId of request.actions.keys()) {
currentAction = request.actions.get(actionId);
if (currentAction.typeActionId == communicationActionTypeId && currentAction.extension != undefined && currentAction.extension.sender != undefined)
{
let attachmentAction = null;
for (attachmentActionIndex of request.actions.keys())
{
if (request.actions.get(attachmentActionIndex).typeActionId == communicationDetailActionTypeId &&
request.actions.get(attachmentActionIndex).hasOwnProperty('extension') &&
request.actions.get(attachmentActionIndex).extension.hasOwnProperty('communicationActionId') &&
request.actions.get(attachmentActionIndex).extension.communicationActionId == currentAction.id)
{
attachmentAction = request.actions.get(attachmentActionIndex);
break;
}
}
djiinUtil.log('action is mail', actionIndex);
if(attachmentAction == null){
requestDisplay += createEmailDivPlaceholder(currentAction.extension, '_mail' + actionIndex, 0);
}else{
requestDisplay += createEmailDiv(currentAction.extension, attachmentAction, '_mail' + actionIndex, 0, 0, emailBodies);
}

//console.log(currentAction);
}
if (currentAction.typeActionId == categorizationActionTypeId)
{
djiinUtil.log('action is categorisation', actionIndex);
requestDisplay +=
'<div class="panel panel-default action-categorisation">\n'+
'<div class="panel-body">\n' +
currentAction.creationDate +
djiinUtil.localize(' : Modification de la catégorisation "') +
djiinUtil.htmlEncode(currentAction.extension.categorisation.type) +
djiinUtil.localize('" à la nouvelle valeur "') +
djiinUtil.htmlEncode(djiinUtil.localize(currentAction.extension.categorisation, 'valeur')) + '"' +
'</div>\n' +
'</div>';
}
if (currentAction.typeActionId == historisationActionTypeId)
{
djiinUtil.log('action is historisation', actionIndex);
requestDisplay +=
'<div class="panel panel-default action-historisation">\n'+
'<div class="panel-body">\n' +
currentAction.creationDate +
(djiinUtil.info.language == 'fr' ? ' : Réouverture du ticket "' : ' : Reopening the ticket "') + djiinUtil.htmlEncode(currentAction.extension.reopeningReason) + '"' +
'</div>\n' +
'</div>';
}
actionIndex ++;
}
$$("#ticketDetailPanel").append(requestDisplay);
//console.log(request);
let shadowContainer;
for (currentMailId in emailBodies)
{
shadowContainer = $$('#shadowBody_' + currentMailId).get(0).attachShadow({mode: 'open'});
let mailContent = $$.parseHTML(emailBodies[currentMailId]);
for (subElement in mailContent) shadowContainer.appendChild(mailContent[subElement]);
}
}
else {
$$("#ticketDetailPanel").html((djiinUtil.info.language == 'fr' ? '<p> Erreur de chargement du fil de discussion. Veuillez contacter votre administrateur (statut : ' : '<p> Error while loading the discussion thread. Please contact your administrator (status : ') +
request.status +')</p>');
// set title text
$$("#sessionSelectionTitle").text("");
}
}

function sortActionDivs(direction){
// Inverting ticketDetailPanel children
var reverseTicketDetailPanel = Array.prototype.slice.call(document.getElementById("ticketDetailPanel").children, 0).reverse();
document.getElementById("ticketDetailPanel").innerHTML = '';
reverseTicketDetailPanel.forEach((node) => {
document.getElementById("ticketDetailPanel").appendChild(node);
});
// Changing buttons
if(direction == 'DESC'){
document.getElementById("ticketSortButton").innerHTML = (djiinUtil.info.language == 'fr' ? 'Tri croissant' : 'Ascending order') + '<i class="bi-arrow-up-short"></i>';
document.getElementById("ticketSortButton").setAttribute("onClick", "javascript:sortActionDivs('ASC')");
}else if(direction == 'ASC'){
document.getElementById("ticketSortButton").innerHTML = (djiinUtil.info.language == 'fr' ? 'Tri décroissant' : 'Descending order') + '<i class="bi-arrow-down-short"></i>';
document.getElementById("ticketSortButton").setAttribute("onClick", "javascript:sortActionDivs('DESC')");
}
}

/**
* Given an email content, builds an email div that is eventually returned
* using given parent email id and adding to the emailBodies list
* TODO
*/
function createEmailDiv(emailContent, attachmentAction, parentEmailId, currentIndex, currentRank, emailBodies)
{
djiinUtil.log(emailContent, attachmentAction, parentEmailId, currentIndex, currentRank, emailBodies);
let recipients = emailAddressesToString(emailContent.recipients);
recipients += emailAddressesToString(emailContent.to);
let replyTo = emailAddressesToString(emailContent.replyTo);
let cc = emailAddressesToString(emailContent.cc);
let bcc = emailAddressesToString(emailContent.bcc);
let currentMailId = parentEmailId + '_' + currentIndex;
emailBodies[currentMailId] = replaceBodyCIDWithBase64(emailContent, attachmentAction);
let attachmentLinks='';
let partIndex;
//console.log('attachment action associated with current communication action ', attachmentAction);
if (attachmentAction != null)
{

for (partIndex in attachmentAction.extension.part)
{
if (! attachmentAction.extension.part[partIndex].hasOwnProperty('contentId') || attachmentAction.extension.part[partIndex].contentId == '')
{
attachmentLinks += '<span class="badge"><a href="#" onclick="javascript: djiinUtil.downloadFile(\'' + djiinUtil.javascriptEncode(attachmentAction.extension.part[partIndex].name) +
'\', \'data:application/octet-stream;base64, ' + attachmentAction.extension.part[partIndex].content + '\');">' +
djiinUtil.htmlEncode(attachmentAction.extension.part[partIndex].name) +'</a></span> ';
}
}
for (attachmentIndex in attachmentAction.extension.attachments)
{
if (! attachmentAction.extension.attachments[attachmentIndex].hasOwnProperty('contentId') || attachmentAction.extension.attachments[attachmentIndex].contentId == '')
{
attachmentLinks += '<span class="badge"><a href="#" onclick="javascript: djiinUtil.downloadFile(\'' + djiinUtil.javascriptEncode(attachmentAction.extension.attachments[attachmentIndex].name) +
'\', \'data:application/octet-stream;base64, ' + attachmentAction.extension.attachments[attachmentIndex].content + '\');">' +
djiinUtil.htmlEncode(attachmentAction.extension.attachments[attachmentIndex].name) +'</a></span> ';
}
}
}
for (partIndex in emailContent.part)
{
if (! emailContent.part[partIndex].hasOwnProperty('contentId') || emailContent.part[partIndex].contentId == '')
{
attachmentLinks += '<span class="badge"><a href="#" onclick="javascript: djiinUtil.downloadFile(\'' + djiinUtil.javascriptEncode(emailContent.part[partIndex].name) +
'\', \'data:application/octet-stream;base64, ' + emailContent.part[partIndex].content + '\');">' +
djiinUtil.htmlEncode(emailContent.part[partIndex].name) +'</a></span> ';
}
}
for (attachmentIndex in emailContent.attachments)
{
if (! emailContent.attachments[attachmentIndex].hasOwnProperty('contentId') || emailContent.attachments[attachmentIndex].contentId == '')
{
attachmentLinks += '<span class="badge"><a href="#" onclick="javascript: djiinUtil.downloadFile(\'' + djiinUtil.javascriptEncode(emailContent.attachments[attachmentIndex].name) +
'\', \'data:application/octet-stream;base64, ' + emailContent.attachments[attachmentIndex].content + '\');">' +
djiinUtil.htmlEncode(emailContent.attachments[attachmentIndex].name) +'</a></span> ';
}
}

let returnValue = '<div class="panel panel-default">\n'+
'<div class="panel-heading">\n' +
'<div>' +
(currentRank > 0 ? '<strong>'+(djiinUtil.info.language == 'fr' ? 'Message lié' : 'Attached message')+'</strong><br/>' : '') +
(emailContent.direction == 'IN' || emailContent.direction == undefined ? (
(djiinUtil.info.language == 'fr' ? '<strong>De</strong> : ' : '<strong>From</strong>: ') + djiinUtil.htmlEncode(emailContent.sender) + ' <i class="bi-inbox" style="position: relative;top: 1;"><i class="bi-arrow-down-short" style="position: relative;left: -13;top: -4;margin-right:-12;"></i></i>') : '') +
(emailContent.direction == 'OUT' ? (
(djiinUtil.info.language == 'fr' ? '<strong>Pour</strong> : ' : '<strong>To</strong>: ') + djiinUtil.htmlEncode(recipients) + ' <i class="bi-inbox" style="position: relative;top: 1;"><i class="bi-arrow-up-short" style="position: relative;left: -13;top: -5;margin-right:-12;"></i></i>') : '') +
' ' +
(emailContent.canal == 'Email' ? '<i class="bi-envelope"></i>' : '') +
(djiinUtil.info.language == 'fr' ? '<br/><strong>Le</strong> : ' : '<br/><strong>On</strong>: ') + djiinUtil.htmlEncode(emailContent.date) +
'<button class="btn btn-default" type="button" data-toggle="collapse" data-target="#mailHeader' + currentMailId + '" aria-expanded="false" aria-controls="mailHeader' + currentMailId + '"><i class="bi-three-dots"></i></button>' +
'</div>' +
'<div aria-expanded="false" class="collapse" id="mailHeader' + currentMailId + '">' +
(emailContent.direction == 'OUT' ? (
(djiinUtil.info.language == 'fr' ? '<strong>De</strong> : ' : '<strong>From</strong>: ') + djiinUtil.htmlEncode(emailContent.sender)) : '') +
(emailContent.direction == 'IN' || emailContent.direction == undefined ? (
(djiinUtil.info.language == 'fr' ? '<strong>Pour</strong> : ' : '<strong>To</strong>: ') + djiinUtil.htmlEncode(recipients)) : '') +
(djiinUtil.info.language == 'fr' ? '<br/><strong>Copie</strong> : ' : '<br/><strong>CC</strong>: ') + djiinUtil.htmlEncode(cc) +
(djiinUtil.info.language == 'fr' ? '<br/><strong>Copie chachée</strong> : ' : '<br/><strong>BCC</strong>: ') + djiinUtil.htmlEncode(bcc) +
(djiinUtil.info.language == 'fr' ? '<br/><strong>Répondre à</strong> : ' : '<br/><strong>Reply to</strong>: ') + djiinUtil.htmlEncode(replyTo) +
(djiinUtil.info.language == 'fr' ? '<br/><strong>Sujet</strong> : ' : '<br/><strong>Subject</strong>: ') + djiinUtil.htmlEncode(emailContent.subject) +
'</div>\n' +
'</div>\n' +
'<div class="panel-body" id="shadowBody_' + currentMailId + '"></div>\n';
for (attachementEmailIndex in emailContent.attachedEmails)
{
returnValue += createEmailDiv(emailContent.attachedEmails[attachementEmailIndex], attachmentAction, currentMailId, attachementEmailIndex, currentRank + 1, emailBodies);
}
returnValue +=
'<div class="panel-footer"><i class="bi-paperclip"></i> ' +
attachmentLinks +
'</div>\n' +
'</div>';
return returnValue;
}

/**
* Placeholder for mail loading
*/
function createEmailDivPlaceholder(emailContent, parentEmailId, currentIndex)
{
djiinUtil.log(emailContent, parentEmailId, currentIndex);
let currentMailId = parentEmailId + '_' + currentIndex;
//console.log('attachment action associated with current communication action ', attachmentAction);

let returnValue = '<div class="panel panel-default">\n'+
'<div class="panel-heading">\n' +
'<div>'+
djiinUtil.htmlEncode(emailContent.date) + ': ' + (djiinUtil.info.language == 'fr' ? '<strong>En cours de chargement...</strong>' : '<strong>Loading...</strong>') +
'</div>' +
'</div>\n' +
'</div>\n';
return returnValue;
}

function emailAddressesToString(addressesArray)
{
let addressesAsString = '';
if (addressesArray != undefined) {
if (Array.isArray(addressesArray)) {
for (index in addressesArray) {
addressesAsString += (index > 0 ? ', ' : '') + addressesArray[index];
}
}
else
{
addressesAsString += addressesArray;
}
}
return addressesAsString;
}

function replaceBodyCIDWithBase64(emailContent, attachmentAction)
{
let body = emailContent.content;
if (body == undefined) body = emailContent.body;
if (body != undefined)
{
if (body.indexOf('<html') == -1 && body.indexOf('<meta') == -1 && body.indexOf('<div') == -1) body = "<html><body>" + djiinUtil.replaceAllInString(body, '\n', '<br/>') + "</body></html>";
let cidIndex;
let cid;
let partIndex;
let done;
const cidMarkup = 'src="cid:';
do {
cidIndex = body.indexOf(cidMarkup);
if (cidIndex != -1)
{
cid = body.substring(cidIndex + cidMarkup.length, body.indexOf('"', cidIndex + cidMarkup.length));
djiinUtil.log(cid);
done = false;
if (emailContent.part !== undefined)
{
for (partIndex in emailContent.part)
{
djiinUtil.log('recherche part', '<'+cid+'>' && ! done);
if (emailContent.part[partIndex].contentId == '<'+cid+'>' && ! done)
{
djiinUtil.log('trouvé part', partIndex, cidMarkup+cid+'"', 'src="data:'+emailContent.part[partIndex].mimeType);//+';base64, '+emailContent.part[partIndex].content+'"');
body = body.replace(cidMarkup+cid+'"', 'src="data:'+emailContent.part[partIndex].mimeType+';base64, '+emailContent.part[partIndex].content+'"');
done = true;
}
}
}
if (!done)
{
if (attachmentAction.extension.part !== undefined)
{
for (partIndex in attachmentAction.extension.part)
{
djiinUtil.log('recherche part action', '<'+cid+'>' && ! done);
if (attachmentAction.extension.part[partIndex].contentId == '<'+cid+'>' && ! done)
{
djiinUtil.log('trouvé part action', partIndex, cidMarkup+cid+'"', 'src="data:'+attachmentAction.extension.part[partIndex].mimeType);//+';base64, '+attachmentAction.extension.part[partIndex].content+'"');
body = body.replace(cidMarkup+cid+'"', 'src="data:'+attachmentAction.extension.part[partIndex].mimeType+';base64, '+attachmentAction.extension.part[partIndex].content+'"');
done = true;
}
}
}
}
if (!done)
{ // everything failed, we cannot display the picture so let's replace cid to break infinite loop
djiinUtil.log('pas trouvé part action', cidMarkup+cid+'"', 'brokencid');
body = body.replace(cidMarkup+cid+'"', 'src="brokencid:'+cid+'"');
done = true;
}
}
} while (cidIndex != -1);
}
else
{
if (djiinUtil.info.language == 'fr')
{
body = "<html><body><p>Mail attaché vide</p></body></html>";
}
else
{
body = "<html><body><p>Attached mail is empty</p></body></html>";
}
}
return body;
}

// loads actions associated with the ticket
function callGetActionsByTicketId(ticketId)
{

let ticketActionsSearchObject = {
requestId: ticketId,
searchExtension:[],
pagination: {
resultCountPerPage: 1000,
pageIndex: 0
}
};
let ticketActions = djiinUtil.callService(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.ticket.action.getList.v2",
ticketActionsSearchObject,
false);


if (ticketActions == undefined) {
djiinUtil.createModal('error-display-popup', false, 'Erreur', (djiinUtil.info.language == 'fr' ? '<h4>Erreur de chargement de ticket ' + ticketsSearchObject.id + '/' + sessionId + '/' + djiinUtil.info.ncfiId + ', veuillez réessayer. En cas d\'échec répété, vérifiez que vous êtes toujours connecté et rafraichissez la page. Si cela ne rétablit pas le chargement, contactez votre administrateur.</h4>' :
'<h4>Ticket ' + ticketsSearchObject.id + '/' + sessionId + '/' + djiinUtil.info.ncfiId + ' loading error , please retry. In case of persistent failure, please check that you are still connected and refresh the page. If it does not restore the loading, contact your administrator.</h4>'));
}
if (ticketActions.code != 200) {
djiinUtil.createModal('error-display-popup', false, 'Erreur', (djiinUtil.info.language == 'fr' ? '<h4>Erreur ' + ticketActions.code + '/' + sessionId + '/' + djiinUtil.info.ncfiId + ' de chargement de ticket ' + ticketsSearchObject.id + ', veuillez réessayer. En cas d\'échec répété, vérifiez que vous êtes toujours connecté et rafraichissez la page. Si cela ne rétablit pas le chargement, contactez votre administrateur.</h4>' :
'<h4>Ticket ' + ticketsSearchObject.id + ' loading error ' + tickets.code + '/' + sessionId + '/' + djiinUtil.info.ncfiId + ', please retry. In case of persistent failure, please check that you are still connected and refresh the page. If it does not restore the loading, contact your administrator.</h4>'));
}
else
{
return ticketActions.response;
}
djiinUtil.log('failed to load actions with criterion : ', ticketActionsSearchObject, ' and response : ', ticketActions, '/session ' + sessionId + ' /ncfiid ' + djiinUtil.info.ncfiId);
return null;
}

/**
* Deletes the ticket, the appointment, closes the session, and refreshes the campaign
*/
function releaseSelectedTicket(buttonElement)
{
if (! confirm((djiinUtil.info.language == 'fr' ? 'Vous allez désaffecter ce ticket, merci de bien vouloir confirmer !' : 'You are about to unassign this ticket, please confirm this operation first!'))) return;
let targetOptions = $$(buttonElement).attr('data-target-options');
targetOptions = JSON.parse(targetOptions);
releaseTicket(targetOptions);
}

/**
* Finds and releases the ticket and updates the category or declaration accordingly
*/
function releaseTicket(targetOptions)
{
var campaignIndex;
var categoryIndex;
if (displayMode == "CATEGORY")
{
for (currentTicketIndex in declarationsAndQualifications[targetOptions.declarationKey][targetOptions.qualificationKey])
{
if (targetOptions.ticketId == declarationsAndQualifications[targetOptions.declarationKey][targetOptions.qualificationKey][currentTicketIndex].id)
{
campaignIndex = declarationsAndQualifications[targetOptions.declarationKey][targetOptions.qualificationKey][currentTicketIndex].categoryAnalyser.campaignIndex;
categoryIndex = declarationsAndQualifications[targetOptions.declarationKey][targetOptions.qualificationKey][currentTicketIndex].categoryAnalyser.categoryIndex;
break;
}
}
}
else if (displayMode == "CAMPAIGN")
{
campaignIndex = targetOptions.campaignIndex;
categoryIndex = targetOptions.categoryIndex;
}
let displayCampaign = djiinTaskManagement.getCampaign(campaignIndex);
let category = djiinTaskManagement.getCategoryInCampaign(campaignIndex, categoryIndex);
// search the ticket
let ticket = null;
let ticketIndex = -1;
for (currentIndex in category.tickets)
{
if (category.tickets[currentIndex].id == targetOptions.ticketId)
{
ticketIndex = currentIndex;
ticket = category.tickets[currentIndex];
}
}
djiinUtil.log("ticket release ", campaignIndex, categoryIndex, ticketIndex, ticket);
// search the appointment
let appointmentSearchObject = {
campaignId: displayCampaign.campaignId,
dashboardId: displayCampaign.dashboardId,
objectId: ticket.extension.contact.sessionId
};
let appointments = djiinUtil.callService(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.calendar.appointment.getList.v1",
appointmentSearchObject,
false);
djiinUtil.log("appointments ", appointments);
// delete the appointment
let appointmentUpdateResult;
for (appointmentIndex in appointments.response)
{
let appointmentUpdateObject = appointments.response[appointmentIndex];
delete appointmentUpdateObject.affectedUserId;
appointmentUpdateResult = djiinUtil.callService(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.calendar.appointment.update.v1",
appointmentUpdateObject,
false);
}

if (displayMode == "CAMPAIGN")
{
// remove the ticket from the campaign and the panel
category.tickets.splice(ticketIndex, 1);
let panel = $$("#djiin_DC" + campaignIndex + "_C" + categoryIndex + "_panelList")[0];
panel.removeChild(panel.childNodes[ticketIndex]);
updateDisplayCampaignBadges(campaignIndex);
asyncReloadDisplayCampaign(campaignIndex, 0, Date.now()); // reload first category after unassignment
}
else if (displayMode == "CATEGORY")
{
new Promise(function(resolve, reject) {
asyncReloadAllDisplayCampaigns();
resolve();
}).then(function(result) {
showCategoryPanel(targetOptions.declarationId, targetOptions.qualificationId);
});
//updateCategoryBadges(targetOptions.declarationId, targetOptions.qualificationId, targetOptions.declarationKey, targetOptions.qualificationKey);
}
}

/**
* Deletes the ticket, the appointment, closes the session, and refreshes the campaign
*/
function deleteSelectedTicket(buttonElement)
{
if (! confirm((djiinUtil.info.language == 'fr' ? 'Vous allez supprimer définitivement ce ticket, merci de bien vouloir confirmer !' : 'You are about to delete this ticket for good, please confirm this operation first!'))) return;
let targetOptions = $$(buttonElement).attr('data-target-options');
targetOptions = JSON.parse(targetOptions);
var campaignIndex;
var categoryIndex;
if (displayMode == "CATEGORY")
{
for (currentTicketIndex in declarationsAndQualifications[targetOptions.declarationKey][targetOptions.qualificationKey])
{
if (targetOptions.ticketId == declarationsAndQualifications[targetOptions.declarationKey][targetOptions.qualificationKey][currentTicketIndex].id)
{
campaignIndex = declarationsAndQualifications[targetOptions.declarationKey][targetOptions.qualificationKey][currentTicketIndex].categoryAnalyser.campaignIndex;
categoryIndex = declarationsAndQualifications[targetOptions.declarationKey][targetOptions.qualificationKey][currentTicketIndex].categoryAnalyser.categoryIndex;
break;
}
}
}
else if (displayMode == "CAMPAIGN")
{
campaignIndex = targetOptions.campaignIndex;
categoryIndex = targetOptions.categoryIndex;
}
let displayCampaign = djiinTaskManagement.getCampaign(campaignIndex);
let category = djiinTaskManagement.getCategoryInCampaign(campaignIndex, categoryIndex);
// search the ticket
let ticket = null;
let ticketIndex = -1;
for (currentIndex in category.tickets)
{
if (category.tickets[currentIndex].id == targetOptions.ticketId)
{
ticketIndex = currentIndex;
ticket = category.tickets[currentIndex];
}
}
djiinUtil.log('DELETE ticket ' + ticket.id + ' :', campaignIndex, categoryIndex, ticketIndex, ticket);
// search the appointment
let appointmentSearchObject = {
campaignId: displayCampaign.campaignId,
dashboardId: displayCampaign.dashboardId,
objectId: ticket.extension.contact.sessionId
};
let appointments = djiinUtil.callService(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.calendar.appointment.getList.v1",
appointmentSearchObject,
false);
djiinUtil.log('DELETE ticket ' + ticket.id + ' :' + ' found appointments', appointments);
// delete the appointment
let appointmentDeletionResult;
for (appointmentIndex in appointments.response)
{
let appointmentDeleteObject = {
id: appointments.response[appointmentIndex].id
};
appointmentDeletionResult = djiinUtil.callService(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.calendar.appointment.delete.v1",
appointmentDeleteObject,
false);
djiinUtil.log('DELETE ticket ' + ticket.id + ' :' + ' appointment deleted', appointmentDeleteObject, appointmentDeletionResult);
}
// close the session
let sessionCloseObject = {
id: ticket.extension.contact.sessionId
};
let sessionClosureResult = djiinUtil.callService(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.khm.session.close.v1",
sessionCloseObject,
false);
djiinUtil.log('DELETE ticket ' + ticket.id + ' :' + ' session closed', sessionCloseObject, sessionClosureResult);
// close the ticket
let ticketCloseObject = {
id: ticket.id
};
let ticketClosureResult = djiinUtil.callService(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.ticket.request.closure.v1",
ticketCloseObject,
false);
djiinUtil.log('DELETE ticket ' + ticket.id + ' :' + ' ticket closed without archive', ticketCloseObject, ticketClosureResult);


if (displayMode == "CAMPAIGN")
{
// remove the ticket from the campaign and the panel
category.tickets.splice(ticketIndex, 1);
let panel = $$("#djiin_DC" + campaignIndex + "_C" + categoryIndex + "_panelList")[0];
djiinUtil.log(appointmentDeletionResult, sessionClosureResult, ticketCloseObject, "#djiin_DC" + campaignIndex + "_C" + categoryIndex + "_panelList", panel);
panel.removeChild(panel.childNodes[ticketIndex]);
updateDisplayCampaignBadges(campaignIndex);
}
else if (displayMode == "CATEGORY")
{
new Promise(function(resolve, reject) {
asyncReloadAllDisplayCampaigns();
resolve();
}).then(function(result) {
showCategoryPanel(targetOptions.declarationId, targetOptions.qualificationId);
});
//asyncReloadAllDisplayCampaigns();
//updateCategoryBadges(targetOptions.declarationId, targetOptions.qualificationId, targetOptions.declarationKey, targetOptions.qualificationKey);
//showCategoryPanel(targetOptions.declarationId, targetOptions.qualificationId);
}
}

/**
* this function actually closes the ticket and all associated info.
*/
function deleteTicket(ticketId, ticketExtensionNameToDelete, ticketExtensionNameToAdd, ticketExtensionValueToAdd)
{
let ticket = callGetTicketById(ticketId);
let extensionNameToDelete = ticketExtensionNameToDelete.trim();
let extensionNameToAdd = ticketExtensionNameToAdd.trim();
let extensionValueToAdd = ticketExtensionValueToAdd;
if (extensionNameToDelete != "" || extensionNameToDelete != "")
{
if (extensionNameToDelete != "") delete ticket.extension[extensionNameToDelete];
if (extensionNameToAdd != "") ticket.extension[extensionNameToAdd] = extensionValueToAdd;
let updateResult = callUpdateTicket(ticket);
djiinUtil.log("ticket update", ticket, updateResult);
}
deleteAppointmentsForSession(ticket.extension.contact.sessionId);
// close the session
let sessionCloseObject = {
id: ticket.extension.contact.sessionId
};
let sessionClosureResult = djiinUtil.callService(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.khm.session.close.v1",
sessionCloseObject,
false);
// close the ticket
let ticketCloseObject = {
id: ticket.id
};
let ticketClosureResult = djiinUtil.callService(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.ticket.request.closure.v1",
ticketCloseObject,
false);
djiinUtil.log("Ticket closed", ticket.id, ticket);
}

/**
* Deletes all appointment associated to the given session id
*/
function deleteAppointmentsForSession(sessionId)
{
// search the appointment
let appointmentSearchObject = {
dashboardId: dashboardId,
objectId: sessionId
};
let appointments = djiinUtil.callService(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.calendar.appointment.getList.v1",
appointmentSearchObject,
false);
djiinUtil.log("Appointments to delete", appointmentSearchObject, appointments);
// delete the appointment
for (appointmentIndex in appointments.response)
{
deleteAppointment(appointments.response[appointmentIndex].id);
}
}

/**
* Deletes an appointment.
*/
function deleteAppointment(appointmentId)
{
let appointmentDeleteObject = {
id: appointmentId
};
djiinUtil.log("Delete appointment", appointmentId);
let appointmentDeletionResult = djiinUtil.callService(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.calendar.appointment.delete.v1",
appointmentDeleteObject,
false);
}

/** Opens a popup div showing the session khapp for this element*/
function openKHAppModal(buttonElement)
{
let target = $$(buttonElement).attr('data-target');
let targetOptions = $$(buttonElement).attr('data-target-options');
targetOptions = JSON.parse(targetOptions);

var callBackFunction = function () {
djiinTaskManagement.plugins.onTreatmentWindowClosed(targetOptions);
showTicketDetail(null, targetOptions.campaignIndex, targetOptions.categoryIndex, targetOptions.ticketId);
asyncReloadDisplayCampaign(targetOptions.campaignIndex, targetOptions.categoryIndex, Date.now()); // reload as things must have changed
};
if (displayMode == "CATEGORY")
{

callBackFunction = function () {
new Promise(function(resolve, reject) {
djiinTaskManagement.plugins.onTreatmentWindowClosed(targetOptions);
asyncReloadAllDisplayCampaigns();
resolve();
}).then(function(result) {
showCategoryPanel(targetOptions.declarationId, targetOptions.qualificationId);
});
};
}
//console.log(buttonElement + ' - ' + target);
djiinUtil.createModal(
"khapp-traitement", // id
{width:98,height:98},
(djiinUtil.info.language == 'fr' ? 'Traitement de la demande' : 'Request processing'), // modal title
'<iframe id="sessionDetailIFrame" src="' + target + '" title="iframe" marginheight="0" marginwidth="0" width="100%" style="height: 100%;" frameborder="0"><p>Your browser does not support iframes.</p></iframe>', // content
null, // no close button
null, // no validate button
null, // no validate callback
callBackFunction
);
}

function showCategoryPanel(declarationId, qualificationId)
{
let declarationKey = getDeclarationNameById(declarationId);
let qualificationKey = getQualificationNameById(qualificationId);
// hide wait text
$$("#campaignSelectionAwaitingText").addClass("hidden");
// hide all but the selected campaign
let categoryNameSelector = "#djiin_D"+declarationId+"_Q"+qualificationId+"_panel";
$$(".displayCategoryTasks").addClass("hidden");
$$(".displayCampaignTasks").addClass("hidden");
$$(categoryNameSelector).removeClass("hidden");
// unselect all tasks
$$(".displayCategoryTasks .list-group-item").removeClass("active");
// no need to load search results, already been done
//if (campaignIndex != -1)
if (displayMode == "CAMPAIGN")
{
asyncReloadDisplayCampaign(campaignIndex, categoryIndex, Date.now() - 60000); // reload if data is old (> 1mn)
let category = djiinTaskManagement.getCategoryInCampaign(campaignIndex, categoryIndex);
whenVisible(category);
}
}

/**
* activates the display campaign category panel and populates it with tickets after the proper request has been issued
*/
function showDisplayCampaignCategoryPanel(campaignIndex, categoryIndex)
{
// hide wait text
$$("#campaignSelectionAwaitingText").addClass("hidden");
// hide all but the selected campaign
let campaignNameSelector = "#djiin_DC"+campaignIndex+"_C"+categoryIndex+"_panel";
$$(".displayCategoryTasks").addClass("hidden");
$$(".displayCampaignTasks").addClass("hidden");
$$(campaignNameSelector).removeClass("hidden");
// unselect all tasks
$$(".displayCampaignTasks .list-group-item").removeClass("active");
// no need to load search results, already been done
if (campaignIndex != -1)
{
asyncReloadDisplayCampaign(campaignIndex, categoryIndex, Date.now() - 60000); // reload if data is old (> 1mn)
let category = djiinTaskManagement.getCategoryInCampaign(campaignIndex, categoryIndex);
whenVisible(category);
}
}

function whenVisible(category){
djiinUtil.log("checking if element visible");
let item = $$("#"+category.domId + '_nextPageLoader');
if (item.length == 0)
{
//console.log("not found", e, this);
return;
}
//console.log("visible ?", item);
if (item.isOnScreen(true))
{
//console.log("yes visible");
//console.log("parent",$$('#'+category.domId+'_panelList'));
$$('#'+category.domId+'_panelList').off("scroll resize", category.whenVisible);
//$$(window).off("scroll resize", category.whenVisible);
//console.log("yes off");
loadNextTicketPage(category.campaignIndex, category.categoryIndex).then(() => {
//console.log("yes loaded", category.campaignIndex, category.categoryIndex);
item.remove();
//console.log("yes removed");
renderDisplayCampaignTaskListPanel(category.campaignIndex);
//reloadTicketFilteredResultsForCampaign(category.campaignIndex, category.campaignIndex);
//console.log("yes rendered", category.campaignIndex);
});
}
}

/**
* Reloads all display campaigns asynchronously
*/
function asyncReloadAllDisplayCampaigns()
{
//$$("#taskListsPanel .tasks-panel").empty();
//$$("#taskListsPanel .tasks-panel").remove(".displayCategoryTasks");

$$("#taskListsPanel .tasks-panel .displayCategoryTasks").not("#campaignSelectionAwaitingText").remove();

$$(".categorizationPanel").remove();
declarationsAndQualifications = new Object();
djiinSpinner.start($$("#taskListsPanel"), 0);
setTimeout(function() {
reloadAllDisplayCampaigns();
//djiinSpinner.stop();
}, 100);
}

/**
* Reloads all display campaigns
*/
let loadedCampaigns = 0;
//let campaignCategories = 0;
function reloadAllDisplayCampaigns()
{
let updateRequestTimestamp = Date.now();
for (displayCampaignIndex in djiinTaskManagement.displayCampaigns)
{
//campaignCategories += djiinTaskManagement.displayCampaigns[displayCampaignIndex].categories.length;
if(djiinTaskManagement.displayCampaigns[displayCampaignIndex].isArchive){
for (categoryIndex in djiinTaskManagement.displayCampaigns[displayCampaignIndex].categories)
{
//console.log(displayCampaignIndex, categoryIndex, djiinTaskManagement.displayCampaigns[displayCampaignIndex].libelle, djiinTaskManagement.displayCampaigns[displayCampaignIndex].categories[categoryIndex].name);
reloadDisplayCampaign(displayCampaignIndex, categoryIndex, updateRequestTimestamp).then(() => {
checkIfAllCampaignsLoaded();
}).catch(() => {
checkIfAllCampaignsLoaded();
});
}
}else{
reloadDisplayCampaign(displayCampaignIndex, 0, updateRequestTimestamp).then(() => {
checkIfAllCampaignsLoaded();
}).catch(() => {
checkIfAllCampaignsLoaded();
});
}
}
}

/**
* Checks if it finished loading all campaign categories
*/
function checkIfAllCampaignsLoaded(){
loadedCampaigns++;
if(loadedCampaigns == djiinTaskManagement.displayCampaigns.length) {
djiinSpinner.stop();
}
}

/**
* Loads asynchronously display campaign, and campaign tickets, then creates ticket DOM entries
*/
function asyncReloadDisplayCampaign(campaignIndex, categoryIndex, updateRequestTimestamp)
{
djiinSpinner.start($$("#taskListsPanel"), 0);
setTimeout(function() {
reloadDisplayCampaign(campaignIndex, categoryIndex, updateRequestTimestamp).then(() => {
djiinSpinner.stop();
});
}, 100);
}

/**
* Loads display campaign, and campaign tickets, then creates ticket DOM entries
*/
function reloadDisplayCampaign(campaignIndex, categoryIndex, updateRequestTimestamp)
{
//console.log("charge campagne",campaignIndex, categoryIndex, updateRequestTimestamp, djiinTaskManagement.displayCampaigns);
return new Promise((resolve, reject) => {
if (campaignIndex >=0) // otherwise it is a search result campaign and does not have to be reloaded
{
let displayCampaign = djiinTaskManagement.displayCampaigns[campaignIndex];
if (! displayCampaign.isSpecial)
{
if (! displayCampaign.isArchive)
{
reloadNonArchiveDisplayCampaign(campaignIndex, categoryIndex, updateRequestTimestamp).then(() => {
resolve()
});
}
else
{
reloadArchiveDisplayCampainCategory(campaignIndex, categoryIndex, updateRequestTimestamp);
resolve();
}
}else{
resolve();
}
}else{
resolve();
}
});

}

/**
* Loads archive display campaign tickets, then creates ticket DOM entries
*/
function reloadArchiveDisplayCampainCategory(campaignIndex, categoryIndex, updateRequestTimestamp)
{
let category = djiinTaskManagement.getCategoryInCampaign(campaignIndex, categoryIndex);
if (updateRequestTimestamp < category.lastUpdateTimestamp)
{
return; // nothing to do then, we are up to date
}
category.currentPageIndex = -1;
category.hasMoreEntries = true;
category.lastDisplayedIndex = -1;
category.tickets = undefined;
if (true)//(displayMode == "CAMPAIGN")
{
loadNextTicketPage(campaignIndex, categoryIndex).then(() => {
renderDisplayCampaignTaskListPanel(campaignIndex);
});
}
}

/**
* loads next result page for the given category.
*/
async function loadNextTicketPage(campaignIndex, categoryIndex)
{
let displayCampaign = djiinTaskManagement.getCampaign(campaignIndex);
let category = djiinTaskManagement.getCategoryInCampaign(campaignIndex, categoryIndex);
if (displayCampaign.isArchive)
{
let ticketSearchObject = {
name : "recherche-ticket-archive",
parameters : [
{
name: displayCampaign.extension.categorisation.source,
value: category.name
},
{
name: "resultCountPerPage",
value: archiveTicketPageSize
},
{
name: "pageIndex",
value: category.currentPageIndex + 1
}
]
};
let returnValue = await callCustomSqlRequestGetTicketList(ticketSearchObject, true);
djiinUtil.log("load archive ticket list", ticketSearchObject, returnValue);
tickets = returnValue.tickets;

if(isFilteringActivated){
filteredTickets = [];
tickets.forEach(ticket => {
if (djiinTaskManagement.plugins.checkTicketVisibility(ticket)) {
filteredTickets.push(ticket);
}
});
tickets = filteredTickets;
}
// Date format : 2020-10-19 19:55:11
//sortTicketList(tickets);
category.hasMoreEntries = tickets.length == archiveTicketPageSize;
category.currentPageIndex ++;
category.tickets = category.tickets == undefined ? tickets : category.tickets.concat(tickets);
category.lastUpdateTimestamp = Date.now();
}
}

async function callCustomSqlRequestGetTicketList (request, showErrorDialog)
{
Array.prototype.push.apply(request.parameters, djiinTaskManagement.buildTicketCustomSqlRequestSearchExtension());

let result = {
tickets : [],
status : 'OK',
errorCode : null
};
let tickets = await djiinUtil.callServiceAsync(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.administration.customSQLRequest.execute.v1",
request,
false);
//djiinUtil.log("load ticket list with request", request, tickets);
if (tickets == undefined) {
if (showErrorDialog)
{
djiinUtil.createModal('error-display-popup', false, 'Error', (djiinUtil.info.language == 'fr' ? '<h4>Erreur de chargement de la campagne, veuillez réessayer. En cas d\'échec répété, vérifiez que vous êtes toujours connecté et rafraichissez la page. Si cela ne rétablit pas le chargement, contactez votre administrateur.</h4>' :
'<h4>Campaign loading error, please retry. In case of persistent failure, please check that you are still connected and refresh the page. If it does not restore the loading, contact your administrator.</h4>'));
}
result.status = "ERROR";
}
else if (tickets.code != 200) {
if (showErrorDialog)
{
djiinUtil.createModal('error-display-popup', false, 'Error', (djiinUtil.info.language == 'fr' ? '<h4>Erreur ' + appointments.code + ' de chargement de la campagne, veuillez réessayer. En cas d\'échec répété, vérifiez que vous êtes toujours connecté et rafraichissez la page. Si cela ne rétablit pas le chargement, contactez votre administrateur.</h4>' :
'<h4>Campaign loading error ' + appointments.code + ', please retry. In case of persistent failure, please check that you are still connected and refresh the page. If it does not restore the loading, contact your administrator.</h4>'));
}
result.status = "ERROR";
result.errorCode = tickets.code;
}
else
{
result.tickets = tickets.response.results;
}
return result;
}


/**
* Loads non archive display campaign, and campaign tickets, then creates ticket DOM entries
*/
async function reloadNonArchiveDisplayCampaign(campaignIndex, categoryIndex, updateRequestTimestamp)
{
let displayCampaign = djiinTaskManagement.getCampaign(campaignIndex);
let category = djiinTaskManagement.getCategoryInCampaign(campaignIndex, categoryIndex);
if (updateRequestTimestamp < category.lastUpdateTimestamp)
{
return; // nothing to do then, we are up to date
}
let appointmentSearchObject = {
campaignId: displayCampaign.campaignId,
dashboardId: displayCampaign.dashboardId,
retrieveExtension: false
};
let appointments = await djiinUtil.callServiceAsync(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.calendar.appointment.getList.v1",
appointmentSearchObject,
false);
djiinUtil.log('reloadNonArchiveDisplayCampaign appointments', appointmentSearchObject, appointments);
if (appointments == undefined) {
djiinUtil.createModal('news-display-popup', false, (djiinUtil.info.language == 'fr' ? 'Information' : 'Information'),
(djiinUtil.info.language == 'fr' ? '<h4>Erreur de chargement de la campagne, veuillez réessayer. En cas d\'échec répété, vérifiez que vous êtes toujours connecté et rafraichissez la page. Si cela ne rétablit pas le chargement, contactez votre administrateur.</h4>' :
'<h4>Campaign loading error, please retry. In case of persistent failure, please check that you are still connected and refresh the page. If it does not restore the loading, contact your administrator.</h4>'));
return "ERROR";
}
if (appointments.code != 200) {
djiinUtil.createModal('news-display-popup', false, (djiinUtil.info.language == 'fr' ? 'Information' : 'Information'),
(djiinUtil.info.language == 'fr' ? '<h4>Erreur ' + appointments.code + ' de chargement de la campagne, veuillez réessayer. En cas d\'échec répété, vérifiez que vous êtes toujours connecté et rafraichissez la page. Si cela ne rétablit pas le chargement, contactez votre administrateur.</h4>' :
'<h4>Campaign loading error ' + appointments.code + ', please retry. In case of persistent failure, please check that you are still connected and refresh the page. If it does not restore the loading, contact your administrator.</h4>'));
return "ERROR";
}
//console.log(appointments);
appointments = appointments.response;

let appointmentsIds = new Array();
for (appointmentIndex in appointments)
{
var appointment = new Object();
appointment.id = appointments[appointmentIndex].id;
appointmentsIds.push(appointment);
}
let displaySourceValuesSearchObject = {
displayCampaignId: displayCampaign.id,
appointments: appointmentsIds
};
let displaySourcesValues = await djiinUtil.callServiceAsync(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.dashboard.displaysourceValues.getList.v1",
displaySourceValuesSearchObject,
false);
displaySourcesValues = displaySourcesValues.response;

let newTickets = [];
let assignedTickets = [];
let unavailableTickets = [];
let ticketIdsToSearch = [];
for (appointmentIndex in appointments)
{
let appointment = appointments[appointmentIndex];
for (sourceIndex in displaySourcesValues)
{
if (displaySourcesValues[sourceIndex].appointmentId == appointment.id)
{
appointment.displayData = new Object();
for (data in displaySourcesValues[sourceIndex].displaySourceData)
{
var fieldName = displaySourcesValues[sourceIndex].displaySourceData[data].displayName;
var fieldValue = displaySourcesValues[sourceIndex].displaySourceData[data].displayValue;
appointment.displayData[fieldName] = fieldValue;
if (fieldName == 'Ticket Id')
{
appointment.ticketId = parseInt(appointment.displayData['Ticket Id'], 10);
}
}
if (!isFilteringActivated || showUnavailableAppointmentsMode // in that case, keep all tickets
|| (appointment.hasOwnProperty('affectedUserId') && appointment.affectedUserId == currentUserId) // or this ticket is mine
|| ! appointment.hasOwnProperty('affectedUserId')) // or this ticket is unassigned
{
ticketIdsToSearch.push(appointment.ticketId);
}
break;
}
}
}
let ticketsSearchResult = await djiinTaskManagement.callGetTicketListByIds(ticketIdsToSearch, 0, ticketPageSize, true);
//console.log(ticketIdsToSearch, ticketsSearchResult);
if (ticketsSearchResult.status == 'ERROR')
{
return 'ERROR';
}
ticketsSearchResult = ticketsSearchResult.tickets;
// Unduely active appointments with closed tickets
let undulyActiveAppointmentsWithClosedTicketsLog = [];
let undulyClosedTicketsLog = [];
for (appointmentIndex in appointments)
{
for (ticketIndex in ticketsSearchResult)
{
if (ticketsSearchResult[ticketIndex].id == parseInt(appointments[appointmentIndex].displayData['Ticket Id'], 10))
{
if (appointments[appointmentIndex].hasOwnProperty('affectedUserId'))
{
if (appointments[appointmentIndex].affectedUserId == currentUserId || !isFilteringActivated)
{
assignedTickets.push(ticketsSearchResult[ticketIndex]);
}
else
{
unavailableTickets.push(ticketsSearchResult[ticketIndex]);
}
}
else
{
newTickets.push(ticketsSearchResult[ticketIndex]);
}
djiinTaskManagement.checkIfTicketIsArchive(ticketsSearchResult[ticketIndex]);
if (! displayCampaign.isArchive // should never be the case anyway here
&& ticketsSearchResult[ticketIndex].isArchive)
{
undulyActiveAppointmentsWithClosedTicketsLog.push(appointments[appointmentIndex].id);
undulyClosedTicketsLog.push(ticketsSearchResult[ticketIndex].id)
}
break;
}
}
}
djiinUtil.log('catégories filtrées pour', displayCampaign, newTickets, assignedTickets, newTickets, ticketsSearchResult)
if (undulyActiveAppointmentsWithClosedTicketsLog.length > 0)
{
console.log("Campaign \"" + displayCampaign.libelle + "\" has " + undulyActiveAppointmentsWithClosedTicketsLog.length + " unduly active appointments",
JSON.stringify(undulyActiveAppointmentsWithClosedTicketsLog), "with closed tickets", JSON.stringify(undulyClosedTicketsLog));
}
sortTicketList(newTickets);
sortTicketList(assignedTickets);
for (categoryIndex in displayCampaign.categories)
{
if (displayCampaign.categories[categoryIndex].ticketHasToBeAssigned)
{
if (displayCampaign.categories[categoryIndex].ticketHasToBeAssignedToSelf)
{
displayCampaign.categories[categoryIndex].tickets = assignedTickets;
}
else
{
displayCampaign.categories[categoryIndex].tickets = unavailableTickets;
}
}
if (! displayCampaign.categories[categoryIndex].ticketHasToBeAssigned)
{
displayCampaign.categories[categoryIndex].tickets = newTickets;
}
displayCampaign.categories[categoryIndex].currentPageIndex = 0;
displayCampaign.categories[categoryIndex].hasMoreEntries = false;
displayCampaign.categories[categoryIndex].lastDisplayedIndex = -1;
displayCampaign.categories[categoryIndex].lastUpdateTimestamp = Date.now();
}

category.currentPageIndex = 0;
category.hasMoreEntries = false;
category.lastDisplayedIndex = -1;
if (displayMode == "CAMPAIGN")
{
renderDisplayCampaignTaskListPanel(campaignIndex);
//for (categoryIndex in displayCampaign.categories)
//{
// reloadTicketFilteredResultsForCampaign(campaignIndex, categoryIndex);
//}
}
else if (displayMode == "CATEGORY")
{
renderSearchPanelForCategory();
renderCategorizedTaskListPanel(campaignIndex);
}
}

function renderSearchPanelForCategory()
{
if ($$("#taskListsPanel .tasks-panel #djiin_DC0_C0_panel").length == 0)
{
let searchPanel =
"<div id=\"djiin_DC0_C0_panel\" class=\"list-group displayCampaignTasks hidden\" style=\"margin: 0%; width:100%; height: 100%;\">"+
" <div class=\"panel-heading\" style=\"background-color: white;\">"+
" <h1 class=\"panel-title\" style=\"padding-top: 10px;padding-bottom: 10px;font-size: 18px;height: 1.1em;\">"+
" <span style=\"float: left;width: calc(100% - 5.75em);line-height: 1.25em;\" class=\"ellipsis\" title=\""+(djiinUtil.info.language=="fr"? "Recherche > Résultats" : (djiinUtil.info.language=="en"? "Search > Results" : ""))+"\">"+(djiinUtil.info.language=="fr"? "Recherche > Résultats" : (djiinUtil.info.language=="en"? "Search > Results" : ""))+" <span id=\"djiin_DC0_C0_panelBadge\" class=\"badge\">--</span></span>"+
" </h1>"+
" </div>"+
" <div id=\"djiin_DC0_C0_panelList\" style=\"overflow:auto; height: calc(100% - 39.8px);\">"+
" </div>"+
"</div>";
$$("#taskListsPanel .tasks-panel").append(searchPanel);
}
}

/**
* applies a decreasing date sort algorithm
*/
function sortTicketList(ticketList)
{
ticketList.sort(function (a, b){
var aDate = undefined;
var jsADate;
try
{
aDate = djiinUtil.getPropertyInTree(a, 'extension.contact.lastEmailReceptionDate');
if (aDate == undefined) aDate = a.creationDate;
// aDate = a.hasOwnProperty('extension') && a.extension.hasOwnProperty('contact') ? a.extension.contact.lastEmailReceptionDate : '1970-09-01 00:00:00';
jsADate = new Date(aDate.replace(' ', 'T')+'.000Z');
}
catch (error)
{
console.error(error, " -A- ", a);
jsADate = new Date('1970-09-01T00:00:00.000Z');
}
var bDate = undefined;
var jsBDate;
try
{
bDate = djiinUtil.getPropertyInTree(b, 'extension.contact.lastEmailReceptionDate');
if (bDate == undefined) bDate = a.creationDate;
// bDate = b.hasOwnProperty('extension') && b.extension.hasOwnProperty('contact') ? b.extension.contact.lastEmailReceptionDate : '1970-09-01 00:00:00';
jsBDate = new Date(bDate.replace(' ', 'T')+'.000Z');
}
catch (error)
{
console.error(error, " -B- ", a);
jsBDate = new Date('1970-09-01T00:00:00.000Z');
}
return jsBDate.getTime() - jsADate.getTime();
});
}

/**
* Render the previously unshown list elements given the campaign and the tickets contained within
*/
function renderDisplayCampaignTaskListPanel(campaignIndex)
{
$$(".displayCampaignPanel").css("display", "block");
let displayCampaign = djiinTaskManagement.getCampaign(campaignIndex);
for (categoryIndex in displayCampaign.categories)
{
let ticketDisplay = '';
let category = djiinTaskManagement.getCategoryInCampaign(campaignIndex, categoryIndex);
let tickets = category.tickets;
if (tickets == undefined)
{
tickets = [];
}
if (category.lastDisplayedIndex < tickets.length - 1 || tickets.length == 0)
{
//category.hasNewMail = false;

// this is the first filling, must empty before filling
if (category.lastDisplayedIndex == -1)
{
$$('#' + category.domId + '_panelList').empty();
}

category.ticketCount = tickets.length;
// Empty tickets
let emptyTicketsLog = [];
// Duplicate tickets
let duplicateTicketsLog = [];
for (let ticketIndex = category.lastDisplayedIndex + 1; ticketIndex < tickets.length; ticketIndex ++)
{
let ticket = tickets[ticketIndex];
djiinTaskManagement.checkIfTicketIsArchive(ticket);
let ticketLocation = {
campaignIndex: campaignIndex,
categoryIndex: categoryIndex
};
ticketDisplay +=
'<div data-ticket-id="' + ticket.id +
'" onclick="javascript:showTicketDetail(this, ' + ticketLocation.campaignIndex + ', ' + ticketLocation.categoryIndex + ', ' + ticket.id + ');" class="list-group-item row">' +
' <div class="col-12">' +
renderTicketListItem(ticketLocation, ticket, 'switchTicketIsNew(this, ' + ticketLocation.campaignIndex + ', ' + ticketLocation.categoryIndex + ', ' + ticket.id + ');') +
' </div>' +
'</div>';
if ((! tickets[ticketIndex].extension.hasOwnProperty('client') ||
tickets[ticketIndex].extension.client.email == undefined ||
tickets[ticketIndex].extension.client.email == null ||
tickets[ticketIndex].extension.client.email.trim() == '') ||
(! tickets[ticketIndex].extension.hasOwnProperty('contact') ||
tickets[ticketIndex].extension.contact.firstEmailSubject == undefined ||
tickets[ticketIndex].extension.contact.firstEmailSubject == null ||
tickets[ticketIndex].extension.contact.firstEmailSubject == ''))
{
emptyTicketsLog.push(tickets[ticketIndex].id);
}
let duplicateKey = (tickets[ticketIndex].extension.hasOwnProperty('client') ? tickets[ticketIndex].extension.client.email : undefined) +
' */* ' + (tickets[ticketIndex].extension.hasOwnProperty('contact') ? tickets[ticketIndex].extension.contact.firstEmailSubject : undefined) +
' */* ' + (tickets[ticketIndex].extension.hasOwnProperty('contact') ? tickets[ticketIndex].extension.contact.lastEmailReceptionDate : undefined);
if (! (duplicateKey in duplicateTicketsLog)) duplicateTicketsLog[duplicateKey] = {ids: []};
duplicateTicketsLog[duplicateKey].ids.push(tickets[ticketIndex].id);
}
//console.log("duplicate list before analysis", duplicateTicketsLog);
for (duplicateKey in duplicateTicketsLog) duplicateTicketsLog[duplicateKey].ids.sort();
let duplicateIds = [];
for (duplicateKey in duplicateTicketsLog)
{
for (idIndex in duplicateTicketsLog[duplicateKey].ids)
{
if (idIndex > 0)
{
duplicateIds.push(duplicateTicketsLog[duplicateKey].ids[idIndex]);
}
}
}
if (duplicateIds.length > 0)
{
console.log("Campaign \"" + displayCampaign.libelle + "\" \"" + category.name + "\" has " + duplicateIds.length + " duplicate tickets",
JSON.stringify(duplicateIds));
}
if (emptyTicketsLog.length > 0)
{
console.log("Campaign \"" + displayCampaign.libelle + "\" \"" + category.name + "\" has " + emptyTicketsLog.length + " empty tickets",
JSON.stringify(emptyTicketsLog));
}
if (category.ticketCount > 0)
{
$$('#'+category.domId+'_panelList').append(ticketDisplay);
}
else if (category.lastDisplayedIndex == -1)
{
$$('#'+category.domId+'_panelList').html(djiinUtil.info.language == 'fr' ? '<p style="text-align: center;padding-top: 2em;">Aucun dossier dans cette catégorie</p>' : '<p style="text-align: center;padding-top: 2em;">No file in this category</p>');
}
category.lastDisplayedIndex = tickets.length - 1;
if (category.hasMoreEntries)
{
$$('#'+category.domId+'_panelList').append(
'<div id="' + category.domId + '_nextPageLoader" class="list-group-item row">' +
' <div class="col-12">' +
' <span class="taskText ellipsis taskText-sender">' + (djiinUtil.info.language == 'fr' ? 'Chargement...' : 'Loading...') +
' </span>' +
' </div>' +
'</div>');
// console.log(category.domId, category.lastDisplayedIndex);
// console.trace();

category.campaignIndex = campaignIndex;
category.categoryIndex = categoryIndex;
category.loadingNextTicketPage = false;
category.whenVisible = function(e)
{
djiinUtil.log("checking if element visible");
let item = $$("#"+this.domId + '_nextPageLoader');
if (item.length == 0)
{
djiinUtil.log("not found", e, this);
return;
}
//console.log("visible ?", item);
if (item.isOnScreen(true))
{
category.loadingNextTicketPage = true;
//console.log("yes visible");
//console.log("parent",$$('#'+this.domId+'_panelList'));
$$('#'+this.domId+'_panelList').off("scroll resize", this.whenVisible);
//$$(window).off("scroll resize", this.whenVisible);
//console.log("yes off");
loadNextTicketPage(this.campaignIndex, this.categoryIndex).then(() => {
//console.log("yes loaded", this.campaignIndex, this.categoryIndex);
item.remove();
//console.log("yes removed");
renderDisplayCampaignTaskListPanel(this.campaignIndex);
category.loadingNextTicketPage = false;
//reloadTicketFilteredResultsForCampaign(this.campaignIndex, this.categoryIndex);
//console.log("yes rendered", this.campaignIndex);
});
}
}.bind(category); // to define "this" for this category object instance
$$('#'+category.domId+'_panelList').on("scroll resize", category.whenVisible);
category.whenVisible(); // to make sure it is called even if already displayed
//$$(window).on("scroll resize", category.whenVisible);
}
}
}
updateDisplayCampaignBadges(campaignIndex);
}

/**
* Update the global declarations/qualifications and its tickets with current campaign declarations/qualifications
*/
function updateGlobalDeclarationsAndQualifications(currentCampaignDeclarationsAndQualifications)
{
for (declarationKey in currentCampaignDeclarationsAndQualifications)
{
if (!declarationsAndQualifications.hasOwnProperty(declarationKey))
{
declarationsAndQualifications[declarationKey] = currentCampaignDeclarationsAndQualifications[declarationKey];
}
else
{
for (qualificationKey in currentCampaignDeclarationsAndQualifications[declarationKey])
{
if (!declarationsAndQualifications[declarationKey].hasOwnProperty(qualificationKey))
{
declarationsAndQualifications[declarationKey][qualificationKey] = currentCampaignDeclarationsAndQualifications[declarationKey][qualificationKey];
}
else
{
for (ticket of currentCampaignDeclarationsAndQualifications[declarationKey][qualificationKey])
{
var ticketDuplicate = false;
for (categoryTicketIndex in declarationsAndQualifications[declarationKey][qualificationKey])
{
if (declarationsAndQualifications[declarationKey][qualificationKey][categoryTicketIndex].id == ticket.id)
{
ticketDuplicate = true;
break;
}
}
if (!ticketDuplicate)
{
declarationsAndQualifications[declarationKey][qualificationKey].push(ticket);
}
}
}
}
}
}
djiinUtil.log(declarationsAndQualifications);
}

function addDeclarationIfNeeded(declarationName)
{
var addingNeeded = true;
for (index in declarationsMap)
{
if (declarationsMap[index].name == declarationName)
{
addingNeeded = false;
}
}
if (addingNeeded)
{
declarationsMap.push({id:declarationsMap.length,name:declarationName});
}
//console.log("declarationsMap", declarationsMap);
}

function addQualificationIfNeeded(qualificationName)
{
var addingNeeded = true;
for (index in qualificationsMap)
{
if (qualificationsMap[index].name == qualificationName)
{
addingNeeded = false;
}
}
if (addingNeeded)
{
qualificationsMap.push({id:qualificationsMap.length,name:qualificationName});
}
//console.log("qualificationsMap", qualificationsMap);
}

function getDeclarationNameById(declarationId)
{
for (declarationIndex in declarationsMap)
{
if (declarationsMap[declarationIndex].id == declarationId)
{
return declarationsMap[declarationIndex].name;
}
}
}

function getDeclarationIdByName(declarationName)
{
addDeclarationIfNeeded(declarationName);
for (declarationIndex in declarationsMap)
{
if (declarationsMap[declarationIndex].name == declarationName)
{
return declarationsMap[declarationIndex].id;
}
}
}

function getQualificationNameById(qualificationId)
{
for (qualificationIndex in qualificationsMap)
{
if (qualificationsMap[qualificationIndex].id == qualificationId)
{
return qualificationsMap[qualificationIndex].name;
}
}
}

function getQualificationIdByName(qualificationName)
{
addQualificationIfNeeded(qualificationName);
for (qualificationIndex in qualificationsMap)
{
if (qualificationsMap[qualificationIndex].name == qualificationName)
{
return qualificationsMap[qualificationIndex].id;
}
}
}

/**
* Render the previously unshown list elements given the campaign and the tickets contained within
*/
function renderCategorizedTaskListPanel(campaignIndex)
{
$$(".displayCampaignPanel").not(".archiveCampaign").remove();
let ticketDisplay = '';
var currentCampaignTickets = new Object();
currentCampaignTickets.assignedTickets = new Array();
currentCampaignTickets.unassignedTickets = new Array();
let displayCampaign = djiinTaskManagement.getCampaign(campaignIndex);
for (categoryIndex in displayCampaign.categories)
{
let category = djiinTaskManagement.getCategoryInCampaign(campaignIndex, categoryIndex);
if (category.tickets != undefined)
{
for (categTicketIndex in category.tickets)
{
category.tickets[categTicketIndex].categoryAnalyser = new Object();
category.tickets[categTicketIndex].categoryAnalyser.campaignIndex = campaignIndex;
category.tickets[categTicketIndex].categoryAnalyser.categoryIndex = categoryIndex;
let ticketDuplicate = false;
for (campaignTicketIndex in currentCampaignTickets)
{
if (currentCampaignTickets[campaignTicketIndex].id == category.tickets[categTicketIndex].id)
{
ticketDuplicate = true;
break;
}
}
if (!ticketDuplicate)
{
if (category.ticketHasToBeAssigned)
{
currentCampaignTickets.assignedTickets.push(category.tickets[categTicketIndex]);
}
else
{
currentCampaignTickets.unassignedTickets.push(category.tickets[categTicketIndex]);
}
}
}
}
}

var currentCampaignDeclarationsAndQualifications = new Object();
for (key in currentCampaignTickets)
{
for (ticketIndex in currentCampaignTickets[key])
{
let ticket = currentCampaignTickets[key][ticketIndex];
let declaration = "NA";
let qualification = "NA";
if (ticket.extension.contact.hasOwnProperty('categorisation'))
{
declaration = djiinUtil.localize(ticket.extension.contact.categorisation, 'declaration');
qualification = djiinUtil.localize(ticket.extension.contact.categorisation, 'qualification');
}
let declarationId = getDeclarationIdByName(declaration);
let qualificationId = getQualificationIdByName(qualification);

if (!currentCampaignDeclarationsAndQualifications.hasOwnProperty(declaration))
{
currentCampaignDeclarationsAndQualifications[declaration] = new Object();
currentCampaignDeclarationsAndQualifications[declaration][qualification] = new Array();
}
else
{
if (!currentCampaignDeclarationsAndQualifications[declaration].hasOwnProperty(qualification))
{
currentCampaignDeclarationsAndQualifications[declaration][qualification] = new Array();
}
}
currentCampaignDeclarationsAndQualifications[declaration][qualification].push(ticket);

djiinTaskManagement.checkIfTicketIsArchive(ticket);
let ticketLocation = {
declarationId: declarationId,
qualificationId: qualificationId,
campaignIndex: campaignIndex,
categoryIndex: categoryIndex,
campaignName: displayCampaign.libelle,
categoryName: (key == "assignedTickets" ? (djiinUtil.info.language == "fr" ? "Mes dossiers" : "My files") : (djiinUtil.info.language == "fr" ? "A traiter" : "Pending"))
}
let ticketRendering = '<div data-ticket-id="' + ticket.id +
'" onclick="javascript:showTicketDetailForCategory(this, \'' + declarationId + '\', \'' + qualificationId + '\', \'' + djiinUtil.javascriptEncode(declaration) + '\', \'' + djiinUtil.javascriptEncode(qualification) + '\', ' + ticket.id + ');" class="list-group-item row">' +
' <div class="col-12">' +
renderTicketListItem(ticketLocation, ticket,
'switchTicketIsNewForCategory(this, \'' + declarationId + '\', \'' + qualificationId + '\', \'' + djiinUtil.javascriptEncode(declaration) + '\', \'' + djiinUtil.javascriptEncode(qualification) + '\', ' + ticketId + ');') +
' </div>' +
'</div>';
$$("#djiin_D"+declarationId+"_Q"+qualificationId+"_panelList").append(ticketRendering);
}
}

updateGlobalDeclarationsAndQualifications(currentCampaignDeclarationsAndQualifications);
// rendering left side panel
for (declarationKey in currentCampaignDeclarationsAndQualifications)
{
let declarationId = getDeclarationIdByName(declarationKey);
let declarationTicketCount = 0;
for (qualificationKey in currentCampaignDeclarationsAndQualifications[declarationKey])
{
declarationTicketCount += currentCampaignDeclarationsAndQualifications[declarationKey][qualificationKey].length
}
// ajouter déclaration si n'existe pas
if ($$("#"+declarationId+"Panel").length == 0)
{
let declarationHasNewMail = false;
let declarationAndItsQualificationsHTML =
"<div id=\""+declarationId+"Panel\" class=\"panel panel-default categorizationPanel\" style=\"display: block;\">\n"+
" <div class=\"panel-heading\">\n"+
" <h4 class=\"panel-title menu-title\">\n"+
" <a class=\"accordion-toggle collapsed menu-entry\" data-toggle=\"collapse\" data-parent=\"#accordion\" href=\"#collapseCategorization"+declarationId+"\">"+declarationKey+" <span class=\"badge\" id=\"djiin_D"+declarationId+"_menuBadge\">"+declarationTicketCount+"</span><span class=\"dotNew\" id=\"djiin_D"+declarationId+"_menuDot\"></span></a>\n"+
" </h4>\n"+
" </div>\n"+
" <div id=\"collapseCategorization"+declarationId+"\" class=\"panel-collapse collapse\">\n"+
" <div class=\"panel-body\">\n"+
" <ul class=\"sub-menu-block\">\n";
for (qualificationKey in currentCampaignDeclarationsAndQualifications[declarationKey])
{
let qualificationHasNewMail = false;
for (ticket of currentCampaignDeclarationsAndQualifications[declarationKey][qualificationKey])
{
if (ticket.extension.contact.hasOwnProperty('hasNewMail') && ticket.extension.contact.hasNewMail)
{
qualificationHasNewMail = true;
declarationHasNewMail = true;
break;
}
}
let qualificationId = getQualificationIdByName(qualificationKey);
declarationAndItsQualificationsHTML +=
" <li id=\""+declarationId+"_"+qualificationId+"Entry\">\n"+
" <a class=\"menu-entry\" href=\"javascript:showCategoryPanel('"+declarationId+"', '"+qualificationId+"');\">\n"+
" "+qualificationKey+"\n"+
" <span class=\"badge\" id=\"djiin_D"+declarationId+"_Q"+qualificationId+"_menuBadge\">"+currentCampaignDeclarationsAndQualifications[declarationKey][qualificationKey].length+"</span>\n"+
" <span class=\"dotNew\" id=\"djiin_D"+declarationId+"_Q"+qualificationId+"_menuDot\"></span>\n"+
" </a>\n"+
" </li>\n";

let categoryPanel =
"<div id=\"djiin_D"+declarationId+"_Q"+qualificationId+"_panel\" class=\"list-group displayCategoryTasks hidden\" style=\"margin: 0%; width:100%; height: 100%;\">"+
" <div class=\"panel-heading\" style=\"background-color: white;\">"+
" <h1 class=\"panel-title\" style=\"padding-top: 10px;padding-bottom: 10px;font-size: 18px;height: 1.1em;\">"+
" <span style=\"float: left;width: calc(100% - 5.75em);line-height: 1.25em;\" class=\"ellipsis\" title=\""+djiinUtil.javascriptEncode(declarationKey)+" > "+ qualificationKey+"\">"+
" "+declarationKey+" > "+qualificationKey+
" <span class=\"badge\" id=\"djiin_D"+declarationId+"_Q"+qualificationId+"_panelBadge\" >"+currentCampaignDeclarationsAndQualifications[declarationKey][qualificationKey].length+"</span>"+
" </span>";
if (djiinTaskManagement.filters.length > 0)
{
categoryPanel +=
" <a href=\"#\" class=\"btn\" onclick=\"javascript:showFiltersUI(this)\" data-target-options=\"{&quot;declarationKey&quot;: &quot;"+declarationKey+"&quot;, &quot;qualificationKey&quot;: &quot;"+qualificationKey+"&quot;}\" style=\"width: 1em;\">"+
" &nbsp;<span class=\"bi-funnel-fill\" style=\"position: relative; left: -3px;\"></span>"+
" </a>"
}
// ALERTE $analyse.displayCampaigns.libelle$
djiinUtil.log("showNewButton",showNewButton);
if (showNewButton != "false" && showNewButton != "faux")
{
categoryPanel +=
" <a href=\"#\" class=\"btn\" onclick=\"javascript:openKHAppModal(this)\" data-target=\"/"+treatmentKHAppName+".kha?contact.canal=Email&contact.email.action=NEW&contact.email.targetCampaign=&contact.email.area=" +
djiinUtil.info.currentUser.userAnalysis.userContext.area + "&contact.email.userAnalysisJSON=" + encodeURIComponent(JSON.stringify(djiinUtil.info.currentUser.userAnalysis)) + "\" data-target-options=\"{&quot;declarationKey&quot;: &quot;"+declarationKey+"&quot;, &quot;qualificationKey&quot;: &quot;"+qualificationKey+"&quot;}\">"+
" "+(djiinUtil.info.language=="fr"?"Nouveau":(djiinUtil.info.language=="en"?"New":""))+"<i class=\"bi-file-earmark-plus\"></i>"+
" </a>";
}
categoryPanel +=
" </h1>"+
" </div>"+
" <div style=\"overflow:auto; height: calc(100% - 39.8px);\" id=\"djiin_D"+declarationId+"_Q"+qualificationId+"_panelList\" >"+
//" <p style=\"text-align: center;padding-top: 2em;\">"+
//" "+(djiinUtil.info.language=="fr"?"Aucun dossier dans cette catégorie":(djiinUtil.info.language=="en"?"No file in this category":""))+
//" </p>"+
" </div>"+
"</div>";
$$("#taskListsPanel .tasks-panel").append(categoryPanel);
if (qualificationHasNewMail)
{
$$("#djiin_D"+declarationId+"_Q"+qualificationId+"_menuDot").addClass('isNewMail');
}
else
{
$$("#djiin_D"+declarationId+"_Q"+qualificationId+"_menuDot").removeClass('isNewMail');
}
}
declarationAndItsQualificationsHTML +=
" </ul>\n"+
" </div>\n"+
" </div>\n"+
"</div>";
if ($$("#menu-bar .archiveCampaign").length > 0)
{
$$( "#menu-bar .archiveCampaign" ).first().before(declarationAndItsQualificationsHTML);
}
else
{
$$("#menu-bar .row").before(declarationAndItsQualificationsHTML);
}
if (declarationHasNewMail)
{
$$("#djiin_D"+declarationId+"_menuDot").addClass('isNewMail');
}
else
{
$$("#djiin_D"+declarationId+"_menuDot").removeClass('isNewMail');
}
}
// mettre à jour déclaration si déjà existante
else
{
let declarationHasNewMail = false;
for (qualificationKey in currentCampaignDeclarationsAndQualifications[declarationKey])
{
let qualificationHasNewMail = false;
for (ticket of currentCampaignDeclarationsAndQualifications[declarationKey][qualificationKey])
{
if (ticket.extension.contact.hasOwnProperty('hasNewMail') && ticket.extension.contact.hasNewMail)
{
qualificationHasNewMail = true;
declarationHasNewMail = true;
break;
}
}
let qualificationId = getQualificationIdByName(qualificationKey);
if ($$("#"+declarationId+"_"+qualificationId+"Entry").length == 0)
{
let qualificationsHTML =
" <li id=\""+declarationId+"_"+qualificationId+"Entry\" class=\""+declarationId+"Entry\">\n"+
" <a class=\"menu-entry\" href=\"javascript:showCategoryPanel('"+declarationId+"', '"+qualificationId+"');\">\n"+
" "+qualificationKey+"\n"+
" <span class=\"badge\" id=\"djiin_D"+declarationId+"_Q"+qualificationId+"_menuBadge\">"+currentCampaignDeclarationsAndQualifications[declarationKey][qualificationKey].length+"</span>\n"+
" <span class=\"dotNew\" id=\"djiin_D"+declarationId+"_Q"+qualificationId+"_menuDot\"></span>\n"+
" </a>\n"+
" </li>\n";
$$("#"+declarationId+"Panel ul").append(qualificationsHTML);

let categoryPanel =
"<div id=\"djiin_D"+declarationId+"_Q"+qualificationId+"_panel\" class=\"list-group displayCategoryTasks hidden\" style=\"margin: 0%; width:100%; height: 100%;\">"+
" <div class=\"panel-heading\" style=\"background-color: white;\">"+
" <h1 class=\"panel-title\" style=\"padding-top: 10px;padding-bottom: 10px;font-size: 18px;height: 1.1em;\">"+
" <span style=\"float: left;width: calc(100% - 5.75em);line-height: 1.25em;\" class=\"ellipsis\" title=\""+djiinUtil.javascriptEncode(declarationKey)+" > "+qualificationKey+"\">"+
" "+declarationKey+" > "+qualificationKey+
" <span class=\"badge\" id=\"djiin_D"+declarationId+"_Q"+qualificationId+"_panelBadge\" >"+currentCampaignDeclarationsAndQualifications[declarationKey][qualificationKey].length+"</span>"+
" </span>";
if (djiinTaskManagement.filters.length > 0)
{
categoryPanel +=
" <a href=\"#\" class=\"btn\" onclick=\"javascript:showFiltersUI(this)\" data-target-options=\"{&quot;declarationKey&quot;: &quot;"+declarationKey+"&quot;, &quot;qualificationKey&quot;: &quot;"+qualificationKey+"&quot;}\">"+
" &nbsp;<i class=\"bi-funnel-fill\" style=\"position: relative; left: -3px;\"></i>"+
" </a>"
}
if (showNewButton != "false" && showNewButton != "faux")
{
categoryPanel +=
" <a href=\"#\" class=\"btn\" onclick=\"javascript:openKHAppModal(this)\" data-target=\"/"+treatmentKHAppName+".kha?contact.canal=Email&contact.email.action=NEW&contact.email.targetCampaign=&contact.email.area=" +
djiinUtil.info.currentUser.userAnalysis.userContext.area + "&contact.email.userAnalysisJSON=" + encodeURIComponent(JSON.stringify(djiinUtil.info.currentUser.userAnalysis)) + "\" data-target-options=\"{&quot;declarationKey&quot;: &quot;"+declarationKey+"&quot;, &quot;qualificationKey&quot;: &quot;"+qualificationKey+"&quot;}\">"+
" "+(djiinUtil.info.language=="fr"?"Nouveau":(djiinUtil.info.language=="en"?"New":""))+"<i class=\"bi-file-earmark-plus\"></i>"+
" </a>";
}
categoryPanel +=
" </h1>"+
" </div>"+
" <div style=\"overflow:auto; height: calc(100% - 39.8px);\" id=\"djiin_D"+declarationId+"_Q"+qualificationId+"_panelList\" >"+
//" <p style=\"text-align: center;padding-top: 2em;\">"+
//" "+(djiinUtil.info.language=="fr"?"Aucun dossier dans cette catégorie":(djiinUtil.info.language=="en"?"No file in this category":""))+
//" </p>"+
" </div>"+
"</div>";
$$("#taskListsPanel .tasks-panel").append(categoryPanel);
let currentTicketCount = $$("#djiin_D"+declarationId+"_menuBadge").html();
currentTicketCount = parseInt(currentTicketCount, 10);
if (isNaN(currentTicketCount)) { currentTicketCount = 0; }
currentTicketCount+=declarationTicketCount;
$$("#djiin_D"+declarationId+"_menuBadge").html(currentTicketCount);
}
else
{
let currentTicketCount = $$("#djiin_D"+declarationId+"_C"+qualificationId+"_menuBadge").html();
currentTicketCount = parseInt(currentTicketCount, 10);
if (isNaN(currentTicketCount)) { currentTicketCount = 0; }
currentTicketCount+=declarationTicketCount;
$$("#djiin_D"+declarationId+"_C"+qualificationId+"_menuBadge").html(currentTicketCount);
$$("#djiin_D"+declarationId+"_C"+qualificationId+"_panelBadge").html(currentTicketCount);
}
if (qualificationHasNewMail)
{
$$("#djiin_D"+declarationId+"_Q"+qualificationId+"_menuDot").addClass('isNewMail');
}
else
{
$$("#djiin_D"+declarationId+"_Q"+qualificationId+"_menuDot").removeClass('isNewMail');
}
}
if (declarationHasNewMail)
{
$$("#djiin_D"+declarationId+"_menuDot").addClass('isNewMail');
}
else
{
$$("#djiin_D"+declarationId+"_menuDot").removeClass('isNewMail');
}
}
}
hoverSubMenus();
}

/**
* Updates display campaign badges and dots only (no reload of tickets or list display updates)
*/
function updateCategoryBadges(declarationId, qualificationId, declarationKey, qualificationKey)
{
let hasMoreEntries = false;
let declarationHasNewMail = false;
let declarationTicketCount = 0;
let qualificationHasNewMail = false;
let qualificationTicketCount = declarationsAndQualifications[declarationKey][qualificationKey].length;
for (ticket of declarationsAndQualifications[declarationKey][qualificationKey])
{
if (ticket.extension.contact.hasNewMail == true)
{
qualificationHasNewMail = true;
break;
}
}
for (qualificationKey in declarationsAndQualifications[declarationKey])
{
for (ticket of declarationsAndQualifications[declarationKey][qualificationKey])
{
declarationTicketCount++;
if (ticket.extension.contact.hasNewMail == true)
{
declarationHasNewMail = true;
}
}
}

djiinUtil.log(declarationsAndQualifications[declarationKey][qualificationKey]);
$$("#djiin_D"+declarationId+"_menuBadge").html(declarationTicketCount);
$$("#djiin_D"+declarationId+"_Q"+qualificationId+"_panelBadge").html(qualificationTicketCount);
$$("#djiin_D"+declarationId+"_Q"+qualificationId+"_menuBadge").html(qualificationTicketCount);

if (declarationHasNewMail)
{
$$("#djiin_D"+declarationId+"_menuDot").addClass('isNewMail');
}
else
{
$$("#djiin_D"+declarationId+"_menuDot").removeClass('isNewMail');
}
if (qualificationHasNewMail)
{
$$("#djiin_D"+declarationId+"_Q"+qualificationId+"_menuDot").addClass('isNewMail');
}
else
{
$$("#djiin_D"+declarationId+"_Q"+qualificationId+"_menuDot").removeClass('isNewMail');
}
}

/**
* Updates display campaign badges and dots only (no reload of tickets or list display updates)
*/
function updateDisplayCampaignBadges(campaignIndex)
{
let displayCampaign = djiinTaskManagement.displayCampaigns[campaignIndex];
displayCampaign.ticketCount = 0;
displayCampaign.hasMoreEntries = false;
displayCampaign.hasNewMail = false;

for (categoryIndex in displayCampaign.categories)
{
let ticketDisplay = '';
let category = displayCampaign.categories[categoryIndex];
let panel = $$('#'+category.domId+'_panel');
let tickets = category.tickets;
if (tickets == undefined)
{
tickets = [];
}
category.hasNewMail = false;
category.ticketCount = 0;
for (ticketIndex in tickets)
{
let ticket = tickets[ticketIndex];
let ticketItem = panel.find('.list-group-item[data-ticket-id="' + ticket.id + '"]');
ticketItem.addClass('hidden');
if (displayCampaign.isSpecial || displayCampaign.isArchive)
{
ticket.matchesFilters = true;
}
else
{
djiinTaskManagement.checkIfTicketMatchesFilters(ticket);
}
if (ticket.matchesFilters)
{
category.ticketCount ++;
let hasNewMail = tickets[ticketIndex].extension.contact.hasOwnProperty('hasNewMail') && tickets[ticketIndex].extension.contact.hasNewMail;
category.hasNewMail = category.hasNewMail || hasNewMail;
ticketItem.removeClass('hidden');
}
}
displayCampaign.ticketCount += category.ticketCount;
displayCampaign.hasMoreEntries = displayCampaign.hasMoreEntries || category.hasMoreEntries;
displayCampaign.hasNewMail = category.hasNewMail || displayCampaign.hasNewMail;
$$('#'+category.domId+'_menuBadge').html(category.ticketCount + (category.hasMoreEntries ? '+' : ''));
$$('#'+category.domId+'_panelBadge').html(category.ticketCount + (category.hasMoreEntries ? '+' : ''));
if (category.hasNewMail)
{
$$('#'+category.domId+'_menuDot').addClass('isNewMail');
}
else
{
$$('#'+category.domId+'_menuDot').removeClass('isNewMail');
}
}
$$('#'+displayCampaign.domId+'_menuBadge').html(displayCampaign.ticketCount + (displayCampaign.hasMoreEntries ? '+' : ''));
if (displayCampaign.hasNewMail)
{
$$('#'+displayCampaign.domId+'_menuDot').addClass('isNewMail');
}
else
{
$$('#'+displayCampaign.domId+'_menuDot').removeClass('isNewMail');
}
}


/**
* creates the dom element source code to display the given ticket info inside of a ticket list
*/
function renderTicketListItem(ticketLocation, ticket, isNewSwitchListener)
{
let pluginRendering = djiinTaskManagement.plugins.renderTicketListItem(ticketLocation, ticket, isNewSwitchListener);
if (pluginRendering != undefined) return pluginRendering;

let ticketId = ticket.id;
let sender = ticket.extension.hasOwnProperty('client') ? ticket.extension.client.email : undefined;
let receptionDate = ticket.extension.hasOwnProperty('contact') ? ticket.extension.contact.lastEmailReceptionDate : undefined;
let subject = ticket.extension.hasOwnProperty('contact') ? ticket.extension.contact.firstEmailSubject : undefined;
let channel = ticket.extension.hasOwnProperty('contact') ? ticket.extension.contact.canal : undefined;
let hasNewMail = ticket.extension.hasOwnProperty('contact') && ticket.extension.contact.hasOwnProperty('hasNewMail') && ticket.extension.contact.hasNewMail;
let declaration = ticket.extension.contact.hasOwnProperty('categorisation') ? djiinUtil.localize(ticket.extension.contact.categorisation, 'declaration') : undefined;
let qualification = ticket.extension.contact.hasOwnProperty('categorisation') ? djiinUtil.localize(ticket.extension.contact.categorisation, 'qualification') : undefined;
let action = ticket.extension.contact.hasOwnProperty('categorisation') ? djiinUtil.localize(ticket.extension.contact.categorisation, 'action') : undefined;
let important = ticket.extension.contact.hasOwnProperty('categorisation') && ticket.extension.contact.categorisation.hasOwnProperty('important') && ticket.extension.contact.categorisation.important;
let isArchive = ticket.isArchive;
let dueDate = undefined;
let to = djiinUtil.getPropertyInTree(ticket.extension, 'contact.tags.to');

let safeReceptionDate;
try
{
safeReceptionDate = receptionDate.substring(0, receptionDate.length - 3);
}
catch (error)
{
safeReceptionDate = '1970-09-01 00:00';
}
let formattedSender = djiinUtil.htmlEncode(sender);
let formattedSenderTooltip = djiinUtil.javascriptEncode(formattedSender);
if (sender == undefined || sender == null || sender.trim() == '')
{
formattedSenderTooltip = djiinUtil.localize('Emetteur inconnu');
formattedSender = '<span class="undefined-ticket-value">&lt;' + formattedSenderTooltip + '&gt;</span>';
}
let formattedSubject = djiinUtil.htmlEncode(subject);
let formattedSubjectTooltip = djiinUtil.javascriptEncode(djiinUtil.htmlEncode('#' + ticketId + ' - ' + subject));
if (subject == undefined || subject == null || subject == '')
{
formattedSubject = (djiinUtil.info.language == 'fr' ? '<span class="undefined-ticket-value">&lt;Sujet vide&gt;</span>' : '<span class="undefined-ticket-value">&lt;Empty subject&gt;</span>');
formattedSubjectTooltip = '#' + ticketId + (djiinUtil.info.language == 'fr' ? ' - Sujet vide' : ' - Empty subject');
}

return ' <span class="taskText ellipsis taskText-sender" title="' + formattedSenderTooltip + '"><i class="bi-envelope"></i>&nbsp;' + formattedSender +
' </span>' +
' <span class="taskText taskText-date">' + safeReceptionDate +
' </span>' +
' <span class="taskText ellipsis taskText-subject" title="' + formattedSubjectTooltip + '">' + formattedSubject +
' </span>' +
' <span class="dotNew ' + (! hasNewMail ? 'isNotNewMail' : 'isNewMail') + '" onclick="javascript:' + isNewSwitchListener + '"></span>' +
' <span class="taskText taskText-badges">' +
' <span class="badge">' + (displayMode == "CATEGORY" ? djiinUtil.htmlEncode(ticketLocation.campaignName != undefined ? ticketLocation.campaignName : 'NA') : djiinUtil.htmlEncode(declaration != undefined ? declaration : 'NA')) +
' </span> ' +
' <span class="badge">' + (displayMode == "CATEGORY" ? djiinUtil.htmlEncode(ticketLocation.categoryName != undefined ? ticketLocation.categoryName : 'NA') : djiinUtil.htmlEncode(qualification != undefined ? qualification : 'NA')) +
' </span> ' +
' <span class="badge">' + djiinUtil.htmlEncode(action != undefined ? action : 'NA') +
' </span> ' +
(isArchive ? '<span class="bi bi-lock-fill" aria-hidden="true" style="vertical-align: middle;" title="' + djiinUtil.localize('Archivé') + '"></span>' : '') +
(important ? '<span class="bi bi-exclamation-triangle-fill" style="color:red; vertical-align: middle;" title="' + djiinUtil.localize('Important') + '"></span>' : '') +
(dueDate != undefined && dueDate != null && dueDate != 'N/A' ? (djiinUtil.info.language == 'fr' ? ' Echéance : ' : ' Due date : ') + dueDate.split(' ')[0] : '') +
' </span>';
}

/**
* Shows the news panel
*/
function showNews(active)
{
let portalSearchObject = {
name: portalName
};
let portals = djiinUtil.callService(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.khm.portal.getList.v1",
portalSearchObject,
false);
if (portals == undefined) {
djiinUtil.createModal('news-display-popup', true, (djiinUtil.info.language == 'fr' ? 'News' : 'News'), (djiinUtil.info.language == 'fr' ? '<h4>Erreur de chargement du portail</h4>' : '<h4>Error while loading the portal</h4>'));
return "ERROR";
}
if (portals.code != 200) {
djiinUtil.createModal('news-display-popup', true, (djiinUtil.info.language == 'fr' ? 'News' : 'News'), (djiinUtil.info.language == 'fr' ? '<h4>Erreur ' + portals.code + ' de chargement du portail</h4>' : '<h4>Error ' + portals.code + ' while loading the portal</h4>'));
return "ERROR";
}
var portal;
for (portalIndex in portals.response)
{
if (portals.response[portalIndex].name == portalName)
{
portal = portals.response[portalIndex];
}
}
let newsSearchObject = {
associatedPortals: portal.id,
active: active
};
let news = djiinUtil.callService(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.khm.news.getList.v1",
newsSearchObject,
false);
if (news == undefined) {
djiinUtil.createModal('news-display-popup', true, (djiinUtil.info.language == 'fr' ? 'News' : 'News'), (djiinUtil.info.language == 'fr' ? '<h4>Erreur de chargement des news</h4>' : '<h4>Error while loading the news</h4>'));
return "ERROR";
}
if (news.code != 200) {
djiinUtil.createModal('news-display-popup', true, (djiinUtil.info.language == 'fr' ? 'News' : 'News'), (djiinUtil.info.language == 'fr' ? '<h4>Erreur ' + portals.code + ' de chargement des news</h4>' : '<h4>Error ' + news.code + ' while loading the news</h4>'));
return "ERROR";
}
let newsDisplay = "";
for (newsIndex in news.response)
{
let author = "";
if (news.response[newsIndex].hasOwnProperty('extension') && news.response[newsIndex].extension.hasOwnProperty('createdByName'))
{
author = (djiinUtil.info.language == 'fr' ? ' <strong>par : </strong>' : ' <strong>by: </strong>') + news.response[newsIndex].extension.createdByName;
}
newsDisplay += '<div class="well"><p>' +
(djiinUtil.info.language == 'fr' ? '<strong>Sujet : </strong>' : '<strong>Subject: </strong>') + news.response[newsIndex].subject + '&nbsp;<br/>' +
(djiinUtil.info.language == 'fr' ? '<strong>Créée le : </strong>' : '<strong>Created on: </strong>') + news.response[newsIndex].creationDate + author + '&nbsp;<br/>' +
(djiinUtil.info.language == 'fr' ? '<strong>Diffusion de : </strong>' : '<strong>Published since: </strong>') + news.response[newsIndex].firstDiffusionDate +
(djiinUtil.info.language == 'fr' ? '<strong> à : </strong>' : '<strong> until: </strong>') + news.response[newsIndex].lastDiffusionDate + '&nbsp;<br/>' +
(djiinUtil.info.language == 'fr' ? '<strong>News : </strong>' : '<strong>News: </strong>') + '&nbsp;<br/></p>' +
news.response[newsIndex].formatedContent +
'</div>';
}
djiinUtil.createModal('news-display-popup', true,
(djiinUtil.info.language == 'fr' ? 'News' : 'News'),
'<h4>' + (active ?
(djiinUtil.info.language == 'fr' ? 'Liste des news actives. <a href="#" data-dismiss="modal" onclick="javascript: showNews(false);" style="margin-left:30px;">[Voir les news passées]</a>' : 'Active news list. <a href="#" data-dismiss="modal" onclick="javascript: showNews(false);" style="margin-left:30px;">[See outdated news]</a>') :
(djiinUtil.info.language == 'fr' ? 'Liste des news passées. <a href="#" data-dismiss="modal" onclick="javascript: showNews(true);" style="margin-left:30px;">[Voir les news actives]</a>' : 'Outdated news list. <a href="#" data-dismiss="modal" onclick="javascript: showNews(true);" style="margin-left:30px;">[See active news]</a>')) +
'</h4>' +
newsDisplay);
}

function showFiltersUI(element)
{
var modalContent =
'<div class="row form-horizontal">' +
' <h3 class="side-margin">' + (djiinUtil.info.language == 'fr' ? 'Filtrage des fils de discussions' : 'Thread filtering') + '</h3>' +
' <h4 class="side-margin bottom-space">' + (djiinUtil.info.language == 'fr' ? 'Saisie des critères' : 'Criteria input') + '</h4>' +
' <p class="side-margin bottom-space">' +
(djiinUtil.info.language == 'fr' ? 'Veuillez saisir des critères de filtrages les plus précis possible. Les résultats filtrés s\'afficheront dans la campagne actuelle.' :
'Please type in filter criteria that are as accurate as possible. The filtered results will be displayed in the current campaign.') +
'</p>' +
'</div>';
for (filterIndex in djiinTaskManagement.filters)
{
let filter = djiinTaskManagement.filters[filterIndex];
modalContent +=
'<div class="row form-horizontal">'+
' <div class="form-group side-margin">' +
' <div class="col-sm-3" style="font-weight: bold">' + (djiinUtil.info.language == 'fr' ? filter.label+' :' : filter["label-en"]+' :') + ' </div>' +
' <div class="col-sm-9"><INPUT id="ticketFilter'+filterIndex+'" name="ticketFilter'+filter.extensionName+'" value="'+(filter.hasOwnProperty("userCriterion") ? filter.userCriterion : "")+'" class="form-control"></div>' +
' </div>' +
'</div>';
}
djiinUtil.createModal('ticket-filter-popup', false, (djiinUtil.info.language == 'fr' ? 'Filtres' : 'Filters'),
modalContent,
(djiinUtil.info.language == 'fr' ? 'Annuler' : 'Cancel'),
(djiinUtil.info.language == 'fr' ? 'Filtrer' : 'Filter'),
function() {
// update user criterion
for (filterIndex in djiinTaskManagement.filters)
{
let ticketFilter = $$('#ticketFilter'+filterIndex).val().trim();
djiinTaskManagement.filters[filterIndex].userCriterion = ticketFilter;
}
for (campaignIndex in djiinTaskManagement.displayCampaigns) updateDisplayCampaignBadges(campaignIndex);//loadTicketFilteredResults(element)
});
}


/**
* Actually loads tickets search results
*/
async function loadTicketSearchResults()
{
let fieldElement;
for (criterionIndex in djiinTaskManagement.searchCriteria)
{
let fieldElement = $$('#ticketSearch'+djiinTaskManagement.searchCriteria[criterionIndex].name);
let ticketSearch = (djiinTaskManagement.searchCriteria[criterionIndex].type == 'boolean' ?
(fieldElement.is(":checked") ? 'true' : 'false') :
fieldElement.val());
ticketSearch = ticketSearch.trim();
djiinTaskManagement.searchCriteria[criterionIndex].userValue = ticketSearch;
}

let ticketSearchTicket = $$('#ticketSearchTicket').val().trim();
let ticketSearchWithoutArchive = $$('#ticketSearchWithoutArchive').is(":checked") ? 'true' : 'false';
//djiinUtil.log('search ', ticketSearchFrom, ticketSearchTo, ticketSearchDate, ticketSearchSubject, ticketSearchBody, ticketSearchTicket, ticketSearchWithoutArchive);


// make list of ticket ids
let ticketIdsToSearch = [];
let tickets =[];
if (djiinTaskManagement.searchRequest.status == 'UNDEFINED')
{
let ticketSearchFrom = $$('#ticketSearchFrom').val().trim();
let ticketSearchTo = $$('#ticketSearchTo').val().trim();
let ticketSearchDate = $$('#ticketSearchDate').val().trim();
let ticketSearchSubject = $$('#ticketSearchSubject').val().trim();
let ticketSearchBody = $$('#ticketSearchBody').val().trim();
if (ticketSearchTicket != null && ticketSearchTicket.length > 0 && ! isNaN(parseInt(ticketSearchTicket)))
{
ticketIdsToSearch.push(parseInt(ticketSearchTicket));
}
let ticketActionsSearchObject = {
searchExtension:[
{
fieldName:'canal',
fieldValue: 'Email'
},
],
typeActionId: communicationActionTypeId,
pagination: {
resultCountPerPage: 2000,
pageIndex: 0
},
retrieveExtension: false
};
if (ticketSearchFrom != null && ticketSearchFrom.length > 0) ticketActionsSearchObject.searchExtension.push({
fieldName:'from',
fieldValue: '*' + ticketSearchFrom + '*'
});
if (ticketSearchTo != null && ticketSearchTo.length > 0) ticketActionsSearchObject.searchExtension.push({
fieldName:'to.*',
fieldValue: '*' + ticketSearchTo + '*'
});
if (ticketSearchDate != null && ticketSearchDate.length > 0) ticketActionsSearchObject.searchExtension.push({
fieldName:'date',
fieldValue: '*' + ticketSearchDate + '*'
});
if (ticketSearchSubject != null && ticketSearchSubject.length > 0) ticketActionsSearchObject.searchExtension.push({
fieldName:'subject',
fieldValue: '*' + ticketSearchSubject + '*'
});
if (ticketSearchBody != null && ticketSearchBody.length > 0) ticketActionsSearchObject.searchExtension.push({
fieldName:'body',
fieldValue: '*' + ticketSearchBody + '*'
});

//console.log(ticketActionsSearchObject);
let ticketActions = djiinUtil.callService(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.ticket.action.getList.v2",
ticketActionsSearchObject,
false);
let status;
if (ticketActions == undefined) {
status = 'Actions KO -1/' + sessionId + '/'+djiinUtil.info.ncfiId;
return 'ERROR';
}
if (ticketActions.code != 200) {
status = 'Actions KO c' + ticketActions.code + '/' + sessionId + '/'+djiinUtil.info.ncfiId;
return 'ERROR';
}
let actions = ticketActions.response;

actions.forEach(function(item) {
if (ticketIdsToSearch.indexOf(item.requestId) == -1)
{
ticketIdsToSearch.push(item.requestId);
}
});

console.log("IDS to search:" + JSON.stringify(ticketIdsToSearch));
let ticketsSearchResult = await djiinTaskManagement.callGetTicketListByIds(ticketIdsToSearch, 0, ticketPageSize, true);
//console.log(ticketIdsToSearch, ticketsSearchResult);
if (ticketsSearchResult.status == 'ERROR')
{
return 'ERROR';
}
console.log("search result:" + JSON.stringify(ticketsSearchResult));
tickets = ticketsSearchResult.tickets;

}
else
{
let customRequestExecutionObject = {
name: djiinTaskManagement.searchRequest.name,
parameters: []
};
for (criterionIndex in djiinTaskManagement.searchCriteria)
{
for (mappingIndex in djiinTaskManagement.searchRequest.mapping)
{
if (djiinTaskManagement.searchRequest.mapping[mappingIndex].criteriaName == djiinTaskManagement.searchCriteria[criterionIndex].name)
{
customRequestExecutionObject.parameters.push(
{
name: djiinTaskManagement.searchRequest.mapping[mappingIndex].requestParameterName,
value: djiinTaskManagement.searchCriteria[criterionIndex].userValue}
);
}
}
}
console.log("New search: " + JSON.stringify(customRequestExecutionObject));
let ticketActions = djiinUtil.callService(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.administration.customSQLRequest.execute.v1",
customRequestExecutionObject,
false);
let status;
if (ticketActions == undefined) {
status = 'Actions KO -1/' + sessionId + '/'+djiinUtil.info.ncfiId;
return 'ERROR';
}
if (ticketActions.code != 200) {
status = 'Actions KO c' + ticketActions.code + '/' + sessionId + '/'+djiinUtil.info.ncfiId;
return 'ERROR';
}
console.log("New search: " + JSON.stringify(ticketActions));
tickets = ticketActions.response.results;
}
let category = djiinTaskManagement.getCategoryInCampaign(searchCampaignIndex, 0);
if(isFilteringActivated){
filteredTickets = [];
tickets.forEach(ticket => {
if (djiinTaskManagement.plugins.checkTicketVisibility(ticket)) {
filteredTickets.push(ticket);
}
});
tickets = filteredTickets;
}
category.tickets = tickets;
if (ticketSearchWithoutArchive == 'true')
{
category.tickets = category.tickets.filter(
function (ticket)
{
djiinTaskManagement.checkIfTicketIsArchive(ticket);
return ! ticket.isArchive;
});
}
category.ticketCount = category.tickets.length;
category.currentPageIndex = 0;
category.hasMoreEntries = false;
category.lastDisplayedIndex = -1;
renderDisplayCampaignTaskListPanel(searchCampaignIndex);
showDisplayCampaignCategoryPanel(searchCampaignIndex, 0);
}





function clearTicketFilteredResultsForCampaign(displayCampaignIndex, categoryIndex)
{
var tickets = $$("#djiin_DC"+displayCampaignIndex+"_C"+categoryIndex+"_panel").find(".list-group-item");
$$(tickets).each(function( index ) {
$$(this).removeClass("hidden");
});
}

function clearTicketFilteredResults()
{
var tickets;
if (displayMode == 'CAMPAIGN')
{
tickets = $$(".displayCampaignTasks").find(".list-group-item");
for (displayCampaignIndex in djiinTaskManagement.displayCampaigns)
{
if (!djiinTaskManagement.displayCampaigns[displayCampaignIndex].isSpecial)
{
$$('#'+djiinTaskManagement.displayCampaigns[displayCampaignIndex].domId+'_menuBadge').html(
djiinTaskManagement.displayCampaigns[displayCampaignIndex].ticketCount +
(djiinTaskManagement.displayCampaigns[displayCampaignIndex].hasMoreEntries ? '+' : ''));
}
}

}
else if (displayMode == 'CATEGORY')
{
tickets = $$(".displayCategoryTasks").find(".list-group-item");
}
$$(tickets).each(function( index ) {
$$(this).removeClass("hidden");
});
}

function loadTicketFilteredResults(element)
{
clearTicketFilteredResults();
//var targetOptions = $$(element).attr('data-target-options');
//targetOptions = JSON.parse(targetOptions);
var ticketIdsToKeep = [];
for (filterIndex in djiinTaskManagement.filters)
{
if (displayMode == 'CAMPAIGN')
{
for (displayCampaignIndex in djiinTaskManagement.displayCampaigns)
{
if (!djiinTaskManagement.displayCampaigns[displayCampaignIndex].isSpecial)
{
for (categoryIndex in djiinTaskManagement.displayCampaigns[displayCampaignIndex].categories)
{
ticketIdsToKeep = getFilteredTicketIdsForCampaign(ticketIdsToKeep, djiinTaskManagement.filters[filterIndex], displayCampaignIndex, categoryIndex);
}
}
}
}
else if (displayMode == 'CATEGORY')
{
for (declarationKey in declarationsAndQualifications)
{
for (qualificationKey in declarationsAndQualifications[declarationKey])
{
ticketIdsToKeep = getFilteredTicketIdsForCategory(ticketIdsToKeep, djiinTaskManagement.filters[filterIndex], declarationKey, qualificationKey);
}
}
}
}
var tickets;
if (displayMode == 'CAMPAIGN')
{
tickets = $$(".displayCampaignTasks").find(".list-group-item");
}
else if (displayMode == 'CATEGORY')
{
tickets = $$(".displayCategoryTasks").find(".list-group-item");
}
djiinUtil.log("filtered tickets", ticketIdsToKeep);
$$(tickets).each(function( index ) {
if (!ticketIdsToKeep.includes(parseInt($$(this).attr("data-ticket-id"))))
{
$$(this).addClass("hidden");
}
});
}


function reloadTicketFilteredResultsForCampaign(displayCampaignIndex, categoryIndex)
{
clearTicketFilteredResultsForCampaign(displayCampaignIndex, categoryIndex);
//var targetOptions = $$(element).attr('data-target-options');
//targetOptions = JSON.parse(targetOptions);
var ticketIdsToKeep = [];
var tickets = $$("#djiin_DC"+displayCampaignIndex+"_C"+categoryIndex+"_panel").find(".list-group-item");
for (filterIndex in djiinTaskManagement.filters)
{
ticketIdsToKeep = getFilteredTicketIdsForCampaign(ticketIdsToKeep, djiinTaskManagement.filters[filterIndex], displayCampaignIndex, categoryIndex);
}
djiinUtil.log("filtered tickets on reload", ticketIdsToKeep);
$$(tickets).each(function( index ) {
if (!ticketIdsToKeep.includes(parseInt($$(this).attr("data-ticket-id"))))
{
$$(this).addClass("hidden");
}
});
}

function getFilteredTicketIdsForCampaign(ticketIdsToKeep, filter, displayCampaignIndex, categoryIndex)
{
var ticketIdsToKeepForCurrentCategory = [];
var category = djiinTaskManagement.displayCampaigns[displayCampaignIndex].categories[categoryIndex];
for (ticketIndex in category.tickets)
{
if (filter.userCriterion == undefined || filter.userCriterion == "")
{
ticketIdsToKeep.push(category.tickets[ticketIndex].id);
ticketIdsToKeepForCurrentCategory.push(category.tickets[ticketIndex].id);
}
else
{
let value = djiinUtil.getPropertyInTree(category.tickets[ticketIndex].extension, filter.extensionName);
if (value != undefined && value.toLowerCase().includes(filter.userCriterion.toLowerCase()))
{
ticketIdsToKeep.push(category.tickets[ticketIndex].id);
ticketIdsToKeepForCurrentCategory.push(category.tickets[ticketIndex].id);
}
}
}

var ticketCount = category.tickets.length-(category.tickets.length-ticketIdsToKeepForCurrentCategory.length);
$$('#'+category.domId+'_menuBadge').html(
ticketCount +
(category.hasMoreEntries ? '+' : ''));
$$('#'+category.domId+'_panelBadge').html(
ticketCount +
(category.hasMoreEntries ? '+' : ''));
if (category.hasNewMail)
{
$$('#'+category.domId+'_menuDot').addClass('isNewMail');
}
else
{
$$('#'+category.domId+'_menuDot').removeClass('isNewMail');
}

var campaignTicketCount = $$('#'+djiinTaskManagement.displayCampaigns[displayCampaignIndex].domId+'_menuBadge').text();
campaignTicketCount = parseInt(campaignTicketCount.replace("+", ""));
campaignTicketCount = campaignTicketCount-category.tickets.length+ticketIdsToKeepForCurrentCategory.length;
$$('#'+djiinTaskManagement.displayCampaigns[displayCampaignIndex].domId+'_menuBadge').html(
campaignTicketCount +
(djiinTaskManagement.displayCampaigns[displayCampaignIndex].hasMoreEntries ? '+' : ''));
if (djiinTaskManagement.displayCampaigns[displayCampaignIndex].hasNewMail)
{
$$('#'+djiinTaskManagement.displayCampaigns[displayCampaignIndex].domId+'_menuDot').addClass('isNewMail');
}
else
{
$$('#'+djiinTaskManagement.displayCampaigns[displayCampaignIndex].domId+'_menuDot').removeClass('isNewMail');
}

return ticketIdsToKeep;
}

function getFilteredTicketIdsForCategory(ticketIdsToKeep, filter, declarationKey, qualificationKey)
{
var ticketIdsToKeepForCurrentCategory = [];
var category = declarationsAndQualifications[declarationKey][qualificationKey];
for (ticketIndex in category)
{
let value = djiinUtil.getPropertyInTree(category[ticketIndex].extension, filter.extensionName);
if (value != undefined && value.toLowerCase().includes(filter.userCriterion.toLowerCase()))
{
ticketIdsToKeep.push(category[ticketIndex].id);
ticketIdsToKeepForCurrentCategory.push(category[ticketIndex].id);
}
}
var qualificationTicketCount = (category.length-ticketIdsToKeepForCurrentCategory.length);
var declarationTicketCount = parseInt($$("#djiin_D"+declarationId+"_menuBadge").text().replace("+", ""));
declarationTicketCount = declarationTicketCount-category.length+ticketIdsToKeepForCurrentCategory.length;
$$("#djiin_D"+declarationId+"_menuBadge").html(declarationTicketCount);
$$("#djiin_D"+declarationId+"_Q"+qualificationId+"_panelBadge").html(qualificationTicketCount);
$$("#djiin_D"+declarationId+"_Q"+qualificationId+"_menuBadge").html(qualificationTicketCount);

if (declarationHasNewMail)
{
$$("#djiin_D"+declarationId+"_menuDot").addClass('isNewMail');
}
else
{
$$("#djiin_D"+declarationId+"_menuDot").removeClass('isNewMail');
}
if (qualificationHasNewMail)
{
$$("#djiin_D"+declarationId+"_Q"+qualificationId+"_menuDot").addClass('isNewMail');
}
else
{
$$("#djiin_D"+declarationId+"_Q"+qualificationId+"_menuDot").removeClass('isNewMail');
}
return ticketIdsToKeep;
}


/**
* Displays a user interface to provide a list of tickets to delete
*/
function showDeleteAllItemsUI() {
djiinUtil.createModal('tickets-delete-popup', false, (djiinUtil.info.language == 'fr' ? 'Liste de ticket à supprimer' : 'List of tickets to delete'),
'<div class="row form-horizontal">' +
' <h3 class="side-margin">'+(djiinUtil.info.language == 'fr' ? 'Suppression de tickets' : 'Ticket deletion')+'</h3>' +
' <h4 class="side-margin bottom-space">'+(djiinUtil.info.language == 'fr' ? 'Saisie de la liste' : 'List input')+'</h4>' +
' <p class="side-margin bottom-space">'+(djiinUtil.info.language == 'fr' ? 'Veuillez saisir un tableau au format [123, 456, 789, ..., 987] ' +
'contenant les identifiants des éléments à supprimer en masse. Si une extension de l\'élément ticket doit être supprimée, ' +
'donner son nom (par exemple archiveCategory). Si une extension de l\'élément doit être définie, donner son nom et sa valeur.' :
'Please provide an array using the format [123, 456, 789, ..., 987] ' +
'containing the identifiers of the items to bulk delete. If an item extension is to be deleted, ' +
'give its name (for example archiveCategory). If an item extension is to be defined, give its name and its value.')+'</p>' +
'</div>'+
'<div class="row form-horizontal">'+
' <div class="form-group side-margin">' +
' <div class="col-sm-3" style="font-weight: bold">'+(djiinUtil.info.language == 'fr' ? 'Type' : 'Type')+' : </div>' +
' <div class="col-sm-9"><select name="itemTypeToDelete" id="itemTypeToDelete" class="form-control"><option value="TICKET">'+(djiinUtil.info.language == 'fr' ? 'Ticket' : 'Ticket')+'</option><option value="APPOINTMENT">'+(djiinUtil.info.language == 'fr' ? 'Rendez-vous' : 'Appointment')+'</option></select></div>' +
' </div>' +
'</div>' +
'<div class="row form-horizontal">'+
' <div class="form-group side-margin">' +
' <div class="col-sm-3" style="font-weight: bold">'+(djiinUtil.info.language == 'fr' ? 'Identifiants' : 'Identifiers')+' : </div>' +
' <div class="col-sm-9"><textarea id="itemIdsToDelete" name="itemIdsToDelete" ' + /*rows="5" cols="33"*/ ' class="form-control"></textarea></div>' +
' </div>' +
'</div>' +
'<div class="row form-horizontal">'+
' <div class="form-group side-margin">' +
' <div class="col-sm-3" style="font-weight: bold">Extension<br>'+(djiinUtil.info.language == 'fr' ? 'à supprimer' : 'to delete')+' : </div>' +
' <div class="col-sm-9"><input type="text" id="itemExtensionNameToDelete" name="itemExtensionNameToDelete" class="form-control"/></div>' +
' </div>' +
'</div>' +
'<div class="row form-horizontal">'+
' <div class="form-group side-margin">' +
' <div class="col-sm-3" style="font-weight: bold">Extension<br>'+(djiinUtil.info.language == 'fr' ? 'à créer' : 'to create')+' : </div>' +
' <div class="col-sm-4"><input type="text" id="ticketExtensionNameToAdd" name="ticketExtensionNameToAdd" class="form-control"/></div>' +
' <div class="col-sm-1"> = </div>' +
' <div class="col-sm-4"><input type="text" id="ticketExtensionValueToAdd" name="ticketExtensionValueToAdd" class="form-control"/></div>' +
' </div>' +
'</div>',
(djiinUtil.info.language == 'fr' ? 'Annuler' : 'Cancel'), (djiinUtil.info.language == 'fr' ? 'Supprimer' : 'Delete'), deleteAllItemsFromUI);
}

/**
* Actually deletes all items from defined in deletion UI
*/
function deleteAllItemsFromUI()
{
let itemType = $$('#itemTypeToDelete').val();
let itemIdsString = $$('#itemIdsToDelete').val();
let itemExtensionNameToDelete = $$('#itemExtensionNameToDelete').val();
let itemExtensionNameToAdd = $$('#ticketExtensionNameToAdd').val();
let itemExtensionValueToAdd = $$('#ticketExtensionValueToAdd').val();
let itemIds = JSON.parse(itemIdsString);
for (itemIndex in itemIds)
{
if (itemType == "TICKET")
{
deleteTicket(itemIds[itemIndex], itemExtensionNameToDelete, itemExtensionNameToAdd, itemExtensionValueToAdd);
}
else if (itemType == "APPOINTMENT")
{
deleteAppointment(itemIds[itemIndex]);
}
else
{
djiinUtil.log('Found nothing to do with id ' + itemIds[itemIndex])
}
}
djiinUtil.createModal('result-display-popup', false, 'Information', '<h4>'+(djiinUtil.info.language == 'fr' ? 'Suppression des ' + itemIds.length + ' éléments de type '+itemType+' effectuée.' : 'Deletion of ' + itemIds.length + ' items of type ' + itemType + ' done.')+'</h4>');
}



/**
* Loads a single ticket by id.
*/
function callGetTicketById(ticketId)
{
let ticketsSearchObject = {
id: ticketId
};
let tickets = djiinUtil.callService(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.ticket.request.get.v1",
ticketsSearchObject,
false);
if (tickets == undefined) {
djiinUtil.createModal('news-display-popup', false, 'Information', (djiinUtil.info.language == 'fr' ? '<h4>Erreur de chargement de ticket ' + ticketsSearchObject.id + ', veuillez réessayer. En cas d\'échec répété, vérifiez que vous êtes toujours connecté et rafraichissez la page. Si cela ne rétablit pas le chargement, contactez votre administrateur.</h4>' :
'<h4>Ticket ' + ticketsSearchObject.id + ' loading error , please retry. In case of persistent failure, please check that you are still connected and refresh the page. If it does not restore the loading, contact your administrator.</h4>'));
}
else if (tickets.code != 200) {
djiinUtil.createModal('news-display-popup', false, 'Information', (djiinUtil.info.language == 'fr' ? '<h4>Erreur ' + tickets.code + ' de chargement de ticket ' + ticketsSearchObject.id + ', veuillez réessayer. En cas d\'échec répété, vérifiez que vous êtes toujours connecté et rafraichissez la page. Si cela ne rétablit pas le chargement, contactez votre administrateur.</h4>' :
'<h4>Ticket ' + ticketsSearchObject.id + ' loading error ' + tickets.code + ', please retry. In case of persistent failure, please check that you are still connected and refresh the page. If it does not restore the loading, contact your administrator.</h4>'));
}
else
{
return tickets.response;
}
djiinUtil.log('failed to load ticket with criterion : ', ticketsSearchObject, ' and response : ', tickets);
return null;
}

/**
* Updates a ticket.
*/
function callUpdateTicket(ticket)
{
let ticketUpdate = djiinUtil.callService(
djiinUtil.info.platformName,
djiinUtil.info.ncfiId,
"djiin-worlds-core:intraneon.ticket.request.update.v3",
ticket,
false);
if (ticketUpdate == undefined) {
djiinUtil.createModal('news-display-popup', false, 'Information', (djiinUtil.info.language == 'fr' ? '<h4>Erreur de mise à jour de ticket ' + ticket.id + ', veuillez réessayer. En cas d\'échec répété, vérifiez que vous êtes toujours connecté et rafraichissez la page. Si cela ne rétablit pas le chargement, contactez votre administrateur.</h4>' :
'<h4>Ticket ' + ticketsSearchObject.id + ' update error , please retry. In case of persistent failure, please check that you are still connected and refresh the page. If it does not restore the loading, contact your administrator.</h4>'));
}
else if (ticketUpdate.code != 200) {
djiinUtil.createModal('news-display-popup', false, 'Information', (djiinUtil.info.language == 'fr' ? '<h4>Erreur ' + ticketUpdate.code + ' de mise à jour de ticket ' + ticket.id + ', veuillez réessayer. En cas d\'échec répété, vérifiez que vous êtes toujours connecté et rafraichissez la page. Si cela ne rétablit pas le chargement, contactez votre administrateur.</h4>' :
'<h4>Ticket ' + ticket.id + ' update error ' + ticketUpdate.code + ', please retry. In case of persistent failure, please check that you are still connected and refresh the page. If it does not restore the loading, contact your administrator.</h4>'));
}
else
{
return ticketUpdate.response;
}
djiinUtil.log('failed to update ticket with criterion : ', ticket, ' and response : ', ticketUpdate);
return null;
}

function hoverSubMenus()
{
$$(".panel-body > ul > li").stop(true, true).hover(
function()
{
$$(this).stop(true, true).animate(
{
backgroundColor: "#002849"
}, 250);
},
function()
{
if ($$(this).hasClass("selected-menu"))
{
$$(this).stop(true, true).animate({
backgroundColor: "#009fe3"
}, 250);
}
else
{
$$(this).stop(true, true).animate(
{
backgroundColor: "transparent"
}, 250);
}
});
}

Back to list