up
This commit is contained in:
+227
-33
@@ -398,6 +398,31 @@
|
||||
transform: translateX(-100%);
|
||||
}
|
||||
}
|
||||
|
||||
.reply-preview {
|
||||
background: #f4f6f8;
|
||||
border-left: 3px solid #d0d7de;
|
||||
padding: 6px 8px;
|
||||
margin-bottom: 6px;
|
||||
font-size: 12px;
|
||||
color: #555;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.reaction-badge {
|
||||
display: inline-block;
|
||||
background: rgba(0,0,0,0.06);
|
||||
padding: 2px 6px;
|
||||
border-radius: 12px;
|
||||
font-size: 12px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.conversation-avatar img, .conversation-avatar-img { max-width: 44px; max-height:44px; border-radius:50%; }
|
||||
.conversation-avatar-wrapper { width:48px; display:flex; align-items:center; justify-content:center }
|
||||
.conversation-item.unread { background: rgba(255, 248, 220, 0.9); }
|
||||
.unread-badge { margin-left: 8px; font-size: 12px; }
|
||||
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
@@ -446,9 +471,12 @@
|
||||
<i class="fas fa-user"></i>
|
||||
</div>
|
||||
<div class="chat-header-info">
|
||||
<h6 id="chat-name">Usuario</h6>
|
||||
<h6 id="chat-name">Usuario <button class="btn btn-sm btn-link" id="edit-user-btn" title="Editar usuario"><i class="fas fa-user-edit"></i></button></h6>
|
||||
<small id="chat-phone">+1234567890</small>
|
||||
</div>
|
||||
<div style="margin-left: auto; display:flex; gap:8px; align-items:center;">
|
||||
<button class="btn btn-sm btn-outline-danger" id="delete-conversation-btn" title="Eliminar conversación"><i class="fas fa-trash"></i></button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="chat-messages" id="chat-messages">
|
||||
@@ -477,6 +505,9 @@
|
||||
<button class="btn" id="attach-btn" title="Adjuntar archivo">
|
||||
<i class="fas fa-paperclip"></i>
|
||||
</button>
|
||||
<div class="quick-replies" id="quick-replies" style="display:flex;gap:6px;align-items:center;">
|
||||
<!-- Quick replies buttons inserted dynamically -->
|
||||
</div>
|
||||
<input type="text" placeholder="Escribe un mensaje..." id="message-input" maxlength="4096">
|
||||
<button class="btn" id="send-btn">
|
||||
<i class="fas fa-paper-plane"></i>
|
||||
@@ -582,43 +613,26 @@
|
||||
return;
|
||||
}
|
||||
|
||||
// Agrupar por usuario
|
||||
const userConversations = {};
|
||||
this.conversations.forEach(conv => {
|
||||
const key = conv.user_id;
|
||||
if (!userConversations[key]) {
|
||||
userConversations[key] = {
|
||||
user_id: conv.user_id,
|
||||
name: conv.name || conv.phone_number,
|
||||
phone_number: conv.phone_number,
|
||||
last_message: conv.content,
|
||||
last_time: conv.created_at,
|
||||
direction: conv.direction,
|
||||
unread: 0
|
||||
};
|
||||
}
|
||||
|
||||
// Mantener el mensaje más reciente
|
||||
if (new Date(conv.created_at) > new Date(userConversations[key].last_time)) {
|
||||
userConversations[key].last_message = conv.content;
|
||||
userConversations[key].last_time = conv.created_at;
|
||||
userConversations[key].direction = conv.direction;
|
||||
}
|
||||
});
|
||||
|
||||
const html = Object.values(userConversations).map(conv => {
|
||||
const initials = this.getInitials(conv.name);
|
||||
// Ahora el backend devuelve por usuario: last_message, last_time, unread_count y avatar_url
|
||||
const html = this.conversations.map(conv => {
|
||||
const isActive = conv.user_id == this.currentUserId ? 'active' : '';
|
||||
const time = this.formatTime(conv.last_time);
|
||||
const preview = this.truncateText(conv.last_message || 'Sin mensajes', 50);
|
||||
const isActive = conv.user_id == this.currentUserId ? 'active' : '';
|
||||
|
||||
|
||||
const avatar = conv.avatar_url ? `<img src="${conv.avatar_url}" alt="avatar" class="conversation-avatar-img">` : `<div class="conversation-avatar">${this.getInitials(conv.name)}</div>`;
|
||||
|
||||
const unreadBadge = conv.unread_count && conv.unread_count > 0 ? `<span class="badge bg-danger unread-badge">${conv.unread_count}</span>` : '';
|
||||
|
||||
// different color if has unread and not active
|
||||
const unreadClass = (conv.unread_count && conv.unread_count > 0 && !isActive) ? 'unread' : '';
|
||||
|
||||
return `
|
||||
<div class="conversation-item ${isActive}" data-user-id="${conv.user_id}" onclick="chat.openConversation(${conv.user_id}, '${conv.name}', '${conv.phone_number}')">
|
||||
<div class="conversation-avatar">
|
||||
${initials}
|
||||
<div class="conversation-item ${isActive} ${unreadClass}" data-user-id="${conv.user_id}" onclick="chat.openConversation(${conv.user_id}, '${conv.name}', '${conv.phone_number}')">
|
||||
<div class="conversation-avatar-wrapper">
|
||||
${avatar}
|
||||
</div>
|
||||
<div class="conversation-info">
|
||||
<div class="conversation-name">${conv.name}</div>
|
||||
<div class="conversation-name">${conv.name} ${unreadBadge}</div>
|
||||
<div class="conversation-preview">
|
||||
${conv.direction === 'outgoing' ? '✓ ' : ''}${preview}
|
||||
</div>
|
||||
@@ -630,6 +644,17 @@
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
// Detectar nuevas notificaciones: comparar unread counts previos
|
||||
if (!this._prevConversations) this._prevConversations = {};
|
||||
this.conversations.forEach(c => {
|
||||
const prev = this._prevConversations[c.user_id] || { unread_count: 0 };
|
||||
if (c.unread_count > prev.unread_count && c.user_id != this.currentUserId) {
|
||||
// nueva notificación
|
||||
this.playNotificationSound();
|
||||
}
|
||||
this._prevConversations[c.user_id] = { unread_count: c.unread_count };
|
||||
});
|
||||
|
||||
container.innerHTML = html;
|
||||
}
|
||||
|
||||
@@ -667,6 +692,24 @@
|
||||
return text.substring(0, maxLength) + '...';
|
||||
}
|
||||
|
||||
playNotificationSound() {
|
||||
try {
|
||||
// Small beep using Web Audio API (no external file needed)
|
||||
const ctx = new (window.AudioContext || window.webkitAudioContext)();
|
||||
const o = ctx.createOscillator();
|
||||
const g = ctx.createGain();
|
||||
o.type = 'sine';
|
||||
o.frequency.value = 880;
|
||||
o.connect(g);
|
||||
g.connect(ctx.destination);
|
||||
g.gain.value = 0.05;
|
||||
o.start();
|
||||
setTimeout(() => { o.stop(); ctx.close(); }, 180);
|
||||
} catch (e) {
|
||||
console.warn('Notification sound failed', e);
|
||||
}
|
||||
}
|
||||
|
||||
async openConversation(userId, userName, phoneNumber) {
|
||||
this.currentUserId = userId;
|
||||
|
||||
@@ -687,6 +730,8 @@
|
||||
|
||||
// Cargar mensajes
|
||||
await this.loadMessages(userId);
|
||||
// Cargar respuestas rápidas
|
||||
await this.loadQuickReplies();
|
||||
}
|
||||
|
||||
async loadMessages(userId, showLoading = true) {
|
||||
@@ -706,6 +751,19 @@
|
||||
this.messages = data;
|
||||
this.renderMessages();
|
||||
this.scrollToBottom();
|
||||
|
||||
// Marcar como leídos en el backend
|
||||
try {
|
||||
await fetch('api/mark_conversation_read.php', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ user_id: userId })
|
||||
});
|
||||
// Recargar lista de conversaciones para refrescar contadores
|
||||
await this.loadConversations();
|
||||
} catch (e) {
|
||||
console.error('Error marking conversation as read', e);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error loading messages:', error);
|
||||
@@ -743,11 +801,27 @@
|
||||
const content = msg.media_url
|
||||
? this.renderMediaMessage(msg)
|
||||
: (msg.content || msg.message_text || '[Mensaje vacío]');
|
||||
|
||||
// Mostrar preview si es reply/context
|
||||
let replyHtml = '';
|
||||
if (msg.reply_to_message_id) {
|
||||
const target = this.messages.find(m => m.message_id == msg.reply_to_message_id);
|
||||
const previewText = target ? (target.content || target.message_text || '').substring(0,140) : ('Mensaje ' + msg.reply_to_message_id);
|
||||
replyHtml = `<div class="reply-preview">En respuesta a: ${previewText}</div>`;
|
||||
}
|
||||
|
||||
// Mostrar reacción si existe
|
||||
let reactionHtml = '';
|
||||
if (msg.reaction_emoji) {
|
||||
reactionHtml = `<div class="reaction-badge">${msg.reaction_emoji}</div>`;
|
||||
}
|
||||
|
||||
return `
|
||||
<div class="message ${msg.direction}">
|
||||
<div class="message-bubble">
|
||||
${replyHtml}
|
||||
${content}
|
||||
${reactionHtml}
|
||||
<div class="message-actions mt-1">
|
||||
<button class="btn btn-sm btn-link" onclick="app.replyToMessage('${msg.message_id}','${msg.user_phone}')" title="Responder"><i class="fas fa-reply"></i></button>
|
||||
<button class="btn btn-sm btn-link" onclick="app.reactToMessage('${msg.message_id}','${msg.user_phone}')" title="Reaccionar"><i class="far fa-grin"></i></button>
|
||||
@@ -773,6 +847,51 @@
|
||||
}
|
||||
}
|
||||
|
||||
async loadQuickReplies() {
|
||||
const container = document.getElementById('quick-replies');
|
||||
container.innerHTML = '';
|
||||
try {
|
||||
const resp = await fetch('api/get_templates.php?approved_only=1&limit=6');
|
||||
const json = await resp.json();
|
||||
if (json && json.success && Array.isArray(json.data)) {
|
||||
json.data.forEach(t => {
|
||||
const btn = document.createElement('button');
|
||||
btn.className = 'btn btn-outline-primary btn-sm';
|
||||
btn.style.marginRight = '6px';
|
||||
btn.textContent = t.name;
|
||||
btn.addEventListener('click', () => this.sendTemplateQuick(t.template_name, t.language_code || 'es'));
|
||||
container.appendChild(btn);
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Error loading quick replies', e);
|
||||
}
|
||||
}
|
||||
|
||||
async sendTemplateQuick(templateName, language) {
|
||||
if (!this.currentUserId) return;
|
||||
const conv = this.conversations.find(c => c.user_id === this.currentUserId);
|
||||
const phone = conv ? conv.user_phone : document.getElementById('chat-phone').textContent;
|
||||
|
||||
try {
|
||||
const resp = await fetch('api/send_message.php', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ recipient: phone, type: 'template', template_name: templateName, language })
|
||||
});
|
||||
const result = await resp.json();
|
||||
if (result.success) {
|
||||
await this.loadMessages(this.currentUserId, false);
|
||||
await this.loadConversations();
|
||||
} else {
|
||||
alert('Error al enviar plantilla: ' + (result.error || JSON.stringify(result)));
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Error sending template quick', e);
|
||||
alert('Error al enviar plantilla');
|
||||
}
|
||||
}
|
||||
|
||||
scrollToBottom() {
|
||||
const container = document.getElementById('chat-messages');
|
||||
container.scrollTop = container.scrollHeight;
|
||||
@@ -812,6 +931,8 @@
|
||||
await this.loadMessages(this.currentUserId, false);
|
||||
// Actualizar lista de conversaciones
|
||||
this.loadConversations();
|
||||
// Actualizar respuestas rápidas
|
||||
await this.loadQuickReplies();
|
||||
} else {
|
||||
alert('Error al enviar mensaje: ' + (result.error || 'Error desconocido'));
|
||||
}
|
||||
@@ -825,6 +946,79 @@
|
||||
}
|
||||
}
|
||||
|
||||
async loadQuickReplies() {
|
||||
try {
|
||||
const resp = await fetch('api/get_templates.php?approved_only=1&limit=10');
|
||||
const json = await resp.json();
|
||||
const container = document.getElementById('quick-replies');
|
||||
if (!container) return;
|
||||
container.innerHTML = '';
|
||||
if (json && json.success && Array.isArray(json.data)) {
|
||||
const templates = json.data.slice(0,5);
|
||||
templates.forEach(t => {
|
||||
const text = (t.body_text || t.name || t.template_name || '').replace(/\n/g,' ');
|
||||
const btn = document.createElement('button');
|
||||
btn.className = 'btn btn-sm btn-outline-secondary';
|
||||
btn.dataset.qr = text;
|
||||
btn.textContent = text.length > 30 ? text.substring(0,30) + '...' : text;
|
||||
container.appendChild(btn);
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('loadQuickReplies error', err);
|
||||
}
|
||||
}
|
||||
|
||||
async promptEditUser() {
|
||||
const currentName = document.getElementById('chat-name').textContent || '';
|
||||
const newName = prompt('Nombre del usuario:', currentName);
|
||||
if (!newName) return;
|
||||
|
||||
try {
|
||||
const resp = await fetch('api/update_user.php', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ user_id: this.currentUserId, name: newName })
|
||||
});
|
||||
const json = await resp.json();
|
||||
if (json && json.success) {
|
||||
document.getElementById('chat-name').textContent = newName;
|
||||
this.showSuccess('Usuario actualizado');
|
||||
this.loadConversations();
|
||||
} else {
|
||||
this.showError('No se pudo actualizar usuario');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
this.showError('Error actualizando usuario');
|
||||
}
|
||||
}
|
||||
|
||||
async deleteCurrentConversation() {
|
||||
if (!confirm('¿Eliminar esta conversación? Se borrará todo el historial.')) return;
|
||||
try {
|
||||
const resp = await fetch('api/delete_conversation.php', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ user_id: this.currentUserId })
|
||||
});
|
||||
const json = await resp.json();
|
||||
if (json && json.success) {
|
||||
this.showSuccess('Conversación eliminada');
|
||||
// reset UI
|
||||
document.getElementById('chat-area').style.display = 'none';
|
||||
document.getElementById('no-conversation').style.display = 'block';
|
||||
this.currentUserId = null;
|
||||
this.loadConversations();
|
||||
} else {
|
||||
this.showError('No se pudo eliminar la conversación');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
this.showError('Error eliminando la conversación');
|
||||
}
|
||||
}
|
||||
|
||||
searchConversations(query) {
|
||||
const items = document.querySelectorAll('.conversation-item');
|
||||
items.forEach(item => {
|
||||
|
||||
Reference in New Issue
Block a user