feature/IO-3000-messaging-sockets-migrations2 -

- A lot of a lot of testing....

Signed-off-by: Dave Richer <dave@imexsystems.ca>
This commit is contained in:
Dave Richer
2024-11-21 22:14:39 -08:00
parent 141deff41e
commit 6504b27eca
5 changed files with 376 additions and 249 deletions

View File

@@ -14,40 +14,46 @@ export const registerMessagingHandlers = ({ socket, client }) => {
const handleNewMessageSummary = async (message) => { const handleNewMessageSummary = async (message) => {
const { conversationId, newConversation, existingConversation, isoutbound } = message; const { conversationId, newConversation, existingConversation, isoutbound } = message;
logLocal("handleNewMessageSummary", message); logLocal("handleNewMessageSummary - Start", { message, isNew: !existingConversation });
const queryVariables = { offset: 0 }; const queryVariables = { offset: 0 };
// Utility function to enrich conversation data
const enrichConversation = (conversation, isOutbound) => ({
...conversation,
updated_at: conversation.updated_at || new Date().toISOString(),
unreadcnt: 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
}
},
__typename: "conversations"
});
// Handle new conversation // 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({ const queryResults = client.cache.readQuery({
query: CONVERSATION_LIST_QUERY, query: CONVERSATION_LIST_QUERY,
variables: queryVariables variables: queryVariables
}); });
const enrichedConversation = { const enrichedConversation = enrichConversation(newConversation, isoutbound);
...newConversation,
updated_at: newConversation.updated_at || new Date().toISOString(),
unreadcnt: newConversation.unreadcnt || 0,
archived: newConversation.archived || false,
label: newConversation.label || null,
job_conversations: newConversation.job_conversations || [],
messages_aggregate: newConversation.messages_aggregate || {
__typename: "messages_aggregate",
aggregate: {
__typename: "messages_aggregate_fields",
count: isoutbound ? 0 : 1
}
},
__typename: "conversations"
};
client.cache.writeQuery({ client.cache.modify({
query: CONVERSATION_LIST_QUERY, id: "ROOT_QUERY",
variables: queryVariables, fields: {
data: { conversations(existingConversations = []) {
conversations: [enrichedConversation, ...(queryResults?.conversations || [])] return [enrichedConversation, ...existingConversations];
}
} }
}); });
} catch (error) { } catch (error) {
@@ -60,13 +66,10 @@ export const registerMessagingHandlers = ({ socket, client }) => {
if (existingConversation) { if (existingConversation) {
let conversationDetails; let conversationDetails;
// Fetch or read the conversation details // Attempt to read existing conversation details from cache
try { try {
conversationDetails = client.cache.readFragment({ conversationDetails = client.cache.readFragment({
id: client.cache.identify({ id: client.cache.identify({ __typename: "conversations", id: conversationId }),
__typename: "conversations",
id: conversationId
}),
fragment: gql` fragment: gql`
fragment ExistingConversation on conversations { fragment ExistingConversation on conversations {
id id
@@ -89,9 +92,10 @@ export const registerMessagingHandlers = ({ socket, client }) => {
` `
}); });
} catch (error) { } catch (error) {
console.warn("Conversation not found in cache, querying server..."); logLocal("handleNewMessageSummary - Cache miss for conversation, fetching from server", { conversationId });
} }
// Fetch conversation details from server if not in cache
if (!conversationDetails) { if (!conversationDetails) {
try { try {
const { data } = await client.query({ const { data } = await client.query({
@@ -106,12 +110,14 @@ export const registerMessagingHandlers = ({ socket, client }) => {
} }
} }
// Validate that conversation details were retrieved
if (!conversationDetails) { if (!conversationDetails) {
console.error("Unable to retrieve conversation details. Skipping cache update."); console.error("Unable to retrieve conversation details. Skipping cache update.");
return; return;
} }
try { try {
// Check if the conversation is already in the cache
const queryResults = client.cache.readQuery({ const queryResults = client.cache.readQuery({
query: CONVERSATION_LIST_QUERY, query: CONVERSATION_LIST_QUERY,
variables: queryVariables variables: queryVariables
@@ -120,46 +126,32 @@ export const registerMessagingHandlers = ({ socket, client }) => {
const isAlreadyInCache = queryResults?.conversations.some((conv) => conv.id === conversationId); const isAlreadyInCache = queryResults?.conversations.some((conv) => conv.id === conversationId);
if (!isAlreadyInCache) { if (!isAlreadyInCache) {
const enrichedConversation = { const enrichedConversation = enrichConversation(conversationDetails, isoutbound);
...conversationDetails,
archived: false,
__typename: "conversations",
messages_aggregate: {
__typename: "messages_aggregate",
aggregate: {
__typename: "messages_aggregate_fields",
count:
conversationDetails.messages?.filter(
(message) => !message.read && !message.isoutbound // Count unread, inbound messages
).length || 0
}
}
};
client.cache.writeQuery({ client.cache.modify({
query: CONVERSATION_LIST_QUERY, id: "ROOT_QUERY",
variables: queryVariables, fields: {
data: { conversations(existingConversations = []) {
conversations: [enrichedConversation, ...(queryResults?.conversations || [])] return [enrichedConversation, ...existingConversations];
}
} }
}); });
} }
// Update existing conversation fields
// Update fields for the existing conversation in the cache
client.cache.modify({ client.cache.modify({
id: client.cache.identify({ id: client.cache.identify({ __typename: "conversations", id: conversationId }),
__typename: "conversations",
id: conversationId
}),
fields: { fields: {
updated_at: () => new Date().toISOString(), updated_at: () => new Date().toISOString(),
archived: () => false, archived: () => false,
messages_aggregate(cached) { messages_aggregate(cached = { aggregate: { count: 0 } }) {
const currentCount = cached.aggregate?.count || 0;
if (!isoutbound) { if (!isoutbound) {
return { return {
__typename: "messages_aggregate", __typename: "messages_aggregate",
aggregate: { aggregate: {
__typename: "messages_aggregate_fields", __typename: "messages_aggregate_fields",
count: cached.aggregate.count + 1 count: currentCount + 1
} }
}; };
} }
@@ -176,80 +168,107 @@ export const registerMessagingHandlers = ({ socket, client }) => {
const handleNewMessageDetailed = (message) => { const handleNewMessageDetailed = (message) => {
const { conversationId, newMessage } = message; const { conversationId, newMessage } = message;
logLocal("handleNewMessageDetailed", message); logLocal("handleNewMessageDetailed - Start", message);
// Append the new message to the conversation's message list try {
// Check if the conversation exists in the cache
const queryResults = client.cache.readQuery({ const queryResults = client.cache.readQuery({
query: GET_CONVERSATION_DETAILS, query: GET_CONVERSATION_DETAILS,
variables: { conversationId } variables: { conversationId }
}); });
if (queryResults) { if (!queryResults?.conversations_by_pk) {
client.cache.writeQuery({ console.warn("Conversation not found in cache:", { conversationId });
query: GET_CONVERSATION_DETAILS, return;
variables: { conversationId }, }
data: {
...queryResults, // Append the new message to the conversation's message list using cache.modify
conversations_by_pk: { client.cache.modify({
...queryResults.conversations_by_pk, id: client.cache.identify({ __typename: "conversations", id: conversationId }),
messages: [...queryResults.conversations_by_pk.messages, newMessage] fields: {
messages(existingMessages = []) {
return [...existingMessages, newMessage];
} }
} }
}); });
logLocal("handleNewMessageDetailed - Message appended successfully", { conversationId, newMessage });
} catch (error) {
console.error("Error updating conversation messages in cache:", error);
} }
}; };
const handleMessageChanged = (message) => { const handleMessageChanged = (message) => {
if (!message) return; if (!message) {
logLocal("handleMessageChanged - No message provided", message);
return;
}
logLocal("handleMessageChanged", message); logLocal("handleMessageChanged - Start", message);
try {
client.cache.modify({ client.cache.modify({
id: client.cache.identify({ __typename: "conversations", id: message.conversationid }), id: client.cache.identify({ __typename: "conversations", id: message.conversationid }),
fields: { fields: {
...(message.type === "status-changed" && { messages(existingMessages = [], { readField }) {
messages(existing = [], { readField }) { return existingMessages.map((messageRef) => {
return existing.map((messageRef) => { // Check if this is the message to update
// Match the message by ID
if (readField("id", messageRef) === message.id) { if (readField("id", messageRef) === message.id) {
const currentStatus = readField("status", messageRef); 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" // Prevent overwriting if the current status is already "delivered"
if (currentStatus === "delivered") { if (currentStatus === "delivered") {
logLocal("handleMessageChanged - Status already delivered, skipping update", {
messageId: message.id
});
return messageRef; return messageRef;
} }
// Update the existing message fields // Update the status field
return client.cache.writeFragment({ return {
id: messageRef.__ref, ...messageRef,
fragment: gql` status: message.status
fragment UpdatedMessage on messages { };
id
status case "text-updated":
conversationid // Handle changes to the message text
__typename return {
...messageRef,
text: message.text
};
// Add cases for other known message types as needed
default:
// Log a warning for unhandled message types
logLocal("handleMessageChanged - Unhandled message type", { type: message.type });
return messageRef;
} }
`,
data: {
__typename: "messages",
...message // Only update the fields provided in the message object
}
});
} }
return messageRef; // Keep other messages unchanged return messageRef; // Keep other messages unchanged
}); });
} }
})
} }
}); });
logLocal("handleMessageChanged - Message updated successfully", { messageId: message.id, type: message.type });
} catch (error) {
console.error("handleMessageChanged - Error modifying cache:", error);
}
}; };
const handleConversationChanged = async (data) => { const handleConversationChanged = async (data) => {
if (!data) return; if (!data) {
logLocal("handleConversationChanged - No data provided", data);
return;
}
const { conversationId, type, job_conversations, ...fields } = data; const { conversationId, type, job_conversations, messageIds, ...fields } = data;
logLocal("handleConversationChanged", data); logLocal("handleConversationChanged - Start", data);
const updatedAt = new Date().toISOString(); const updatedAt = new Date().toISOString();
@@ -263,9 +282,7 @@ export const registerMessagingHandlers = ({ socket, client }) => {
const updatedList = existingList?.conversations const updatedList = existingList?.conversations
? [ ? [
newConversation, newConversation,
...existingList.conversations.filter( ...existingList.conversations.filter((conv) => conv.id !== newConversation.id) // Prevent duplicates
(conv) => conv.id !== newConversation.id // Prevent duplicates
)
] ]
: [newConversation]; : [newConversation];
@@ -276,32 +293,51 @@ export const registerMessagingHandlers = ({ socket, client }) => {
conversations: updatedList conversations: updatedList
} }
}); });
logLocal("handleConversationChanged - Conversation list updated successfully", newConversation);
} catch (error) { } catch (error) {
console.error("Error updating conversation list in the cache:", error); console.error("Error updating conversation list in the cache:", error);
} }
}; };
if (type === "conversation-created") { // Handle specific types
updateConversationList({ ...fields, job_conversations, updated_at: updatedAt }); try {
return; 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;
const cacheId = client.cache.identify({
__typename: "conversations",
id: conversationId
}); });
},
if (!cacheId) { messages_aggregate: () => ({
console.error(`Could not find conversation with id: ${conversationId}`); __typename: "messages_aggregate",
return; aggregate: { __typename: "messages_aggregate_fields", count: 0 }
})
} }
});
}
break;
if (type === "conversation-unarchived" || type === "conversation-archived") { case "conversation-created":
updateConversationList({ ...fields, job_conversations, updated_at: updatedAt });
break;
case "conversation-unarchived":
case "conversation-archived":
// Would like to someday figure out how to get this working without refetch queries,
// But I have but a solid 4 hours into it, and there are just too many weird occurrences
try { try {
const listQueryVariables = { offset: 0 }; const listQueryVariables = { offset: 0 };
const detailsQueryVariables = { conversationId }; const detailsQueryVariables = { conversationId };
// Refetch the conversation list and details queries // Refetch conversation list and details
await client.refetchQueries({ await client.refetchQueries({
include: [CONVERSATION_LIST_QUERY, GET_CONVERSATION_DETAILS], include: [CONVERSATION_LIST_QUERY, GET_CONVERSATION_DETAILS],
variables: [ variables: [
@@ -310,54 +346,67 @@ export const registerMessagingHandlers = ({ socket, client }) => {
] ]
}); });
console.log("Refetched conversation list and details after state change."); logLocal("handleConversationChanged - Refetched queries after state change", { conversationId, type });
} catch (error) { } catch (error) {
console.error("Error refetching queries after conversation state change:", error); console.error("Error refetching queries after conversation state change:", error);
} }
break;
return; case "tag-added":
}
// Handle other types of updates (e.g., marked read, tags added/removed)
client.cache.modify({ client.cache.modify({
id: cacheId, id: client.cache.identify({ __typename: "conversations", id: conversationId }),
fields: {
job_conversations: (existing = []) => [...existing, ...job_conversations]
}
});
break;
case "tag-removed":
client.cache.modify({
id: client.cache.identify({ __typename: "conversations", id: conversationId }),
fields: {
job_conversations: (existing = [], { readField }) =>
existing.filter((jobRef) => readField("jobid", jobRef) !== fields.jobId)
}
});
break;
default:
logLocal("handleConversationChanged - Unhandled type", { type });
client.cache.modify({
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)])
), )
...(type === "conversation-marked-read" && {
messages_aggregate: () => ({
__typename: "messages_aggregate",
aggregate: { __typename: "messages_aggregate_fields", count: 0 }
})
}),
...(type === "tag-added" && {
job_conversations: (existing = []) => [...existing, ...job_conversations]
}),
...(type === "tag-removed" && {
job_conversations: (existing = [], { readField }) =>
existing.filter((jobRef) => readField("jobid", jobRef) !== data.jobId)
})
} }
}); });
}
} catch (error) {
console.error("Error handling conversation changes:", { type, error });
}
}; };
const handleNewMessage = ({ conversationId, message }) => { const handleNewMessage = ({ conversationId, message }) => {
if (!conversationId || !message?.id || !message?.text) { if (!conversationId || !message?.id || !message?.text) {
logLocal("handleNewMessage - Missing conversationId or message details", { conversationId, message });
return; return;
} }
logLocal("handleNewMessage", { conversationId, message }); logLocal("handleNewMessage - Start", { conversationId, message });
try {
// Add the new message to the cache
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(existing = []) { messages(existing = []) {
// Ensure that the `message` object matches the schema // Write the new message to the cache
const newMessageRef = client.cache.writeFragment({ const newMessageRef = client.cache.writeFragment({
data: { data: {
__typename: "messages", __typename: "messages",
id: message.id, id: message.id,
body: message.text, text: message.text,
selectedMedia: message.image_path || [], selectedMedia: message.image_path || [],
imexshopid: message.userid, imexshopid: message.userid,
status: message.status, status: message.status,
@@ -367,7 +416,7 @@ export const registerMessagingHandlers = ({ socket, client }) => {
fragment: gql` fragment: gql`
fragment NewMessage on messages { fragment NewMessage on messages {
id id
body text
selectedMedia selectedMedia
imexshopid imexshopid
status status
@@ -377,28 +426,16 @@ export const registerMessagingHandlers = ({ socket, client }) => {
` `
}); });
// Prevent duplicates by checking if the message already exists // The merge function defined in the cache will handle deduplication
const isDuplicate = existing.some( return [...existing, newMessageRef];
(msgRef) =>
client.cache.readFragment({
id: msgRef.__ref,
fragment: gql`
fragment CheckMessage on messages {
id
}
`
})?.id === message.id
);
// We already have it, so return the existing list
if (isDuplicate) {
return existing;
}
return [...existing, newMessageRef]; // Add the new message reference
} }
} }
}); });
logLocal("handleNewMessage - Message added to cache", { conversationId, messageId: message.id });
} catch (error) {
console.error("handleNewMessage - Error modifying cache:", error);
}
}; };
socket.on("new-message-summary", handleNewMessageSummary); socket.on("new-message-summary", handleNewMessageSummary);

View File

@@ -1,4 +1,4 @@
import { useQuery } from "@apollo/client"; import { useApolloClient, useQuery } from "@apollo/client";
import axios from "axios"; import axios from "axios";
import React, { useContext, useEffect, useState } from "react"; import React, { useContext, useEffect, useState } from "react";
import { connect } from "react-redux"; import { connect } from "react-redux";
@@ -17,19 +17,73 @@ const mapStateToProps = createStructuredSelector({
export default connect(mapStateToProps, null)(ChatConversationContainer); export default connect(mapStateToProps, null)(ChatConversationContainer);
export function ChatConversationContainer({ bodyshop, selectedConversation }) { export function ChatConversationContainer({ bodyshop, selectedConversation }) {
const client = useApolloClient();
const { socket } = useContext(SocketContext);
const [markingAsReadInProgress, setMarkingAsReadInProgress] = useState(false);
const { const {
loading: convoLoading, loading: convoLoading,
error: convoError, error: convoError,
data: convoData data: convoData
} = useQuery(GET_CONVERSATION_DETAILS, { } = useQuery(GET_CONVERSATION_DETAILS, {
variables: { conversationId: selectedConversation }, variables: { conversationId: selectedConversation },
fetchPolicy: "network-only", fetchPolicy: "network-only"
nextFetchPolicy: "network-only"
}); });
const { socket } = useContext(SocketContext);
// Utility to update Apollo cache
const updateCacheWithReadMessages = (conversationId, messageIds) => {
if (!conversationId || !messageIds || messageIds.length === 0) return;
messageIds.forEach((messageId) => {
client.cache.modify({
id: client.cache.identify({ __typename: "messages", id: messageId }),
fields: {
read() {
return true; // Mark message as read
}
}
});
});
// Optionally update aggregate unread count
client.cache.modify({
id: client.cache.identify({ __typename: "conversations", id: conversationId }),
fields: {
messages_aggregate(existingAggregate) {
const updatedAggregate = {
...existingAggregate,
aggregate: {
...existingAggregate.aggregate,
count: 0 // No unread messages remaining
}
};
return updatedAggregate;
}
}
});
};
// Handle WebSocket events
useEffect(() => {
if (!socket || !socket.connected) return;
const handleConversationChange = (data) => {
if (data.type === "conversation-marked-read") {
const { conversationId, messageIds } = data;
console.log("Conversation change received:", data);
updateCacheWithReadMessages(conversationId, messageIds);
}
};
socket.on("conversation-changed", handleConversationChange);
return () => {
socket.off("conversation-changed", handleConversationChange);
};
}, [socket, client]);
// Handle joining/leaving conversation
useEffect(() => { useEffect(() => {
// Early gate, we have no socket, bail.
if (!socket || !socket.connected) return; if (!socket || !socket.connected) return;
socket.emit("join-bodyshop-conversation", { socket.emit("join-bodyshop-conversation", {
@@ -45,26 +99,42 @@ export function ChatConversationContainer({ bodyshop, selectedConversation }) {
}; };
}, [selectedConversation, bodyshop, socket]); }, [selectedConversation, bodyshop, socket]);
const [markingAsReadInProgress, setMarkingAsReadInProgress] = useState(false); // Handle marking conversation as read
const unreadCount =
convoData &&
convoData.conversations_by_pk &&
convoData.conversations_by_pk.messages &&
convoData.conversations_by_pk.messages.reduce((acc, val) => {
return !val.read && !val.isoutbound ? acc + 1 : acc;
}, 0);
const handleMarkConversationAsRead = async () => { const handleMarkConversationAsRead = async () => {
if (unreadCount > 0 && !!selectedConversation && !markingAsReadInProgress) { if (!convoData || !selectedConversation || markingAsReadInProgress) return;
const conversation = convoData.conversations_by_pk;
if (!conversation) {
console.warn(`No data found for conversation ID: ${selectedConversation}`);
return;
}
const unreadMessageIds = conversation.messages
?.filter((message) => !message.read && !message.isoutbound)
.map((message) => message.id);
if (unreadMessageIds?.length > 0) {
setMarkingAsReadInProgress(true); setMarkingAsReadInProgress(true);
await axios.post("/sms/markConversationRead", {
conversationid: selectedConversation, try {
imexshopid: bodyshop.imexshopid, const payload = {
bodyshopid: bodyshop.id conversation,
}); imexshopid: bodyshop?.imexshopid,
bodyshopid: bodyshop?.id
};
console.log("Marking conversation as read:", payload);
await axios.post("/sms/markConversationRead", payload);
// Update local cache
updateCacheWithReadMessages(selectedConversation, unreadMessageIds);
} catch (error) {
console.error("Error marking conversation as read:", error.response?.data || error.message);
} finally {
setMarkingAsReadInProgress(false); setMarkingAsReadInProgress(false);
} }
}
}; };
return ( return (

View File

@@ -162,6 +162,22 @@ const cache = new InMemoryCache({
(incomingItem) => !existing.some((existingItem) => existingItem.__ref === incomingItem.__ref) (incomingItem) => !existing.some((existingItem) => existingItem.__ref === incomingItem.__ref)
) )
]; ];
return merged;
}
},
messages: {
keyArgs: false, // Ignore arguments when determining uniqueness (like `order_by`).
merge(existing = [], incoming = [], { readField }) {
const existingIds = new Set(existing.map((message) => readField("id", message)));
// Merge incoming messages, avoiding duplicates
const merged = [...existing];
incoming.forEach((message) => {
if (!existingIds.has(readField("id", message))) {
merged.push(message);
}
});
return merged; return merged;
} }
} }

View File

@@ -2569,6 +2569,9 @@ exports.GET_JOBS_BY_PKS = `query GET_JOBS_BY_PKS($ids: [uuid!]!) {
exports.MARK_MESSAGES_AS_READ = `mutation MARK_MESSAGES_AS_READ($conversationId: uuid!) { exports.MARK_MESSAGES_AS_READ = `mutation MARK_MESSAGES_AS_READ($conversationId: uuid!) {
update_messages(where: { conversationid: { _eq: $conversationId } }, _set: { read: true }) { update_messages(where: { conversationid: { _eq: $conversationId } }, _set: { read: true }) {
returning {
id
}
affected_rows affected_rows
} }
} }

View File

@@ -58,48 +58,49 @@ exports.status = async (req, res) => {
logger.log("sms-status-update-error", "ERROR", "api", null, { logger.log("sms-status-update-error", "ERROR", "api", null, {
msid: SmsSid, msid: SmsSid,
fields: { status: SmsStatus }, fields: { status: SmsStatus },
error stack: error.stack,
message: error.message
}); });
res.status(500).json({ error: "Failed to update message status." }); res.status(500).json({ error: "Failed to update message status." });
} }
}; };
exports.markConversationRead = async (req, res) => { exports.markConversationRead = async (req, res) => {
const { conversationid, imexshopid, bodyshopid } = req.body;
const { const {
ioRedis, ioRedis,
ioHelpers: { getBodyshopRoom, getBodyshopConversationRoom } ioHelpers: { getBodyshopRoom, getBodyshopConversationRoom }
} = req; } = req;
const { conversation, imexshopid, bodyshopid } = req.body;
// Alternatively, support both payload formats
const conversationId = conversation?.id || req.body.conversationId;
if (!conversationId || !imexshopid || !bodyshopid) {
return res.status(400).json({ error: "Invalid conversation data provided." });
}
try { try {
// Mark messages in the conversation as read
const response = await client.request(queries.MARK_MESSAGES_AS_READ, { const response = await client.request(queries.MARK_MESSAGES_AS_READ, {
conversationId: conversationid conversationId
}); });
const updatedMessages = response.update_messages.affected_rows; const updatedMessageIds = response.update_messages.returning.map((message) => message.id);
logger.log("conversation-mark-read", "DEBUG", "api", null, {
conversationid,
imexshopid,
bodyshopid,
updatedMessages
});
const broadcastRoom = getBodyshopRoom(bodyshopid); const broadcastRoom = getBodyshopRoom(bodyshopid);
ioRedis.to(broadcastRoom).emit("conversation-changed", { ioRedis.to(broadcastRoom).emit("conversation-changed", {
type: "conversation-marked-read", type: "conversation-marked-read",
conversationId: conversationid conversationId,
affectedMessages: response.update_messages.affected_rows,
messageIds: updatedMessageIds
}); });
res.status(200).json({ success: true, message: "Conversation marked as read." }); res.status(200).json({
} catch (error) { success: true,
logger.log("conversation-mark-read-error", "ERROR", "api", null, { message: "Conversation marked as read."
conversationid,
imexshopid,
error
}); });
} catch (error) {
console.error("Error marking conversation as read:", error);
res.status(500).json({ error: "Failed to mark conversation as read." }); res.status(500).json({ error: "Failed to mark conversation as read." });
} }
}; };