funcional
This commit is contained in:
+480
-30
@@ -409,11 +409,11 @@ class SimpleWhatsAppManager {
|
||||
this.log('Cargando conversaciones');
|
||||
|
||||
try {
|
||||
const response = await this.apiCall('get_conversations.php');
|
||||
console.log('Respuesta get_conversations:', response); // Debug
|
||||
const response = await this.apiCall('get_conversation_list.php');
|
||||
console.log('Respuesta get_conversation_list:', response); // Debug
|
||||
|
||||
if (response && response.success && Array.isArray(response.data)) {
|
||||
this.updateConversationsList(response.data);
|
||||
if (response && response.success && Array.isArray(response.conversations)) {
|
||||
this.updateConversationsList(response.conversations);
|
||||
} else if (response && Array.isArray(response)) {
|
||||
// Retrocompatibilidad por si la API devuelve directamente el array
|
||||
this.updateConversationsList(response);
|
||||
@@ -428,46 +428,201 @@ class SimpleWhatsAppManager {
|
||||
}
|
||||
|
||||
updateConversationsList(conversations) {
|
||||
const container = document.getElementById('conversations-table');
|
||||
const container = document.getElementById('conversations-container');
|
||||
if (!container) return;
|
||||
|
||||
if (conversations.length === 0) {
|
||||
container.innerHTML = '<tr><td colspan="6" class="text-center text-muted">No hay conversaciones</td></tr>';
|
||||
container.innerHTML = `
|
||||
<div class="conversation-empty">
|
||||
<div class="empty-icon">
|
||||
<i class="fas fa-comments"></i>
|
||||
</div>
|
||||
<h5>No hay conversaciones</h5>
|
||||
<p>Los chats aparecerán aquí cuando recibas o envíes mensajes</p>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
let html = '';
|
||||
|
||||
conversations.forEach(conv => {
|
||||
const date = new Date(conv.created_at);
|
||||
const formatDate = date.toLocaleDateString() + ' ' + date.toLocaleTimeString('es', { hour: '2-digit', minute: '2-digit' });
|
||||
const timeAgo = conv.time_ago || this.formatTimeAgo(conv.last_message_time || conv.created_at);
|
||||
const lastMessage = conv.last_message || conv.content || 'Sin mensajes';
|
||||
const userName = conv.name || conv.phone_number;
|
||||
const userInitial = userName.charAt(0).toUpperCase();
|
||||
const isOnline = Math.random() > 0.6; // Simulación de estado online
|
||||
|
||||
// Unread badge
|
||||
const unreadBadge = (conv.unread_count && conv.unread_count > 0) ?
|
||||
`<div class="conversation-unread">${conv.unread_count}</div>` : '';
|
||||
|
||||
// Status icon
|
||||
const statusIcon = conv.last_direction === 'outgoing'
|
||||
? '<i class="fas fa-check-double conversation-status-icon outgoing"></i>'
|
||||
: '<i class="fas fa-arrow-down conversation-status-icon incoming"></i>';
|
||||
|
||||
// Message type indicator
|
||||
const messageTypeIcon = conv.last_message_type === 'template'
|
||||
? '<i class="fas fa-file-alt text-primary" title="Plantilla"></i> '
|
||||
: conv.last_message_type === 'image'
|
||||
? '<i class="fas fa-image text-info" title="Imagen"></i> '
|
||||
: '';
|
||||
|
||||
html += `
|
||||
<tr>
|
||||
<td>
|
||||
<div>
|
||||
<strong>${conv.name || conv.phone_number}</strong><br>
|
||||
<small class="text-muted">${conv.phone_number}</small>
|
||||
<div class="conversation-item" onclick="openChatWindow(${conv.user_id})">
|
||||
<div class="conversation-avatar ${isOnline ? 'online' : ''}">
|
||||
${userInitial}
|
||||
</div>
|
||||
<div class="conversation-details">
|
||||
<div class="conversation-header">
|
||||
<div class="conversation-name">
|
||||
${userName}
|
||||
${conv.last_message_status === 'read' ? '<i class="fas fa-check-double text-primary" title="Leído"></i>' : ''}
|
||||
</div>
|
||||
<div class="conversation-time">${timeAgo}</div>
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<div style="max-width: 200px; overflow: hidden; text-overflow: ellipsis;">
|
||||
${conv.content || 'Sin contenido'}
|
||||
<div class="conversation-preview">
|
||||
${statusIcon}
|
||||
<div class="conversation-last-message">
|
||||
${messageTypeIcon}${lastMessage}
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td><span class="badge bg-info">${conv.message_type || 'text'}</span></td>
|
||||
<td><span class="badge bg-${conv.status === 'sent' ? 'success' : 'warning'}">${conv.status || 'unknown'}</span></td>
|
||||
<td>${formatDate}</td>
|
||||
<td>
|
||||
<button class="btn btn-sm btn-outline-primary" onclick="viewConversation(${conv.user_id})">
|
||||
<i class="fas fa-eye"></i> Ver
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</div>
|
||||
<div class="conversation-meta">
|
||||
${unreadBadge}
|
||||
<div class="conversation-actions">
|
||||
<button class="btn btn-sm" onclick="event.stopPropagation(); openChatWindow(${conv.user_id})" title="Abrir chat">
|
||||
<i class="fas fa-comments"></i>
|
||||
</button>
|
||||
<button class="btn btn-sm" onclick="event.stopPropagation(); viewConversationDetails(${conv.user_id})" title="Ver detalles">
|
||||
<i class="fas fa-info-circle"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
|
||||
container.innerHTML = html;
|
||||
|
||||
// Agregar funcionalidad de búsqueda
|
||||
this.setupConversationSearch(conversations);
|
||||
}
|
||||
|
||||
setupConversationSearch(conversations) {
|
||||
const searchInput = document.getElementById('search-conversations');
|
||||
if (!searchInput) return;
|
||||
|
||||
searchInput.addEventListener('input', (e) => {
|
||||
const query = e.target.value.toLowerCase().trim();
|
||||
|
||||
if (!query) {
|
||||
this.updateConversationsDisplay(conversations);
|
||||
return;
|
||||
}
|
||||
|
||||
const filtered = conversations.filter(conv => {
|
||||
const name = (conv.name || '').toLowerCase();
|
||||
const phone = (conv.phone_number || '').toLowerCase();
|
||||
const message = (conv.last_message || conv.content || '').toLowerCase();
|
||||
|
||||
return name.includes(query) ||
|
||||
phone.includes(query) ||
|
||||
message.includes(query);
|
||||
});
|
||||
|
||||
this.updateConversationsDisplay(filtered);
|
||||
});
|
||||
}
|
||||
|
||||
updateConversationsDisplay(conversations) {
|
||||
const container = document.getElementById('conversations-container');
|
||||
if (!container) return;
|
||||
|
||||
if (conversations.length === 0) {
|
||||
container.innerHTML = `
|
||||
<div class="conversation-empty">
|
||||
<div class="empty-icon">
|
||||
<i class="fas fa-search"></i>
|
||||
</div>
|
||||
<h5>No se encontraron conversaciones</h5>
|
||||
<p>Intenta con otros términos de búsqueda</p>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
let html = '';
|
||||
conversations.forEach(conv => {
|
||||
const timeAgo = conv.time_ago || this.formatTimeAgo(conv.last_message_time || conv.created_at);
|
||||
const lastMessage = conv.last_message || conv.content || 'Sin mensajes';
|
||||
const userName = conv.name || conv.phone_number;
|
||||
const userInitial = userName.charAt(0).toUpperCase();
|
||||
const isOnline = Math.random() > 0.6;
|
||||
|
||||
const unreadBadge = (conv.unread_count && conv.unread_count > 0) ?
|
||||
`<div class="conversation-unread">${conv.unread_count}</div>` : '';
|
||||
|
||||
const statusIcon = conv.last_direction === 'outgoing'
|
||||
? '<i class="fas fa-check-double conversation-status-icon outgoing"></i>'
|
||||
: '<i class="fas fa-arrow-down conversation-status-icon incoming"></i>';
|
||||
|
||||
const messageTypeIcon = conv.last_message_type === 'template'
|
||||
? '<i class="fas fa-file-alt text-primary" title="Plantilla"></i> '
|
||||
: conv.last_message_type === 'image'
|
||||
? '<i class="fas fa-image text-info" title="Imagen"></i> '
|
||||
: '';
|
||||
|
||||
html += `
|
||||
<div class="conversation-item" onclick="openChatWindow(${conv.user_id})">
|
||||
<div class="conversation-avatar ${isOnline ? 'online' : ''}">
|
||||
${userInitial}
|
||||
</div>
|
||||
<div class="conversation-details">
|
||||
<div class="conversation-header">
|
||||
<div class="conversation-name">
|
||||
${userName}
|
||||
${conv.last_message_status === 'read' ? '<i class="fas fa-check-double text-primary" title="Leído"></i>' : ''}
|
||||
</div>
|
||||
<div class="conversation-time">${timeAgo}</div>
|
||||
</div>
|
||||
<div class="conversation-preview">
|
||||
${statusIcon}
|
||||
<div class="conversation-last-message">
|
||||
${messageTypeIcon}${lastMessage}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="conversation-meta">
|
||||
${unreadBadge}
|
||||
<div class="conversation-actions">
|
||||
<button class="btn btn-sm" onclick="event.stopPropagation(); openChatWindow(${conv.user_id})" title="Abrir chat">
|
||||
<i class="fas fa-comments"></i>
|
||||
</button>
|
||||
<button class="btn btn-sm" onclick="event.stopPropagation(); viewConversationDetails(${conv.user_id})" title="Ver detalles">
|
||||
<i class="fas fa-info-circle"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
|
||||
container.innerHTML = html;
|
||||
}
|
||||
|
||||
formatTimeAgo(datetime) {
|
||||
if (!datetime) return '';
|
||||
const now = new Date();
|
||||
const date = new Date(datetime);
|
||||
const diff = Math.floor((now - date) / 1000);
|
||||
|
||||
if (diff < 60) return 'Ahora';
|
||||
if (diff < 3600) return `${Math.floor(diff/60)}m`;
|
||||
if (diff < 86400) return `${Math.floor(diff/3600)}h`;
|
||||
if (diff < 2592000) return `${Math.floor(diff/86400)}d`;
|
||||
return date.toLocaleDateString();
|
||||
}
|
||||
|
||||
async loadSettings() {
|
||||
@@ -918,10 +1073,305 @@ window.debugAPI = async function (endpoint) {
|
||||
}
|
||||
};
|
||||
|
||||
// Función para ver conversación específica
|
||||
// Función para abrir ventana de chat
|
||||
window.openChatWindow = function (userId) {
|
||||
console.log('Abriendo chat del usuario:', userId);
|
||||
|
||||
// Abrir nueva ventana de chat
|
||||
const chatUrl = `chat_window.php?user_id=${userId}&debug=true`;
|
||||
const windowFeatures = 'width=1000,height=700,resizable=yes,scrollbars=yes,status=yes,toolbar=no,menubar=no,location=no';
|
||||
|
||||
const chatWindow = window.open(chatUrl, `chat_${userId}`, windowFeatures);
|
||||
|
||||
if (chatWindow) {
|
||||
chatWindow.focus();
|
||||
} else {
|
||||
alert('No se pudo abrir la ventana de chat. Verifica que tu navegador permita ventanas emergentes.');
|
||||
}
|
||||
};
|
||||
|
||||
// Función para mostrar modal de chat
|
||||
function showChatModal(user, messages) {
|
||||
// Escapar datos del usuario para evitar XSS
|
||||
const userName = escapeHtml(user.name || 'Usuario');
|
||||
const userPhone = escapeHtml(user.phone_number || '');
|
||||
|
||||
const modalHtml = `
|
||||
<div class="modal fade" id="chatModal" tabindex="-1" aria-labelledby="chatModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog modal-lg">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header bg-success text-white">
|
||||
<h5 class="modal-title" id="chatModalLabel">
|
||||
<i class="fab fa-whatsapp"></i> ${userName}
|
||||
<small class="opacity-75">(${userPhone})</small>
|
||||
</h5>
|
||||
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body p-0">
|
||||
<div id="chat-messages" class="chat-container" style="height: 400px; overflow-y: auto; padding: 15px; background-color: #e5ddd5;">
|
||||
${generateChatMessages(messages)}
|
||||
</div>
|
||||
<div class="border-top p-3">
|
||||
<div class="row">
|
||||
<div class="col">
|
||||
<div class="input-group">
|
||||
<select id="messageType" class="form-select" style="max-width: 120px;">
|
||||
<option value="text">Texto</option>
|
||||
<option value="template">Plantilla</option>
|
||||
</select>
|
||||
<input type="text" id="messageInput" class="form-control" placeholder="Escribe tu mensaje...">
|
||||
<button class="btn btn-success" onclick="sendChatMessage(${user.id})">
|
||||
<i class="fas fa-paper-plane"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="templateSelector" class="mt-2" style="display: none;">
|
||||
<select id="templateSelect" class="form-select">
|
||||
<option value="">Selecciona una plantilla...</option>
|
||||
<option value="hello_world">hello_world</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Remover modal anterior si existe
|
||||
const existingModal = document.getElementById('chatModal');
|
||||
if (existingModal) {
|
||||
existingModal.remove();
|
||||
}
|
||||
|
||||
document.body.insertAdjacentHTML('beforeend', modalHtml);
|
||||
|
||||
// Event listener para cambio de tipo de mensaje
|
||||
document.getElementById('messageType').addEventListener('change', function() {
|
||||
const templateSelector = document.getElementById('templateSelector');
|
||||
const messageInput = document.getElementById('messageInput');
|
||||
|
||||
if (this.value === 'template') {
|
||||
templateSelector.style.display = 'block';
|
||||
messageInput.placeholder = 'Parámetros de la plantilla (opcional)';
|
||||
} else {
|
||||
templateSelector.style.display = 'none';
|
||||
messageInput.placeholder = 'Escribe tu mensaje...';
|
||||
}
|
||||
});
|
||||
|
||||
// Mostrar modal
|
||||
const modal = new bootstrap.Modal(document.getElementById('chatModal'));
|
||||
modal.show();
|
||||
|
||||
// Scroll al final
|
||||
setTimeout(() => {
|
||||
const chatContainer = document.getElementById('chat-messages');
|
||||
chatContainer.scrollTop = chatContainer.scrollHeight;
|
||||
}, 200);
|
||||
}
|
||||
|
||||
// Generar HTML de mensajes del chat
|
||||
function generateChatMessages(messages) {
|
||||
if (!messages || messages.length === 0) {
|
||||
return '<div class="text-center text-muted py-4"><i class="fas fa-comments fa-3x"></i><br><br>No hay mensajes en esta conversación</div>';
|
||||
}
|
||||
|
||||
let html = '';
|
||||
messages.forEach(msg => {
|
||||
const isOutgoing = msg.direction === 'outgoing';
|
||||
const messageClass = isOutgoing ? 'outgoing' : 'incoming';
|
||||
const alignClass = isOutgoing ? 'justify-content-end' : 'justify-content-start';
|
||||
const bgClass = isOutgoing ? 'bg-success text-white' : 'bg-white';
|
||||
|
||||
// Escapar el contenido del mensaje
|
||||
const messageContent = escapeHtml(msg.content) || '<em>Sin contenido</em>';
|
||||
const messageTime = escapeHtml(msg.time || '');
|
||||
|
||||
html += `
|
||||
<div class="d-flex ${alignClass} mb-2">
|
||||
<div class="message-bubble ${bgClass} rounded-3 p-2 shadow-sm" style="max-width: 70%;">
|
||||
<div class="message-content">
|
||||
${messageContent}
|
||||
</div>
|
||||
<div class="message-time text-${isOutgoing ? 'light' : 'muted'}" style="font-size: 0.75rem;">
|
||||
${messageTime} ${isOutgoing ? '✓✓' : ''}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
|
||||
return html;
|
||||
}
|
||||
|
||||
// Función para escapar HTML y prevenir XSS
|
||||
function escapeHtml(text) {
|
||||
if (!text) return '';
|
||||
const map = {
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"',
|
||||
"'": '''
|
||||
};
|
||||
return text.toString().replace(/[&<>"']/g, function(m) { return map[m]; });
|
||||
}
|
||||
|
||||
// Función para enviar mensaje desde el chat
|
||||
window.sendChatMessage = async function (userId) {
|
||||
const messageType = document.getElementById('messageType').value;
|
||||
const messageInput = document.getElementById('messageInput');
|
||||
const message = messageInput.value.trim();
|
||||
|
||||
if (!message && messageType === 'text') {
|
||||
alert('Por favor escribe un mensaje');
|
||||
return;
|
||||
}
|
||||
|
||||
if (messageType === 'template') {
|
||||
const templateSelect = document.getElementById('templateSelect');
|
||||
const template = templateSelect.value;
|
||||
|
||||
if (!template) {
|
||||
alert('Por favor selecciona una plantilla');
|
||||
return;
|
||||
}
|
||||
|
||||
await sendTemplateMessage(userId, template, message);
|
||||
} else {
|
||||
await sendTextMessage(userId, message);
|
||||
}
|
||||
|
||||
messageInput.value = '';
|
||||
};
|
||||
|
||||
// Función para enviar mensaje de texto
|
||||
async function sendTextMessage(userId, message) {
|
||||
try {
|
||||
const manager = window.whatsappManager;
|
||||
const usersResponse = await manager.apiCall('get_users.php?debug=true');
|
||||
|
||||
// Manejar diferentes formatos de respuesta
|
||||
let users = [];
|
||||
if (Array.isArray(usersResponse)) {
|
||||
users = usersResponse;
|
||||
} else if (usersResponse && usersResponse.data && Array.isArray(usersResponse.data)) {
|
||||
users = usersResponse.data;
|
||||
} else if (usersResponse && usersResponse.users && Array.isArray(usersResponse.users)) {
|
||||
users = usersResponse.users;
|
||||
} else {
|
||||
console.error('Formato de respuesta de usuarios inesperado:', usersResponse);
|
||||
throw new Error('Error obteniendo lista de usuarios');
|
||||
}
|
||||
|
||||
const user = users.find(u => u.id == userId);
|
||||
|
||||
if (!user) {
|
||||
throw new Error('Usuario no encontrado');
|
||||
}
|
||||
|
||||
const response = await manager.apiCall('send_message.php', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
recipient: user.phone_number,
|
||||
type: 'text',
|
||||
message: message
|
||||
}
|
||||
});
|
||||
|
||||
if (response && response.success) {
|
||||
// Refrescar chat
|
||||
openChatWindow(userId);
|
||||
showAlert('Mensaje enviado correctamente', 'success');
|
||||
} else {
|
||||
throw new Error(response.error || 'Error enviando mensaje');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error enviando mensaje:', error);
|
||||
showAlert('Error enviando mensaje: ' + error.message, 'danger');
|
||||
}
|
||||
}
|
||||
|
||||
// Función para enviar mensaje de plantilla
|
||||
async function sendTemplateMessage(userId, template, parameters) {
|
||||
try {
|
||||
const manager = window.whatsappManager;
|
||||
const usersResponse = await manager.apiCall('get_users.php?debug=true');
|
||||
|
||||
// Manejar diferentes formatos de respuesta
|
||||
let users = [];
|
||||
if (Array.isArray(usersResponse)) {
|
||||
users = usersResponse;
|
||||
} else if (usersResponse && usersResponse.data && Array.isArray(usersResponse.data)) {
|
||||
users = usersResponse.data;
|
||||
} else if (usersResponse && usersResponse.users && Array.isArray(usersResponse.users)) {
|
||||
users = usersResponse.users;
|
||||
} else {
|
||||
console.error('Formato de respuesta de usuarios inesperado:', usersResponse);
|
||||
throw new Error('Error obteniendo lista de usuarios');
|
||||
}
|
||||
|
||||
const user = users.find(u => u.id == userId);
|
||||
|
||||
if (!user) {
|
||||
throw new Error('Usuario no encontrado');
|
||||
}
|
||||
|
||||
const response = await manager.apiCall('send_message.php', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
recipient: user.phone_number,
|
||||
type: 'template',
|
||||
template: template,
|
||||
language: 'en_US',
|
||||
parameters: parameters ? parameters.split(',') : []
|
||||
}
|
||||
});
|
||||
|
||||
if (response && response.success) {
|
||||
// Refrescar chat
|
||||
openChatWindow(userId);
|
||||
showAlert('Mensaje de plantilla enviado correctamente', 'success');
|
||||
} else {
|
||||
throw new Error(response.error || 'Error enviando plantilla');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error enviando plantilla:', error);
|
||||
showAlert('Error enviando plantilla: ' + error.message, 'danger');
|
||||
}
|
||||
}
|
||||
|
||||
// Función para ver detalles de conversación
|
||||
window.viewConversationDetails = function (userId) {
|
||||
console.log('Viendo detalles de conversación del usuario:', userId);
|
||||
openChatWindow(userId);
|
||||
};
|
||||
|
||||
// Función para mostrar alertas
|
||||
function showAlert(message, type = 'info') {
|
||||
const alertHtml = `
|
||||
<div class="alert alert-${type} alert-dismissible fade show position-fixed" style="top: 20px; right: 20px; z-index: 9999;" role="alert">
|
||||
${message}
|
||||
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
document.body.insertAdjacentHTML('beforeend', alertHtml);
|
||||
|
||||
// Auto-dismiss después de 5 segundos
|
||||
setTimeout(() => {
|
||||
const alert = document.querySelector('.alert');
|
||||
if (alert) {
|
||||
alert.remove();
|
||||
}
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
// Función para ver conversación específica (mantener compatibilidad)
|
||||
window.viewConversation = function (userId) {
|
||||
console.log('Viendo conversación del usuario:', userId);
|
||||
alert(`Ver conversación del usuario ${userId} - Función en desarrollo`);
|
||||
openChatWindow(userId);
|
||||
};
|
||||
|
||||
// Función para editar usuario
|
||||
|
||||
Reference in New Issue
Block a user