From 63397769d20cbba2a7aede51280f22eea1d9fee9 Mon Sep 17 00:00:00 2001 From: Dave Richer Date: Tue, 26 Nov 2024 10:29:57 -0800 Subject: [PATCH] feature/IO-3000-messaging-sockets-migration2 - Take last conversation if more than one exists. Signed-off-by: Dave Richer --- client/src/graphql/conversations.queries.js | 1 + client/src/redux/messaging/messaging.sagas.js | 7 ++++++- server/graphql-client/queries.js | 1 + server/sms/receive.js | 7 ++++++- 4 files changed, 14 insertions(+), 2 deletions(-) diff --git a/client/src/graphql/conversations.queries.js b/client/src/graphql/conversations.queries.js index 33009ffbe..2379eb922 100644 --- a/client/src/graphql/conversations.queries.js +++ b/client/src/graphql/conversations.queries.js @@ -96,6 +96,7 @@ export const CONVERSATION_ID_BY_PHONE = gql` archived label unreadcnt + created_at job_conversations { jobid conversationid diff --git a/client/src/redux/messaging/messaging.sagas.js b/client/src/redux/messaging/messaging.sagas.js index e2cbb3bc8..644a940c5 100644 --- a/client/src/redux/messaging/messaging.sagas.js +++ b/client/src/redux/messaging/messaging.sagas.js @@ -47,7 +47,12 @@ export function* openChatByPhone({ payload }) { fetchPolicy: "no-cache" // Ensure the query always gets the latest data }); - const existingConversation = conversations?.find((c) => c.phone_num === p.number); + // Sort conversations by `updated_at` or `created_at` and pick the last one for the given phone number + const sortedConversations = conversations + ?.filter((c) => c.phone_num === p.number) // Filter to match the phone number + .sort((a, b) => new Date(a.created_at) - new Date(b.created_at)); // Sort by `updated_at` + + const existingConversation = sortedConversations?.[sortedConversations.length - 1] || null; if (existingConversation) { let updatedConversation = existingConversation; diff --git a/server/graphql-client/queries.js b/server/graphql-client/queries.js index 46837b6b6..da2aaac89 100644 --- a/server/graphql-client/queries.js +++ b/server/graphql-client/queries.js @@ -4,6 +4,7 @@ query FIND_BODYSHOP_BY_MESSAGING_SERVICE_SID($mssid: String!, $phone: String!) { id conversations(where: { phone_num: { _eq: $phone } }) { id + created_at } } }`; diff --git a/server/sms/receive.js b/server/sms/receive.js index fef921912..99ff90af6 100644 --- a/server/sms/receive.js +++ b/server/sms/receive.js @@ -45,7 +45,12 @@ exports.receive = async (req, res) => { } const bodyshop = response.bodyshops[0]; - const existingConversation = bodyshop.conversations[0]; // Expect only one conversation per phone number per bodyshop + + // Sort conversations by `updated_at` (or `created_at`) and pick the last one + const sortedConversations = bodyshop.conversations.sort((a, b) => new Date(a.created_at) - new Date(b.created_at)); + const existingConversation = sortedConversations.length + ? sortedConversations[sortedConversations.length - 1] + : null; let conversationid; let newMessage = {