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

View File

@@ -13,68 +13,241 @@ const logLocal = (message, ...args) => {
}
};
// Utility function to enrich conversation data
const enrichConversation = (conversation, isOutbound) => ({
const safeIsoNow = () => new Date().toISOString();
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,
updated_at: conversation.updated_at || new Date().toISOString(),
unreadcnt: conversation.unreadcnt || 0,
archived: conversation.archived || false,
label: conversation.label || null,
updated_at: conversation.updated_at || safeIsoNow(),
unreadcnt: typeof conversation.unreadcnt === "number" ? conversation.unreadcnt : 0,
archived: conversation.archived ?? false,
label: conversation.label ?? null,
job_conversations: conversation.job_conversations || [],
messages_aggregate: conversation.messages_aggregate || {
__typename: "messages_aggregate",
aggregate: {
__typename: "messages_aggregate_fields",
count: isOutbound ? 0 : 1
count: isoutbound || isSystem ? 0 : 1
}
},
__typename: "conversations"
});
// Can be uncommonted to test the playback of the notification sound
// window.testTone = () => {
// const notificationSound = new Audio(newMessageSound);
// notificationSound.play().catch((error) => {
// console.error("Error playing notification sound:", error);
// });
// };
const upsertConversationIntoOffsetZeroList = (client, conversationObj, { isoutbound, isSystem } = {}) => {
const normalized = normalizeConversationForList(conversationObj, { isoutbound, isSystem });
if (!normalized?.id) return;
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 }) => {
if (!(socket && client)) return;
const handleNewMessageSummary = async (message) => {
const { conversationId, newConversation, existingConversation, isoutbound } = message;
// Coalesce unread refetches (avoid spamming during bursts)
let unreadRefetchInFlight = null;
const refetchUnreadCount = () => {
if (unreadRefetchInFlight) return;
// True only when DB value is strictly true; falls back to true on cache miss
const isNewMessageSoundEnabled = (client) => {
unreadRefetchInFlight = 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 {
const email = currentUser?.email;
if (!email) return true; // default allow if we can't resolve user
const res = client.readQuery({
if (!email) return true;
const res = clientInstance.readQuery({
query: QUERY_ACTIVE_ASSOCIATION_SOUND,
variables: { email }
});
const flag = res?.associations?.[0]?.new_message_sound;
return flag === true; // strictly true => enabled
return flag === true;
} catch {
// If the query hasn't been seeded in cache yet, default ON
return true;
}
};
logLocal("handleNewMessageSummary - Start", { message, isNew: !existingConversation });
const queryVariables = { offset: 0 };
if (!isoutbound) {
// Play notification sound for new inbound message (scoped to bodyshop)
if (isLeaderTab(bodyshop.id) && isNewMessageSoundEnabled(client)) {
playNewMessageSound(bodyshop.id);
}
// Real-time badge update for affix (best-effort, coalesced)
if (!isSystem) {
refetchUnreadCount();
}
}
if (!existingConversation && conversationId) {
// Attempt to read from the cache to determine if this is actually a new conversation
try {
const cachedConversation = client.cache.readFragment({
id: client.cache.identify({ __typename: "conversations", id: conversationId }),
@@ -86,75 +259,54 @@ export const registerMessagingHandlers = ({ socket, client, currentUser, bodysho
});
if (cachedConversation) {
logLocal("handleNewMessageSummary - Existing Conversation inferred from cache", {
conversationId
});
return handleNewMessageSummary({
...message,
existingConversation: true
});
logLocal("handleNewMessageSummary - Existing Conversation inferred from cache", { conversationId });
return handleNewMessageSummary({ ...message, existingConversation: true });
}
} catch {
logLocal("handleNewMessageSummary - Cache miss", { conversationId });
// Cache miss is normal
}
}
// Handle new conversation
if (!existingConversation && newConversation?.phone_num) {
logLocal("handleNewMessageSummary - New Conversation", newConversation);
try {
const queryResults = client.cache.readQuery({
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];
}
}
});
}
upsertConversationIntoOffsetZeroList(client, newConversation, { isoutbound, isSystem });
} catch (error) {
console.error("Error updating cache for new conversation:", error);
}
return;
}
// Handle existing conversation
if (existingConversation) {
if (existingConversation && conversationId) {
try {
client.cache.modify({
id: client.cache.identify({ __typename: "conversations", id: conversationId }),
fields: {
updated_at: () => new Date().toISOString(),
updated_at: () => updated_at || safeIsoNow(),
archived: () => false,
messages_aggregate(cached = { aggregate: { count: 0 } }) {
const currentCount = cached.aggregate?.count || 0;
if (!isoutbound) {
return {
__typename: "messages_aggregate",
aggregate: {
__typename: "messages_aggregate_fields",
count: currentCount + 1
}
};
}
return cached;
messages_aggregate(cached = null) {
if (isoutbound || isSystem) return cached;
const currentCount = cached?.aggregate?.count ?? 0;
return {
__typename: "messages_aggregate",
aggregate: {
__typename: "messages_aggregate_fields",
count: currentCount + 1
}
};
},
unreadcnt(cached) {
if (isoutbound || isSystem) return cached;
const n = typeof cached === "number" ? cached : 0;
return n + 1;
}
}
});
} catch (error) {
console.error("Error updating cache for existing conversation:", error);
}
return;
}
@@ -166,88 +318,78 @@ export const registerMessagingHandlers = ({ socket, client, currentUser, bodysho
logLocal("handleNewMessageDetailed - Start", message);
try {
// Check if the conversation exists in the cache
const queryResults = client.cache.readQuery({
query: GET_CONVERSATION_DETAILS,
variables: { conversationId }
});
if (!conversationId || !isConversationDetailsCached(client, conversationId)) return;
if (!queryResults?.conversations_by_pk) {
console.warn("Conversation not found in cache:", { conversationId });
try {
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;
}
// 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({
id: client.cache.identify({ __typename: "conversations", id: conversationId }),
fields: {
messages(existingMessages = []) {
return [...existingMessages, newMessage];
messages(existing = [], { readField }) {
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", {
conversationId,
newMessage
});
logLocal("handleNewMessageDetailed - Message appended successfully", { conversationId });
} catch (error) {
console.error("Error updating conversation messages in cache:", error);
}
};
const handleMessageChanged = (message) => {
if (!message) {
logLocal("handleMessageChanged - No message provided", message);
return;
}
if (!message?.id) return;
logLocal("handleMessageChanged - Start", message);
if (!messageEntityCached(client, message.id)) return;
try {
const msgCacheId = client.cache.identify({ __typename: "messages", id: message.id });
client.cache.modify({
id: client.cache.identify({ __typename: "conversations", id: message.conversationid }),
id: msgCacheId,
fields: {
messages(existingMessages = [], { readField }) {
return existingMessages.map((messageRef) => {
// Check if this is the message to update
if (readField("id", messageRef) === message.id) {
const currentStatus = readField("status", messageRef);
// 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;
});
status(existing) {
return message.type === "status-changed" ? (message.status ?? existing) : existing;
},
text(existing) {
return message.type === "text-updated" ? (message.text ?? existing) : existing;
}
}
});
@@ -262,149 +404,140 @@ export const registerMessagingHandlers = ({ socket, client, currentUser, bodysho
};
const handleConversationChanged = async (data) => {
if (!data) {
logLocal("handleConversationChanged - No data provided", data);
return;
}
if (!data?.conversationId) return;
const {
conversationId,
type,
job_conversations,
messageIds,
messageIdsMarkedRead,
lastUnreadMessageId,
unreadCount,
...fields
} = data;
const { conversationId, type, job_conversations, messageIds, ...fields } = 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 {
switch (type) {
case "conversation-marked-read":
if (conversationId && messageIds?.length > 0) {
client.cache.modify({
id: client.cache.identify({ __typename: "conversations", id: conversationId }),
fields: {
messages(existingMessages = [], { readField }) {
return existingMessages.map((message) => {
if (messageIds.includes(readField("id", message))) {
return { ...message, read: true };
}
return message;
});
},
messages_aggregate: () => ({
__typename: "messages_aggregate",
aggregate: { __typename: "messages_aggregate_fields", count: 0 }
})
}
case "conversation-marked-read": {
refetchUnreadCount();
if (detailsCached && Array.isArray(messageIds)) {
messageIds.forEach((id) => {
if (!messageEntityCached(client, id)) return;
client.cache.modify({
id: client.cache.identify({ __typename: "messages", id }),
fields: { read: () => true }
});
});
}
break;
case "conversation-created":
updateConversationList({ ...fields, job_conversations, updated_at: updatedAt });
client.cache.modify({
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;
}
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-archived":
try {
const listQueryVariables = { offset: 0 };
const detailsQueryVariables = { conversationId };
case "conversation-archived": {
// Keep unread badge correct even if archiving affects counts
refetchUnreadCount();
// Check if conversation details exist in the cache
const detailsExist = !!client.cache.readQuery({
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);
}
await client.refetchQueries({
include: [CONVERSATION_LIST_QUERY, GET_CONVERSATION_DETAILS]
});
break;
}
case "tag-added": {
// Ensure `job_conversations` is properly formatted
const formattedJobConversations = job_conversations.map((jc) => ({
const formattedJobConversations = (job_conversations || []).map((jc) => ({
__typename: "job_conversations",
jobid: jc.jobid || jc.job?.id,
conversationid: conversationId,
job: jc.job || {
job: {
__typename: "jobs",
id: data.selectedJob.id,
ro_number: data.selectedJob.ro_number,
ownr_co_nm: data.selectedJob.ownr_co_nm,
ownr_fn: data.selectedJob.ownr_fn,
ownr_ln: data.selectedJob.ownr_ln
id: jc.job?.id,
ro_number: jc.job?.ro_number,
ownr_co_nm: jc.job?.ownr_co_nm,
ownr_fn: jc.job?.ownr_fn,
ownr_ln: jc.job?.ownr_ln
}
}));
client.cache.modify({
id: client.cache.identify({ __typename: "conversations", id: conversationId }),
fields: {
job_conversations: (existing = []) => {
// Ensure no duplicates based on both `conversationid` and `jobid`
const existingLinks = new Set(
existing.map((jc) => {
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];
job_conversations(existing = [], { readField }) {
const seen = new Set(existing.map((x) => readField("jobid", x)).filter(Boolean));
const incoming = formattedJobConversations.filter((x) => x.jobid && !seen.has(x.jobid));
return [...existing, ...incoming];
}
}
});
@@ -412,46 +545,31 @@ export const registerMessagingHandlers = ({ socket, client, currentUser, bodysho
break;
}
case "tag-removed":
try {
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);
}
case "tag-removed": {
const conversationCacheId = client.cache.identify({ __typename: "conversations", id: conversationId });
client.cache.evict({
id: conversationCacheId,
fieldName: "job_conversations"
});
client.cache.gc();
break;
}
default:
logLocal("handleConversationChanged - Unhandled type", { type });
default: {
client.cache.modify({
id: client.cache.identify({ __typename: "conversations", id: conversationId }),
fields: {
...Object.fromEntries(
Object.entries(fields).map(([key, value]) => [key, (cached) => (value !== undefined ? value : cached)])
)
}
fields: Object.fromEntries(
Object.entries(fields).map(([key, value]) => [key, (cached) => (value !== undefined ? value : cached)])
)
});
}
}
} catch (error) {
console.error("Error handling conversation changes:", { type, error });
}
};
// Existing handler for phone number opt-out
const handlePhoneNumberOptedOut = async (data) => {
const { bodyshopid, phone_number } = data;
logLocal("handlePhoneNumberOptedOut - Start", data);
@@ -461,22 +579,18 @@ export const registerMessagingHandlers = ({ socket, client, currentUser, bodysho
id: "ROOT_QUERY",
fields: {
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
);
if (phoneNumberExists) {
logLocal("handlePhoneNumberOptedOut - Phone number already in cache", { phone_number, bodyshopid });
return existing;
}
if (exists) return existing;
const newOptOut = {
__typename: "phone_number_opt_out",
id: `temporary-${phone_number}-${Date.now()}`,
bodyshopid,
phone_number,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString()
created_at: safeIsoNow(),
updated_at: safeIsoNow()
};
return [...existing, newOptOut];
@@ -491,46 +605,36 @@ export const registerMessagingHandlers = ({ socket, client, currentUser, bodysho
args: { bodyshopid, search: phone_number }
});
client.cache.gc();
logLocal("handlePhoneNumberOptedOut - Cache updated successfully", data);
} catch (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 { bodyshopid, phone_number } = data;
logLocal("handlePhoneNumberOptedIn - Start", data);
try {
// Update the Apollo cache for GET_PHONE_NUMBER_OPT_OUTS by removing the phone number
client.cache.modify({
id: "ROOT_QUERY",
fields: {
phone_number_opt_out(existing = [], { readField }) {
// Filter out the phone number from the opt-out list
return existing.filter(
(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({
id: "ROOT_QUERY",
fieldName: "phone_number_opt_out",
args: { bodyshopid, search: phone_number }
});
client.cache.gc();
logLocal("handlePhoneNumberOptedIn - Cache updated successfully", data);
} catch (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 "./chat-conversation-list.styles.scss";
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 { useTranslation } from "react-i18next";
import { selectBodyshop } from "../../redux/user/user.selectors";
@@ -29,13 +29,26 @@ const mapDispatchToProps = (dispatch) => ({
function ChatConversationListComponent({ conversationList, selectedConversation, setSelectedConversation, bodyshop }) {
const { t } = useTranslation();
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: {
bodyshopid: bodyshop.id,
bodyshopid: bodyshop?.id,
phone_numbers: phoneNumbers
},
skip: !conversationList.length,
skip: !bodyshop?.id || phoneNumbers.length === 0,
fetchPolicy: "cache-and-network"
});
@@ -58,15 +71,25 @@ function ChatConversationListComponent({ conversationList, selectedConversation,
return _.orderBy(conversationList, ["updated_at"], ["desc"]);
}, [conversationList]);
const renderConversation = (index, t) => {
const renderConversation = (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 cardContentLeft =
item.job_conversations.length > 0
? item.job_conversations.map((j, idx) => <Tag key={idx}>{j.job.ro_number}</Tag>)
: null;
const names = <>{_.uniq(item.job_conversations.map((j) => OwnerNameDisplayFunction(j.job)))}</>;
const cardTitle = (
<>
@@ -80,9 +103,10 @@ function ChatConversationListComponent({ conversationList, selectedConversation,
)}
</>
);
const cardExtra = (
<>
<Badge count={item.messages_aggregate.aggregate.count} />
<Badge count={item.messages_aggregate?.aggregate?.count || 0} />
{hasOptOutEntry && (
<Tooltip title={t("consent.text_body")}>
<Tag color="red" icon={<ExclamationCircleOutlined />}>
@@ -92,6 +116,7 @@ function ChatConversationListComponent({ conversationList, selectedConversation,
)}
</>
);
const getCardStyle = () =>
item.id === selectedConversation
? { backgroundColor: "var(--card-selected-bg)" }
@@ -104,24 +129,8 @@ function ChatConversationListComponent({ conversationList, selectedConversation,
className={`chat-list-item ${item.id === selectedConversation ? "chat-list-selected-conversation" : ""}`}
>
<Card style={getCardStyle()} variant={true} size="small" extra={cardExtra} title={cardTitle}>
<div
style={{
display: "inline-block",
width: "70%",
textAlign: "left"
}}
>
{cardContentLeft}
</div>
<div
style={{
display: "inline-block",
width: "30%",
textAlign: "right"
}}
>
{cardContentRight}
</div>
<div style={{ display: "inline-block", width: "70%", textAlign: "left" }}>{cardContentLeft}</div>
<div style={{ display: "inline-block", width: "30%", textAlign: "right" }}>{cardContentRight}</div>
</Card>
</List.Item>
);
@@ -131,7 +140,7 @@ function ChatConversationListComponent({ conversationList, selectedConversation,
<div className="chat-list-container">
<Virtuoso
data={sortedConversationList}
itemContent={(index) => renderConversation(index, t)}
itemContent={(index) => renderConversation(index)}
style={{ height: "100%", width: "100%" }}
/>
</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 ChatPrintButton from "../chat-print-button/chat-print-button.component";
import ChatTagRoContainer from "../chat-tag-ro/chat-tag-ro.container";
import { createStructuredSelector } from "reselect";
import { connect } from "react-redux";
import ChatMarkUnreadButton from "../chat-mark-unread-button/chat-mark-unread-button.component";
const mapStateToProps = createStructuredSelector({});
const mapDispatchToProps = () => ({});
export function ChatConversationTitle({ conversation }) {
export function ChatConversationTitle({ conversation, onMarkUnread, markUnreadDisabled, markUnreadLoading }) {
return (
<Space className="chat-title" wrap>
<PhoneNumberFormatter>{conversation?.phone_num}</PhoneNumberFormatter>
<ChatLabelComponent conversation={conversation} />
<ChatPrintButton conversation={conversation} />
<ChatConversationTitleTags jobConversations={conversation?.job_conversations || []} />
<ChatTagRoContainer conversation={conversation || []} />
<ChatMarkUnreadButton disabled={markUnreadDisabled} loading={markUnreadLoading} onMarkUnread={onMarkUnread} />
<ChatArchiveButton conversation={conversation} />
</Space>
);
}
export default connect(mapStateToProps, mapDispatchToProps)(ChatConversationTitle);
export default ChatConversationTitle;

View File

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

View File

@@ -1,6 +1,6 @@
import { gql, useApolloClient, useQuery, useSubscription } from "@apollo/client";
import axios from "axios";
import { useCallback, useEffect, useState } from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { CONVERSATION_SUBSCRIPTION_BY_PK, GET_CONVERSATION_DETAILS } from "../../graphql/conversations.queries";
@@ -18,8 +18,8 @@ function ChatConversationContainer({ bodyshop, selectedConversation }) {
const client = useApolloClient();
const { socket } = useSocket();
const [markingAsReadInProgress, setMarkingAsReadInProgress] = useState(false);
const [markingAsUnreadInProgress, setMarkingAsUnreadInProgress] = useState(false);
// Fetch conversation details
const {
loading: convoLoading,
error: convoError,
@@ -27,24 +27,23 @@ function ChatConversationContainer({ bodyshop, selectedConversation }) {
} = useQuery(GET_CONVERSATION_DETAILS, {
variables: { conversationId: selectedConversation },
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, {
skip: socket?.connected,
skip: socket?.connected || !selectedConversation,
variables: { conversationId: selectedConversation },
onData: ({ data: subscriptionResult, client }) => {
// Extract the messages array from the result
const messages = subscriptionResult?.data?.messages;
if (!messages || messages.length === 0) {
console.warn("No messages found in subscription result.");
return;
}
if (!messages || messages.length === 0) return;
messages.forEach((message) => {
const messageRef = client.cache.identify(message);
// Write the new message to the cache
client.cache.writeFragment({
id: messageRef,
fragment: gql`
@@ -64,7 +63,6 @@ function ChatConversationContainer({ bodyshop, selectedConversation }) {
data: message
});
// Update the conversation cache to include the new message
client.cache.modify({
id: client.cache.identify({ __typename: "conversations", id: selectedConversation }),
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(
(conversationId, messageIds) => {
if (!conversationId || !messageIds?.length) return;
@@ -89,13 +109,34 @@ function ChatConversationContainer({ bodyshop, selectedConversation }) {
messageIds.forEach((messageId) => {
client.cache.modify({
id: client.cache.identify({ __typename: "messages", id: messageId }),
fields: {
read: () => true
}
fields: { 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
@@ -103,20 +144,25 @@ function ChatConversationContainer({ bodyshop, selectedConversation }) {
if (!socket?.connected) return;
const handleConversationChange = (data) => {
if (data.type === "conversation-marked-read") {
const { conversationId, messageIds } = data;
updateCacheWithReadMessages(conversationId, messageIds);
if (data?.type === "conversation-marked-read") {
updateCacheWithReadMessages(data.conversationId, data.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);
return () => socket.off("conversation-changed", handleConversationChange);
}, [socket, updateCacheWithReadMessages, applyUnreadStateWithMaxOneUnread]);
return () => {
socket.off("conversation-changed", handleConversationChange);
};
}, [socket, updateCacheWithReadMessages]);
// Join and leave conversation via WebSocket
// Join/leave conversation via WebSocket
useEffect(() => {
if (!socket?.connected || !selectedConversation || !bodyshop?.id) return;
@@ -133,15 +179,21 @@ function ChatConversationContainer({ bodyshop, selectedConversation }) {
};
}, [socket, bodyshop, selectedConversation]);
// Mark conversation as read
const handleMarkConversationAsRead = async () => {
if (!convoData || markingAsReadInProgress) return;
const inboundNonSystemMessages = useMemo(() => {
const msgs = conversation?.messages || [];
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;
if (!conversation) return;
const canMarkUnread = inboundNonSystemMessages.length > 0;
const handleMarkConversationAsRead = async () => {
if (!conversation || markingAsReadInProgress) return;
const unreadMessageIds = conversation.messages
?.filter((message) => !message.read && !message.isoutbound)
?.filter((message) => !message.read && !message.isoutbound && !message.is_system)
.map((message) => message.id);
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 (
<ChatConversationComponent
subState={[convoLoading, convoError]}
conversation={convoData?.conversations_by_pk || {}}
messages={convoData?.conversations_by_pk?.messages || []}
conversation={conversation || {}}
messages={conversation?.messages || []}
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;
}
.unread-button {
height: 20px;
border-radius: 4px;
}
.chat-title {
margin-bottom: 5px;
}

View File

@@ -2,7 +2,27 @@ import { gql } from "@apollo/client";
export const UNREAD_CONVERSATION_COUNT = gql`
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 {
count
}
@@ -19,7 +39,7 @@ export const CONVERSATION_LIST_QUERY = gql`
unreadcnt
archived
label
messages_aggregate(where: { read: { _eq: false }, isoutbound: { _eq: false } }) {
messages_aggregate(where: { read: { _eq: false }, isoutbound: { _eq: false }, is_system: { _eq: false } }) {
aggregate {
count
}
@@ -41,6 +61,7 @@ export const CONVERSATION_SUBSCRIPTION_BY_PK = gql`
subscription CONVERSATION_SUBSCRIPTION_BY_PK($conversationId: uuid!) {
messages(order_by: { created_at: asc_nulls_first }, where: { conversationid: { _eq: $conversationId } }) {
id
conversationid
status
text
is_system
@@ -76,6 +97,7 @@ export const GET_CONVERSATION_DETAILS = gql`
}
messages(order_by: { created_at: asc_nulls_first }) {
id
conversationid
status
text
is_system
@@ -110,7 +132,7 @@ export const CONVERSATION_ID_BY_PHONE = gql`
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 {
count
}
@@ -139,7 +161,7 @@ export const CREATE_CONVERSATION = gql`
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 {
count
}

View File

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

View File

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

View File

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

View File

@@ -148,6 +148,26 @@ const cache = new InMemoryCache({
Query: {
fields: {
// 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: {
merge(existing = [], incoming = [], { readField }) {
// Create a map to deduplicate by __ref

View File

@@ -123,7 +123,7 @@ mutation RECEIVE_MESSAGE($msg: [messages_insert_input!]!) {
exports.INSERT_MESSAGE = `
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
archived
}
@@ -147,6 +147,7 @@ mutation INSERT_MESSAGE($msg: [messages_insert_input!]!, $conversationid: uuid!)
image_path
image
isoutbound
is_system
msid
read
text

View File

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

View File

@@ -61,7 +61,8 @@ const send = async (req, res) => {
isoutbound: true,
userid: req.user.email,
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 {

View File

@@ -8,6 +8,46 @@ const {
const logger = require("../utils/logger");
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
* @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 = {
status,
markConversationRead
markConversationRead,
markLastMessageUnread
};