funcional
This commit is contained in:
@@ -782,4 +782,304 @@ body {
|
||||
box-shadow: none;
|
||||
border: 1px solid #ddd;
|
||||
}
|
||||
}
|
||||
|
||||
/* =================================
|
||||
CHAT STYLES
|
||||
================================= */
|
||||
|
||||
.chat-container {
|
||||
background: linear-gradient(135deg, #e5ddd5 0%, #d4c5b9 100%);
|
||||
}
|
||||
|
||||
.conversation-row:hover {
|
||||
background-color: #f8f9fa !important;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.message-bubble {
|
||||
position: relative;
|
||||
word-wrap: break-word;
|
||||
border: none;
|
||||
}
|
||||
|
||||
.message-bubble.outgoing {
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.message-bubble.incoming {
|
||||
margin-right: auto;
|
||||
}
|
||||
|
||||
.message-time {
|
||||
text-align: right;
|
||||
margin-top: 4px;
|
||||
font-size: 0.7rem;
|
||||
}
|
||||
|
||||
.avatar-placeholder {
|
||||
font-weight: bold;
|
||||
font-size: 16px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* Modal de chat personalizado */
|
||||
#chatModal .modal-content {
|
||||
border: none;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
#chatModal .modal-header {
|
||||
border-radius: 12px 12px 0 0;
|
||||
border-bottom: 1px solid rgba(255,255,255,0.2);
|
||||
}
|
||||
|
||||
#chatModal .modal-body {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.message-bubble.bg-success {
|
||||
background: linear-gradient(135deg, #25d366, #20b358) !important;
|
||||
}
|
||||
|
||||
.message-bubble.bg-white {
|
||||
background: #ffffff !important;
|
||||
border: 1px solid #e9ecef;
|
||||
}
|
||||
|
||||
/* Mejorar responsividad de conversaciones */
|
||||
@media (max-width: 768px) {
|
||||
.conversation-row .btn-group .btn {
|
||||
padding: 0.25rem 0.5rem;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.message-bubble {
|
||||
max-width: 85% !important;
|
||||
}
|
||||
|
||||
#chatModal .modal-dialog {
|
||||
max-width: 95%;
|
||||
margin: 1rem auto;
|
||||
}
|
||||
}
|
||||
|
||||
/* Animaciones para mensajes */
|
||||
.message-bubble {
|
||||
animation: messageAppear 0.3s ease-out;
|
||||
}
|
||||
|
||||
@keyframes messageAppear {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(10px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
/* Estilos mejorados para lista de conversaciones */
|
||||
.conversation-card {
|
||||
border: none;
|
||||
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
|
||||
border-radius: 20px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.conversation-card .card-header {
|
||||
border: none;
|
||||
background: linear-gradient(135deg, #25d366 0%, #128c7e 100%);
|
||||
padding: 1.5rem;
|
||||
}
|
||||
|
||||
.conversation-list {
|
||||
max-height: 600px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.conversation-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 15px 20px;
|
||||
border-bottom: 1px solid #f0f0f0;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
position: relative;
|
||||
background: white;
|
||||
}
|
||||
|
||||
.conversation-item:hover {
|
||||
background: #f8f9fa;
|
||||
transform: translateX(5px);
|
||||
}
|
||||
|
||||
.conversation-item:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.conversation-avatar {
|
||||
width: 55px;
|
||||
height: 55px;
|
||||
background: linear-gradient(135deg, #25d366, #128c7e);
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: white;
|
||||
font-weight: bold;
|
||||
font-size: 1.4rem;
|
||||
margin-right: 15px;
|
||||
box-shadow: 0 4px 12px rgba(37, 211, 102, 0.3);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.conversation-avatar.online::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
bottom: 2px;
|
||||
right: 2px;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
background: #4ade80;
|
||||
border: 2px solid white;
|
||||
border-radius: 50%;
|
||||
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.conversation-details {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.conversation-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
.conversation-name {
|
||||
font-weight: 600;
|
||||
font-size: 1.1rem;
|
||||
color: #1f2937;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.conversation-time {
|
||||
font-size: 0.8rem;
|
||||
color: #9ca3af;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.conversation-preview {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.conversation-last-message {
|
||||
color: #6b7280;
|
||||
font-size: 0.9rem;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.conversation-meta {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.conversation-unread {
|
||||
background: #25d366;
|
||||
color: white;
|
||||
border-radius: 50%;
|
||||
padding: 4px 8px;
|
||||
font-size: 0.75rem;
|
||||
font-weight: bold;
|
||||
min-width: 20px;
|
||||
height: 20px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.conversation-status-icon {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.conversation-status-icon.outgoing {
|
||||
color: #25d366;
|
||||
}
|
||||
|
||||
.conversation-status-icon.incoming {
|
||||
color: #3b82f6;
|
||||
}
|
||||
|
||||
.conversation-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
opacity: 0;
|
||||
transition: opacity 0.2s ease;
|
||||
}
|
||||
|
||||
.conversation-item:hover .conversation-actions {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.conversation-actions .btn {
|
||||
padding: 6px 10px;
|
||||
font-size: 0.8rem;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #e5e7eb;
|
||||
background: white;
|
||||
color: #6b7280;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.conversation-actions .btn:hover {
|
||||
background: #25d366;
|
||||
color: white;
|
||||
border-color: #25d366;
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.conversation-empty {
|
||||
text-align: center;
|
||||
padding: 60px 20px;
|
||||
color: #9ca3af;
|
||||
}
|
||||
|
||||
.conversation-empty .empty-icon {
|
||||
font-size: 4rem;
|
||||
color: #d1d5db;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.conversation-search {
|
||||
border-radius: 25px;
|
||||
border: none;
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
color: white;
|
||||
padding: 8px 20px;
|
||||
}
|
||||
|
||||
.conversation-search::placeholder {
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
}
|
||||
|
||||
.conversation-search:focus {
|
||||
background: rgba(255, 255, 255, 0.3);
|
||||
color: white;
|
||||
box-shadow: none;
|
||||
border: 1px solid rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
+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