Compare commits
15
Commits
87bc7d9591
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3c34cbb439 | ||
|
|
62249b18b3 | ||
|
|
bd92137fdc | ||
|
|
db9a8e9d7b | ||
|
|
da611b81b6 | ||
|
|
64407d0241 | ||
|
|
c126032cc9 | ||
|
|
c5567413e1 | ||
|
|
aa23e73b34 | ||
|
|
c9f584ce2a | ||
|
|
9248ef775a | ||
|
|
c78f9bc944 | ||
|
|
f4f781b835 | ||
|
|
9fd01d6f78 | ||
|
|
5a9ba0cc23 |
No files matched your search
+8
-5
@@ -51,7 +51,8 @@ AWS_USE_PATH_STYLE_ENDPOINT=false
|
|||||||
CHAT_SUPPORT_USER_ID=
|
CHAT_SUPPORT_USER_ID=
|
||||||
|
|
||||||
# Laravel Reverb (`php artisan reverb:start` / supervisor).
|
# Laravel Reverb (`php artisan reverb:start` / supervisor).
|
||||||
# PHP broadcasts to this host. Browsers use nginx at wss://mm.com.tm/app.
|
# PHP publishes events to 127.0.0.1:8080 (REVERB_BROADCAST_* / SERVER_PORT).
|
||||||
|
# Browsers use nginx at wss://mm.com.tm/app (VITE_REVERB_*).
|
||||||
# Local:
|
# Local:
|
||||||
REVERB_APP_ID=
|
REVERB_APP_ID=
|
||||||
REVERB_APP_KEY=
|
REVERB_APP_KEY=
|
||||||
@@ -61,10 +62,12 @@ REVERB_PORT=8080
|
|||||||
REVERB_SCHEME=http
|
REVERB_SCHEME=http
|
||||||
REVERB_SERVER_HOST=0.0.0.0
|
REVERB_SERVER_HOST=0.0.0.0
|
||||||
REVERB_SERVER_PORT=8080
|
REVERB_SERVER_PORT=8080
|
||||||
# Production (keep SERVER_* on 8080; PHP can still use 127.0.0.1:8080):
|
REVERB_BROADCAST_HOST=127.0.0.1
|
||||||
# REVERB_HOST=127.0.0.1
|
REVERB_BROADCAST_PORT=8080
|
||||||
# REVERB_PORT=8080
|
REVERB_BROADCAST_SCHEME=http
|
||||||
# REVERB_SCHEME=http
|
# Production: keep BROADCAST_* and SERVER_* on 127.0.0.1:8080.
|
||||||
|
# Set VITE_REVERB_HOST=mm.com.tm VITE_REVERB_PORT=443 VITE_REVERB_SCHEME=https
|
||||||
|
# on the frontend build. Do not point PHP at mm.com.tm:443.
|
||||||
|
|
||||||
VITE_REVERB_APP_KEY="${REVERB_APP_KEY}"
|
VITE_REVERB_APP_KEY="${REVERB_APP_KEY}"
|
||||||
VITE_REVERB_HOST="${REVERB_HOST}"
|
VITE_REVERB_HOST="${REVERB_HOST}"
|
||||||
|
|||||||
@@ -87,10 +87,15 @@ public function send(ChatSendMessageRequest $request, Conversation $conversation
|
|||||||
|
|
||||||
public function read(Conversation $conversation): JsonResponse
|
public function read(Conversation $conversation): JsonResponse
|
||||||
{
|
{
|
||||||
$sender = $this->assertCanReply(request()->user(), $conversation);
|
$actor = request()->user();
|
||||||
|
$this->assertCanView($actor, $conversation);
|
||||||
|
|
||||||
|
$excludeId = ChatSupport::isOperator($actor)
|
||||||
|
? ChatSupport::user()->id
|
||||||
|
: $actor->id;
|
||||||
|
|
||||||
$conversation->messages()
|
$conversation->messages()
|
||||||
->where('user_id', '!=', $sender->id)
|
->where('user_id', '!=', $excludeId)
|
||||||
->whereNull('seen_at')
|
->whereNull('seen_at')
|
||||||
->update(['seen_at' => now()]);
|
->update(['seen_at' => now()]);
|
||||||
|
|
||||||
|
|||||||
@@ -236,7 +236,7 @@ public function setupNavigation(): void
|
|||||||
|
|
||||||
MenuSection::make(__('Backups'), [
|
MenuSection::make(__('Backups'), [
|
||||||
MenuItem::make('Backups')->path('/backups'),
|
MenuItem::make('Backups')->path('/backups'),
|
||||||
])->canSee(fn () => false)->icon('server')->collapsedByDefault(),
|
])->canSee(fn () => auth()->user()->isAdmin() || auth()->user()->isDirektor())->icon('server')->collapsedByDefault(),
|
||||||
];
|
];
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,10 +36,10 @@
|
|||||||
'secret' => env('REVERB_APP_SECRET'),
|
'secret' => env('REVERB_APP_SECRET'),
|
||||||
'app_id' => env('REVERB_APP_ID'),
|
'app_id' => env('REVERB_APP_ID'),
|
||||||
'options' => [
|
'options' => [
|
||||||
'host' => env('REVERB_HOST'),
|
'host' => env('REVERB_BROADCAST_HOST', '127.0.0.1'),
|
||||||
'port' => env('REVERB_PORT', 443),
|
'port' => (int) env('REVERB_BROADCAST_PORT', env('REVERB_SERVER_PORT', 8080)),
|
||||||
'scheme' => env('REVERB_SCHEME', 'https'),
|
'scheme' => env('REVERB_BROADCAST_SCHEME', 'http'),
|
||||||
'useTLS' => env('REVERB_SCHEME', 'https') === 'https',
|
'useTLS' => env('REVERB_BROADCAST_SCHEME', 'http') === 'https',
|
||||||
'path' => env('REVERB_SERVER_PATH', ''),
|
'path' => env('REVERB_SERVER_PATH', ''),
|
||||||
],
|
],
|
||||||
'client_options' => [
|
'client_options' => [
|
||||||
|
|||||||
Binary file not shown.
+266
-136
@@ -1,4 +1,6 @@
|
|||||||
(function () {
|
(function () {
|
||||||
|
"use strict";
|
||||||
|
|
||||||
const config = window.MM_CHAT || {};
|
const config = window.MM_CHAT || {};
|
||||||
const listEl = document.getElementById("mm-chat-list");
|
const listEl = document.getElementById("mm-chat-list");
|
||||||
const emptyInboxEl = document.getElementById("mm-chat-empty-inbox");
|
const emptyInboxEl = document.getElementById("mm-chat-empty-inbox");
|
||||||
@@ -19,52 +21,132 @@
|
|||||||
echo: null,
|
echo: null,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 1. NOTIFICATION MANAGER (Visual Toast UI)
|
||||||
|
// =========================================================================
|
||||||
|
const notifiedIds = new Set();
|
||||||
|
let inboxReady = false;
|
||||||
|
let toastContainer = null;
|
||||||
|
|
||||||
|
function initToastContainer() {
|
||||||
|
if (toastContainer) return;
|
||||||
|
toastContainer = document.createElement("div");
|
||||||
|
toastContainer.className = "mm-chat-toast-container";
|
||||||
|
toastContainer.style.cssText = `
|
||||||
|
position: absolute;
|
||||||
|
top: 15px;
|
||||||
|
left: 50%;
|
||||||
|
transform: translateX(-50%);
|
||||||
|
z-index: 9999;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
pointer-events: none;
|
||||||
|
width: 90%;
|
||||||
|
max-width: 320px;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const chatPane = messagesEl ? messagesEl.parentElement : document.body;
|
||||||
|
if (chatPane) {
|
||||||
|
if (getComputedStyle(chatPane).position === "static") {
|
||||||
|
chatPane.style.position = "relative";
|
||||||
|
}
|
||||||
|
chatPane.appendChild(toastContainer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function showNotification(title, text, conversationId) {
|
||||||
|
initToastContainer();
|
||||||
|
const toast = document.createElement("div");
|
||||||
|
toast.style.cssText = `
|
||||||
|
background-color: #1e293b;
|
||||||
|
color: #f8fafc;
|
||||||
|
padding: 12px 16px;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 13px;
|
||||||
|
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
|
||||||
|
pointer-events: auto;
|
||||||
|
cursor: pointer;
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(-10px);
|
||||||
|
transition: all 0.3s ease;
|
||||||
|
border: 1px solid #334155;
|
||||||
|
`;
|
||||||
|
|
||||||
|
toast.innerHTML = `
|
||||||
|
<div style="font-weight: 600; margin-bottom: 2px;">${title}</div>
|
||||||
|
<div style="opacity: 0.8; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${text}</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
toast.addEventListener("click", () => {
|
||||||
|
if (conversationId) openConversation(conversationId);
|
||||||
|
toast.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
toastContainer.appendChild(toast);
|
||||||
|
|
||||||
|
// Animate in
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
toast.style.opacity = "1";
|
||||||
|
toast.style.transform = "translateY(0)";
|
||||||
|
});
|
||||||
|
|
||||||
|
// Auto-remove after 4 seconds
|
||||||
|
setTimeout(() => {
|
||||||
|
toast.style.opacity = "0";
|
||||||
|
toast.style.transform = "translateY(-10px)";
|
||||||
|
setTimeout(() => toast.remove(), 300);
|
||||||
|
}, 4000);
|
||||||
|
}
|
||||||
|
|
||||||
|
function notifyIncoming(message, conversation) {
|
||||||
|
const key = messageKey(message);
|
||||||
|
if (!key || notifiedIds.has(key)) return;
|
||||||
|
notifiedIds.add(key);
|
||||||
|
|
||||||
|
// Skip toast if they are actively looking at this exact chat thread
|
||||||
|
if (state.activeId === message.conversation_id && document.visibilityState === "visible") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const senderName = (conversation && conversation.user && conversation.user.name) || "New Message";
|
||||||
|
showNotification(senderName, preview(message.body), message.conversation_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 2. CHAT HELPERS & RENDERING
|
||||||
|
// =========================================================================
|
||||||
function headers(json) {
|
function headers(json) {
|
||||||
const next = {
|
const next = {
|
||||||
Accept: "application/json",
|
Accept: "application/json",
|
||||||
"X-CSRF-TOKEN": config.csrf,
|
"X-CSRF-TOKEN": config.csrf,
|
||||||
"X-Requested-With": "XMLHttpRequest",
|
"X-Requested-With": "XMLHttpRequest",
|
||||||
};
|
};
|
||||||
|
if (json) next["Content-Type"] = "application/json";
|
||||||
if (json) {
|
|
||||||
next["Content-Type"] = "application/json";
|
|
||||||
}
|
|
||||||
|
|
||||||
return next;
|
return next;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function request(url, options) {
|
async function request(url, options) {
|
||||||
const response = await fetch(url, options);
|
const response = await fetch(url, options);
|
||||||
if (!response.ok) {
|
if (!response.ok) throw new Error("Chat request failed");
|
||||||
throw new Error("Chat request failed");
|
|
||||||
}
|
|
||||||
return response.json();
|
return response.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatTime(value) {
|
function formatTime(value) {
|
||||||
if (!value) {
|
if (!value) return "";
|
||||||
return "";
|
|
||||||
}
|
|
||||||
const date = new Date(value);
|
const date = new Date(value);
|
||||||
if (Number.isNaN(date.getTime())) {
|
if (Number.isNaN(date.getTime())) return "";
|
||||||
return "";
|
|
||||||
}
|
|
||||||
const pad = (n) => String(n).padStart(2, "0");
|
const pad = (n) => String(n).padStart(2, "0");
|
||||||
return `${pad(date.getHours())}:${pad(date.getMinutes())}, ${pad(date.getDate())}.${pad(date.getMonth() + 1)}.${date.getFullYear()}`;
|
return `${pad(date.getHours())}:${pad(date.getMinutes())}, ${pad(date.getDate())}.${pad(date.getMonth() + 1)}.${pad(date.getFullYear())}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function preview(body) {
|
function preview(body) {
|
||||||
if (!body) {
|
if (!body) return "";
|
||||||
return "";
|
|
||||||
}
|
|
||||||
return body.length > 80 ? `${body.slice(0, 80)}…` : body;
|
return body.length > 80 ? `${body.slice(0, 80)}…` : body;
|
||||||
}
|
}
|
||||||
|
|
||||||
function updateUnreadBadge() {
|
function updateUnreadBadge() {
|
||||||
const total = state.conversations.reduce(
|
const total = state.conversations.reduce((sum, conv) => sum + (conv.unread_count || 0), 0);
|
||||||
(sum, conversation) => sum + (conversation.unread_count || 0),
|
|
||||||
0
|
|
||||||
);
|
|
||||||
unreadEl.textContent = String(total);
|
unreadEl.textContent = String(total);
|
||||||
unreadEl.hidden = total < 1;
|
unreadEl.hidden = total < 1;
|
||||||
}
|
}
|
||||||
@@ -77,9 +159,7 @@
|
|||||||
const button = document.createElement("button");
|
const button = document.createElement("button");
|
||||||
button.type = "button";
|
button.type = "button";
|
||||||
button.className = "mm-chat__item";
|
button.className = "mm-chat__item";
|
||||||
if (conversation.id === state.activeId) {
|
if (conversation.id === state.activeId) button.classList.add("is-active");
|
||||||
button.classList.add("is-active");
|
|
||||||
}
|
|
||||||
|
|
||||||
const name = (conversation.user && conversation.user.name) || `#${conversation.id}`;
|
const name = (conversation.user && conversation.user.name) || `#${conversation.id}`;
|
||||||
const phone = conversation.user && conversation.user.phone_number;
|
const phone = conversation.user && conversation.user.phone_number;
|
||||||
@@ -103,27 +183,61 @@
|
|||||||
button.querySelector(".mm-chat__item-name").textContent = name;
|
button.querySelector(".mm-chat__item-name").textContent = name;
|
||||||
button.querySelector(".mm-chat__item-time").textContent = time;
|
button.querySelector(".mm-chat__item-time").textContent = time;
|
||||||
button.querySelector(".mm-chat__item-sub").textContent = subtitle;
|
button.querySelector(".mm-chat__item-sub").textContent = subtitle;
|
||||||
if (phone) {
|
if (phone) button.querySelector(".mm-chat__item-phone").textContent = String(phone);
|
||||||
button.querySelector(".mm-chat__item-phone").textContent = String(phone);
|
button.querySelector(".mm-chat__item-preview").textContent = last ? preview(last.body) : "";
|
||||||
}
|
|
||||||
button.querySelector(".mm-chat__item-preview").textContent = last
|
|
||||||
? preview(last.body)
|
|
||||||
: "";
|
|
||||||
const unread = button.querySelector(".mm-chat__item-unread");
|
const unread = button.querySelector(".mm-chat__item-unread");
|
||||||
if (unread) {
|
if (unread) unread.textContent = String(conversation.unread_count);
|
||||||
unread.textContent = String(conversation.unread_count);
|
|
||||||
}
|
|
||||||
|
|
||||||
button.addEventListener("click", () => openConversation(conversation.id));
|
button.addEventListener("click", () => openConversation(conversation.id));
|
||||||
listEl.appendChild(button);
|
listEl.appendChild(button);
|
||||||
});
|
});
|
||||||
|
|
||||||
updateUnreadBadge();
|
updateUnreadBadge();
|
||||||
}
|
}
|
||||||
|
|
||||||
function isOutgoing(message, conversation) {
|
function isOutgoing(message, conversation) {
|
||||||
|
if (!message) return false;
|
||||||
|
if (message.tempId || String(message.id).startsWith("temp-")) return true;
|
||||||
|
if (message.is_outgoing || message.sender_type === "admin" || message.sender_type === "operator") return true;
|
||||||
|
|
||||||
const otherId = conversation && conversation.user && conversation.user.id;
|
const otherId = conversation && conversation.user && conversation.user.id;
|
||||||
return !otherId || message.user?.id !== otherId;
|
if (!otherId) return true;
|
||||||
|
return String(message.user?.id) !== String(otherId);
|
||||||
|
}
|
||||||
|
|
||||||
|
function messageKey(message) {
|
||||||
|
return message && message.id != null ? String(message.id) : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeIncoming(payload) {
|
||||||
|
if (!payload || typeof payload !== "object") return payload;
|
||||||
|
if (payload.conversation_id && payload.id) return payload;
|
||||||
|
if (payload.message && payload.message.id) return payload.message;
|
||||||
|
if (payload.data && payload.data.id) return payload.data;
|
||||||
|
return payload;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Double message fix core: explicitly handles temp messages
|
||||||
|
function addOrUpdateMessage(message) {
|
||||||
|
if (!message || !message.id) return false;
|
||||||
|
|
||||||
|
// 1. If it's a real server message, scrub out any optimistic duplicates based on body
|
||||||
|
if (!String(message.id).startsWith("temp-")) {
|
||||||
|
const tempIdx = state.messages.findIndex(m => m.tempId && m.body === message.body);
|
||||||
|
if (tempIdx !== -1) {
|
||||||
|
state.messages.splice(tempIdx, 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Add or update by ID
|
||||||
|
const existingIdx = state.messages.findIndex(m => String(m.id) === String(message.id));
|
||||||
|
if (existingIdx !== -1) {
|
||||||
|
state.messages[existingIdx] = message;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
state.messages.push(message);
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderMessages() {
|
function renderMessages() {
|
||||||
@@ -140,14 +254,14 @@
|
|||||||
|
|
||||||
state.messages.forEach((message) => {
|
state.messages.forEach((message) => {
|
||||||
const bubble = document.createElement("div");
|
const bubble = document.createElement("div");
|
||||||
bubble.className = `mm-chat__bubble ${
|
bubble.className = `mm-chat__bubble ${isOutgoing(message, conversation) ? "mm-chat__bubble--out" : "mm-chat__bubble--in"
|
||||||
isOutgoing(message, conversation) ? "mm-chat__bubble--out" : "mm-chat__bubble--in"
|
}`;
|
||||||
}`;
|
|
||||||
const body = document.createElement("div");
|
const body = document.createElement("div");
|
||||||
body.textContent = message.body;
|
body.textContent = message.body;
|
||||||
const meta = document.createElement("span");
|
const meta = document.createElement("span");
|
||||||
meta.className = "mm-chat__meta";
|
meta.className = "mm-chat__meta";
|
||||||
meta.textContent = formatTime(message.created_at);
|
meta.textContent = formatTime(message.created_at);
|
||||||
|
|
||||||
bubble.appendChild(body);
|
bubble.appendChild(body);
|
||||||
bubble.appendChild(meta);
|
bubble.appendChild(meta);
|
||||||
messagesEl.appendChild(bubble);
|
messagesEl.appendChild(bubble);
|
||||||
@@ -158,20 +272,34 @@
|
|||||||
|
|
||||||
async function loadInbox() {
|
async function loadInbox() {
|
||||||
const payload = await request(config.conversationsUrl, { headers: headers() });
|
const payload = await request(config.conversationsUrl, { headers: headers() });
|
||||||
|
const previous = state.conversations;
|
||||||
state.conversations = payload.data || [];
|
state.conversations = payload.data || [];
|
||||||
|
|
||||||
|
if (inboxReady) {
|
||||||
|
state.conversations.forEach((conversation) => {
|
||||||
|
const prev = previous.find((item) => item.id === conversation.id);
|
||||||
|
const last = conversation.last_message;
|
||||||
|
const lastChanged = Boolean(last) && messageKey(last) !== messageKey(prev && prev.last_message);
|
||||||
|
|
||||||
|
if (lastChanged && !isOutgoing(last, conversation)) {
|
||||||
|
notifyIncoming(last, conversation);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
inboxReady = true;
|
||||||
|
state.conversations.forEach((conversation) => {
|
||||||
|
const key = messageKey(conversation.last_message);
|
||||||
|
if (key) notifiedIds.add(key);
|
||||||
|
});
|
||||||
|
}
|
||||||
renderInbox();
|
renderInbox();
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadMessages(conversationId, reset) {
|
async function loadMessages(conversationId, reset) {
|
||||||
if (state.loadingMessages) {
|
if (state.loadingMessages) return;
|
||||||
return;
|
|
||||||
}
|
|
||||||
state.loadingMessages = true;
|
state.loadingMessages = true;
|
||||||
|
|
||||||
const url = reset
|
const url = reset ? `${config.messagesUrl}/${conversationId}/messages?perPage=50` : state.nextPageUrl;
|
||||||
? `${config.messagesUrl}/${conversationId}/messages?perPage=50`
|
|
||||||
: state.nextPageUrl;
|
|
||||||
|
|
||||||
if (!url) {
|
if (!url) {
|
||||||
state.loadingMessages = false;
|
state.loadingMessages = false;
|
||||||
return;
|
return;
|
||||||
@@ -183,22 +311,25 @@
|
|||||||
state.nextPageUrl = payload.pagination && payload.pagination.next_page_url;
|
state.nextPageUrl = payload.pagination && payload.pagination.next_page_url;
|
||||||
|
|
||||||
if (reset) {
|
if (reset) {
|
||||||
state.messages = items;
|
state.messages = [];
|
||||||
|
items.forEach(addOrUpdateMessage);
|
||||||
} else {
|
} else {
|
||||||
state.messages = items.concat(state.messages);
|
const oldMessages = state.messages;
|
||||||
|
state.messages = [];
|
||||||
|
items.forEach(addOrUpdateMessage);
|
||||||
|
oldMessages.forEach(addOrUpdateMessage);
|
||||||
}
|
}
|
||||||
|
|
||||||
renderMessages();
|
renderMessages();
|
||||||
} finally {
|
} finally {
|
||||||
state.loadingMessages = false;
|
state.loadingMessages = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function markRead(conversationId) {
|
async function markRead(conversationId, force) {
|
||||||
|
if (!conversationId || conversationId !== state.activeId) return;
|
||||||
|
|
||||||
const conversation = state.conversations.find((item) => item.id === conversationId);
|
const conversation = state.conversations.find((item) => item.id === conversationId);
|
||||||
if (!conversation || conversation.can_reply === false) {
|
if (!conversation || (!force && !conversation.unread_count)) return;
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
await request(`${config.messagesUrl}/${conversationId}/read`, {
|
await request(`${config.messagesUrl}/${conversationId}/read`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@@ -211,78 +342,101 @@
|
|||||||
function setComposer(conversation) {
|
function setComposer(conversation) {
|
||||||
const canReply = Boolean(conversation && conversation.can_reply);
|
const canReply = Boolean(conversation && conversation.can_reply);
|
||||||
formEl.hidden = !canReply;
|
formEl.hidden = !canReply;
|
||||||
if (viewOnlyEl) {
|
if (viewOnlyEl) viewOnlyEl.hidden = canReply || !conversation;
|
||||||
viewOnlyEl.hidden = canReply || !conversation;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function openConversation(conversationId) {
|
async function openConversation(conversationId) {
|
||||||
state.activeId = conversationId;
|
state.activeId = conversationId;
|
||||||
const conversation = state.conversations.find((item) => item.id === conversationId);
|
const conversation = state.conversations.find((item) => item.id === conversationId);
|
||||||
|
|
||||||
const name = (conversation && conversation.user && conversation.user.name) || `#${conversationId}`;
|
const name = (conversation && conversation.user && conversation.user.name) || `#${conversationId}`;
|
||||||
const phone = conversation && conversation.user && conversation.user.phone_number;
|
const phone = conversation && conversation.user && conversation.user.phone_number;
|
||||||
const subtitle = conversation && conversation.channel && conversation.channel.name
|
const subtitle = conversation && conversation.channel && conversation.channel.name
|
||||||
? conversation.channel.name
|
? conversation.channel.name
|
||||||
: (config.strings && config.strings.support) || "Support";
|
: (config.strings && config.strings.support) || "Support";
|
||||||
|
|
||||||
headEl.textContent = phone ? `${name} · ${phone} · ${subtitle}` : `${name} · ${subtitle}`;
|
headEl.textContent = phone ? `${name} · ${phone} · ${subtitle}` : `${name} · ${subtitle}`;
|
||||||
|
|
||||||
setComposer(conversation);
|
setComposer(conversation);
|
||||||
renderInbox();
|
renderInbox();
|
||||||
await loadMessages(conversationId, true);
|
await loadMessages(conversationId, true);
|
||||||
await markRead(conversationId);
|
await markRead(conversationId, true);
|
||||||
subscribeThread(conversationId);
|
subscribeThread(conversationId);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function sendMessage(event) {
|
async function sendMessage(event) {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
|
|
||||||
const body = (inputEl.value || "").trim();
|
const body = (inputEl.value || "").trim();
|
||||||
const conversation = state.conversations.find((item) => item.id === state.activeId);
|
const conversation = state.conversations.find((item) => item.id === state.activeId);
|
||||||
if (!body || !state.activeId || !conversation || conversation.can_reply === false) {
|
if (!body || !state.activeId || !conversation || conversation.can_reply === false) return;
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
sendEl.disabled = true;
|
sendEl.disabled = true;
|
||||||
|
inputEl.value = "";
|
||||||
|
|
||||||
|
const tempId = "temp-" + Date.now();
|
||||||
|
const optimisticMsg = {
|
||||||
|
id: tempId,
|
||||||
|
tempId: tempId,
|
||||||
|
conversation_id: state.activeId,
|
||||||
|
body: body,
|
||||||
|
created_at: new Date().toISOString(),
|
||||||
|
sender_type: "admin"
|
||||||
|
};
|
||||||
|
|
||||||
|
addOrUpdateMessage(optimisticMsg);
|
||||||
|
renderMessages();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const payload = await request(
|
const payload = await request(`${config.messagesUrl}/${state.activeId}/messages`, {
|
||||||
`${config.messagesUrl}/${state.activeId}/messages`,
|
method: "POST",
|
||||||
{
|
headers: headers(true),
|
||||||
method: "POST",
|
body: JSON.stringify({ body }),
|
||||||
headers: headers(true),
|
});
|
||||||
body: JSON.stringify({ body }),
|
|
||||||
}
|
const serverMsg = payload.data;
|
||||||
);
|
if (serverMsg && serverMsg.id) {
|
||||||
const message = payload.data;
|
notifiedIds.add(messageKey(serverMsg)); // Prevent self-notifying
|
||||||
if (message && !state.messages.some((item) => item.id === message.id)) {
|
|
||||||
state.messages.push(message);
|
// **CRITICAL FIX**: Explicitly delete the temporary message by its exact tempId
|
||||||
|
state.messages = state.messages.filter(m => m.tempId !== tempId);
|
||||||
|
|
||||||
|
addOrUpdateMessage(serverMsg);
|
||||||
|
state.messages.sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
|
||||||
renderMessages();
|
renderMessages();
|
||||||
}
|
}
|
||||||
inputEl.value = "";
|
|
||||||
await loadInbox();
|
await loadInbox();
|
||||||
|
} catch (err) {
|
||||||
|
// Revert message on network failure
|
||||||
|
state.messages = state.messages.filter(m => m.tempId !== tempId);
|
||||||
|
renderMessages();
|
||||||
} finally {
|
} finally {
|
||||||
sendEl.disabled = false;
|
sendEl.disabled = false;
|
||||||
inputEl.focus();
|
inputEl.focus();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function upsertIncoming(message) {
|
function upsertIncoming(payload) {
|
||||||
if (!message || !message.conversation_id) {
|
const message = normalizeIncoming(payload);
|
||||||
return;
|
if (!message || !message.conversation_id) return;
|
||||||
|
|
||||||
|
const conversation = state.conversations.find((item) => item.id === message.conversation_id);
|
||||||
|
|
||||||
|
if (!isOutgoing(message, conversation)) {
|
||||||
|
notifyIncoming(message, conversation);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (state.activeId === message.conversation_id) {
|
if (state.activeId === message.conversation_id) {
|
||||||
if (!state.messages.some((item) => item.id === message.id)) {
|
addOrUpdateMessage(message);
|
||||||
state.messages.push(message);
|
state.messages.sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
|
||||||
renderMessages();
|
renderMessages();
|
||||||
}
|
markRead(message.conversation_id, true);
|
||||||
markRead(message.conversation_id);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
loadInbox();
|
loadInbox();
|
||||||
}
|
}
|
||||||
|
|
||||||
function subscribeThread(conversationId) {
|
function subscribeThread(conversationId) {
|
||||||
if (!state.echo) {
|
if (!state.echo) return;
|
||||||
return;
|
|
||||||
}
|
|
||||||
state.echo.private(`chat.${conversationId}`).listen(".message.sent", upsertIncoming);
|
state.echo.private(`chat.${conversationId}`).listen(".message.sent", upsertIncoming);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -294,13 +448,8 @@
|
|||||||
const pageHost = window.location.hostname;
|
const pageHost = window.location.hostname;
|
||||||
if (!isLoopbackHost(pageHost)) {
|
if (!isLoopbackHost(pageHost)) {
|
||||||
const https = window.location.protocol === "https:";
|
const https = window.location.protocol === "https:";
|
||||||
return {
|
return { host: pageHost, port: https ? 443 : 80, forceTLS: https };
|
||||||
host: pageHost,
|
|
||||||
port: https ? 443 : 80,
|
|
||||||
forceTLS: https,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
host: pusher.host || "127.0.0.1",
|
host: pusher.host || "127.0.0.1",
|
||||||
port: pusher.port || 8080,
|
port: pusher.port || 8080,
|
||||||
@@ -311,9 +460,7 @@
|
|||||||
function bootEcho() {
|
function bootEcho() {
|
||||||
const pusher = config.pusher || {};
|
const pusher = config.pusher || {};
|
||||||
const EchoClass = window.Echo;
|
const EchoClass = window.Echo;
|
||||||
if (typeof EchoClass !== "function" || !window.Pusher || !pusher.key) {
|
if (typeof EchoClass !== "function" || !window.Pusher || !pusher.key) return;
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const endpoint = echoEndpoint(pusher);
|
const endpoint = echoEndpoint(pusher);
|
||||||
|
|
||||||
@@ -337,33 +484,6 @@
|
|||||||
"X-Requested-With": "XMLHttpRequest",
|
"X-Requested-With": "XMLHttpRequest",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
authorizer: (channel) => ({
|
|
||||||
authorize: (socketId, callback) => {
|
|
||||||
fetch(config.broadcastAuthPath || config.broadcastAuth || "/panel/broadcasting/auth", {
|
|
||||||
method: "POST",
|
|
||||||
credentials: "same-origin",
|
|
||||||
headers: headers(true),
|
|
||||||
body: JSON.stringify({
|
|
||||||
socket_id: socketId,
|
|
||||||
channel_name: channel.name,
|
|
||||||
}),
|
|
||||||
})
|
|
||||||
.then(async (response) => {
|
|
||||||
let data = {};
|
|
||||||
try {
|
|
||||||
data = await response.json();
|
|
||||||
} catch (error) {
|
|
||||||
data = {};
|
|
||||||
}
|
|
||||||
if (!response.ok) {
|
|
||||||
callback(true, data);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
callback(false, data);
|
|
||||||
})
|
|
||||||
.catch((error) => callback(true, error));
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
state.echo.private(config.inboxChannel || "chat.support").listen(".message.sent", upsertIncoming);
|
state.echo.private(config.inboxChannel || "chat.support").listen(".message.sent", upsertIncoming);
|
||||||
@@ -373,33 +493,32 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function mergeActiveMessages() {
|
async function mergeActiveMessages() {
|
||||||
if (!state.activeId || state.loadingMessages) {
|
if (!state.activeId || state.loadingMessages) return false;
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const payload = await request(
|
const payload = await request(`${config.messagesUrl}/${state.activeId}/messages?perPage=50`, { headers: headers() });
|
||||||
`${config.messagesUrl}/${state.activeId}/messages?perPage=50`,
|
|
||||||
{ headers: headers() }
|
|
||||||
);
|
|
||||||
const items = (payload.data || []).slice().reverse();
|
const items = (payload.data || []).slice().reverse();
|
||||||
const known = new Set(state.messages.map((item) => item.id));
|
|
||||||
let added = false;
|
let added = false;
|
||||||
|
|
||||||
items.forEach((message) => {
|
items.forEach((message) => {
|
||||||
if (!known.has(message.id)) {
|
const isNew = addOrUpdateMessage(message);
|
||||||
state.messages.push(message);
|
if (isNew) {
|
||||||
added = true;
|
added = true;
|
||||||
|
const conversation = state.conversations.find((i) => i.id === state.activeId);
|
||||||
|
if (!isOutgoing(message, conversation)) {
|
||||||
|
notifyIncoming(message, conversation);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
if (added) {
|
if (added) {
|
||||||
state.messages.sort(
|
state.messages.sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
|
||||||
(a, b) => new Date(a.created_at) - new Date(b.created_at)
|
|
||||||
);
|
|
||||||
renderMessages();
|
renderMessages();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return added;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Event Listeners
|
||||||
formEl.addEventListener("submit", sendMessage);
|
formEl.addEventListener("submit", sendMessage);
|
||||||
inputEl.addEventListener("keydown", (event) => {
|
inputEl.addEventListener("keydown", (event) => {
|
||||||
if (event.key === "Enter" && !event.shiftKey) {
|
if (event.key === "Enter" && !event.shiftKey) {
|
||||||
@@ -417,13 +536,24 @@
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Initialize
|
||||||
loadInbox();
|
loadInbox();
|
||||||
bootEcho();
|
bootEcho();
|
||||||
|
|
||||||
setInterval(() => {
|
setInterval(() => {
|
||||||
loadInbox().then(() => {
|
loadInbox().then(async () => {
|
||||||
if (state.activeId) {
|
if (!state.activeId) return;
|
||||||
mergeActiveMessages();
|
const added = await mergeActiveMessages();
|
||||||
|
const conversation = state.conversations.find((item) => item.id === state.activeId);
|
||||||
|
if (added || (conversation && conversation.unread_count > 0)) {
|
||||||
|
await markRead(state.activeId, true);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}, 4000);
|
}, 4000);
|
||||||
|
|
||||||
|
document.addEventListener("visibilitychange", () => {
|
||||||
|
if (document.visibilityState === "visible" && state.activeId) {
|
||||||
|
markRead(state.activeId);
|
||||||
|
}
|
||||||
|
});
|
||||||
})();
|
})();
|
||||||
@@ -41,6 +41,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<audio id="mm-chat-sound" src="/assets/panel/audio/sound.mp3" preload="auto" playsinline></audio>
|
||||||
<script>
|
<script>
|
||||||
window.MM_CHAT = {
|
window.MM_CHAT = {
|
||||||
conversationsUrl: @json(url('/panel/chat/conversations')),
|
conversationsUrl: @json(url('/panel/chat/conversations')),
|
||||||
|
|||||||
Reference in new issue
Block a user