Implement chat support functionality: update .env.example for Reverb integration, enhance ChatController with support conversation methods, and modify Conversation model for improved chat handling. Add middleware for chat operator checks and update broadcasting configuration for Reverb.

This commit is contained in:
Mekan1206 committed 2026-08-15 17:48:39 +05:00
1 parent ccfffe6173
commit da530f6b36
21 files changed
+2034 -39

No files matched your search

+256
View File
@@ -0,0 +1,256 @@
*,
*::before,
*::after {
box-sizing: border-box;
}
html,
body {
margin: 0;
height: 100%;
font-family: Nunito, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background: #0f172a;
color: #0f172a;
}
.mm-chat {
display: flex;
flex-direction: column;
height: 100%;
min-height: 100vh;
}
.mm-chat__top {
display: flex;
align-items: center;
gap: 16px;
padding: 12px 20px;
background: #1e293b;
color: #f8fafc;
flex-shrink: 0;
}
.mm-chat__top h1 {
margin: 0;
font-size: 18px;
font-weight: 700;
}
.mm-chat__back {
color: #cbd5e1;
text-decoration: none;
font-size: 13px;
}
.mm-chat__back:hover {
color: #fff;
}
.mm-chat__badge {
margin-left: auto;
min-width: 22px;
height: 22px;
padding: 0 7px;
border-radius: 999px;
background: #d32824;
color: #fff;
font-size: 12px;
line-height: 22px;
text-align: center;
font-weight: 700;
}
.mm-chat__shell {
display: grid;
grid-template-columns: 320px 1fr;
flex: 1;
min-height: 0;
background: #e2e8f0;
}
.mm-chat__inbox {
display: flex;
flex-direction: column;
background: #fff;
border-right: 1px solid #e2e8f0;
min-height: 0;
}
.mm-chat__inbox-head {
padding: 14px 16px;
font-size: 12px;
font-weight: 700;
letter-spacing: 0.04em;
text-transform: uppercase;
color: #64748b;
border-bottom: 1px solid #e2e8f0;
}
.mm-chat__list {
overflow-y: auto;
flex: 1;
}
.mm-chat__empty {
margin: 24px 16px;
color: #94a3b8;
font-size: 13px;
}
.mm-chat__item {
display: block;
width: 100%;
text-align: left;
border: 0;
border-bottom: 1px solid #f1f5f9;
background: #fff;
padding: 12px 16px;
cursor: pointer;
}
.mm-chat__item:hover,
.mm-chat__item.is-active {
background: #f8fafc;
}
.mm-chat__item-row {
display: flex;
justify-content: space-between;
gap: 8px;
align-items: center;
}
.mm-chat__item-name {
font-weight: 700;
font-size: 14px;
color: #0f172a;
}
.mm-chat__item-time {
font-size: 11px;
color: #94a3b8;
white-space: nowrap;
}
.mm-chat__item-preview {
margin-top: 4px;
font-size: 13px;
color: #64748b;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.mm-chat__item-phone {
font-size: 12px;
color: #94a3b8;
}
.mm-chat__item-unread {
display: inline-flex;
min-width: 18px;
height: 18px;
margin-top: 6px;
padding: 0 6px;
border-radius: 999px;
background: #d32824;
color: #fff;
font-size: 11px;
font-weight: 700;
align-items: center;
justify-content: center;
}
.mm-chat__thread {
display: flex;
flex-direction: column;
min-width: 0;
min-height: 0;
}
.mm-chat__thread-head {
padding: 14px 20px;
background: #fff;
border-bottom: 1px solid #e2e8f0;
font-weight: 700;
font-size: 15px;
}
.mm-chat__messages {
flex: 1;
overflow-y: auto;
padding: 20px;
display: flex;
flex-direction: column;
gap: 10px;
}
.mm-chat__bubble {
max-width: 72%;
padding: 10px 12px;
border-radius: 14px;
font-size: 14px;
line-height: 1.45;
white-space: pre-wrap;
word-break: break-word;
}
.mm-chat__bubble--in {
align-self: flex-start;
background: #fff;
color: #0f172a;
}
.mm-chat__bubble--out {
align-self: flex-end;
background: #d32824;
color: #fff;
}
.mm-chat__meta {
display: block;
margin-top: 4px;
font-size: 11px;
opacity: 0.7;
}
.mm-chat__composer {
display: flex;
gap: 10px;
padding: 12px 16px;
background: #fff;
border-top: 1px solid #e2e8f0;
}
.mm-chat__composer textarea {
flex: 1;
resize: none;
border: 1px solid #cbd5e1;
border-radius: 10px;
padding: 10px 12px;
font: inherit;
min-height: 44px;
max-height: 140px;
}
.mm-chat__composer button {
border: 0;
border-radius: 10px;
background: #d32824;
color: #fff;
font-weight: 700;
padding: 0 18px;
cursor: pointer;
}
.mm-chat__composer button:disabled {
opacity: 0.55;
cursor: not-allowed;
}
@media (max-width: 800px) {
.mm-chat__shell {
grid-template-columns: 1fr;
grid-template-rows: 40% 1fr;
}
}
+359
View File
@@ -0,0 +1,359 @@
(function () {
const config = window.MM_CHAT || {};
const listEl = document.getElementById("mm-chat-list");
const emptyInboxEl = document.getElementById("mm-chat-empty-inbox");
const messagesEl = document.getElementById("mm-chat-messages");
const headEl = document.getElementById("mm-chat-thread-head");
const formEl = document.getElementById("mm-chat-form");
const inputEl = document.getElementById("mm-chat-input");
const sendEl = document.getElementById("mm-chat-send");
const unreadEl = document.getElementById("mm-chat-unread");
const state = {
conversations: [],
activeId: null,
messages: [],
nextPageUrl: null,
loadingMessages: false,
echo: null,
};
function headers(json) {
const next = {
Accept: "application/json",
"X-CSRF-TOKEN": config.csrf,
"X-Requested-With": "XMLHttpRequest",
};
if (json) {
next["Content-Type"] = "application/json";
}
return next;
}
async function request(url, options) {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error("Chat request failed");
}
return response.json();
}
function formatTime(value) {
if (!value) {
return "";
}
const date = new Date(value);
if (Number.isNaN(date.getTime())) {
return "";
}
const pad = (n) => String(n).padStart(2, "0");
return `${pad(date.getHours())}:${pad(date.getMinutes())}, ${pad(date.getDate())}.${pad(date.getMonth() + 1)}.${date.getFullYear()}`;
}
function preview(body) {
if (!body) {
return "";
}
return body.length > 80 ? `${body.slice(0, 80)}…` : body;
}
function updateUnreadBadge() {
const total = state.conversations.reduce(
(sum, conversation) => sum + (conversation.unread_count || 0),
0
);
unreadEl.textContent = String(total);
unreadEl.hidden = total < 1;
}
function renderInbox() {
listEl.innerHTML = "";
emptyInboxEl.hidden = state.conversations.length > 0;
state.conversations.forEach((conversation) => {
const button = document.createElement("button");
button.type = "button";
button.className = "mm-chat__item";
if (conversation.id === state.activeId) {
button.classList.add("is-active");
}
const name = (conversation.user && conversation.user.name) || `#${conversation.id}`;
const phone = conversation.user && conversation.user.phone_number;
const last = conversation.last_message;
const time = last ? formatTime(last.created_at) : "";
button.innerHTML = `
<div class="mm-chat__item-row">
<span class="mm-chat__item-name"></span>
<span class="mm-chat__item-time"></span>
</div>
${phone ? '<div class="mm-chat__item-phone"></div>' : ""}
<div class="mm-chat__item-preview"></div>
${conversation.unread_count ? '<span class="mm-chat__item-unread"></span>' : ""}
`;
button.querySelector(".mm-chat__item-name").textContent = name;
button.querySelector(".mm-chat__item-time").textContent = time;
if (phone) {
button.querySelector(".mm-chat__item-phone").textContent = String(phone);
}
button.querySelector(".mm-chat__item-preview").textContent = last
? preview(last.body)
: "";
const unread = button.querySelector(".mm-chat__item-unread");
if (unread) {
unread.textContent = String(conversation.unread_count);
}
button.addEventListener("click", () => openConversation(conversation.id));
listEl.appendChild(button);
});
updateUnreadBadge();
}
function isOutgoing(message, conversation) {
const otherId = conversation && conversation.user && conversation.user.id;
return !otherId || message.user?.id !== otherId;
}
function renderMessages() {
const conversation = state.conversations.find((item) => item.id === state.activeId);
messagesEl.innerHTML = "";
if (!state.messages.length) {
const empty = document.createElement("p");
empty.className = "mm-chat__empty";
empty.textContent = config.strings.noMessages;
messagesEl.appendChild(empty);
return;
}
state.messages.forEach((message) => {
const bubble = document.createElement("div");
bubble.className = `mm-chat__bubble ${
isOutgoing(message, conversation) ? "mm-chat__bubble--out" : "mm-chat__bubble--in"
}`;
const body = document.createElement("div");
body.textContent = message.body;
const meta = document.createElement("span");
meta.className = "mm-chat__meta";
meta.textContent = formatTime(message.created_at);
bubble.appendChild(body);
bubble.appendChild(meta);
messagesEl.appendChild(bubble);
});
messagesEl.scrollTop = messagesEl.scrollHeight;
}
async function loadInbox() {
const payload = await request(config.conversationsUrl, { headers: headers() });
state.conversations = payload.data || [];
renderInbox();
}
async function loadMessages(conversationId, reset) {
if (state.loadingMessages) {
return;
}
state.loadingMessages = true;
const url = reset
? `${config.messagesUrl}/${conversationId}/messages?perPage=50`
: state.nextPageUrl;
if (!url) {
state.loadingMessages = false;
return;
}
try {
const payload = await request(url, { headers: headers() });
const items = (payload.data || []).slice().reverse();
state.nextPageUrl = payload.pagination && payload.pagination.next_page_url;
if (reset) {
state.messages = items;
} else {
state.messages = items.concat(state.messages);
}
renderMessages();
} finally {
state.loadingMessages = false;
}
}
async function markRead(conversationId) {
await request(`${config.messagesUrl}/${conversationId}/read`, {
method: "POST",
headers: headers(true),
});
const conversation = state.conversations.find((item) => item.id === conversationId);
if (conversation) {
conversation.unread_count = 0;
renderInbox();
}
}
async function openConversation(conversationId) {
state.activeId = conversationId;
const conversation = state.conversations.find((item) => item.id === conversationId);
const name = (conversation && conversation.user && conversation.user.name) || `#${conversationId}`;
const phone = conversation && conversation.user && conversation.user.phone_number;
headEl.textContent = phone ? `${name} · ${phone}` : name;
formEl.hidden = false;
renderInbox();
await loadMessages(conversationId, true);
await markRead(conversationId);
subscribeThread(conversationId);
}
async function sendMessage(event) {
event.preventDefault();
const body = (inputEl.value || "").trim();
if (!body || !state.activeId) {
return;
}
sendEl.disabled = true;
try {
const payload = await request(
`${config.messagesUrl}/${state.activeId}/messages`,
{
method: "POST",
headers: headers(true),
body: JSON.stringify({ body }),
}
);
const message = payload.data;
if (message && !state.messages.some((item) => item.id === message.id)) {
state.messages.push(message);
renderMessages();
}
inputEl.value = "";
await loadInbox();
} finally {
sendEl.disabled = false;
inputEl.focus();
}
}
function upsertIncoming(message) {
if (!message || !message.conversation_id) {
return;
}
if (state.activeId === message.conversation_id) {
if (!state.messages.some((item) => item.id === message.id)) {
state.messages.push(message);
renderMessages();
}
markRead(message.conversation_id);
}
loadInbox();
}
function subscribeThread(conversationId) {
if (!state.echo) {
return;
}
state.echo.private(`chat.${conversationId}`).listen(".message.sent", upsertIncoming);
}
function bootEcho() {
const pusher = config.pusher || {};
const EchoClass = window.Echo;
if (typeof EchoClass !== "function" || !window.Pusher || !pusher.key) {
return;
}
const scheme = pusher.scheme || "https";
const forceTLS = scheme === "https";
try {
state.echo = new EchoClass({
broadcaster: "reverb",
key: pusher.key,
wsHost: pusher.host || undefined,
wsPort: pusher.port || undefined,
wssPort: pusher.port || undefined,
forceTLS,
enabledTransports: ["ws", "wss"],
disableStats: true,
cluster: "mt1",
authEndpoint: config.broadcastAuth,
auth: {
headers: {
"X-CSRF-TOKEN": config.csrf,
Accept: "application/json",
},
},
});
state.echo.private("chat.support").listen(".message.sent", upsertIncoming);
} catch (err) {
state.echo = null;
}
}
async function mergeActiveMessages() {
if (!state.activeId || state.loadingMessages) {
return;
}
const payload = await request(
`${config.messagesUrl}/${state.activeId}/messages?perPage=50`,
{ headers: headers() }
);
const items = (payload.data || []).slice().reverse();
const known = new Set(state.messages.map((item) => item.id));
let added = false;
items.forEach((message) => {
if (!known.has(message.id)) {
state.messages.push(message);
added = true;
}
});
if (added) {
state.messages.sort(
(a, b) => new Date(a.created_at) - new Date(b.created_at)
);
renderMessages();
}
}
formEl.addEventListener("submit", sendMessage);
inputEl.addEventListener("keydown", (event) => {
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
formEl.requestSubmit();
}
});
messagesEl.addEventListener("scroll", () => {
if (messagesEl.scrollTop < 40 && state.nextPageUrl && state.activeId) {
const previousHeight = messagesEl.scrollHeight;
loadMessages(state.activeId, false).then(() => {
messagesEl.scrollTop = messagesEl.scrollHeight - previousHeight;
});
}
});
loadInbox();
bootEcho();
setInterval(() => {
loadInbox().then(() => {
if (state.activeId) {
mergeActiveMessages();
}
});
}, 4000);
})();