/**
* File: tusa-chatbot.js
*/
jQuery(document).ready(function($) {
// Elementi UI
const $chatbotContainer = $('#tusa-chatbot-container');
const $messagesContainer = $('#tusa-chatbot-messages');
const $chatInput = $('#tusa-chatbot-input');
const $sendBtn = $('#tusa-chatbot-send');
const $toggleBtn = $('#tusa-chatbot-toggle');
// Verifica che gli elementi esistano nella pagina
console.log('ChatBot Init - Container exists:', $chatbotContainer.length > 0);
console.log('ChatBot Init - Messages container exists:', $messagesContainer.length > 0);
console.log('ChatBot Init - Input exists:', $chatInput.length > 0);
console.log('ChatBot Init - Send button exists:', $sendBtn.length > 0);
console.log('ChatBot Init - Toggle button exists:', $toggleBtn.length > 0);
// Toggle expanded/collapsed state del chatbot
$toggleBtn.on('click', function(e) {
e.preventDefault();
console.log('Toggle button clicked');
$chatbotContainer.toggleClass('collapsed');
// Cambia icona in base allo stato
if($chatbotContainer.hasClass('collapsed')) {
$toggleBtn.find('.dashicons').removeClass('dashicons-arrow-up-alt2').addClass('dashicons-arrow-down-alt2');
} else {
$toggleBtn.find('.dashicons').removeClass('dashicons-arrow-down-alt2').addClass('dashicons-arrow-up-alt2');
// Focus sull'input quando si espande
$chatInput.focus();
}
});
// Invia messaggio quando si preme INVIO
$chatInput.on('keypress', function(e) {
if(e.which === 13) { // Codice tasto INVIO
e.preventDefault();
console.log('Enter key pressed');
sendMessage();
}
});
// Invia messaggio quando si clicca sul pulsante
$sendBtn.on('click', function(e) {
e.preventDefault();
console.log('Send button clicked');
sendMessage();
});
/**
* Invia messaggio al chatbot
*/
function sendMessage() {
const message = $chatInput.val().trim();
console.log('Sending message:', message);
if(message === '') {
console.log('Message is empty, not sending');
return;
}
// Aggiungi messaggio dell'utente alla chat
addMessage('user', message);
// Pulisci input
$chatInput.val('').focus();
// Mostra indicatore "sta scrivendo..."
addTypingIndicator();
// Verifica i dati che stiamo inviando
console.log('AJAX data:', {
action: tusaChatbot.action,
nonce: tusaChatbot.nonce,
message: message
});
// Invia richiesta al server
$.ajax({
url: tusaChatbot.ajaxUrl,
type: 'POST',
dataType: 'json',
data: {
action: tusaChatbot.action,
nonce: tusaChatbot.nonce,
message: message
},
success: function(response) {
console.log('AJAX success:', response);
// Rimuovi indicatore "sta scrivendo..."
removeTypingIndicator();
if(response.success) {
// Aggiungi risposta del bot
addMessage('bot', response.data.botMessage);
// Aggiorna i select con i filtri trovati
updateFilters(response.data.filters);
// Aggiorna la tabella dei risultati
$('#tusa-results').html(response.data.tableHtml);
// Aggiorna le opzioni dei select con i nuovi valori distinti
updateDistinctValues(response.data.distinct);
// Scorri la chat all'ultimo messaggio
scrollToBottom();
} else {
// Mostra errore
const errorMsg = response.data || 'Errore sconosciuto';
console.error('AJAX error from server:', errorMsg);
addMessage('bot', 'Mi dispiace, si è verificato un errore: ' + errorMsg);
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.error('AJAX error:', textStatus, errorThrown);
console.log('Response text:', jqXHR.responseText);
// Rimuovi indicatore "sta scrivendo..."
removeTypingIndicator();
// Mostra errore generico
addMessage('bot', 'Mi dispiace, si è verificato un errore di comunicazione. Riprova più tardi. (Errore: ' + textStatus + ')');
}
});
}
/**
* Aggiunge un messaggio alla chat
*/
function addMessage(type, content) {
console.log('Adding message:', type, content);
const avatar = type === 'user' ? '👤' : '🤖';
// Trasforma il contenuto per mostrare correttamente il json eventualmente contenuto
const formattedContent = formatMessageContent(content);
const $message = $(`
${avatar}
${formattedContent}
`);
$messagesContainer.append($message);
scrollToBottom();
}
/**
* Formatta il contenuto del messaggio
*/
function formatMessageContent(content) {
if (typeof content !== 'string') {
console.warn('Content is not a string:', content);
content = String(content || '');
}
// Rimuovi eventuali json dalla visualizzazione per l'utente
return content.replace(/\{.*?\}/gs, '');
}
/**
* Aggiunge indicatore "sta scrivendo..."
*/
function addTypingIndicator() {
console.log('Adding typing indicator');
const $indicator = $(`
`);
$messagesContainer.append($indicator);
scrollToBottom();
}
/**
* Rimuove indicatore "sta scrivendo..."
*/
function removeTypingIndicator() {
console.log('Removing typing indicator');
$messagesContainer.find('.typing-indicator').remove();
}
/**
* Scorre la chat all'ultimo messaggio
*/
function scrollToBottom() {
$messagesContainer.scrollTop($messagesContainer[0].scrollHeight);
}
/**
* Aggiorna i select con i filtri trovati dall'assistente
*/
function updateFilters(filters) {
console.log('Updating filters with:', filters);
if (!filters) {
console.warn('No filters provided to update');
return;
}
// Per ogni filtro nel json restituito, aggiorna il relativo select
Object.keys(filters).forEach(function(filterKey) {
const value = filters[filterKey];
const $select = $(`#tusa-${filterKey}`);
if (!$select.length) {
console.warn(`Select #tusa-${filterKey} not found`);
return;
}
if(value !== '') {
console.log(`Setting ${filterKey} to ${value}`);
$select.val(value).trigger('change');
}
});
}
/**
* Aggiorna le opzioni dei select con i nuovi valori distinti
* Funzione estratta da tusa-filter.js originale
*/
function updateDistinctValues(newDistinct) {
console.log('Updating distinct values with:', newDistinct);
if (!newDistinct) {
console.warn('No distinct values provided to update');
return;
}
function updateSelect($select, newValues, placeholder) {
if (!$select.length) {
console.warn(`Select for ${placeholder} not found`);
return;
}
// Valore attuale
let currentVal = $select.val() || '';
console.log(`Updating select ${$select.attr('id')}, current value: ${currentVal}`);
// Svuotiamo le opzioni (Select2 e DOM)
$select.html('');
// Aggiungiamo l'opzione placeholder
$select.append('' + placeholder + ' ');
// Aggiungiamo le nuove opzioni
if (Array.isArray(newValues)) {
newValues.forEach(function(val) {
$select.append('' + val + ' ');
});
// Se il currentVal rientra tra i newValues, lo reimpostiamo
if(currentVal && newValues.includes(currentVal)) {
$select.val(currentVal);
} else {
// Altrimenti rimane su "" (placeholder)
$select.val('');
}
} else {
console.warn(`New values for ${placeholder} is not an array:`, newValues);
}
// Aggiorna l'interfaccia Select2
if ($.fn.select2 && typeof $select.select2 === 'function') {
$select.trigger('change.select2');
} else {
console.warn('Select2 not available for', $select.attr('id'));
$select.trigger('change');
}
}
// Aggiorno d1..l3
updateSelect($('#tusa-d1'), newDistinct.d1, 'd1');
updateSelect($('#tusa-d2'), newDistinct.d2, 'd2');
updateSelect($('#tusa-d3'), newDistinct.d3, 'd3');
updateSelect($('#tusa-l1'), newDistinct.l1, 'l1');
updateSelect($('#tusa-l2'), newDistinct.l2, 'l2');
updateSelect($('#tusa-l3'), newDistinct.l3, 'l3');
}
// Inizializza il chatbot espanso
if($chatbotContainer.length) {
console.log('ChatBot initialized');
// Verifica se abbiamo tutte le dipendenze necessarie
console.log('jQuery version:', $.fn.jquery);
console.log('Select2 available:', typeof $.fn.select2 === 'function');
// Focus sull'input
$chatInput.focus();
} else {
console.warn('ChatBot container not found in the page');
}
});
Production - Tusa Precision Tools
Nous utilisons des cookies pour vous offrir la meilleure expérience sur notre site.
Vous pouvez en savoir plus sur les cookies que nous utilisons ou sur la façon de les désactiver dans les paramètres .
Accept
Close GDPR Cookie Settings
Privacy Overview
This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.
Strictly Necessary Cookies
Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.
If you disable this cookie, we will not be able to save your preferences. This means that every time you visit this website you will need to enable or disable cookies again.
Cookie Policy
More information about our Cookie Policy