Merged in release/2025-12-19 (pull request #2753)

Release/2025 12 19
This commit is contained in:
Dave Richer
2025-12-30 19:21:50 +00:00
17 changed files with 802 additions and 387 deletions

View File

@@ -2,7 +2,6 @@ import { useApolloClient } from "@apollo/client";
import { getToken } from "@firebase/messaging"; import { getToken } from "@firebase/messaging";
import axios from "axios"; import axios from "axios";
import { useEffect } from "react"; import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { messaging, requestForToken } from "../../firebase/firebase.utils"; import { messaging, requestForToken } from "../../firebase/firebase.utils";
import ChatPopupComponent from "../chat-popup/chat-popup.component"; import ChatPopupComponent from "../chat-popup/chat-popup.component";
import "./chat-affix.styles.scss"; import "./chat-affix.styles.scss";
@@ -10,14 +9,14 @@ import { registerMessagingHandlers, unregisterMessagingHandlers } from "./regist
import { useSocket } from "../../contexts/SocketIO/useSocket.js"; import { useSocket } from "../../contexts/SocketIO/useSocket.js";
export function ChatAffixContainer({ bodyshop, chatVisible, currentUser }) { export function ChatAffixContainer({ bodyshop, chatVisible, currentUser }) {
const { t } = useTranslation();
const client = useApolloClient(); const client = useApolloClient();
const { socket } = useSocket(); const { socket } = useSocket();
// 1) FCM subscription (independent of socket handler registration)
useEffect(() => { useEffect(() => {
if (!bodyshop?.messagingservicesid) return; if (!bodyshop?.messagingservicesid) return;
async function SubscribeToTopicForFCMNotification() { async function subscribeToTopicForFCMNotification() {
try { try {
await requestForToken(); await requestForToken();
await axios.post("/notifications/subscribe", { await axios.post("/notifications/subscribe", {
@@ -32,17 +31,35 @@ export function ChatAffixContainer({ bodyshop, chatVisible, currentUser }) {
} }
} }
SubscribeToTopicForFCMNotification(); subscribeToTopicForFCMNotification();
}, [bodyshop?.messagingservicesid, bodyshop?.imexshopid]);
// Register WebSocket handlers // 2) Register socket handlers as soon as socket is connected (regardless of chatVisible)
if (socket?.connected) { useEffect(() => {
registerMessagingHandlers({ socket, client, currentUser, bodyshop, t }); if (!socket) return;
if (!bodyshop?.messagingservicesid) return;
if (!bodyshop?.id) return;
return () => { // If socket isn't connected yet, ensure no stale handlers remain.
unregisterMessagingHandlers({ socket }); if (!socket.connected) {
}; unregisterMessagingHandlers({ socket });
return;
} }
}, [bodyshop, socket, t, client]);
// Prevent duplicate listeners if this effect runs more than once.
unregisterMessagingHandlers({ socket });
registerMessagingHandlers({
socket,
client,
currentUser,
bodyshop
});
return () => {
unregisterMessagingHandlers({ socket });
};
}, [socket, socket?.connected, bodyshop?.id, bodyshop?.messagingservicesid, client, currentUser?.email]);
if (!bodyshop?.messagingservicesid) return <></>; if (!bodyshop?.messagingservicesid) return <></>;

View File

@@ -13,68 +13,241 @@ const logLocal = (message, ...args) => {
} }
}; };
// Utility function to enrich conversation data const safeIsoNow = () => new Date().toISOString();
const enrichConversation = (conversation, isOutbound) => ({ const isSystemMsid = (msid) => typeof msid === "string" && msid.startsWith("SYS_");
const normalizeConversationForList = (raw, { isoutbound, isSystem } = {}) => {
const c = raw || {};
const id = c.id;
return {
__typename: "conversations",
id,
phone_num: c.phone_num ?? null,
updated_at: c.updated_at ?? safeIsoNow(),
unreadcnt: typeof c.unreadcnt === "number" ? c.unreadcnt : 0,
archived: c.archived ?? false,
label: c.label ?? null,
job_conversations: Array.isArray(c.job_conversations)
? c.job_conversations.map((jc) => {
const job = jc?.job || {};
const jobId = jc?.jobid ?? job?.id ?? null;
return {
__typename: "job_conversations",
jobid: jobId,
conversationid: jc?.conversationid ?? id ?? null,
job: {
__typename: "jobs",
id: jobId,
ro_number: job?.ro_number ?? null,
ownr_fn: job?.ownr_fn ?? null,
ownr_ln: job?.ownr_ln ?? null,
ownr_co_nm: job?.ownr_co_nm ?? null
}
};
})
: [],
messages_aggregate: c.messages_aggregate || {
__typename: "messages_aggregate",
aggregate: {
__typename: "messages_aggregate_fields",
count: isoutbound || isSystem ? 0 : 1
}
}
};
};
const CONVERSATION_LIST_ITEM_FRAGMENT = gql`
fragment _ConversationListItem on conversations {
id
phone_num
updated_at
unreadcnt
archived
label
job_conversations {
jobid
conversationid
job {
id
ro_number
ownr_fn
ownr_ln
ownr_co_nm
}
}
messages_aggregate(where: { read: { _eq: false }, isoutbound: { _eq: false }, is_system: { _eq: false } }) {
aggregate {
count
}
}
}
`;
const normalizeMessageForCache = (raw, fallbackConversationId) => {
const m = raw || {};
return {
__typename: "messages",
id: m.id,
conversationid: m.conversationid ?? m.conversation?.id ?? fallbackConversationId,
status: m.status ?? null,
text: m.text ?? "",
is_system: typeof m.is_system === "boolean" ? m.is_system : false,
isoutbound: typeof m.isoutbound === "boolean" ? m.isoutbound : false,
image: typeof m.image === "boolean" ? m.image : false,
image_path: m.image_path ?? null,
userid: m.userid ?? null,
created_at: m.created_at ?? safeIsoNow(),
read: typeof m.read === "boolean" ? m.read : false
};
};
const isConversationDetailsCached = (client, conversationId) => {
try {
return !!client.cache.readQuery({
query: GET_CONVERSATION_DETAILS,
variables: { conversationId }
})?.conversations_by_pk;
} catch {
return false;
}
};
const conversationDetailsCached = (client, conversationId) => {
try {
const res = client.cache.readQuery({
query: GET_CONVERSATION_DETAILS,
variables: { conversationId }
});
return !!res?.conversations_by_pk;
} catch {
return false;
}
};
const messageEntityCached = (client, messageId) => {
const cacheId = client.cache.identify({ __typename: "messages", id: messageId });
if (!cacheId) return false;
try {
client.cache.readFragment({
id: cacheId,
fragment: gql`
fragment _MsgExists on messages {
id
}
`
});
return true;
} catch {
return false;
}
};
const enrichConversation = (conversation, { isoutbound, isSystem }) => ({
...conversation, ...conversation,
updated_at: conversation.updated_at || new Date().toISOString(), updated_at: conversation.updated_at || safeIsoNow(),
unreadcnt: conversation.unreadcnt || 0, unreadcnt: typeof conversation.unreadcnt === "number" ? conversation.unreadcnt : 0,
archived: conversation.archived || false, archived: conversation.archived ?? false,
label: conversation.label || null, label: conversation.label ?? null,
job_conversations: conversation.job_conversations || [], job_conversations: conversation.job_conversations || [],
messages_aggregate: conversation.messages_aggregate || { messages_aggregate: conversation.messages_aggregate || {
__typename: "messages_aggregate", __typename: "messages_aggregate",
aggregate: { aggregate: {
__typename: "messages_aggregate_fields", __typename: "messages_aggregate_fields",
count: isOutbound ? 0 : 1 count: isoutbound || isSystem ? 0 : 1
} }
}, },
__typename: "conversations" __typename: "conversations"
}); });
// Can be uncommonted to test the playback of the notification sound const upsertConversationIntoOffsetZeroList = (client, conversationObj, { isoutbound, isSystem } = {}) => {
// window.testTone = () => { const normalized = normalizeConversationForList(conversationObj, { isoutbound, isSystem });
// const notificationSound = new Audio(newMessageSound); if (!normalized?.id) return;
// notificationSound.play().catch((error) => {
// console.error("Error playing notification sound:", error); const convCacheId = client.cache.identify(normalized);
// }); if (!convCacheId) return;
// };
client.cache.writeFragment({
id: convCacheId,
fragment: CONVERSATION_LIST_ITEM_FRAGMENT,
data: normalized
});
client.cache.modify({
id: "ROOT_QUERY",
fields: {
conversations(existing = [], { args, readField }) {
if (!args || args.offset !== 0) return existing;
const archivedEq = args?.where?.archived?._eq;
if (archivedEq === true) return existing;
const without = existing.filter((c) => readField("id", c) !== normalized.id);
return [{ __ref: convCacheId }, ...without];
}
}
});
};
export const registerMessagingHandlers = ({ socket, client, currentUser, bodyshop }) => { export const registerMessagingHandlers = ({ socket, client, currentUser, bodyshop }) => {
if (!(socket && client)) return; if (!(socket && client)) return;
const handleNewMessageSummary = async (message) => { // Coalesce unread refetches (avoid spamming during bursts)
const { conversationId, newConversation, existingConversation, isoutbound } = message; let unreadRefetchInFlight = null;
const refetchUnreadCount = () => {
if (unreadRefetchInFlight) return;
// True only when DB value is strictly true; falls back to true on cache miss unreadRefetchInFlight = client
const isNewMessageSoundEnabled = (client) => { .refetchQueries({
include: ["UNREAD_CONVERSATION_COUNT"]
})
.catch(() => {
// best-effort
})
.finally(() => {
unreadRefetchInFlight = null;
});
};
const handleNewMessageSummary = async (message) => {
const { conversationId, newConversation, existingConversation, isoutbound, msid, updated_at } = message;
const isSystem = isSystemMsid(msid);
const isNewMessageSoundEnabled = (clientInstance) => {
try { try {
const email = currentUser?.email; const email = currentUser?.email;
if (!email) return true; // default allow if we can't resolve user if (!email) return true;
const res = client.readQuery({ const res = clientInstance.readQuery({
query: QUERY_ACTIVE_ASSOCIATION_SOUND, query: QUERY_ACTIVE_ASSOCIATION_SOUND,
variables: { email } variables: { email }
}); });
const flag = res?.associations?.[0]?.new_message_sound; const flag = res?.associations?.[0]?.new_message_sound;
return flag === true; // strictly true => enabled return flag === true;
} catch { } catch {
// If the query hasn't been seeded in cache yet, default ON
return true; return true;
} }
}; };
logLocal("handleNewMessageSummary - Start", { message, isNew: !existingConversation }); logLocal("handleNewMessageSummary - Start", { message, isNew: !existingConversation });
const queryVariables = { offset: 0 };
if (!isoutbound) { if (!isoutbound) {
// Play notification sound for new inbound message (scoped to bodyshop)
if (isLeaderTab(bodyshop.id) && isNewMessageSoundEnabled(client)) { if (isLeaderTab(bodyshop.id) && isNewMessageSoundEnabled(client)) {
playNewMessageSound(bodyshop.id); playNewMessageSound(bodyshop.id);
} }
// Real-time badge update for affix (best-effort, coalesced)
if (!isSystem) {
refetchUnreadCount();
}
} }
if (!existingConversation && conversationId) { if (!existingConversation && conversationId) {
// Attempt to read from the cache to determine if this is actually a new conversation
try { try {
const cachedConversation = client.cache.readFragment({ const cachedConversation = client.cache.readFragment({
id: client.cache.identify({ __typename: "conversations", id: conversationId }), id: client.cache.identify({ __typename: "conversations", id: conversationId }),
@@ -86,75 +259,54 @@ export const registerMessagingHandlers = ({ socket, client, currentUser, bodysho
}); });
if (cachedConversation) { if (cachedConversation) {
logLocal("handleNewMessageSummary - Existing Conversation inferred from cache", { logLocal("handleNewMessageSummary - Existing Conversation inferred from cache", { conversationId });
conversationId return handleNewMessageSummary({ ...message, existingConversation: true });
});
return handleNewMessageSummary({
...message,
existingConversation: true
});
} }
} catch { } catch {
logLocal("handleNewMessageSummary - Cache miss", { conversationId }); // Cache miss is normal
} }
} }
// Handle new conversation
if (!existingConversation && newConversation?.phone_num) { if (!existingConversation && newConversation?.phone_num) {
logLocal("handleNewMessageSummary - New Conversation", newConversation);
try { try {
const queryResults = client.cache.readQuery({ upsertConversationIntoOffsetZeroList(client, newConversation, { isoutbound, isSystem });
query: CONVERSATION_LIST_QUERY,
variables: queryVariables
});
const existingConversations = queryResults?.conversations || [];
const enrichedConversation = enrichConversation(newConversation, isoutbound);
if (!existingConversations.some((conv) => conv.id === enrichedConversation.id)) {
client.cache.modify({
id: "ROOT_QUERY",
fields: {
conversations(existingConversations = []) {
return [enrichedConversation, ...existingConversations];
}
}
});
}
} catch (error) { } catch (error) {
console.error("Error updating cache for new conversation:", error); console.error("Error updating cache for new conversation:", error);
} }
return; return;
} }
// Handle existing conversation if (existingConversation && conversationId) {
if (existingConversation) {
try { try {
client.cache.modify({ client.cache.modify({
id: client.cache.identify({ __typename: "conversations", id: conversationId }), id: client.cache.identify({ __typename: "conversations", id: conversationId }),
fields: { fields: {
updated_at: () => new Date().toISOString(), updated_at: () => updated_at || safeIsoNow(),
archived: () => false, archived: () => false,
messages_aggregate(cached = { aggregate: { count: 0 } }) {
const currentCount = cached.aggregate?.count || 0; messages_aggregate(cached = null) {
if (!isoutbound) { if (isoutbound || isSystem) return cached;
return {
__typename: "messages_aggregate", const currentCount = cached?.aggregate?.count ?? 0;
aggregate: { return {
__typename: "messages_aggregate_fields", __typename: "messages_aggregate",
count: currentCount + 1 aggregate: {
} __typename: "messages_aggregate_fields",
}; count: currentCount + 1
} }
return cached; };
},
unreadcnt(cached) {
if (isoutbound || isSystem) return cached;
const n = typeof cached === "number" ? cached : 0;
return n + 1;
} }
} }
}); });
} catch (error) { } catch (error) {
console.error("Error updating cache for existing conversation:", error); console.error("Error updating cache for existing conversation:", error);
} }
return; return;
} }
@@ -166,88 +318,78 @@ export const registerMessagingHandlers = ({ socket, client, currentUser, bodysho
logLocal("handleNewMessageDetailed - Start", message); logLocal("handleNewMessageDetailed - Start", message);
try { if (!conversationId || !isConversationDetailsCached(client, conversationId)) return;
// Check if the conversation exists in the cache
const queryResults = client.cache.readQuery({
query: GET_CONVERSATION_DETAILS,
variables: { conversationId }
});
if (!queryResults?.conversations_by_pk) { try {
console.warn("Conversation not found in cache:", { conversationId }); const normalized = normalizeMessageForCache(newMessage, conversationId);
const messageCacheId = client.cache.identify(normalized);
if (!messageCacheId) {
console.warn("handleNewMessageDetailed - Could not identify message for cache", {
conversationId,
newMessageId: newMessage?.id
});
return; return;
} }
// Append the new message to the conversation's message list using cache.modify client.cache.writeFragment({
id: messageCacheId,
fragment: gql`
fragment _IncomingMessage on messages {
id
conversationid
status
text
is_system
isoutbound
image
image_path
userid
created_at
read
}
`,
data: normalized
});
client.cache.modify({ client.cache.modify({
id: client.cache.identify({ __typename: "conversations", id: conversationId }), id: client.cache.identify({ __typename: "conversations", id: conversationId }),
fields: { fields: {
messages(existingMessages = []) { messages(existing = [], { readField }) {
return [...existingMessages, newMessage]; const already = existing.some((ref) => readField("id", ref) === normalized.id);
if (already) return existing;
return [...existing, { __ref: messageCacheId }];
},
updated_at() {
return normalized.created_at || safeIsoNow();
} }
} }
}); });
logLocal("handleNewMessageDetailed - Message appended successfully", { logLocal("handleNewMessageDetailed - Message appended successfully", { conversationId });
conversationId,
newMessage
});
} catch (error) { } catch (error) {
console.error("Error updating conversation messages in cache:", error); console.error("Error updating conversation messages in cache:", error);
} }
}; };
const handleMessageChanged = (message) => { const handleMessageChanged = (message) => {
if (!message) { if (!message?.id) return;
logLocal("handleMessageChanged - No message provided", message);
return;
}
logLocal("handleMessageChanged - Start", message); logLocal("handleMessageChanged - Start", message);
if (!messageEntityCached(client, message.id)) return;
try { try {
const msgCacheId = client.cache.identify({ __typename: "messages", id: message.id });
client.cache.modify({ client.cache.modify({
id: client.cache.identify({ __typename: "conversations", id: message.conversationid }), id: msgCacheId,
fields: { fields: {
messages(existingMessages = [], { readField }) { status(existing) {
return existingMessages.map((messageRef) => { return message.type === "status-changed" ? (message.status ?? existing) : existing;
// Check if this is the message to update },
if (readField("id", messageRef) === message.id) { text(existing) {
const currentStatus = readField("status", messageRef); return message.type === "text-updated" ? (message.text ?? existing) : existing;
// Handle known types of message changes
switch (message.type) {
case "status-changed":
// Prevent overwriting if the current status is already "delivered"
if (currentStatus === "delivered") {
logLocal("handleMessageChanged - Status already delivered, skipping update", {
messageId: message.id
});
return messageRef;
}
// Update the status field
return {
...messageRef,
status: message.status
};
case "text-updated":
// Handle changes to the message text
return {
...messageRef,
text: message.text
};
default:
// Log a warning for unhandled message types
logLocal("handleMessageChanged - Unhandled message type", { type: message.type });
return messageRef;
}
}
return messageRef;
});
} }
} }
}); });
@@ -262,149 +404,140 @@ export const registerMessagingHandlers = ({ socket, client, currentUser, bodysho
}; };
const handleConversationChanged = async (data) => { const handleConversationChanged = async (data) => {
if (!data) { if (!data?.conversationId) return;
logLocal("handleConversationChanged - No data provided", data);
return; const {
} conversationId,
type,
job_conversations,
messageIds,
messageIdsMarkedRead,
lastUnreadMessageId,
unreadCount,
...fields
} = data;
const { conversationId, type, job_conversations, messageIds, ...fields } = data;
logLocal("handleConversationChanged - Start", data); logLocal("handleConversationChanged - Start", data);
const updatedAt = new Date().toISOString(); const updatedAt = safeIsoNow();
const detailsCached = conversationDetailsCached(client, conversationId);
const updateConversationList = (newConversation) => {
try {
const existingList = client.cache.readQuery({
query: CONVERSATION_LIST_QUERY,
variables: { offset: 0 }
});
const updatedList = existingList?.conversations
? [newConversation, ...existingList.conversations.filter((conv) => conv.id !== newConversation.id)]
: [newConversation]; // Prevent duplicates
client.cache.writeQuery({
query: CONVERSATION_LIST_QUERY,
variables: { offset: 0 },
data: {
conversations: updatedList
}
});
logLocal("handleConversationChanged - Conversation list updated successfully", newConversation);
} catch (error) {
console.error("Error updating conversation list in the cache:", error);
}
};
// Handle specific types
try { try {
switch (type) { switch (type) {
case "conversation-marked-read": case "conversation-marked-read": {
if (conversationId && messageIds?.length > 0) { refetchUnreadCount();
client.cache.modify({
id: client.cache.identify({ __typename: "conversations", id: conversationId }), if (detailsCached && Array.isArray(messageIds)) {
fields: { messageIds.forEach((id) => {
messages(existingMessages = [], { readField }) { if (!messageEntityCached(client, id)) return;
return existingMessages.map((message) => { client.cache.modify({
if (messageIds.includes(readField("id", message))) { id: client.cache.identify({ __typename: "messages", id }),
return { ...message, read: true }; fields: { read: () => true }
} });
return message;
});
},
messages_aggregate: () => ({
__typename: "messages_aggregate",
aggregate: { __typename: "messages_aggregate_fields", count: 0 }
})
}
}); });
} }
break;
case "conversation-created": client.cache.modify({
updateConversationList({ ...fields, job_conversations, updated_at: updatedAt }); id: client.cache.identify({ __typename: "conversations", id: conversationId }),
fields: {
messages_aggregate: () => ({
__typename: "messages_aggregate",
aggregate: { __typename: "messages_aggregate_fields", count: 0 }
}),
unreadcnt: () => 0,
updated_at: () => updatedAt
}
});
break; break;
}
case "conversation-marked-unread": {
refetchUnreadCount();
const safeUnreadCount = typeof unreadCount === "number" ? unreadCount : 1;
const idsMarkedRead = Array.isArray(messageIdsMarkedRead) ? messageIdsMarkedRead : [];
if (detailsCached) {
idsMarkedRead.forEach((id) => {
if (!messageEntityCached(client, id)) return;
client.cache.modify({
id: client.cache.identify({ __typename: "messages", id }),
fields: { read: () => true }
});
});
if (lastUnreadMessageId && messageEntityCached(client, lastUnreadMessageId)) {
client.cache.modify({
id: client.cache.identify({ __typename: "messages", id: lastUnreadMessageId }),
fields: { read: () => false }
});
}
}
client.cache.modify({
id: client.cache.identify({ __typename: "conversations", id: conversationId }),
fields: {
updated_at: () => updatedAt,
messages_aggregate: () => ({
__typename: "messages_aggregate",
aggregate: {
__typename: "messages_aggregate_fields",
count: safeUnreadCount
}
}),
unreadcnt: () => safeUnreadCount
}
});
break;
}
case "conversation-created": {
// New conversation likely implies new unread inbound message(s)
refetchUnreadCount();
const conv = enrichConversation(
{ id: conversationId, job_conversations, ...fields, updated_at: updatedAt },
{ isoutbound: false, isSystem: false }
);
upsertConversationIntoOffsetZeroList(client, conv);
break;
}
case "conversation-unarchived": case "conversation-unarchived":
case "conversation-archived": case "conversation-archived": {
try { // Keep unread badge correct even if archiving affects counts
const listQueryVariables = { offset: 0 }; refetchUnreadCount();
const detailsQueryVariables = { conversationId };
// Check if conversation details exist in the cache await client.refetchQueries({
const detailsExist = !!client.cache.readQuery({ include: [CONVERSATION_LIST_QUERY, GET_CONVERSATION_DETAILS]
query: GET_CONVERSATION_DETAILS, });
variables: detailsQueryVariables
});
// Refetch conversation list
await client.refetchQueries({
include: [CONVERSATION_LIST_QUERY, ...(detailsExist ? [GET_CONVERSATION_DETAILS] : [])],
variables: [
{ query: CONVERSATION_LIST_QUERY, variables: listQueryVariables },
...(detailsExist
? [
{
query: GET_CONVERSATION_DETAILS,
variables: detailsQueryVariables
}
]
: [])
]
});
logLocal("handleConversationChanged - Refetched queries after state change", {
conversationId,
type
});
} catch (error) {
console.error("Error refetching queries after conversation state change:", error);
}
break; break;
}
case "tag-added": { case "tag-added": {
// Ensure `job_conversations` is properly formatted const formattedJobConversations = (job_conversations || []).map((jc) => ({
const formattedJobConversations = job_conversations.map((jc) => ({
__typename: "job_conversations", __typename: "job_conversations",
jobid: jc.jobid || jc.job?.id, jobid: jc.jobid || jc.job?.id,
conversationid: conversationId, conversationid: conversationId,
job: jc.job || { job: {
__typename: "jobs", __typename: "jobs",
id: data.selectedJob.id, id: jc.job?.id,
ro_number: data.selectedJob.ro_number, ro_number: jc.job?.ro_number,
ownr_co_nm: data.selectedJob.ownr_co_nm, ownr_co_nm: jc.job?.ownr_co_nm,
ownr_fn: data.selectedJob.ownr_fn, ownr_fn: jc.job?.ownr_fn,
ownr_ln: data.selectedJob.ownr_ln ownr_ln: jc.job?.ownr_ln
} }
})); }));
client.cache.modify({ client.cache.modify({
id: client.cache.identify({ __typename: "conversations", id: conversationId }), id: client.cache.identify({ __typename: "conversations", id: conversationId }),
fields: { fields: {
job_conversations: (existing = []) => { job_conversations(existing = [], { readField }) {
// Ensure no duplicates based on both `conversationid` and `jobid` const seen = new Set(existing.map((x) => readField("jobid", x)).filter(Boolean));
const existingLinks = new Set( const incoming = formattedJobConversations.filter((x) => x.jobid && !seen.has(x.jobid));
existing.map((jc) => { return [...existing, ...incoming];
const jobId = client.cache.readFragment({
id: client.cache.identify(jc),
fragment: gql`
fragment JobConversationLinkAdded on job_conversations {
jobid
conversationid
}
`
})?.jobid;
return `${jobId}:${conversationId}`; // Unique identifier for a job-conversation link
})
);
const newItems = formattedJobConversations.filter((jc) => {
const uniqueLink = `${jc.jobid}:${jc.conversationid}`;
return !existingLinks.has(uniqueLink);
});
return [...existing, ...newItems];
} }
} }
}); });
@@ -412,46 +545,31 @@ export const registerMessagingHandlers = ({ socket, client, currentUser, bodysho
break; break;
} }
case "tag-removed": case "tag-removed": {
try { const conversationCacheId = client.cache.identify({ __typename: "conversations", id: conversationId });
const conversationCacheId = client.cache.identify({ __typename: "conversations", id: conversationId });
// Evict the specific cache entry for job_conversations
client.cache.evict({
id: conversationCacheId,
fieldName: "job_conversations"
});
// Garbage collect evicted entries
client.cache.gc();
logLocal("handleConversationChanged - tag removed - Refetched conversation list after state change", {
conversationId,
type
});
} catch (error) {
console.error("Error refetching queries after conversation state change: (Tag Removed)", error);
}
client.cache.evict({
id: conversationCacheId,
fieldName: "job_conversations"
});
client.cache.gc();
break; break;
}
default: default: {
logLocal("handleConversationChanged - Unhandled type", { type });
client.cache.modify({ client.cache.modify({
id: client.cache.identify({ __typename: "conversations", id: conversationId }), id: client.cache.identify({ __typename: "conversations", id: conversationId }),
fields: { fields: Object.fromEntries(
...Object.fromEntries( Object.entries(fields).map(([key, value]) => [key, (cached) => (value !== undefined ? value : cached)])
Object.entries(fields).map(([key, value]) => [key, (cached) => (value !== undefined ? value : cached)]) )
)
}
}); });
}
} }
} catch (error) { } catch (error) {
console.error("Error handling conversation changes:", { type, error }); console.error("Error handling conversation changes:", { type, error });
} }
}; };
// Existing handler for phone number opt-out
const handlePhoneNumberOptedOut = async (data) => { const handlePhoneNumberOptedOut = async (data) => {
const { bodyshopid, phone_number } = data; const { bodyshopid, phone_number } = data;
logLocal("handlePhoneNumberOptedOut - Start", data); logLocal("handlePhoneNumberOptedOut - Start", data);
@@ -461,22 +579,18 @@ export const registerMessagingHandlers = ({ socket, client, currentUser, bodysho
id: "ROOT_QUERY", id: "ROOT_QUERY",
fields: { fields: {
phone_number_opt_out(existing = [], { readField }) { phone_number_opt_out(existing = [], { readField }) {
const phoneNumberExists = existing.some( const exists = existing.some(
(ref) => readField("phone_number", ref) === phone_number && readField("bodyshopid", ref) === bodyshopid (ref) => readField("phone_number", ref) === phone_number && readField("bodyshopid", ref) === bodyshopid
); );
if (exists) return existing;
if (phoneNumberExists) {
logLocal("handlePhoneNumberOptedOut - Phone number already in cache", { phone_number, bodyshopid });
return existing;
}
const newOptOut = { const newOptOut = {
__typename: "phone_number_opt_out", __typename: "phone_number_opt_out",
id: `temporary-${phone_number}-${Date.now()}`, id: `temporary-${phone_number}-${Date.now()}`,
bodyshopid, bodyshopid,
phone_number, phone_number,
created_at: new Date().toISOString(), created_at: safeIsoNow(),
updated_at: new Date().toISOString() updated_at: safeIsoNow()
}; };
return [...existing, newOptOut]; return [...existing, newOptOut];
@@ -491,46 +605,36 @@ export const registerMessagingHandlers = ({ socket, client, currentUser, bodysho
args: { bodyshopid, search: phone_number } args: { bodyshopid, search: phone_number }
}); });
client.cache.gc(); client.cache.gc();
logLocal("handlePhoneNumberOptedOut - Cache updated successfully", data);
} catch (error) { } catch (error) {
console.error("Error updating cache for phone number opt-out:", error); console.error("Error updating cache for phone number opt-out:", error);
logLocal("handlePhoneNumberOptedOut - Error", { error: error.message });
} }
}; };
// New handler for phone number opt-in
const handlePhoneNumberOptedIn = async (data) => { const handlePhoneNumberOptedIn = async (data) => {
const { bodyshopid, phone_number } = data; const { bodyshopid, phone_number } = data;
logLocal("handlePhoneNumberOptedIn - Start", data); logLocal("handlePhoneNumberOptedIn - Start", data);
try { try {
// Update the Apollo cache for GET_PHONE_NUMBER_OPT_OUTS by removing the phone number
client.cache.modify({ client.cache.modify({
id: "ROOT_QUERY", id: "ROOT_QUERY",
fields: { fields: {
phone_number_opt_out(existing = [], { readField }) { phone_number_opt_out(existing = [], { readField }) {
// Filter out the phone number from the opt-out list
return existing.filter( return existing.filter(
(ref) => !(readField("phone_number", ref) === phone_number && readField("bodyshopid", ref) === bodyshopid) (ref) => !(readField("phone_number", ref) === phone_number && readField("bodyshopid", ref) === bodyshopid)
); );
} }
}, },
broadcast: true // Trigger UI updates broadcast: true
}); });
// Evict the cache entry to force a refetch on next query
client.cache.evict({ client.cache.evict({
id: "ROOT_QUERY", id: "ROOT_QUERY",
fieldName: "phone_number_opt_out", fieldName: "phone_number_opt_out",
args: { bodyshopid, search: phone_number } args: { bodyshopid, search: phone_number }
}); });
client.cache.gc(); client.cache.gc();
logLocal("handlePhoneNumberOptedIn - Cache updated successfully", data);
} catch (error) { } catch (error) {
console.error("Error updating cache for phone number opt-in:", error); console.error("Error updating cache for phone number opt-in:", error);
logLocal("handlePhoneNumberOptedIn - Error", { error: error.message });
} }
}; };

View File

@@ -12,7 +12,7 @@ import _ from "lodash";
import { ExclamationCircleOutlined } from "@ant-design/icons"; import { ExclamationCircleOutlined } from "@ant-design/icons";
import "./chat-conversation-list.styles.scss"; import "./chat-conversation-list.styles.scss";
import { useQuery } from "@apollo/client"; import { useQuery } from "@apollo/client";
import { GET_PHONE_NUMBER_OPT_OUTS } from "../../graphql/phone-number-opt-out.queries.js"; import { GET_PHONE_NUMBER_OPT_OUTS_BY_NUMBERS } from "../../graphql/phone-number-opt-out.queries.js";
import { phone } from "phone"; import { phone } from "phone";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { selectBodyshop } from "../../redux/user/user.selectors"; import { selectBodyshop } from "../../redux/user/user.selectors";
@@ -29,13 +29,26 @@ const mapDispatchToProps = (dispatch) => ({
function ChatConversationListComponent({ conversationList, selectedConversation, setSelectedConversation, bodyshop }) { function ChatConversationListComponent({ conversationList, selectedConversation, setSelectedConversation, bodyshop }) {
const { t } = useTranslation(); const { t } = useTranslation();
const [, forceUpdate] = useState(false); const [, forceUpdate] = useState(false);
const phoneNumbers = conversationList.map((item) => phone(item.phone_num, "CA").phoneNumber.replace(/^\+1/, ""));
const { data: optOutData } = useQuery(GET_PHONE_NUMBER_OPT_OUTS, { const phoneNumbers = useMemo(() => {
return (conversationList || [])
.map((item) => {
try {
const p = phone(item.phone_num, "CA")?.phoneNumber;
return p ? p.replace(/^\+1/, "") : null;
} catch {
return null;
}
})
.filter(Boolean);
}, [conversationList]);
const { data: optOutData } = useQuery(GET_PHONE_NUMBER_OPT_OUTS_BY_NUMBERS, {
variables: { variables: {
bodyshopid: bodyshop.id, bodyshopid: bodyshop?.id,
phone_numbers: phoneNumbers phone_numbers: phoneNumbers
}, },
skip: !conversationList.length, skip: !bodyshop?.id || phoneNumbers.length === 0,
fetchPolicy: "cache-and-network" fetchPolicy: "cache-and-network"
}); });
@@ -58,15 +71,25 @@ function ChatConversationListComponent({ conversationList, selectedConversation,
return _.orderBy(conversationList, ["updated_at"], ["desc"]); return _.orderBy(conversationList, ["updated_at"], ["desc"]);
}, [conversationList]); }, [conversationList]);
const renderConversation = (index, t) => { const renderConversation = (index) => {
const item = sortedConversationList[index]; const item = sortedConversationList[index];
const normalizedPhone = phone(item.phone_num, "CA").phoneNumber.replace(/^\+1/, "");
const hasOptOutEntry = optOutMap.has(normalizedPhone); const normalizedPhone = (() => {
try {
return phone(item.phone_num, "CA")?.phoneNumber?.replace(/^\+1/, "") || "";
} catch {
return "";
}
})();
const hasOptOutEntry = normalizedPhone ? optOutMap.has(normalizedPhone) : false;
const cardContentRight = <TimeAgoFormatter>{item.updated_at}</TimeAgoFormatter>; const cardContentRight = <TimeAgoFormatter>{item.updated_at}</TimeAgoFormatter>;
const cardContentLeft = const cardContentLeft =
item.job_conversations.length > 0 item.job_conversations.length > 0
? item.job_conversations.map((j, idx) => <Tag key={idx}>{j.job.ro_number}</Tag>) ? item.job_conversations.map((j, idx) => <Tag key={idx}>{j.job.ro_number}</Tag>)
: null; : null;
const names = <>{_.uniq(item.job_conversations.map((j) => OwnerNameDisplayFunction(j.job)))}</>; const names = <>{_.uniq(item.job_conversations.map((j) => OwnerNameDisplayFunction(j.job)))}</>;
const cardTitle = ( const cardTitle = (
<> <>
@@ -80,9 +103,10 @@ function ChatConversationListComponent({ conversationList, selectedConversation,
)} )}
</> </>
); );
const cardExtra = ( const cardExtra = (
<> <>
<Badge count={item.messages_aggregate.aggregate.count} /> <Badge count={item.messages_aggregate?.aggregate?.count || 0} />
{hasOptOutEntry && ( {hasOptOutEntry && (
<Tooltip title={t("consent.text_body")}> <Tooltip title={t("consent.text_body")}>
<Tag color="red" icon={<ExclamationCircleOutlined />}> <Tag color="red" icon={<ExclamationCircleOutlined />}>
@@ -92,6 +116,7 @@ function ChatConversationListComponent({ conversationList, selectedConversation,
)} )}
</> </>
); );
const getCardStyle = () => const getCardStyle = () =>
item.id === selectedConversation item.id === selectedConversation
? { backgroundColor: "var(--card-selected-bg)" } ? { backgroundColor: "var(--card-selected-bg)" }
@@ -104,24 +129,8 @@ function ChatConversationListComponent({ conversationList, selectedConversation,
className={`chat-list-item ${item.id === selectedConversation ? "chat-list-selected-conversation" : ""}`} className={`chat-list-item ${item.id === selectedConversation ? "chat-list-selected-conversation" : ""}`}
> >
<Card style={getCardStyle()} variant={true} size="small" extra={cardExtra} title={cardTitle}> <Card style={getCardStyle()} variant={true} size="small" extra={cardExtra} title={cardTitle}>
<div <div style={{ display: "inline-block", width: "70%", textAlign: "left" }}>{cardContentLeft}</div>
style={{ <div style={{ display: "inline-block", width: "30%", textAlign: "right" }}>{cardContentRight}</div>
display: "inline-block",
width: "70%",
textAlign: "left"
}}
>
{cardContentLeft}
</div>
<div
style={{
display: "inline-block",
width: "30%",
textAlign: "right"
}}
>
{cardContentRight}
</div>
</Card> </Card>
</List.Item> </List.Item>
); );
@@ -131,7 +140,7 @@ function ChatConversationListComponent({ conversationList, selectedConversation,
<div className="chat-list-container"> <div className="chat-list-container">
<Virtuoso <Virtuoso
data={sortedConversationList} data={sortedConversationList}
itemContent={(index) => renderConversation(index, t)} itemContent={(index) => renderConversation(index)}
style={{ height: "100%", width: "100%" }} style={{ height: "100%", width: "100%" }}
/> />
</div> </div>

View File

@@ -5,24 +5,24 @@ import ChatConversationTitleTags from "../chat-conversation-title-tags/chat-conv
import ChatLabelComponent from "../chat-label/chat-label.component"; import ChatLabelComponent from "../chat-label/chat-label.component";
import ChatPrintButton from "../chat-print-button/chat-print-button.component"; import ChatPrintButton from "../chat-print-button/chat-print-button.component";
import ChatTagRoContainer from "../chat-tag-ro/chat-tag-ro.container"; import ChatTagRoContainer from "../chat-tag-ro/chat-tag-ro.container";
import { createStructuredSelector } from "reselect"; import ChatMarkUnreadButton from "../chat-mark-unread-button/chat-mark-unread-button.component";
import { connect } from "react-redux";
const mapStateToProps = createStructuredSelector({}); export function ChatConversationTitle({ conversation, onMarkUnread, markUnreadDisabled, markUnreadLoading }) {
const mapDispatchToProps = () => ({});
export function ChatConversationTitle({ conversation }) {
return ( return (
<Space className="chat-title" wrap> <Space className="chat-title" wrap>
<PhoneNumberFormatter>{conversation?.phone_num}</PhoneNumberFormatter> <PhoneNumberFormatter>{conversation?.phone_num}</PhoneNumberFormatter>
<ChatLabelComponent conversation={conversation} /> <ChatLabelComponent conversation={conversation} />
<ChatPrintButton conversation={conversation} /> <ChatPrintButton conversation={conversation} />
<ChatConversationTitleTags jobConversations={conversation?.job_conversations || []} /> <ChatConversationTitleTags jobConversations={conversation?.job_conversations || []} />
<ChatTagRoContainer conversation={conversation || []} /> <ChatTagRoContainer conversation={conversation || []} />
<ChatMarkUnreadButton disabled={markUnreadDisabled} loading={markUnreadLoading} onMarkUnread={onMarkUnread} />
<ChatArchiveButton conversation={conversation} /> <ChatArchiveButton conversation={conversation} />
</Space> </Space>
); );
} }
export default connect(mapStateToProps, mapDispatchToProps)(ChatConversationTitle); export default ChatConversationTitle;

View File

@@ -19,7 +19,9 @@ export function ChatConversationComponent({
conversation, conversation,
messages, messages,
handleMarkConversationAsRead, handleMarkConversationAsRead,
bodyshop handleMarkLastMessageAsUnread,
markingAsUnreadInProgress,
canMarkUnread
}) { }) {
const [loading, error] = subState; const [loading, error] = subState;
@@ -33,7 +35,12 @@ export function ChatConversationComponent({
onMouseDown={handleMarkConversationAsRead} onMouseDown={handleMarkConversationAsRead}
onKeyDown={handleMarkConversationAsRead} onKeyDown={handleMarkConversationAsRead}
> >
<ChatConversationTitle conversation={conversation} bodyshop={bodyshop} /> <ChatConversationTitle
conversation={conversation}
onMarkUnread={handleMarkLastMessageAsUnread}
markUnreadDisabled={!canMarkUnread}
markUnreadLoading={markingAsUnreadInProgress}
/>
<ChatMessageListComponent messages={messages} /> <ChatMessageListComponent messages={messages} />
<ChatSendMessage conversation={conversation} /> <ChatSendMessage conversation={conversation} />
</div> </div>

View File

@@ -1,6 +1,6 @@
import { gql, useApolloClient, useQuery, useSubscription } from "@apollo/client"; import { gql, useApolloClient, useQuery, useSubscription } from "@apollo/client";
import axios from "axios"; import axios from "axios";
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useMemo, useState } from "react";
import { connect } from "react-redux"; import { connect } from "react-redux";
import { createStructuredSelector } from "reselect"; import { createStructuredSelector } from "reselect";
import { CONVERSATION_SUBSCRIPTION_BY_PK, GET_CONVERSATION_DETAILS } from "../../graphql/conversations.queries"; import { CONVERSATION_SUBSCRIPTION_BY_PK, GET_CONVERSATION_DETAILS } from "../../graphql/conversations.queries";
@@ -18,8 +18,8 @@ function ChatConversationContainer({ bodyshop, selectedConversation }) {
const client = useApolloClient(); const client = useApolloClient();
const { socket } = useSocket(); const { socket } = useSocket();
const [markingAsReadInProgress, setMarkingAsReadInProgress] = useState(false); const [markingAsReadInProgress, setMarkingAsReadInProgress] = useState(false);
const [markingAsUnreadInProgress, setMarkingAsUnreadInProgress] = useState(false);
// Fetch conversation details
const { const {
loading: convoLoading, loading: convoLoading,
error: convoError, error: convoError,
@@ -27,24 +27,23 @@ function ChatConversationContainer({ bodyshop, selectedConversation }) {
} = useQuery(GET_CONVERSATION_DETAILS, { } = useQuery(GET_CONVERSATION_DETAILS, {
variables: { conversationId: selectedConversation }, variables: { conversationId: selectedConversation },
fetchPolicy: "network-only", fetchPolicy: "network-only",
nextFetchPolicy: "network-only" nextFetchPolicy: "network-only",
skip: !selectedConversation
}); });
// Subscription for conversation updates const conversation = convoData?.conversations_by_pk;
// Subscription for conversation updates (used when socket is NOT connected)
useSubscription(CONVERSATION_SUBSCRIPTION_BY_PK, { useSubscription(CONVERSATION_SUBSCRIPTION_BY_PK, {
skip: socket?.connected, skip: socket?.connected || !selectedConversation,
variables: { conversationId: selectedConversation }, variables: { conversationId: selectedConversation },
onData: ({ data: subscriptionResult, client }) => { onData: ({ data: subscriptionResult, client }) => {
// Extract the messages array from the result
const messages = subscriptionResult?.data?.messages; const messages = subscriptionResult?.data?.messages;
if (!messages || messages.length === 0) { if (!messages || messages.length === 0) return;
console.warn("No messages found in subscription result.");
return;
}
messages.forEach((message) => { messages.forEach((message) => {
const messageRef = client.cache.identify(message); const messageRef = client.cache.identify(message);
// Write the new message to the cache
client.cache.writeFragment({ client.cache.writeFragment({
id: messageRef, id: messageRef,
fragment: gql` fragment: gql`
@@ -64,7 +63,6 @@ function ChatConversationContainer({ bodyshop, selectedConversation }) {
data: message data: message
}); });
// Update the conversation cache to include the new message
client.cache.modify({ client.cache.modify({
id: client.cache.identify({ __typename: "conversations", id: selectedConversation }), id: client.cache.identify({ __typename: "conversations", id: selectedConversation }),
fields: { fields: {
@@ -82,6 +80,28 @@ function ChatConversationContainer({ bodyshop, selectedConversation }) {
} }
}); });
/**
* Best-effort badge update:
* This assumes your list query uses messages_aggregate.aggregate.count as UNREAD inbound count.
* If its total messages, rename/create a dedicated unread aggregate in the list query and update that field instead.
*/
const setConversationUnreadCountBestEffort = useCallback(
(conversationId, unreadCount) => {
if (!conversationId) return;
client.cache.modify({
id: client.cache.identify({ __typename: "conversations", id: conversationId }),
fields: {
messages_aggregate(existing) {
if (!existing?.aggregate) return existing;
return { ...existing, aggregate: { ...existing.aggregate, count: unreadCount } };
}
}
});
},
[client.cache]
);
const updateCacheWithReadMessages = useCallback( const updateCacheWithReadMessages = useCallback(
(conversationId, messageIds) => { (conversationId, messageIds) => {
if (!conversationId || !messageIds?.length) return; if (!conversationId || !messageIds?.length) return;
@@ -89,13 +109,34 @@ function ChatConversationContainer({ bodyshop, selectedConversation }) {
messageIds.forEach((messageId) => { messageIds.forEach((messageId) => {
client.cache.modify({ client.cache.modify({
id: client.cache.identify({ __typename: "messages", id: messageId }), id: client.cache.identify({ __typename: "messages", id: messageId }),
fields: { fields: { read: () => true }
read: () => true
}
}); });
}); });
setConversationUnreadCountBestEffort(conversationId, 0);
}, },
[client.cache] [client.cache, setConversationUnreadCountBestEffort]
);
const applyUnreadStateWithMaxOneUnread = useCallback(
({ conversationId, lastUnreadMessageId, messageIdsMarkedRead = [], unreadCount = 1 }) => {
if (!conversationId || !lastUnreadMessageId) return;
messageIdsMarkedRead.forEach((id) => {
client.cache.modify({
id: client.cache.identify({ __typename: "messages", id }),
fields: { read: () => true }
});
});
client.cache.modify({
id: client.cache.identify({ __typename: "messages", id: lastUnreadMessageId }),
fields: { read: () => false }
});
setConversationUnreadCountBestEffort(conversationId, unreadCount);
},
[client.cache, setConversationUnreadCountBestEffort]
); );
// WebSocket event handlers // WebSocket event handlers
@@ -103,20 +144,25 @@ function ChatConversationContainer({ bodyshop, selectedConversation }) {
if (!socket?.connected) return; if (!socket?.connected) return;
const handleConversationChange = (data) => { const handleConversationChange = (data) => {
if (data.type === "conversation-marked-read") { if (data?.type === "conversation-marked-read") {
const { conversationId, messageIds } = data; updateCacheWithReadMessages(data.conversationId, data.messageIds);
updateCacheWithReadMessages(conversationId, messageIds); }
if (data?.type === "conversation-marked-unread") {
applyUnreadStateWithMaxOneUnread({
conversationId: data.conversationId,
lastUnreadMessageId: data.lastUnreadMessageId,
messageIdsMarkedRead: data.messageIdsMarkedRead,
unreadCount: data.unreadCount
});
} }
}; };
socket.on("conversation-changed", handleConversationChange); socket.on("conversation-changed", handleConversationChange);
return () => socket.off("conversation-changed", handleConversationChange);
}, [socket, updateCacheWithReadMessages, applyUnreadStateWithMaxOneUnread]);
return () => { // Join/leave conversation via WebSocket
socket.off("conversation-changed", handleConversationChange);
};
}, [socket, updateCacheWithReadMessages]);
// Join and leave conversation via WebSocket
useEffect(() => { useEffect(() => {
if (!socket?.connected || !selectedConversation || !bodyshop?.id) return; if (!socket?.connected || !selectedConversation || !bodyshop?.id) return;
@@ -133,15 +179,21 @@ function ChatConversationContainer({ bodyshop, selectedConversation }) {
}; };
}, [socket, bodyshop, selectedConversation]); }, [socket, bodyshop, selectedConversation]);
// Mark conversation as read const inboundNonSystemMessages = useMemo(() => {
const handleMarkConversationAsRead = async () => { const msgs = conversation?.messages || [];
if (!convoData || markingAsReadInProgress) return; return msgs
.filter((m) => m && !m.isoutbound && !m.is_system)
.slice()
.sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime());
}, [conversation?.messages]);
const conversation = convoData.conversations_by_pk; const canMarkUnread = inboundNonSystemMessages.length > 0;
if (!conversation) return;
const handleMarkConversationAsRead = async () => {
if (!conversation || markingAsReadInProgress) return;
const unreadMessageIds = conversation.messages const unreadMessageIds = conversation.messages
?.filter((message) => !message.read && !message.isoutbound) ?.filter((message) => !message.read && !message.isoutbound && !message.is_system)
.map((message) => message.id); .map((message) => message.id);
if (unreadMessageIds?.length > 0) { if (unreadMessageIds?.length > 0) {
@@ -162,12 +214,48 @@ function ChatConversationContainer({ bodyshop, selectedConversation }) {
} }
}; };
const handleMarkLastMessageAsUnread = async () => {
if (!conversation || markingAsUnreadInProgress) return;
if (!bodyshop?.id || !bodyshop?.imexshopid) return;
const lastInbound = inboundNonSystemMessages[inboundNonSystemMessages.length - 1];
if (!lastInbound?.id) return;
setMarkingAsUnreadInProgress(true);
try {
const res = await axios.post("/sms/markLastMessageUnread", {
conversationId: conversation.id,
imexshopid: bodyshop.imexshopid,
bodyshopid: bodyshop.id
});
const payload = res?.data || {};
if (payload.lastUnreadMessageId) {
applyUnreadStateWithMaxOneUnread({
conversationId: conversation.id,
lastUnreadMessageId: payload.lastUnreadMessageId,
messageIdsMarkedRead: payload.messageIdsMarkedRead || [],
unreadCount: typeof payload.unreadCount === "number" ? payload.unreadCount : 1
});
} else {
setConversationUnreadCountBestEffort(conversation.id, 0);
}
} catch (error) {
console.error("Error marking last message unread:", error.message);
} finally {
setMarkingAsUnreadInProgress(false);
}
};
return ( return (
<ChatConversationComponent <ChatConversationComponent
subState={[convoLoading, convoError]} subState={[convoLoading, convoError]}
conversation={convoData?.conversations_by_pk || {}} conversation={conversation || {}}
messages={convoData?.conversations_by_pk?.messages || []} messages={conversation?.messages || []}
handleMarkConversationAsRead={handleMarkConversationAsRead} handleMarkConversationAsRead={handleMarkConversationAsRead}
handleMarkLastMessageAsUnread={handleMarkLastMessageAsUnread}
markingAsUnreadInProgress={markingAsUnreadInProgress}
canMarkUnread={canMarkUnread}
/> />
); );
} }

View File

@@ -0,0 +1,24 @@
import { Button, Tooltip } from "antd";
import { useTranslation } from "react-i18next";
export default function ChatMarkUnreadButton({ disabled, loading, onMarkUnread }) {
const { t } = useTranslation();
return (
<Tooltip title={t("messaging.labels.mark_unread")}>
<Button
size="small"
className="unread-button"
type="primary"
children={t("messaging.labels.mark_unread")}
loading={loading}
disabled={disabled}
onMouseDown={(e) => e.stopPropagation()} // prevent parent mark-read handler
onClick={(e) => {
e.stopPropagation();
onMarkUnread?.();
}}
/>
</Tooltip>
);
}

View File

@@ -10,6 +10,11 @@
border-radius: 4px; border-radius: 4px;
} }
.unread-button {
height: 20px;
border-radius: 4px;
}
.chat-title { .chat-title {
margin-bottom: 5px; margin-bottom: 5px;
} }

View File

@@ -2,7 +2,27 @@ import { gql } from "@apollo/client";
export const UNREAD_CONVERSATION_COUNT = gql` export const UNREAD_CONVERSATION_COUNT = gql`
query UNREAD_CONVERSATION_COUNT { query UNREAD_CONVERSATION_COUNT {
messages_aggregate(where: { read: { _eq: false }, isoutbound: { _eq: false } }) { # How many conversations have at least one unread inbound, non-system message
conversations_aggregate(
where: {
archived: { _eq: false }
messages: { read: { _eq: false }, isoutbound: { _eq: false }, is_system: { _eq: false } }
}
) {
aggregate {
count
}
}
# How many unread inbound, non-system messages exist (excluding archived conversations)
messages_aggregate(
where: {
read: { _eq: false }
isoutbound: { _eq: false }
is_system: { _eq: false }
conversation: { archived: { _eq: false } }
}
) {
aggregate { aggregate {
count count
} }
@@ -19,7 +39,7 @@ export const CONVERSATION_LIST_QUERY = gql`
unreadcnt unreadcnt
archived archived
label label
messages_aggregate(where: { read: { _eq: false }, isoutbound: { _eq: false } }) { messages_aggregate(where: { read: { _eq: false }, isoutbound: { _eq: false }, is_system: { _eq: false } }) {
aggregate { aggregate {
count count
} }
@@ -41,6 +61,7 @@ export const CONVERSATION_SUBSCRIPTION_BY_PK = gql`
subscription CONVERSATION_SUBSCRIPTION_BY_PK($conversationId: uuid!) { subscription CONVERSATION_SUBSCRIPTION_BY_PK($conversationId: uuid!) {
messages(order_by: { created_at: asc_nulls_first }, where: { conversationid: { _eq: $conversationId } }) { messages(order_by: { created_at: asc_nulls_first }, where: { conversationid: { _eq: $conversationId } }) {
id id
conversationid
status status
text text
is_system is_system
@@ -76,6 +97,7 @@ export const GET_CONVERSATION_DETAILS = gql`
} }
messages(order_by: { created_at: asc_nulls_first }) { messages(order_by: { created_at: asc_nulls_first }) {
id id
conversationid
status status
text text
is_system is_system
@@ -110,7 +132,7 @@ export const CONVERSATION_ID_BY_PHONE = gql`
ro_number ro_number
} }
} }
messages_aggregate(where: { read: { _eq: false }, isoutbound: { _eq: false } }) { messages_aggregate(where: { read: { _eq: false }, isoutbound: { _eq: false }, is_system: { _eq: false } }) {
aggregate { aggregate {
count count
} }
@@ -139,7 +161,7 @@ export const CREATE_CONVERSATION = gql`
ro_number ro_number
} }
} }
messages_aggregate(where: { read: { _eq: false }, isoutbound: { _eq: false } }) { messages_aggregate(where: { read: { _eq: false }, isoutbound: { _eq: false }, is_system: { _eq: false } }) {
aggregate { aggregate {
count count
} }

View File

@@ -2445,7 +2445,8 @@
"selectmedia": "Select Media", "selectmedia": "Select Media",
"sentby": "Sent by {{by}} at {{time}}", "sentby": "Sent by {{by}} at {{time}}",
"typeamessage": "Send a message...", "typeamessage": "Send a message...",
"unarchive": "Unarchive" "unarchive": "Unarchive",
"mark_unread": "Mark as unread"
}, },
"render": { "render": {
"conversation_list": "Conversation List" "conversation_list": "Conversation List"

View File

@@ -2442,7 +2442,8 @@
"selectmedia": "", "selectmedia": "",
"sentby": "", "sentby": "",
"typeamessage": "Enviar un mensaje...", "typeamessage": "Enviar un mensaje...",
"unarchive": "" "unarchive": "",
"mark_unread": ""
}, },
"render": { "render": {
"conversation_list": "" "conversation_list": ""

View File

@@ -2442,7 +2442,8 @@
"selectmedia": "", "selectmedia": "",
"sentby": "", "sentby": "",
"typeamessage": "Envoyer un message...", "typeamessage": "Envoyer un message...",
"unarchive": "" "unarchive": "",
"mark_unread": ""
}, },
"render": { "render": {
"conversation_list": "" "conversation_list": ""

View File

@@ -148,6 +148,26 @@ const cache = new InMemoryCache({
Query: { Query: {
fields: { fields: {
// Note: This is required because we switch from a read to an unread state with a toggle, // Note: This is required because we switch from a read to an unread state with a toggle,
conversations: {
keyArgs: ["where", "order_by"], // keep separate caches for archived/unarchived + sort
merge(existing = [], incoming = [], { args, readField }) {
const offset = args?.offset ?? 0;
const merged = existing ? existing.slice(0) : [];
for (let i = 0; i < incoming.length; i++) {
merged[offset + i] = incoming[i];
}
// Deduplicate by id (important when you also upsert via sockets)
const seen = new Set();
return merged.filter((ref) => {
const id = readField("id", ref);
if (!id || seen.has(id)) return false;
seen.add(id);
return true;
});
}
},
notifications: { notifications: {
merge(existing = [], incoming = [], { readField }) { merge(existing = [], incoming = [], { readField }) {
// Create a map to deduplicate by __ref // Create a map to deduplicate by __ref

View File

@@ -123,7 +123,7 @@ mutation RECEIVE_MESSAGE($msg: [messages_insert_input!]!) {
exports.INSERT_MESSAGE = ` exports.INSERT_MESSAGE = `
mutation INSERT_MESSAGE($msg: [messages_insert_input!]!, $conversationid: uuid!) { mutation INSERT_MESSAGE($msg: [messages_insert_input!]!, $conversationid: uuid!) {
update_conversations_by_pk(pk_columns: {id: $conversationid}, _set: {archived: false}) { update_conversations_by_pk(pk_columns: { id: $conversationid }, _set: { archived: false }) {
id id
archived archived
} }
@@ -147,6 +147,7 @@ mutation INSERT_MESSAGE($msg: [messages_insert_input!]!, $conversationid: uuid!)
image_path image_path
image image
isoutbound isoutbound
is_system
msid msid
read read
text text

View File

@@ -3,7 +3,7 @@ const router = express.Router();
const twilio = require("twilio"); const twilio = require("twilio");
const { receive } = require("../sms/receive"); const { receive } = require("../sms/receive");
const { send } = require("../sms/send"); const { send } = require("../sms/send");
const { status, markConversationRead } = require("../sms/status"); const { status, markConversationRead, markLastMessageUnread } = require("../sms/status");
const validateFirebaseIdTokenMiddleware = require("../middleware/validateFirebaseIdTokenMiddleware"); const validateFirebaseIdTokenMiddleware = require("../middleware/validateFirebaseIdTokenMiddleware");
// Twilio Webhook Middleware for production // Twilio Webhook Middleware for production
@@ -14,5 +14,6 @@ router.post("/receive", twilioWebhookMiddleware, receive);
router.post("/send", validateFirebaseIdTokenMiddleware, send); router.post("/send", validateFirebaseIdTokenMiddleware, send);
router.post("/status", twilioWebhookMiddleware, status); router.post("/status", twilioWebhookMiddleware, status);
router.post("/markConversationRead", validateFirebaseIdTokenMiddleware, markConversationRead); router.post("/markConversationRead", validateFirebaseIdTokenMiddleware, markConversationRead);
router.post("/markLastMessageUnread", validateFirebaseIdTokenMiddleware, markLastMessageUnread);
module.exports = router; module.exports = router;

View File

@@ -61,7 +61,8 @@ const send = async (req, res) => {
isoutbound: true, isoutbound: true,
userid: req.user.email, userid: req.user.email,
image: selectedMedia.length > 0, image: selectedMedia.length > 0,
image_path: selectedMedia.length > 0 ? selectedMedia.map((i) => i.src) : [] image_path: selectedMedia.length > 0 ? selectedMedia.map((i) => i.src) : [],
is_system: false
}; };
try { try {

View File

@@ -8,6 +8,46 @@ const {
const logger = require("../utils/logger"); const logger = require("../utils/logger");
const { phone } = require("phone"); const { phone } = require("phone");
// Local GraphQL for “mark unread” (kept here to avoid requiring edits to graphql-client/queries.js)
const GET_LAST_INBOUND_NON_SYSTEM_MESSAGE = `
query GetLastInboundNonSystemMessage($conversationId: uuid!) {
messages(
where: {
conversationid: { _eq: $conversationId }
isoutbound: { _eq: false }
is_system: { _eq: false }
}
order_by: { created_at: desc }
limit: 1
) {
id
created_at
read
}
}
`;
const MARK_LAST_INBOUND_MESSAGE_UNREAD_MAX_ONE = `
mutation MarkLastInboundMessageUnreadMaxOne($conversationId: uuid!, $lastId: uuid!) {
markOthersRead: update_messages(
_set: { read: true }
where: {
conversationid: { _eq: $conversationId }
isoutbound: { _eq: false }
is_system: { _eq: false }
id: { _neq: $lastId }
}
) {
affected_rows
returning { id }
}
markLastUnread: update_messages_by_pk(pk_columns: { id: $lastId }, _set: { read: false }) {
id
}
}
`;
/** /**
* Handle the status of an SMS message * Handle the status of an SMS message
* @param req * @param req
@@ -176,7 +216,80 @@ const markConversationRead = async (req, res) => {
} }
}; };
/**
* Mark last inbound (customer) non-system message as unread.
* Enforces: max unread inbound non-system messages per thread = 1
*
* Body: { conversationId, imexshopid, bodyshopid }
*/
const markLastMessageUnread = async (req, res) => {
const {
ioRedis,
ioHelpers: { getBodyshopRoom }
} = req;
const { conversationId, imexshopid, bodyshopid } = req.body;
if (!conversationId || !imexshopid || !bodyshopid) {
return res.status(400).json({ error: "Invalid conversation data provided." });
}
try {
const lastResp = await client.request(GET_LAST_INBOUND_NON_SYSTEM_MESSAGE, { conversationId });
const last = lastResp?.messages?.[0];
if (!last?.id) {
// No inbound message to mark unread
const broadcastRoom = getBodyshopRoom(bodyshopid);
ioRedis.to(broadcastRoom).emit("conversation-changed", {
type: "conversation-marked-unread",
conversationId,
lastUnreadMessageId: null,
messageIdsMarkedRead: [],
unreadCount: 0
});
return res.status(200).json({
success: true,
conversationId,
lastUnreadMessageId: null,
messageIdsMarkedRead: [],
unreadCount: 0
});
}
const mutResp = await client.request(MARK_LAST_INBOUND_MESSAGE_UNREAD_MAX_ONE, {
conversationId,
lastId: last.id
});
const messageIdsMarkedRead = mutResp?.markOthersRead?.returning?.map((m) => m.id) || [];
const broadcastRoom = getBodyshopRoom(bodyshopid);
ioRedis.to(broadcastRoom).emit("conversation-changed", {
type: "conversation-marked-unread",
conversationId,
lastUnreadMessageId: last.id,
messageIdsMarkedRead,
unreadCount: 1
});
return res.status(200).json({
success: true,
conversationId,
lastUnreadMessageId: last.id,
messageIdsMarkedRead,
unreadCount: 1
});
} catch (error) {
console.error("Error marking last message unread:", error);
return res.status(500).json({ error: "Failed to mark last message unread." });
}
};
module.exports = { module.exports = {
status, status,
markConversationRead markConversationRead,
markLastMessageUnread
}; };