diff --git a/modules/turnero/views/chat.php b/modules/turnero/views/chat.php index 0ac7df7..c5c4ae8 100644 --- a/modules/turnero/views/chat.php +++ b/modules/turnero/views/chat.php @@ -525,10 +525,12 @@ function closeChatMobile() { // ── Mensajes ────────────────────────────────────────────────────────────────── async function fetchMessages() { if (!state.activeUserId) return; - const url = BASE + API_MESSAGES + '?user_id=' + state.activeUserId + '&limit=50'; + const forUser = state.activeUserId; // captura antes del await + const url = BASE + API_MESSAGES + '?user_id=' + forUser + '&limit=50'; try { const res = await fetch(url); const json = await res.json(); + if (forUser !== state.activeUserId) return; // usuario cambió mientras esperaba if (!json.success) return; state.messages = json.data; state.hasMore = json.has_more; @@ -541,14 +543,16 @@ async function fetchMessages() { async function loadMoreMessages() { if (!state.activeUserId || !state.earliest) return; + const forUser = state.activeUserId; const url = BASE + API_MESSAGES - + '?user_id=' + state.activeUserId + + '?user_id=' + forUser + '&limit=50' + '&before=' + encodeURIComponent(state.earliest) + (state.earliestId ? '&before_id=' + state.earliestId : ''); try { const res = await fetch(url); const json = await res.json(); + if (forUser !== state.activeUserId) return; if (!json.success || !json.data.length) { document.getElementById('loadMoreBtn').style.display = 'none'; return; @@ -563,13 +567,16 @@ async function loadMoreMessages() { async function pollMessages() { if (!state.activeUserId || !state.lastPollTime) return; + const forUser = state.activeUserId; + const sinceTime = state.lastPollTime; const url = BASE + API_MESSAGES - + '?user_id=' + state.activeUserId + + '?user_id=' + forUser + '&limit=50' - + '&since=' + encodeURIComponent(state.lastPollTime); + + '&since=' + encodeURIComponent(sinceTime); try { const res = await fetch(url); const json = await res.json(); + if (forUser !== state.activeUserId) return; // usuario cambió mientras esperaba if (!json.success || !json.data.length) return; json.data.forEach(m => { if (!state.messages.find(x => x.id === m.id)) { @@ -578,7 +585,7 @@ async function pollMessages() { } }); state.lastPollTime = json.data[json.data.length - 1].created_at; - markRead(state.activeUserId); + markRead(forUser); loadContacts(document.getElementById('searchInput').value.trim(), true); } catch(e) {} }