Compare commits
3 Commits
feature/IO
...
feature/IO
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
00bf5977ae | ||
|
|
4cdc15f70b | ||
|
|
4190372b92 |
@@ -2,6 +2,7 @@ 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";
|
||||||
@@ -9,14 +10,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", {
|
||||||
@@ -31,35 +32,17 @@ export function ChatAffixContainer({ bodyshop, chatVisible, currentUser }) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
subscribeToTopicForFCMNotification();
|
SubscribeToTopicForFCMNotification();
|
||||||
}, [bodyshop?.messagingservicesid, bodyshop?.imexshopid]);
|
|
||||||
|
|
||||||
// 2) Register socket handlers as soon as socket is connected (regardless of chatVisible)
|
// Register WebSocket handlers
|
||||||
useEffect(() => {
|
if (socket?.connected) {
|
||||||
if (!socket) return;
|
registerMessagingHandlers({ socket, client, currentUser, bodyshop, t });
|
||||||
if (!bodyshop?.messagingservicesid) return;
|
|
||||||
if (!bodyshop?.id) return;
|
|
||||||
|
|
||||||
// If socket isn't connected yet, ensure no stale handlers remain.
|
return () => {
|
||||||
if (!socket.connected) {
|
unregisterMessagingHandlers({ socket });
|
||||||
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 <></>;
|
||||||
|
|
||||||
|
|||||||
@@ -13,241 +13,68 @@ const logLocal = (message, ...args) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const safeIsoNow = () => new Date().toISOString();
|
// Utility function to enrich conversation data
|
||||||
const isSystemMsid = (msid) => typeof msid === "string" && msid.startsWith("SYS_");
|
const enrichConversation = (conversation, isOutbound) => ({
|
||||||
|
|
||||||
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 || safeIsoNow(),
|
updated_at: conversation.updated_at || new Date().toISOString(),
|
||||||
unreadcnt: typeof conversation.unreadcnt === "number" ? conversation.unreadcnt : 0,
|
unreadcnt: 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 || isSystem ? 0 : 1
|
count: isOutbound ? 0 : 1
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
__typename: "conversations"
|
__typename: "conversations"
|
||||||
});
|
});
|
||||||
|
|
||||||
const upsertConversationIntoOffsetZeroList = (client, conversationObj, { isoutbound, isSystem } = {}) => {
|
// Can be uncommonted to test the playback of the notification sound
|
||||||
const normalized = normalizeConversationForList(conversationObj, { isoutbound, isSystem });
|
// window.testTone = () => {
|
||||||
if (!normalized?.id) return;
|
// const notificationSound = new Audio(newMessageSound);
|
||||||
|
// notificationSound.play().catch((error) => {
|
||||||
const convCacheId = client.cache.identify(normalized);
|
// console.error("Error playing notification sound:", error);
|
||||||
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;
|
||||||
|
|
||||||
// Coalesce unread refetches (avoid spamming during bursts)
|
|
||||||
let unreadRefetchInFlight = null;
|
|
||||||
const refetchUnreadCount = () => {
|
|
||||||
if (unreadRefetchInFlight) return;
|
|
||||||
|
|
||||||
unreadRefetchInFlight = client
|
|
||||||
.refetchQueries({
|
|
||||||
include: ["UNREAD_CONVERSATION_COUNT"]
|
|
||||||
})
|
|
||||||
.catch(() => {
|
|
||||||
// best-effort
|
|
||||||
})
|
|
||||||
.finally(() => {
|
|
||||||
unreadRefetchInFlight = null;
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleNewMessageSummary = async (message) => {
|
const handleNewMessageSummary = async (message) => {
|
||||||
const { conversationId, newConversation, existingConversation, isoutbound, msid, updated_at } = message;
|
const { conversationId, newConversation, existingConversation, isoutbound } = message;
|
||||||
const isSystem = isSystemMsid(msid);
|
|
||||||
|
|
||||||
const isNewMessageSoundEnabled = (clientInstance) => {
|
// True only when DB value is strictly true; falls back to true on cache miss
|
||||||
|
const isNewMessageSoundEnabled = (client) => {
|
||||||
try {
|
try {
|
||||||
const email = currentUser?.email;
|
const email = currentUser?.email;
|
||||||
if (!email) return true;
|
if (!email) return true; // default allow if we can't resolve user
|
||||||
const res = clientInstance.readQuery({
|
const res = client.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;
|
return flag === true; // strictly true => enabled
|
||||||
} 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 }),
|
||||||
@@ -259,54 +86,75 @@ export const registerMessagingHandlers = ({ socket, client, currentUser, bodysho
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (cachedConversation) {
|
if (cachedConversation) {
|
||||||
logLocal("handleNewMessageSummary - Existing Conversation inferred from cache", { conversationId });
|
logLocal("handleNewMessageSummary - Existing Conversation inferred from cache", {
|
||||||
return handleNewMessageSummary({ ...message, existingConversation: true });
|
conversationId
|
||||||
|
});
|
||||||
|
return handleNewMessageSummary({
|
||||||
|
...message,
|
||||||
|
existingConversation: true
|
||||||
|
});
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// Cache miss is normal
|
logLocal("handleNewMessageSummary - Cache miss", { conversationId });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Handle new conversation
|
||||||
if (!existingConversation && newConversation?.phone_num) {
|
if (!existingConversation && newConversation?.phone_num) {
|
||||||
|
logLocal("handleNewMessageSummary - New Conversation", newConversation);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
upsertConversationIntoOffsetZeroList(client, newConversation, { isoutbound, isSystem });
|
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];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error updating cache for new conversation:", error);
|
console.error("Error updating cache for new conversation:", error);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (existingConversation && conversationId) {
|
// Handle existing conversation
|
||||||
|
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: () => updated_at || safeIsoNow(),
|
updated_at: () => new Date().toISOString(),
|
||||||
archived: () => false,
|
archived: () => false,
|
||||||
|
messages_aggregate(cached = { aggregate: { count: 0 } }) {
|
||||||
messages_aggregate(cached = null) {
|
const currentCount = cached.aggregate?.count || 0;
|
||||||
if (isoutbound || isSystem) return cached;
|
if (!isoutbound) {
|
||||||
|
return {
|
||||||
const currentCount = cached?.aggregate?.count ?? 0;
|
__typename: "messages_aggregate",
|
||||||
return {
|
aggregate: {
|
||||||
__typename: "messages_aggregate",
|
__typename: "messages_aggregate_fields",
|
||||||
aggregate: {
|
count: currentCount + 1
|
||||||
__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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -318,78 +166,88 @@ export const registerMessagingHandlers = ({ socket, client, currentUser, bodysho
|
|||||||
|
|
||||||
logLocal("handleNewMessageDetailed - Start", message);
|
logLocal("handleNewMessageDetailed - Start", message);
|
||||||
|
|
||||||
if (!conversationId || !isConversationDetailsCached(client, conversationId)) return;
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const normalized = normalizeMessageForCache(newMessage, conversationId);
|
// Check if the conversation exists in the cache
|
||||||
|
const queryResults = client.cache.readQuery({
|
||||||
|
query: GET_CONVERSATION_DETAILS,
|
||||||
|
variables: { conversationId }
|
||||||
|
});
|
||||||
|
|
||||||
const messageCacheId = client.cache.identify(normalized);
|
if (!queryResults?.conversations_by_pk) {
|
||||||
if (!messageCacheId) {
|
console.warn("Conversation not found in cache:", { conversationId });
|
||||||
console.warn("handleNewMessageDetailed - Could not identify message for cache", {
|
|
||||||
conversationId,
|
|
||||||
newMessageId: newMessage?.id
|
|
||||||
});
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
client.cache.writeFragment({
|
// Append the new message to the conversation's message list using cache.modify
|
||||||
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(existing = [], { readField }) {
|
messages(existingMessages = []) {
|
||||||
const already = existing.some((ref) => readField("id", ref) === normalized.id);
|
return [...existingMessages, newMessage];
|
||||||
if (already) return existing;
|
|
||||||
return [...existing, { __ref: messageCacheId }];
|
|
||||||
},
|
|
||||||
updated_at() {
|
|
||||||
return normalized.created_at || safeIsoNow();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
logLocal("handleNewMessageDetailed - Message appended successfully", { conversationId });
|
logLocal("handleNewMessageDetailed - Message appended successfully", {
|
||||||
|
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?.id) return;
|
if (!message) {
|
||||||
|
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: msgCacheId,
|
id: client.cache.identify({ __typename: "conversations", id: message.conversationid }),
|
||||||
fields: {
|
fields: {
|
||||||
status(existing) {
|
messages(existingMessages = [], { readField }) {
|
||||||
return message.type === "status-changed" ? (message.status ?? existing) : existing;
|
return existingMessages.map((messageRef) => {
|
||||||
},
|
// Check if this is the message to update
|
||||||
text(existing) {
|
if (readField("id", messageRef) === message.id) {
|
||||||
return message.type === "text-updated" ? (message.text ?? existing) : existing;
|
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;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -404,140 +262,149 @@ export const registerMessagingHandlers = ({ socket, client, currentUser, bodysho
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleConversationChanged = async (data) => {
|
const handleConversationChanged = async (data) => {
|
||||||
if (!data?.conversationId) return;
|
if (!data) {
|
||||||
|
logLocal("handleConversationChanged - No data provided", data);
|
||||||
const {
|
return;
|
||||||
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 = safeIsoNow();
|
const updatedAt = new Date().toISOString();
|
||||||
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":
|
||||||
refetchUnreadCount();
|
if (conversationId && messageIds?.length > 0) {
|
||||||
|
client.cache.modify({
|
||||||
if (detailsCached && Array.isArray(messageIds)) {
|
id: client.cache.identify({ __typename: "conversations", id: conversationId }),
|
||||||
messageIds.forEach((id) => {
|
fields: {
|
||||||
if (!messageEntityCached(client, id)) return;
|
messages(existingMessages = [], { readField }) {
|
||||||
client.cache.modify({
|
return existingMessages.map((message) => {
|
||||||
id: client.cache.identify({ __typename: "messages", id }),
|
if (messageIds.includes(readField("id", message))) {
|
||||||
fields: { read: () => true }
|
return { ...message, read: true };
|
||||||
});
|
}
|
||||||
|
return message;
|
||||||
|
});
|
||||||
|
},
|
||||||
|
messages_aggregate: () => ({
|
||||||
|
__typename: "messages_aggregate",
|
||||||
|
aggregate: { __typename: "messages_aggregate_fields", count: 0 }
|
||||||
|
})
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
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;
|
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
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
|
case "conversation-created":
|
||||||
|
updateConversationList({ ...fields, job_conversations, updated_at: updatedAt });
|
||||||
break;
|
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":
|
||||||
// Keep unread badge correct even if archiving affects counts
|
try {
|
||||||
refetchUnreadCount();
|
const listQueryVariables = { offset: 0 };
|
||||||
|
const detailsQueryVariables = { conversationId };
|
||||||
|
|
||||||
await client.refetchQueries({
|
// Check if conversation details exist in the cache
|
||||||
include: [CONVERSATION_LIST_QUERY, GET_CONVERSATION_DETAILS]
|
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);
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
}
|
|
||||||
|
|
||||||
case "tag-added": {
|
case "tag-added": {
|
||||||
const formattedJobConversations = (job_conversations || []).map((jc) => ({
|
// Ensure `job_conversations` is properly formatted
|
||||||
|
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: {
|
job: jc.job || {
|
||||||
__typename: "jobs",
|
__typename: "jobs",
|
||||||
id: jc.job?.id,
|
id: data.selectedJob.id,
|
||||||
ro_number: jc.job?.ro_number,
|
ro_number: data.selectedJob.ro_number,
|
||||||
ownr_co_nm: jc.job?.ownr_co_nm,
|
ownr_co_nm: data.selectedJob.ownr_co_nm,
|
||||||
ownr_fn: jc.job?.ownr_fn,
|
ownr_fn: data.selectedJob.ownr_fn,
|
||||||
ownr_ln: jc.job?.ownr_ln
|
ownr_ln: data.selectedJob.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 = [], { readField }) {
|
job_conversations: (existing = []) => {
|
||||||
const seen = new Set(existing.map((x) => readField("jobid", x)).filter(Boolean));
|
// Ensure no duplicates based on both `conversationid` and `jobid`
|
||||||
const incoming = formattedJobConversations.filter((x) => x.jobid && !seen.has(x.jobid));
|
const existingLinks = new Set(
|
||||||
return [...existing, ...incoming];
|
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];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -545,31 +412,46 @@ export const registerMessagingHandlers = ({ socket, client, currentUser, bodysho
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case "tag-removed": {
|
case "tag-removed":
|
||||||
const conversationCacheId = client.cache.identify({ __typename: "conversations", id: conversationId });
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
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: Object.fromEntries(
|
fields: {
|
||||||
Object.entries(fields).map(([key, value]) => [key, (cached) => (value !== undefined ? value : cached)])
|
...Object.fromEntries(
|
||||||
)
|
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);
|
||||||
@@ -579,18 +461,22 @@ 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 exists = existing.some(
|
const phoneNumberExists = 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: safeIsoNow(),
|
created_at: new Date().toISOString(),
|
||||||
updated_at: safeIsoNow()
|
updated_at: new Date().toISOString()
|
||||||
};
|
};
|
||||||
|
|
||||||
return [...existing, newOptOut];
|
return [...existing, newOptOut];
|
||||||
@@ -605,36 +491,46 @@ 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
|
broadcast: true // Trigger UI updates
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 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 });
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -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_BY_NUMBERS } from "../../graphql/phone-number-opt-out.queries.js";
|
import { GET_PHONE_NUMBER_OPT_OUTS } 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,26 +29,13 @@ 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 phoneNumbers = useMemo(() => {
|
const { data: optOutData } = useQuery(GET_PHONE_NUMBER_OPT_OUTS, {
|
||||||
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: !bodyshop?.id || phoneNumbers.length === 0,
|
skip: !conversationList.length,
|
||||||
fetchPolicy: "cache-and-network"
|
fetchPolicy: "cache-and-network"
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -71,25 +58,15 @@ function ChatConversationListComponent({ conversationList, selectedConversation,
|
|||||||
return _.orderBy(conversationList, ["updated_at"], ["desc"]);
|
return _.orderBy(conversationList, ["updated_at"], ["desc"]);
|
||||||
}, [conversationList]);
|
}, [conversationList]);
|
||||||
|
|
||||||
const renderConversation = (index) => {
|
const renderConversation = (index, t) => {
|
||||||
const item = sortedConversationList[index];
|
const item = sortedConversationList[index];
|
||||||
|
const normalizedPhone = phone(item.phone_num, "CA").phoneNumber.replace(/^\+1/, "");
|
||||||
const normalizedPhone = (() => {
|
const hasOptOutEntry = optOutMap.has(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 = (
|
||||||
<>
|
<>
|
||||||
@@ -103,10 +80,9 @@ function ChatConversationListComponent({ conversationList, selectedConversation,
|
|||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|
||||||
const cardExtra = (
|
const cardExtra = (
|
||||||
<>
|
<>
|
||||||
<Badge count={item.messages_aggregate?.aggregate?.count || 0} />
|
<Badge count={item.messages_aggregate.aggregate.count} />
|
||||||
{hasOptOutEntry && (
|
{hasOptOutEntry && (
|
||||||
<Tooltip title={t("consent.text_body")}>
|
<Tooltip title={t("consent.text_body")}>
|
||||||
<Tag color="red" icon={<ExclamationCircleOutlined />}>
|
<Tag color="red" icon={<ExclamationCircleOutlined />}>
|
||||||
@@ -116,7 +92,6 @@ function ChatConversationListComponent({ conversationList, selectedConversation,
|
|||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|
||||||
const getCardStyle = () =>
|
const getCardStyle = () =>
|
||||||
item.id === selectedConversation
|
item.id === selectedConversation
|
||||||
? { backgroundColor: "var(--card-selected-bg)" }
|
? { backgroundColor: "var(--card-selected-bg)" }
|
||||||
@@ -129,8 +104,24 @@ 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 style={{ display: "inline-block", width: "70%", textAlign: "left" }}>{cardContentLeft}</div>
|
<div
|
||||||
<div style={{ display: "inline-block", width: "30%", textAlign: "right" }}>{cardContentRight}</div>
|
style={{
|
||||||
|
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>
|
||||||
);
|
);
|
||||||
@@ -140,7 +131,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)}
|
itemContent={(index) => renderConversation(index, t)}
|
||||||
style={{ height: "100%", width: "100%" }}
|
style={{ height: "100%", width: "100%" }}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -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 ChatMarkUnreadButton from "../chat-mark-unread-button/chat-mark-unread-button.component";
|
import { createStructuredSelector } from "reselect";
|
||||||
|
import { connect } from "react-redux";
|
||||||
|
|
||||||
export function ChatConversationTitle({ conversation, onMarkUnread, markUnreadDisabled, markUnreadLoading }) {
|
const mapStateToProps = createStructuredSelector({});
|
||||||
|
|
||||||
|
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 ChatConversationTitle;
|
export default connect(mapStateToProps, mapDispatchToProps)(ChatConversationTitle);
|
||||||
|
|||||||
@@ -19,9 +19,7 @@ export function ChatConversationComponent({
|
|||||||
conversation,
|
conversation,
|
||||||
messages,
|
messages,
|
||||||
handleMarkConversationAsRead,
|
handleMarkConversationAsRead,
|
||||||
handleMarkLastMessageAsUnread,
|
bodyshop
|
||||||
markingAsUnreadInProgress,
|
|
||||||
canMarkUnread
|
|
||||||
}) {
|
}) {
|
||||||
const [loading, error] = subState;
|
const [loading, error] = subState;
|
||||||
|
|
||||||
@@ -35,12 +33,7 @@ export function ChatConversationComponent({
|
|||||||
onMouseDown={handleMarkConversationAsRead}
|
onMouseDown={handleMarkConversationAsRead}
|
||||||
onKeyDown={handleMarkConversationAsRead}
|
onKeyDown={handleMarkConversationAsRead}
|
||||||
>
|
>
|
||||||
<ChatConversationTitle
|
<ChatConversationTitle conversation={conversation} bodyshop={bodyshop} />
|
||||||
conversation={conversation}
|
|
||||||
onMarkUnread={handleMarkLastMessageAsUnread}
|
|
||||||
markUnreadDisabled={!canMarkUnread}
|
|
||||||
markUnreadLoading={markingAsUnreadInProgress}
|
|
||||||
/>
|
|
||||||
<ChatMessageListComponent messages={messages} />
|
<ChatMessageListComponent messages={messages} />
|
||||||
<ChatSendMessage conversation={conversation} />
|
<ChatSendMessage conversation={conversation} />
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -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, useMemo, useState } from "react";
|
import { useCallback, useEffect, 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,23 +27,24 @@ 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
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const conversation = convoData?.conversations_by_pk;
|
// Subscription for conversation updates
|
||||||
|
|
||||||
// Subscription for conversation updates (used when socket is NOT connected)
|
|
||||||
useSubscription(CONVERSATION_SUBSCRIPTION_BY_PK, {
|
useSubscription(CONVERSATION_SUBSCRIPTION_BY_PK, {
|
||||||
skip: socket?.connected || !selectedConversation,
|
skip: socket?.connected,
|
||||||
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) return;
|
if (!messages || messages.length === 0) {
|
||||||
|
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`
|
||||||
@@ -63,6 +64,7 @@ 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: {
|
||||||
@@ -80,28 +82,6 @@ function ChatConversationContainer({ bodyshop, selectedConversation }) {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
|
||||||
* Best-effort badge update:
|
|
||||||
* This assumes your list query uses messages_aggregate.aggregate.count as UNREAD inbound count.
|
|
||||||
* If it’s 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;
|
||||||
@@ -109,34 +89,13 @@ 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: { read: () => true }
|
fields: {
|
||||||
|
read: () => true
|
||||||
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
setConversationUnreadCountBestEffort(conversationId, 0);
|
|
||||||
},
|
},
|
||||||
[client.cache, setConversationUnreadCountBestEffort]
|
[client.cache]
|
||||||
);
|
|
||||||
|
|
||||||
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
|
||||||
@@ -144,25 +103,20 @@ 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") {
|
||||||
updateCacheWithReadMessages(data.conversationId, data.messageIds);
|
const { conversationId, messageIds } = data;
|
||||||
}
|
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]);
|
|
||||||
|
|
||||||
// Join/leave conversation via WebSocket
|
return () => {
|
||||||
|
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;
|
||||||
|
|
||||||
@@ -179,21 +133,15 @@ function ChatConversationContainer({ bodyshop, selectedConversation }) {
|
|||||||
};
|
};
|
||||||
}, [socket, bodyshop, selectedConversation]);
|
}, [socket, bodyshop, selectedConversation]);
|
||||||
|
|
||||||
const inboundNonSystemMessages = useMemo(() => {
|
// Mark conversation as read
|
||||||
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 canMarkUnread = inboundNonSystemMessages.length > 0;
|
|
||||||
|
|
||||||
const handleMarkConversationAsRead = async () => {
|
const handleMarkConversationAsRead = async () => {
|
||||||
if (!conversation || markingAsReadInProgress) return;
|
if (!convoData || markingAsReadInProgress) return;
|
||||||
|
|
||||||
|
const conversation = convoData.conversations_by_pk;
|
||||||
|
if (!conversation) return;
|
||||||
|
|
||||||
const unreadMessageIds = conversation.messages
|
const unreadMessageIds = conversation.messages
|
||||||
?.filter((message) => !message.read && !message.isoutbound && !message.is_system)
|
?.filter((message) => !message.read && !message.isoutbound)
|
||||||
.map((message) => message.id);
|
.map((message) => message.id);
|
||||||
|
|
||||||
if (unreadMessageIds?.length > 0) {
|
if (unreadMessageIds?.length > 0) {
|
||||||
@@ -214,48 +162,12 @@ 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={conversation || {}}
|
conversation={convoData?.conversations_by_pk || {}}
|
||||||
messages={conversation?.messages || []}
|
messages={convoData?.conversations_by_pk?.messages || []}
|
||||||
handleMarkConversationAsRead={handleMarkConversationAsRead}
|
handleMarkConversationAsRead={handleMarkConversationAsRead}
|
||||||
handleMarkLastMessageAsUnread={handleMarkLastMessageAsUnread}
|
|
||||||
markingAsUnreadInProgress={markingAsUnreadInProgress}
|
|
||||||
canMarkUnread={canMarkUnread}
|
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,24 +0,0 @@
|
|||||||
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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -10,11 +10,6 @@
|
|||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.unread-button {
|
|
||||||
height: 20px;
|
|
||||||
border-radius: 4px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.chat-title {
|
.chat-title {
|
||||||
margin-bottom: 5px;
|
margin-bottom: 5px;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -132,7 +132,7 @@ const NotificationSettingsForm = ({ currentUser, bodyshop }) => {
|
|||||||
dataIndex: "scenarioLabel",
|
dataIndex: "scenarioLabel",
|
||||||
key: "scenario",
|
key: "scenario",
|
||||||
render: (_, record) => t(`notifications.scenarios.${record.key}`),
|
render: (_, record) => t(`notifications.scenarios.${record.key}`),
|
||||||
width: "90%"
|
width: "80%"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: <ColumnHeaderCheckbox channel="app" form={form} onHeaderChange={() => setIsDirty(true)} />,
|
title: <ColumnHeaderCheckbox channel="app" form={form} onHeaderChange={() => setIsDirty(true)} />,
|
||||||
@@ -156,20 +156,23 @@ const NotificationSettingsForm = ({ currentUser, bodyshop }) => {
|
|||||||
</Form.Item>
|
</Form.Item>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
// TODO: Disabled for now until FCM is implemented.
|
|
||||||
// {
|
|
||||||
// title: <ColumnHeaderCheckbox channel="fcm" form={form} disabled onHeaderChange={() => setIsDirty(true)} />,
|
|
||||||
// dataIndex: "fcm",
|
|
||||||
// key: "fcm",
|
|
||||||
// align: "center",
|
|
||||||
// render: (_, record) => (
|
|
||||||
// <Form.Item name={[record.key, "fcm"]} valuePropName="checked" noStyle>
|
|
||||||
// <Checkbox disabled />
|
|
||||||
// </Form.Item>
|
|
||||||
// )
|
|
||||||
// }
|
|
||||||
];
|
];
|
||||||
|
|
||||||
|
// Currently disabled for prod
|
||||||
|
if (!import.meta.env.PROD) {
|
||||||
|
columns.push({
|
||||||
|
title: <ColumnHeaderCheckbox channel="fcm" form={form} onHeaderChange={() => setIsDirty(true)} />,
|
||||||
|
dataIndex: "fcm",
|
||||||
|
key: "fcm",
|
||||||
|
align: "center",
|
||||||
|
render: (_, record) => (
|
||||||
|
<Form.Item name={[record.key, "fcm"]} valuePropName="checked" noStyle>
|
||||||
|
<Checkbox />
|
||||||
|
</Form.Item>
|
||||||
|
)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const dataSource = notificationScenarios.map((scenario) => ({ key: scenario }));
|
const dataSource = notificationScenarios.map((scenario) => ({ key: scenario }));
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -186,13 +189,7 @@ const NotificationSettingsForm = ({ currentUser, bodyshop }) => {
|
|||||||
extra={
|
extra={
|
||||||
<Space>
|
<Space>
|
||||||
<Typography.Text type="secondary">{t("notifications.labels.auto-add")}</Typography.Text>
|
<Typography.Text type="secondary">{t("notifications.labels.auto-add")}</Typography.Text>
|
||||||
<Switch
|
<Switch checked={autoAddEnabled} onChange={handleAutoAddToggle} loading={savingAutoAdd} />
|
||||||
checked={autoAddEnabled}
|
|
||||||
onChange={handleAutoAddToggle}
|
|
||||||
loading={savingAutoAdd}
|
|
||||||
// checkedChildren={t("notifications.labels.auto-add-on")}
|
|
||||||
// unCheckedChildren={t("notifications.labels.auto-add-off")}
|
|
||||||
/>
|
|
||||||
<Button type="default" onClick={handleReset} disabled={!isDirty && !isAutoAddDirty}>
|
<Button type="default" onClick={handleReset} disabled={!isDirty && !isAutoAddDirty}>
|
||||||
{t("general.actions.clear")}
|
{t("general.actions.clear")}
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -2,27 +2,7 @@ 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 {
|
||||||
# How many conversations have at least one unread inbound, non-system message
|
messages_aggregate(where: { read: { _eq: false }, isoutbound: { _eq: false } }) {
|
||||||
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
|
||||||
}
|
}
|
||||||
@@ -39,7 +19,7 @@ export const CONVERSATION_LIST_QUERY = gql`
|
|||||||
unreadcnt
|
unreadcnt
|
||||||
archived
|
archived
|
||||||
label
|
label
|
||||||
messages_aggregate(where: { read: { _eq: false }, isoutbound: { _eq: false }, is_system: { _eq: false } }) {
|
messages_aggregate(where: { read: { _eq: false }, isoutbound: { _eq: false } }) {
|
||||||
aggregate {
|
aggregate {
|
||||||
count
|
count
|
||||||
}
|
}
|
||||||
@@ -61,7 +41,6 @@ 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
|
||||||
@@ -97,7 +76,6 @@ 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
|
||||||
@@ -132,7 +110,7 @@ export const CONVERSATION_ID_BY_PHONE = gql`
|
|||||||
ro_number
|
ro_number
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
messages_aggregate(where: { read: { _eq: false }, isoutbound: { _eq: false }, is_system: { _eq: false } }) {
|
messages_aggregate(where: { read: { _eq: false }, isoutbound: { _eq: false } }) {
|
||||||
aggregate {
|
aggregate {
|
||||||
count
|
count
|
||||||
}
|
}
|
||||||
@@ -161,7 +139,7 @@ export const CREATE_CONVERSATION = gql`
|
|||||||
ro_number
|
ro_number
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
messages_aggregate(where: { read: { _eq: false }, isoutbound: { _eq: false }, is_system: { _eq: false } }) {
|
messages_aggregate(where: { read: { _eq: false }, isoutbound: { _eq: false } }) {
|
||||||
aggregate {
|
aggregate {
|
||||||
count
|
count
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2430,8 +2430,7 @@
|
|||||||
"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"
|
||||||
|
|||||||
@@ -2430,8 +2430,7 @@
|
|||||||
"selectmedia": "",
|
"selectmedia": "",
|
||||||
"sentby": "",
|
"sentby": "",
|
||||||
"typeamessage": "Enviar un mensaje...",
|
"typeamessage": "Enviar un mensaje...",
|
||||||
"unarchive": "",
|
"unarchive": ""
|
||||||
"mark_unread": ""
|
|
||||||
},
|
},
|
||||||
"render": {
|
"render": {
|
||||||
"conversation_list": ""
|
"conversation_list": ""
|
||||||
|
|||||||
@@ -2430,8 +2430,7 @@
|
|||||||
"selectmedia": "",
|
"selectmedia": "",
|
||||||
"sentby": "",
|
"sentby": "",
|
||||||
"typeamessage": "Envoyer un message...",
|
"typeamessage": "Envoyer un message...",
|
||||||
"unarchive": "",
|
"unarchive": ""
|
||||||
"mark_unread": ""
|
|
||||||
},
|
},
|
||||||
"render": {
|
"render": {
|
||||||
"conversation_list": ""
|
"conversation_list": ""
|
||||||
|
|||||||
@@ -148,26 +148,6 @@ 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
|
||||||
|
|||||||
10
server.js
10
server.js
@@ -38,6 +38,7 @@ const { registerCleanupTask, initializeCleanupManager } = require("./server/util
|
|||||||
|
|
||||||
const { loadEmailQueue } = require("./server/notifications/queues/emailQueue");
|
const { loadEmailQueue } = require("./server/notifications/queues/emailQueue");
|
||||||
const { loadAppQueue } = require("./server/notifications/queues/appQueue");
|
const { loadAppQueue } = require("./server/notifications/queues/appQueue");
|
||||||
|
const { loadFcmQueue } = require("./server/notifications/queues/fcmQueue");
|
||||||
|
|
||||||
const CLUSTER_RETRY_BASE_DELAY = 100;
|
const CLUSTER_RETRY_BASE_DELAY = 100;
|
||||||
const CLUSTER_RETRY_MAX_DELAY = 5000;
|
const CLUSTER_RETRY_MAX_DELAY = 5000;
|
||||||
@@ -355,9 +356,10 @@ const loadQueues = async ({ pubClient, logger, redisHelpers, ioRedis }) => {
|
|||||||
const queueSettings = { pubClient, logger, redisHelpers, ioRedis };
|
const queueSettings = { pubClient, logger, redisHelpers, ioRedis };
|
||||||
|
|
||||||
// Assuming loadEmailQueue and loadAppQueue return Promises
|
// Assuming loadEmailQueue and loadAppQueue return Promises
|
||||||
const [notificationsEmailsQueue, notificationsAppQueue] = await Promise.all([
|
const [notificationsEmailsQueue, notificationsAppQueue, notificationsFcmQueue] = await Promise.all([
|
||||||
loadEmailQueue(queueSettings),
|
loadEmailQueue(queueSettings),
|
||||||
loadAppQueue(queueSettings)
|
loadAppQueue(queueSettings),
|
||||||
|
loadFcmQueue(queueSettings)
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// Add error listeners or other setup for queues if needed
|
// Add error listeners or other setup for queues if needed
|
||||||
@@ -368,6 +370,10 @@ const loadQueues = async ({ pubClient, logger, redisHelpers, ioRedis }) => {
|
|||||||
notificationsAppQueue.on("error", (error) => {
|
notificationsAppQueue.on("error", (error) => {
|
||||||
logger.log(`Error in notificationsAppQueue: ${error}`, "ERROR", "queue", "api", null, { error: error?.message });
|
logger.log(`Error in notificationsAppQueue: ${error}`, "ERROR", "queue", "api", null, { error: error?.message });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
notificationsFcmQueue.on("error", (error) => {
|
||||||
|
logger.log(`Error in notificationsFCMQueue: ${error}`, "ERROR", "queue", "api", null, { error: error?.message });
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -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,7 +147,6 @@ 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
|
||||||
@@ -3188,3 +3187,20 @@ mutation INSERT_MEDIA_ANALYTICS($mediaObject: media_analytics_insert_input!) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
`;
|
`;
|
||||||
|
|
||||||
|
exports.GET_USERS_FCM_TOKENS_BY_EMAILS = /* GraphQL */ `
|
||||||
|
query GET_USERS_FCM_TOKENS_BY_EMAILS($emails: [String!]!) {
|
||||||
|
users(where: { email: { _in: $emails } }) {
|
||||||
|
email
|
||||||
|
fcmtokens
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports.UPDATE_USER_FCM_TOKENS_BY_EMAIL = /* GraphQL */ `
|
||||||
|
mutation UPDATE_USER_FCM_TOKENS_BY_EMAIL($email: String!, $fcmtokens: jsonb) {
|
||||||
|
update_users(where: { email: { _eq: $email } }, _set: { fcmtokens: $fcmtokens }) {
|
||||||
|
affected_rows
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|||||||
@@ -205,9 +205,8 @@ const handleTaskSocketEmit = (req) => {
|
|||||||
* @returns {Promise<Object>} JSON response with a success message.
|
* @returns {Promise<Object>} JSON response with a success message.
|
||||||
*/
|
*/
|
||||||
const handleTasksChange = async (req, res) => {
|
const handleTasksChange = async (req, res) => {
|
||||||
// Handle Notification Event
|
|
||||||
processNotificationEvent(req, res, "req.body.event.new.jobid", "Tasks Notifications Event Handled.");
|
|
||||||
handleTaskSocketEmit(req);
|
handleTaskSocketEmit(req);
|
||||||
|
return processNotificationEvent(req, res, "req.body.event.new.jobid", "Tasks Notifications Event Handled.");
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -42,6 +42,13 @@ const buildNotificationContent = (notifications) => {
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert MS to S
|
||||||
|
* @param ms
|
||||||
|
* @returns {number}
|
||||||
|
*/
|
||||||
|
const seconds = (ms) => Math.max(1, Math.ceil(ms / 1000));
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initializes the notification queues and workers for adding and consolidating notifications.
|
* Initializes the notification queues and workers for adding and consolidating notifications.
|
||||||
*/
|
*/
|
||||||
@@ -52,6 +59,13 @@ const loadAppQueue = async ({ pubClient, logger, redisHelpers, ioRedis }) => {
|
|||||||
|
|
||||||
devDebugLogger(`Initializing Notifications Queues with prefix: ${prefix}`);
|
devDebugLogger(`Initializing Notifications Queues with prefix: ${prefix}`);
|
||||||
|
|
||||||
|
// Redis key helpers (per jobId)
|
||||||
|
const recipientsSetKey = (jobId) => `app:${devKey}:recipients:${jobId}`; // set of `${user}:${bodyShopId}`
|
||||||
|
const recipientAssocHashKey = (jobId) => `app:${devKey}:recipientAssoc:${jobId}`; // hash `${user}:${bodyShopId}` => associationId
|
||||||
|
const consolidateFlagKey = (jobId) => `app:${devKey}:consolidate:${jobId}`;
|
||||||
|
const lockKeyForJob = (jobId) => `lock:${devKey}:consolidate:${jobId}`;
|
||||||
|
const listKey = ({ jobId, user, bodyShopId }) => `app:${devKey}:notifications:${jobId}:${user}:${bodyShopId}`;
|
||||||
|
|
||||||
addQueue = new Queue("notificationsAdd", {
|
addQueue = new Queue("notificationsAdd", {
|
||||||
prefix,
|
prefix,
|
||||||
connection: pubClient,
|
connection: pubClient,
|
||||||
@@ -70,27 +84,39 @@ const loadAppQueue = async ({ pubClient, logger, redisHelpers, ioRedis }) => {
|
|||||||
const { jobId, key, variables, recipients, body, jobRoNumber } = job.data;
|
const { jobId, key, variables, recipients, body, jobRoNumber } = job.data;
|
||||||
devDebugLogger(`Adding notifications for jobId ${jobId}`);
|
devDebugLogger(`Adding notifications for jobId ${jobId}`);
|
||||||
|
|
||||||
const redisKeyPrefix = `app:${devKey}:notifications:${jobId}`;
|
|
||||||
const notification = { key, variables, body, jobRoNumber, timestamp: Date.now() };
|
const notification = { key, variables, body, jobRoNumber, timestamp: Date.now() };
|
||||||
|
|
||||||
for (const recipient of recipients) {
|
// Store notifications atomically (RPUSH) and store recipients in a Redis set
|
||||||
const { user } = recipient;
|
for (const recipient of recipients || []) {
|
||||||
const userKey = `${redisKeyPrefix}:${user}`;
|
const { user, bodyShopId, associationId } = recipient;
|
||||||
const existingNotifications = await pubClient.get(userKey);
|
if (!user || !bodyShopId) continue;
|
||||||
const notifications = existingNotifications ? JSON.parse(existingNotifications) : [];
|
|
||||||
notifications.push(notification);
|
const rk = `${user}:${bodyShopId}`;
|
||||||
await pubClient.set(userKey, JSON.stringify(notifications), "EX", NOTIFICATION_STORAGE_EXPIRATION / 1000);
|
|
||||||
devDebugLogger(`Stored notification for ${user} under ${userKey}: ${JSON.stringify(notifications)}`);
|
// (1) Store notification payload in a list (atomic append)
|
||||||
|
const lk = listKey({ jobId, user, bodyShopId });
|
||||||
|
await pubClient.rpush(lk, JSON.stringify(notification));
|
||||||
|
await pubClient.expire(lk, seconds(NOTIFICATION_STORAGE_EXPIRATION));
|
||||||
|
|
||||||
|
// (2) Track recipients in a set, and associationId in a hash
|
||||||
|
await pubClient.sadd(recipientsSetKey(jobId), rk);
|
||||||
|
await pubClient.expire(recipientsSetKey(jobId), seconds(NOTIFICATION_STORAGE_EXPIRATION));
|
||||||
|
|
||||||
|
if (associationId) {
|
||||||
|
await pubClient.hset(recipientAssocHashKey(jobId), rk, String(associationId));
|
||||||
|
}
|
||||||
|
await pubClient.expire(recipientAssocHashKey(jobId), seconds(NOTIFICATION_STORAGE_EXPIRATION));
|
||||||
}
|
}
|
||||||
|
|
||||||
const consolidateKey = `app:${devKey}:consolidate:${jobId}`;
|
// Schedule consolidation once per jobId
|
||||||
const flagSet = await pubClient.setnx(consolidateKey, "pending");
|
const flagKey = consolidateFlagKey(jobId);
|
||||||
|
const flagSet = await pubClient.setnx(flagKey, "pending");
|
||||||
devDebugLogger(`Consolidation flag set for jobId ${jobId}: ${flagSet}`);
|
devDebugLogger(`Consolidation flag set for jobId ${jobId}: ${flagSet}`);
|
||||||
|
|
||||||
if (flagSet) {
|
if (flagSet) {
|
||||||
await consolidateQueue.add(
|
await consolidateQueue.add(
|
||||||
"consolidate-notifications",
|
"consolidate-notifications",
|
||||||
{ jobId, recipients },
|
{ jobId },
|
||||||
{
|
{
|
||||||
jobId: `consolidate-${jobId}`,
|
jobId: `consolidate-${jobId}`,
|
||||||
delay: APP_CONSOLIDATION_DELAY,
|
delay: APP_CONSOLIDATION_DELAY,
|
||||||
@@ -98,8 +124,9 @@ const loadAppQueue = async ({ pubClient, logger, redisHelpers, ioRedis }) => {
|
|||||||
backoff: LOCK_EXPIRATION
|
backoff: LOCK_EXPIRATION
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
|
await pubClient.expire(flagKey, seconds(CONSOLIDATION_FLAG_EXPIRATION));
|
||||||
devDebugLogger(`Scheduled consolidation for jobId ${jobId}`);
|
devDebugLogger(`Scheduled consolidation for jobId ${jobId}`);
|
||||||
await pubClient.expire(consolidateKey, CONSOLIDATION_FLAG_EXPIRATION / 1000);
|
|
||||||
} else {
|
} else {
|
||||||
devDebugLogger(`Consolidation already scheduled for jobId ${jobId}`);
|
devDebugLogger(`Consolidation already scheduled for jobId ${jobId}`);
|
||||||
}
|
}
|
||||||
@@ -114,122 +141,167 @@ const loadAppQueue = async ({ pubClient, logger, redisHelpers, ioRedis }) => {
|
|||||||
const consolidateWorker = new Worker(
|
const consolidateWorker = new Worker(
|
||||||
"notificationsConsolidate",
|
"notificationsConsolidate",
|
||||||
async (job) => {
|
async (job) => {
|
||||||
const { jobId, recipients } = job.data;
|
const { jobId } = job.data;
|
||||||
devDebugLogger(`Consolidating notifications for jobId ${jobId}`);
|
devDebugLogger(`Consolidating notifications for jobId ${jobId}`);
|
||||||
|
|
||||||
const redisKeyPrefix = `app:${devKey}:notifications:${jobId}`;
|
const lockKey = lockKeyForJob(jobId);
|
||||||
const lockKey = `lock:${devKey}:consolidate:${jobId}`;
|
const lockAcquired = await pubClient.set(lockKey, "locked", "NX", "EX", seconds(LOCK_EXPIRATION));
|
||||||
|
|
||||||
const lockAcquired = await pubClient.set(lockKey, "locked", "NX", "EX", LOCK_EXPIRATION / 1000);
|
|
||||||
devDebugLogger(`Lock acquisition for jobId ${jobId}: ${lockAcquired}`);
|
devDebugLogger(`Lock acquisition for jobId ${jobId}: ${lockAcquired}`);
|
||||||
|
|
||||||
if (lockAcquired) {
|
if (!lockAcquired) {
|
||||||
try {
|
|
||||||
const allNotifications = {};
|
|
||||||
const uniqueUsers = [...new Set(recipients.map((r) => r.user))];
|
|
||||||
devDebugLogger(`Unique users for jobId ${jobId}: ${uniqueUsers}`);
|
|
||||||
|
|
||||||
for (const user of uniqueUsers) {
|
|
||||||
const userKey = `${redisKeyPrefix}:${user}`;
|
|
||||||
const notifications = await pubClient.get(userKey);
|
|
||||||
devDebugLogger(`Retrieved notifications for ${user}: ${notifications}`);
|
|
||||||
|
|
||||||
if (notifications) {
|
|
||||||
const parsedNotifications = JSON.parse(notifications);
|
|
||||||
const userRecipients = recipients.filter((r) => r.user === user);
|
|
||||||
for (const { bodyShopId } of userRecipients) {
|
|
||||||
allNotifications[user] = allNotifications[user] || {};
|
|
||||||
allNotifications[user][bodyShopId] = parsedNotifications;
|
|
||||||
}
|
|
||||||
await pubClient.del(userKey);
|
|
||||||
devDebugLogger(`Deleted Redis key ${userKey}`);
|
|
||||||
} else {
|
|
||||||
devDebugLogger(`No notifications found for ${user} under ${userKey}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
devDebugLogger(`Consolidated notifications: ${JSON.stringify(allNotifications)}`);
|
|
||||||
|
|
||||||
// Insert notifications into the database and collect IDs
|
|
||||||
const notificationInserts = [];
|
|
||||||
const notificationIdMap = new Map();
|
|
||||||
|
|
||||||
for (const [user, bodyShopData] of Object.entries(allNotifications)) {
|
|
||||||
const userRecipients = recipients.filter((r) => r.user === user);
|
|
||||||
const associationId = userRecipients[0]?.associationId;
|
|
||||||
|
|
||||||
for (const [bodyShopId, notifications] of Object.entries(bodyShopData)) {
|
|
||||||
const { scenario_text, fcm_text, scenario_meta } = buildNotificationContent(notifications);
|
|
||||||
notificationInserts.push({
|
|
||||||
jobid: jobId,
|
|
||||||
associationid: associationId,
|
|
||||||
scenario_text: JSON.stringify(scenario_text),
|
|
||||||
fcm_text: fcm_text,
|
|
||||||
scenario_meta: JSON.stringify(scenario_meta)
|
|
||||||
});
|
|
||||||
notificationIdMap.set(`${user}:${bodyShopId}`, null);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (notificationInserts.length > 0) {
|
|
||||||
const insertResponse = await graphQLClient.request(INSERT_NOTIFICATIONS_MUTATION, {
|
|
||||||
objects: notificationInserts
|
|
||||||
});
|
|
||||||
devDebugLogger(
|
|
||||||
`Inserted ${insertResponse.insert_notifications.affected_rows} notifications for jobId ${jobId}`
|
|
||||||
);
|
|
||||||
|
|
||||||
insertResponse.insert_notifications.returning.forEach((row, index) => {
|
|
||||||
const user = uniqueUsers[Math.floor(index / Object.keys(allNotifications[uniqueUsers[0]]).length)];
|
|
||||||
const bodyShopId = Object.keys(allNotifications[user])[
|
|
||||||
index % Object.keys(allNotifications[user]).length
|
|
||||||
];
|
|
||||||
notificationIdMap.set(`${user}:${bodyShopId}`, row.id);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Emit notifications to users via Socket.io with notification ID
|
|
||||||
for (const [user, bodyShopData] of Object.entries(allNotifications)) {
|
|
||||||
const userMapping = await redisHelpers.getUserSocketMapping(user);
|
|
||||||
const userRecipients = recipients.filter((r) => r.user === user);
|
|
||||||
const associationId = userRecipients[0]?.associationId;
|
|
||||||
|
|
||||||
for (const [bodyShopId, notifications] of Object.entries(bodyShopData)) {
|
|
||||||
const notificationId = notificationIdMap.get(`${user}:${bodyShopId}`);
|
|
||||||
const jobRoNumber = notifications[0]?.jobRoNumber;
|
|
||||||
|
|
||||||
if (userMapping && userMapping[bodyShopId]?.socketIds) {
|
|
||||||
userMapping[bodyShopId].socketIds.forEach((socketId) => {
|
|
||||||
ioRedis.to(socketId).emit("notification", {
|
|
||||||
jobId,
|
|
||||||
jobRoNumber,
|
|
||||||
bodyShopId,
|
|
||||||
notifications,
|
|
||||||
notificationId,
|
|
||||||
associationId
|
|
||||||
});
|
|
||||||
});
|
|
||||||
devDebugLogger(
|
|
||||||
`Sent ${notifications.length} consolidated notifications to ${user} for jobId ${jobId} with notificationId ${notificationId}`
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
devDebugLogger(`No socket IDs found for ${user} in bodyShopId ${bodyShopId}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
await pubClient.del(`app:${devKey}:consolidate:${jobId}`);
|
|
||||||
} catch (err) {
|
|
||||||
logger.log(`app-queue-consolidation-error`, "ERROR", "notifications", "api", {
|
|
||||||
message: err?.message,
|
|
||||||
stack: err?.stack
|
|
||||||
});
|
|
||||||
throw err;
|
|
||||||
} finally {
|
|
||||||
await pubClient.del(lockKey);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
devDebugLogger(`Skipped consolidation for jobId ${jobId} - lock held by another worker`);
|
devDebugLogger(`Skipped consolidation for jobId ${jobId} - lock held by another worker`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const rkSet = recipientsSetKey(jobId);
|
||||||
|
const assocHash = recipientAssocHashKey(jobId);
|
||||||
|
|
||||||
|
const recipientKeys = await pubClient.smembers(rkSet);
|
||||||
|
if (!recipientKeys?.length) {
|
||||||
|
devDebugLogger(`No recipients found for jobId ${jobId}, nothing to consolidate.`);
|
||||||
|
await pubClient.del(consolidateFlagKey(jobId));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const assocMap = await pubClient.hgetall(assocHash);
|
||||||
|
|
||||||
|
// Collect notifications by recipientKey
|
||||||
|
const notificationsByRecipient = new Map(); // rk => parsed notifications array
|
||||||
|
const listKeysToDelete = []; // delete only after successful insert+emit
|
||||||
|
|
||||||
|
for (const rk of recipientKeys) {
|
||||||
|
const [user, bodyShopId] = rk.split(":");
|
||||||
|
const lk = listKey({ jobId, user, bodyShopId });
|
||||||
|
|
||||||
|
const items = await pubClient.lrange(lk, 0, -1);
|
||||||
|
if (!items?.length) continue;
|
||||||
|
|
||||||
|
const parsed = items
|
||||||
|
.map((x) => {
|
||||||
|
try {
|
||||||
|
return JSON.parse(x);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.filter(Boolean);
|
||||||
|
|
||||||
|
if (parsed.length) {
|
||||||
|
notificationsByRecipient.set(rk, parsed);
|
||||||
|
|
||||||
|
// IMPORTANT: do NOT delete list yet; only delete after successful insert+emit
|
||||||
|
listKeysToDelete.push(lk);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!notificationsByRecipient.size) {
|
||||||
|
devDebugLogger(`No notifications found in lists for jobId ${jobId}, nothing to insert/emit.`);
|
||||||
|
if (listKeysToDelete.length) {
|
||||||
|
await pubClient.del(...listKeysToDelete);
|
||||||
|
}
|
||||||
|
await pubClient.del(rkSet);
|
||||||
|
await pubClient.del(assocHash);
|
||||||
|
await pubClient.del(consolidateFlagKey(jobId));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build DB inserts
|
||||||
|
const inserts = [];
|
||||||
|
const insertMeta = []; // keep rk + associationId to emit after insert
|
||||||
|
|
||||||
|
for (const [rk, notifications] of notificationsByRecipient.entries()) {
|
||||||
|
const associationId = assocMap?.[rk];
|
||||||
|
|
||||||
|
// If your DB requires associationid NOT NULL, skip if missing
|
||||||
|
if (!associationId) {
|
||||||
|
devDebugLogger(`Skipping insert for ${rk} (missing associationId).`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { scenario_text, fcm_text, scenario_meta } = buildNotificationContent(notifications);
|
||||||
|
|
||||||
|
inserts.push({
|
||||||
|
jobid: jobId,
|
||||||
|
associationid: associationId,
|
||||||
|
// NOTE: if these are jsonb columns, remove JSON.stringify and pass arrays directly.
|
||||||
|
scenario_text: JSON.stringify(scenario_text),
|
||||||
|
fcm_text,
|
||||||
|
scenario_meta: JSON.stringify(scenario_meta)
|
||||||
|
});
|
||||||
|
|
||||||
|
insertMeta.push({ rk, associationId });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Map notificationId by associationId from Hasura returning rows
|
||||||
|
const idByAssociationId = new Map();
|
||||||
|
|
||||||
|
if (inserts.length > 0) {
|
||||||
|
const insertResponse = await graphQLClient.request(INSERT_NOTIFICATIONS_MUTATION, { objects: inserts });
|
||||||
|
|
||||||
|
const returning = insertResponse?.insert_notifications?.returning || [];
|
||||||
|
returning.forEach((row) => {
|
||||||
|
// Expecting your mutation to return associationid as well as id.
|
||||||
|
// If your mutation currently doesn’t return associationid, update it.
|
||||||
|
if (row?.associationid) idByAssociationId.set(String(row.associationid), row.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
devDebugLogger(
|
||||||
|
`Inserted ${insertResponse.insert_notifications.affected_rows} notifications for jobId ${jobId}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Emit via Socket.io
|
||||||
|
// Group by user to reduce mapping lookups
|
||||||
|
const uniqueUsers = [...new Set(insertMeta.map(({ rk }) => rk.split(":")[0]))];
|
||||||
|
|
||||||
|
for (const user of uniqueUsers) {
|
||||||
|
const userMapping = await redisHelpers.getUserSocketMapping(user);
|
||||||
|
const entriesForUser = insertMeta
|
||||||
|
.map((m) => ({ ...m, user: m.rk.split(":")[0], bodyShopId: m.rk.split(":")[1] }))
|
||||||
|
.filter((m) => m.user === user);
|
||||||
|
|
||||||
|
for (const entry of entriesForUser) {
|
||||||
|
const { rk, bodyShopId, associationId } = entry;
|
||||||
|
const notifications = notificationsByRecipient.get(rk) || [];
|
||||||
|
if (!notifications.length) continue;
|
||||||
|
|
||||||
|
const jobRoNumber = notifications[0]?.jobRoNumber;
|
||||||
|
const notificationId = idByAssociationId.get(String(associationId)) || null;
|
||||||
|
|
||||||
|
if (userMapping && userMapping[bodyShopId]?.socketIds) {
|
||||||
|
userMapping[bodyShopId].socketIds.forEach((socketId) => {
|
||||||
|
ioRedis.to(socketId).emit("notification", {
|
||||||
|
jobId,
|
||||||
|
jobRoNumber,
|
||||||
|
bodyShopId,
|
||||||
|
notifications,
|
||||||
|
notificationId,
|
||||||
|
associationId
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
devDebugLogger(
|
||||||
|
`Sent ${notifications.length} consolidated notifications to ${user} for jobId ${jobId} (notificationId ${notificationId})`
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
devDebugLogger(`No socket IDs found for ${user} in bodyShopId ${bodyShopId}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cleanup recipient tracking keys + consolidation flag
|
||||||
|
await pubClient.del(rkSet);
|
||||||
|
await pubClient.del(assocHash);
|
||||||
|
await pubClient.del(consolidateFlagKey(jobId));
|
||||||
|
} catch (err) {
|
||||||
|
logger.log("app-queue-consolidation-error", "ERROR", "notifications", "api", {
|
||||||
|
message: err?.message,
|
||||||
|
stack: err?.stack
|
||||||
|
});
|
||||||
|
throw err;
|
||||||
|
} finally {
|
||||||
|
await pubClient.del(lockKey);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -244,13 +316,14 @@ const loadAppQueue = async ({ pubClient, logger, redisHelpers, ioRedis }) => {
|
|||||||
consolidateWorker.on("completed", (job) => devDebugLogger(`Consolidate job ${job.id} completed`));
|
consolidateWorker.on("completed", (job) => devDebugLogger(`Consolidate job ${job.id} completed`));
|
||||||
|
|
||||||
addWorker.on("failed", (job, err) =>
|
addWorker.on("failed", (job, err) =>
|
||||||
logger.log(`app-queue-notification-error`, "ERROR", "notifications", "api", {
|
logger.log("app-queue-notification-error", "ERROR", "notifications", "api", {
|
||||||
message: err?.message,
|
message: err?.message,
|
||||||
stack: err?.stack
|
stack: err?.stack
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
consolidateWorker.on("failed", (job, err) =>
|
consolidateWorker.on("failed", (job, err) =>
|
||||||
logger.log(`app-queue-consolidation-failed:`, "ERROR", "notifications", "api", {
|
logger.log("app-queue-consolidation-failed", "ERROR", "notifications", "api", {
|
||||||
message: err?.message,
|
message: err?.message,
|
||||||
stack: err?.stack
|
stack: err?.stack
|
||||||
})
|
})
|
||||||
@@ -285,11 +358,13 @@ const dispatchAppsToQueue = async ({ appsToDispatch }) => {
|
|||||||
|
|
||||||
for (const app of appsToDispatch) {
|
for (const app of appsToDispatch) {
|
||||||
const { jobId, bodyShopId, key, variables, recipients, body, jobRoNumber } = app;
|
const { jobId, bodyShopId, key, variables, recipients, body, jobRoNumber } = app;
|
||||||
|
|
||||||
await appQueue.add(
|
await appQueue.add(
|
||||||
"add-notification",
|
"add-notification",
|
||||||
{ jobId, bodyShopId, key, variables, recipients, body, jobRoNumber },
|
{ jobId, bodyShopId, key, variables, recipients, body, jobRoNumber },
|
||||||
{ jobId: `${jobId}-${Date.now()}` }
|
{ jobId: `${jobId}-${Date.now()}` }
|
||||||
);
|
);
|
||||||
|
|
||||||
devDebugLogger(`Added notification to queue for jobId ${jobId} with ${recipients.length} recipients`);
|
devDebugLogger(`Added notification to queue for jobId ${jobId} with ${recipients.length} recipients`);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -27,6 +27,16 @@ let emailConsolidateQueue;
|
|||||||
let emailAddWorker;
|
let emailAddWorker;
|
||||||
let emailConsolidateWorker;
|
let emailConsolidateWorker;
|
||||||
|
|
||||||
|
const seconds = (ms) => Math.max(1, Math.ceil(ms / 1000));
|
||||||
|
|
||||||
|
const escapeHtml = (s = "") =>
|
||||||
|
String(s)
|
||||||
|
.replace(/&/g, "&")
|
||||||
|
.replace(/</g, "<")
|
||||||
|
.replace(/>/g, ">")
|
||||||
|
.replace(/"/g, """)
|
||||||
|
.replace(/'/g, "'");
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initializes the email notification queues and workers.
|
* Initializes the email notification queues and workers.
|
||||||
*
|
*
|
||||||
@@ -65,17 +75,21 @@ const loadEmailQueue = async ({ pubClient, logger }) => {
|
|||||||
|
|
||||||
const redisKeyPrefix = `email:${devKey}:notifications:${jobId}`;
|
const redisKeyPrefix = `email:${devKey}:notifications:${jobId}`;
|
||||||
|
|
||||||
for (const recipient of recipients) {
|
for (const recipient of recipients || []) {
|
||||||
const { user, firstName, lastName } = recipient;
|
const { user, firstName, lastName } = recipient;
|
||||||
|
if (!user) continue;
|
||||||
const userKey = `${redisKeyPrefix}:${user}`;
|
const userKey = `${redisKeyPrefix}:${user}`;
|
||||||
await pubClient.rpush(userKey, body);
|
await pubClient.rpush(userKey, body);
|
||||||
await pubClient.expire(userKey, NOTIFICATION_EXPIRATION / 1000);
|
await pubClient.expire(userKey, seconds(NOTIFICATION_EXPIRATION));
|
||||||
const detailsKey = `email:${devKey}:recipientDetails:${jobId}:${user}`;
|
const detailsKey = `email:${devKey}:recipientDetails:${jobId}:${user}`;
|
||||||
await pubClient.hsetnx(detailsKey, "firstName", firstName || "");
|
await pubClient.hsetnx(detailsKey, "firstName", firstName || "");
|
||||||
await pubClient.hsetnx(detailsKey, "lastName", lastName || "");
|
await pubClient.hsetnx(detailsKey, "lastName", lastName || "");
|
||||||
await pubClient.hsetnx(detailsKey, "bodyShopTimezone", bodyShopTimezone);
|
const tzValue = bodyShopTimezone || "UTC";
|
||||||
await pubClient.expire(detailsKey, NOTIFICATION_EXPIRATION / 1000);
|
await pubClient.hsetnx(detailsKey, "bodyShopTimezone", tzValue);
|
||||||
await pubClient.sadd(`email:${devKey}:recipients:${jobId}`, user);
|
await pubClient.expire(detailsKey, seconds(NOTIFICATION_EXPIRATION));
|
||||||
|
const recipientsSetKey = `email:${devKey}:recipients:${jobId}`;
|
||||||
|
await pubClient.sadd(recipientsSetKey, user);
|
||||||
|
await pubClient.expire(recipientsSetKey, seconds(NOTIFICATION_EXPIRATION));
|
||||||
devDebugLogger(`Stored message for ${user} under ${userKey}: ${body}`);
|
devDebugLogger(`Stored message for ${user} under ${userKey}: ${body}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,7 +107,7 @@ const loadEmailQueue = async ({ pubClient, logger }) => {
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
devDebugLogger(`Scheduled email consolidation for jobId ${jobId}`);
|
devDebugLogger(`Scheduled email consolidation for jobId ${jobId}`);
|
||||||
await pubClient.expire(consolidateKey, CONSOLIDATION_KEY_EXPIRATION / 1000);
|
await pubClient.expire(consolidateKey, seconds(CONSOLIDATION_KEY_EXPIRATION));
|
||||||
} else {
|
} else {
|
||||||
devDebugLogger(`Email consolidation already scheduled for jobId ${jobId}`);
|
devDebugLogger(`Email consolidation already scheduled for jobId ${jobId}`);
|
||||||
}
|
}
|
||||||
@@ -113,7 +127,7 @@ const loadEmailQueue = async ({ pubClient, logger }) => {
|
|||||||
devDebugLogger(`Consolidating emails for jobId ${jobId}`);
|
devDebugLogger(`Consolidating emails for jobId ${jobId}`);
|
||||||
|
|
||||||
const lockKey = `lock:${devKey}:emailConsolidate:${jobId}`;
|
const lockKey = `lock:${devKey}:emailConsolidate:${jobId}`;
|
||||||
const lockAcquired = await pubClient.set(lockKey, "locked", "NX", "EX", LOCK_EXPIRATION / 1000);
|
const lockAcquired = await pubClient.set(lockKey, "locked", "NX", "EX", seconds(LOCK_EXPIRATION));
|
||||||
if (lockAcquired) {
|
if (lockAcquired) {
|
||||||
try {
|
try {
|
||||||
const recipientsSet = `email:${devKey}:recipients:${jobId}`;
|
const recipientsSet = `email:${devKey}:recipients:${jobId}`;
|
||||||
@@ -139,7 +153,7 @@ const loadEmailQueue = async ({ pubClient, logger }) => {
|
|||||||
<table class="row" style="border-spacing: 0; border-collapse: collapse; padding-top: 0; padding-right: 0; padding-bottom: 0; padding-left: 0; vertical-align: top; text-align: left; font-family: 'Montserrat', 'Montserrat Alternates', sans-serif; padding: 0; width: 100%; position: relative; display: table;"><tbody style="font-family: 'Montserrat', 'Montserrat Alternates', sans-serif; display: table-row-group;"><tr style="padding-top: 0; padding-right: 0; padding-bottom: 0; padding-left: 0; vertical-align: top; text-align: left; font-family: 'Montserrat', 'Montserrat Alternates', sans-serif;">
|
<table class="row" style="border-spacing: 0; border-collapse: collapse; padding-top: 0; padding-right: 0; padding-bottom: 0; padding-left: 0; vertical-align: top; text-align: left; font-family: 'Montserrat', 'Montserrat Alternates', sans-serif; padding: 0; width: 100%; position: relative; display: table;"><tbody style="font-family: 'Montserrat', 'Montserrat Alternates', sans-serif; display: table-row-group;"><tr style="padding-top: 0; padding-right: 0; padding-bottom: 0; padding-left: 0; vertical-align: top; text-align: left; font-family: 'Montserrat', 'Montserrat Alternates', sans-serif;">
|
||||||
<th class="small-12 large-12 columns first last" style="word-wrap: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; vertical-align: top; color: #0a0a0a; font-weight: normal; padding-top: 0; text-align: left; font-family: 'Montserrat', 'Montserrat Alternates', sans-serif; font-size: 15px; line-height: 1.2; margin: 0 auto; Margin: 0 auto; padding-bottom: 16px; width: 734px; padding-left: 8px; padding-right: 8px; border-collapse: collapse;"><table style="border-spacing: 0; border-collapse: collapse; padding-top: 0; padding-right: 0; padding-bottom: 0; padding-left: 0; vertical-align: top; text-align: left; font-family: 'Montserrat', 'Montserrat Alternates', sans-serif; width: 100%;"><tr style="padding-top: 0; padding-right: 0; padding-bottom: 0; padding-left: 0; vertical-align: top; text-align: left; font-family: 'Montserrat', 'Montserrat Alternates', sans-serif;"><td style="word-wrap: break-word; vertical-align: top; color: #0a0a0a; font-weight: normal; padding-top: 0; padding-right: 0; padding-bottom: 0; padding-left: 0; margin: 0; Margin: 0; text-align: left; font-family: 'Montserrat', 'Montserrat Alternates', sans-serif; font-size: 15px; word-break: keep-all; -moz-hyphens: none; -ms-hyphens: none; -webkit-hyphens: none; hyphens: none; line-height: 1.2; border-collapse: collapse;">
|
<th class="small-12 large-12 columns first last" style="word-wrap: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; vertical-align: top; color: #0a0a0a; font-weight: normal; padding-top: 0; text-align: left; font-family: 'Montserrat', 'Montserrat Alternates', sans-serif; font-size: 15px; line-height: 1.2; margin: 0 auto; Margin: 0 auto; padding-bottom: 16px; width: 734px; padding-left: 8px; padding-right: 8px; border-collapse: collapse;"><table style="border-spacing: 0; border-collapse: collapse; padding-top: 0; padding-right: 0; padding-bottom: 0; padding-left: 0; vertical-align: top; text-align: left; font-family: 'Montserrat', 'Montserrat Alternates', sans-serif; width: 100%;"><tr style="padding-top: 0; padding-right: 0; padding-bottom: 0; padding-left: 0; vertical-align: top; text-align: left; font-family: 'Montserrat', 'Montserrat Alternates', sans-serif;"><td style="word-wrap: break-word; vertical-align: top; color: #0a0a0a; font-weight: normal; padding-top: 0; padding-right: 0; padding-bottom: 0; padding-left: 0; margin: 0; Margin: 0; text-align: left; font-family: 'Montserrat', 'Montserrat Alternates', sans-serif; font-size: 15px; word-break: keep-all; -moz-hyphens: none; -ms-hyphens: none; -webkit-hyphens: none; hyphens: none; line-height: 1.2; border-collapse: collapse;">
|
||||||
<ul style="font-family: 'Montserrat', 'Montserrat Alternates', sans-serif; margin: 1%; padding-left: 30px;">
|
<ul style="font-family: 'Montserrat', 'Montserrat Alternates', sans-serif; margin: 1%; padding-left: 30px;">
|
||||||
${messages.map((msg) => `<li style="font-family: 'Montserrat', 'Montserrat Alternates', sans-serif; font-size: 90%;">${msg}</li>`).join("")}
|
${messages.map((msg) => `<li style="font-family: 'Montserrat', 'Montserrat Alternates', sans-serif; font-size: 90%;">${escapeHtml(msg)}</li>`).join("")}
|
||||||
</ul>
|
</ul>
|
||||||
</td></tr></table></th>
|
</td></tr></table></th>
|
||||||
</tr><tbody></table>
|
</tr><tbody></table>
|
||||||
@@ -239,7 +253,13 @@ const dispatchEmailsToQueue = async ({ emailsToDispatch, logger }) => {
|
|||||||
const emailAddQueue = getQueue();
|
const emailAddQueue = getQueue();
|
||||||
|
|
||||||
for (const email of emailsToDispatch) {
|
for (const email of emailsToDispatch) {
|
||||||
const { jobId, jobRoNumber, bodyShopName, bodyShopTimezone, body, recipients } = email;
|
const { jobId, bodyShopName, bodyShopTimezone, body, recipients } = email;
|
||||||
|
let { jobRoNumber } = email;
|
||||||
|
|
||||||
|
// Make sure Jobs that have not been coverted yet can still get notifications
|
||||||
|
if (jobRoNumber === null) {
|
||||||
|
jobRoNumber = "N/A";
|
||||||
|
}
|
||||||
|
|
||||||
if (!jobId || !jobRoNumber || !bodyShopName || !body || !recipients.length) {
|
if (!jobId || !jobRoNumber || !bodyShopName || !body || !recipients.length) {
|
||||||
devDebugLogger(
|
devDebugLogger(
|
||||||
|
|||||||
569
server/notifications/queues/fcmQueue.js
Normal file
569
server/notifications/queues/fcmQueue.js
Normal file
@@ -0,0 +1,569 @@
|
|||||||
|
// NOTE: Despite the filename, this implementation targets Expo Push Tokens (ExponentPushToken[...]).
|
||||||
|
// It does NOT use Firebase Admin and does NOT require credentials (no EXPO_ACCESS_TOKEN).
|
||||||
|
|
||||||
|
const { Queue, Worker } = require("bullmq");
|
||||||
|
const { registerCleanupTask } = require("../../utils/cleanupManager");
|
||||||
|
const getBullMQPrefix = require("../../utils/getBullMQPrefix");
|
||||||
|
const devDebugLogger = require("../../utils/devDebugLogger");
|
||||||
|
|
||||||
|
const { client: gqlClient } = require("../../graphql-client/graphql-client");
|
||||||
|
const { GET_USERS_FCM_TOKENS_BY_EMAILS, UPDATE_USER_FCM_TOKENS_BY_EMAIL } = require("../../graphql-client/queries");
|
||||||
|
|
||||||
|
const FCM_CONSOLIDATION_DELAY_IN_MINS = (() => {
|
||||||
|
const envValue = process.env?.FCM_CONSOLIDATION_DELAY_IN_MINS;
|
||||||
|
const parsedValue = envValue ? parseInt(envValue, 10) : NaN;
|
||||||
|
return isNaN(parsedValue) ? 3 : Math.max(1, parsedValue);
|
||||||
|
})();
|
||||||
|
|
||||||
|
const FCM_CONSOLIDATION_DELAY = FCM_CONSOLIDATION_DELAY_IN_MINS * 60000;
|
||||||
|
|
||||||
|
// pegged constants (pattern matches your other queues)
|
||||||
|
const CONSOLIDATION_KEY_EXPIRATION = FCM_CONSOLIDATION_DELAY * 1.5;
|
||||||
|
|
||||||
|
// IMPORTANT: lock must outlive a full consolidation run to avoid duplicate sends.
|
||||||
|
const LOCK_EXPIRATION = FCM_CONSOLIDATION_DELAY * 1.5;
|
||||||
|
|
||||||
|
// Keep Bull backoff separate from lock TTL to avoid unexpected long retries.
|
||||||
|
const BACKOFF_DELAY = Math.max(1000, Math.floor(FCM_CONSOLIDATION_DELAY * 0.25));
|
||||||
|
|
||||||
|
const RATE_LIMITER_DURATION = FCM_CONSOLIDATION_DELAY * 0.1;
|
||||||
|
const NOTIFICATION_EXPIRATION = FCM_CONSOLIDATION_DELAY * 1.5;
|
||||||
|
|
||||||
|
const EXPO_PUSH_ENDPOINT = "https://exp.host/--/api/v2/push/send";
|
||||||
|
const EXPO_MAX_MESSAGES_PER_REQUEST = 100;
|
||||||
|
|
||||||
|
let fcmAddQueue;
|
||||||
|
let fcmConsolidateQueue;
|
||||||
|
let fcmAddWorker;
|
||||||
|
let fcmConsolidateWorker;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Milliseconds to seconds.
|
||||||
|
* @param ms
|
||||||
|
* @returns {number}
|
||||||
|
*/
|
||||||
|
const seconds = (ms) => Math.max(1, Math.ceil(ms / 1000));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Chunk an array into smaller arrays of given size.
|
||||||
|
* @param arr
|
||||||
|
* @param size
|
||||||
|
* @returns {*[]}
|
||||||
|
*/
|
||||||
|
const chunk = (arr, size) => {
|
||||||
|
const out = [];
|
||||||
|
for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size));
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if a string is an Expo push token.
|
||||||
|
* @param s
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
const isExpoPushToken = (s) => {
|
||||||
|
if (!s || typeof s !== "string") return false;
|
||||||
|
// Common formats observed in the wild:
|
||||||
|
// - ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]
|
||||||
|
// - ExpoPushToken[xxxxxxxxxxxxxxxxxxxxxx]
|
||||||
|
return /^ExponentPushToken\[[^\]]+\]$/.test(s) || /^ExpoPushToken\[[^\]]+\]$/.test(s);
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get unique, trimmed strings from an array.
|
||||||
|
* @param arr
|
||||||
|
* @returns {any[]}
|
||||||
|
*/
|
||||||
|
const uniqStrings = (arr) => [
|
||||||
|
...new Set(
|
||||||
|
arr
|
||||||
|
.filter(Boolean)
|
||||||
|
.map((x) => String(x).trim())
|
||||||
|
.filter(Boolean)
|
||||||
|
)
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Normalize users.fcmtokens (jsonb) into an array of Expo push tokens.
|
||||||
|
*
|
||||||
|
* New expected shape (example):
|
||||||
|
* {
|
||||||
|
* "ExponentPushToken[dksJAdLUTofdEk7P59thue]": {
|
||||||
|
* "platform": "ios",
|
||||||
|
* "timestamp": 1767397802709,
|
||||||
|
* "pushTokenString": "ExponentPushToken[dksJAdLUTofdEk7P59thue]"
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* Also supports older/alternate shapes:
|
||||||
|
* - string: "ExponentPushToken[...]"
|
||||||
|
* - array: ["ExponentPushToken[...]", ...]
|
||||||
|
* - object: token keys OR values containing token-like fields
|
||||||
|
* @param fcmtokens
|
||||||
|
* @returns {string[]|*[]}
|
||||||
|
*/
|
||||||
|
const normalizeTokens = (fcmtokens) => {
|
||||||
|
if (!fcmtokens) return [];
|
||||||
|
|
||||||
|
if (typeof fcmtokens === "string") {
|
||||||
|
const s = fcmtokens.trim();
|
||||||
|
return isExpoPushToken(s) ? [s] : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Array.isArray(fcmtokens)) {
|
||||||
|
return uniqStrings(fcmtokens).filter(isExpoPushToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof fcmtokens === "object") {
|
||||||
|
const keys = Object.keys(fcmtokens || {});
|
||||||
|
const vals = Object.values(fcmtokens || {});
|
||||||
|
|
||||||
|
const fromKeys = keys.filter(isExpoPushToken);
|
||||||
|
|
||||||
|
const fromValues = vals
|
||||||
|
.map((v) => {
|
||||||
|
if (!v) return null;
|
||||||
|
|
||||||
|
// Some shapes store token as a string value directly
|
||||||
|
if (typeof v === "string") return v;
|
||||||
|
|
||||||
|
if (typeof v === "object") {
|
||||||
|
// Your new shape uses pushTokenString
|
||||||
|
return v.pushTokenString || v.token || v.expoPushToken || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
})
|
||||||
|
.filter(Boolean)
|
||||||
|
.map(String);
|
||||||
|
|
||||||
|
return uniqStrings([...fromKeys, ...fromValues]).filter(isExpoPushToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
return [];
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove specified tokens from the stored fcmtokens jsonb while preserving the original shape.
|
||||||
|
* @param fcmtokens
|
||||||
|
* @param tokensToRemove
|
||||||
|
* @returns {*}
|
||||||
|
*/
|
||||||
|
const removeTokensFromFcmtokens = (fcmtokens, tokensToRemove) => {
|
||||||
|
const remove = new Set((tokensToRemove || []).map((t) => String(t).trim()).filter(Boolean));
|
||||||
|
if (!remove.size) return fcmtokens;
|
||||||
|
if (!fcmtokens) return fcmtokens;
|
||||||
|
|
||||||
|
if (typeof fcmtokens === "string") {
|
||||||
|
const s = fcmtokens.trim();
|
||||||
|
return remove.has(s) ? null : fcmtokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Array.isArray(fcmtokens)) {
|
||||||
|
const next = fcmtokens.filter((t) => !remove.has(String(t).trim()));
|
||||||
|
return next.length ? next : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof fcmtokens === "object") {
|
||||||
|
const next = {};
|
||||||
|
for (const [k, v] of Object.entries(fcmtokens)) {
|
||||||
|
const keyIsToken = isExpoPushToken(k) && remove.has(k);
|
||||||
|
|
||||||
|
let valueToken = null;
|
||||||
|
if (typeof v === "string") valueToken = v;
|
||||||
|
else if (v && typeof v === "object") valueToken = v.pushTokenString || v.token || v.expoPushToken || null;
|
||||||
|
|
||||||
|
const valueIsToken = valueToken && remove.has(String(valueToken).trim());
|
||||||
|
|
||||||
|
if (keyIsToken || valueIsToken) continue;
|
||||||
|
next[k] = v;
|
||||||
|
}
|
||||||
|
return Object.keys(next).length ? next : {};
|
||||||
|
}
|
||||||
|
|
||||||
|
return fcmtokens;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Safely parse JSON response.
|
||||||
|
* @param res
|
||||||
|
* @returns {Promise<*|null>}
|
||||||
|
*/
|
||||||
|
const safeJson = async (res) => {
|
||||||
|
try {
|
||||||
|
return await res.json();
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send Expo push notifications.
|
||||||
|
* Returns invalid tokens that should be removed (e.g., DeviceNotRegistered).
|
||||||
|
*
|
||||||
|
* @param {Array<Object>} messages Expo messages array
|
||||||
|
* @param {Object} logger
|
||||||
|
* @returns {Promise<{invalidTokens: string[], ticketIds: string[]}>}
|
||||||
|
*/
|
||||||
|
const sendExpoPush = async ({ messages, logger }) => {
|
||||||
|
if (!messages?.length) return { invalidTokens: [], ticketIds: [] };
|
||||||
|
|
||||||
|
const invalidTokens = new Set();
|
||||||
|
const ticketIds = [];
|
||||||
|
|
||||||
|
for (const batch of chunk(messages, EXPO_MAX_MESSAGES_PER_REQUEST)) {
|
||||||
|
const res = await fetch(EXPO_PUSH_ENDPOINT, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
accept: "application/json",
|
||||||
|
"content-type": "application/json"
|
||||||
|
},
|
||||||
|
body: JSON.stringify(batch)
|
||||||
|
});
|
||||||
|
|
||||||
|
const payload = await safeJson(res);
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
logger?.log?.("expo-push-http-error", "ERROR", "notifications", "api", {
|
||||||
|
status: res.status,
|
||||||
|
statusText: res.statusText,
|
||||||
|
payload
|
||||||
|
});
|
||||||
|
throw new Error(`Expo push HTTP error: ${res.status} ${res.statusText}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const tickets = Array.isArray(payload?.data) ? payload.data : payload?.data ? [payload.data] : [];
|
||||||
|
|
||||||
|
if (!tickets.length) {
|
||||||
|
logger?.log?.("expo-push-bad-response", "ERROR", "notifications", "api", { payload });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Expo returns tickets in the same order as messages in the request batch
|
||||||
|
for (let i = 0; i < tickets.length; i++) {
|
||||||
|
const t = tickets[i];
|
||||||
|
const msg = batch[i];
|
||||||
|
const token = typeof msg?.to === "string" ? msg.to : null;
|
||||||
|
|
||||||
|
if (t?.status === "ok" && t?.id) ticketIds.push(String(t.id));
|
||||||
|
|
||||||
|
if (t?.status === "error") {
|
||||||
|
const errCode = t?.details?.error;
|
||||||
|
const msgText = String(t?.message || "");
|
||||||
|
|
||||||
|
const shouldDelete =
|
||||||
|
errCode === "DeviceNotRegistered" || /not a registered push notification recipient/i.test(msgText);
|
||||||
|
|
||||||
|
if (shouldDelete && token && isExpoPushToken(token)) {
|
||||||
|
invalidTokens.add(token);
|
||||||
|
}
|
||||||
|
|
||||||
|
logger?.log?.("expo-push-ticket-error", "ERROR", "notifications", "api", {
|
||||||
|
token,
|
||||||
|
ticket: t
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { invalidTokens: [...invalidTokens], ticketIds };
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build a summary string for push notification body.
|
||||||
|
* @param count
|
||||||
|
* @param jobRoNumber
|
||||||
|
* @param bodyShopName
|
||||||
|
* @returns {`${string} ${string} for ${string|string}${string|string}`}
|
||||||
|
*/
|
||||||
|
const buildPushSummary = ({ count, jobRoNumber, bodyShopName }) => {
|
||||||
|
const updates = count === 1 ? "update" : "updates";
|
||||||
|
const ro = jobRoNumber ? `RO ${jobRoNumber}` : "a job";
|
||||||
|
const shop = bodyShopName ? ` at ${bodyShopName}` : "";
|
||||||
|
return `${count} ${updates} for ${ro}${shop}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Loads the push notification queues and workers (Expo push).
|
||||||
|
* @param pubClient
|
||||||
|
* @param logger
|
||||||
|
* @returns {Promise<Queue|null>}
|
||||||
|
*/
|
||||||
|
const loadFcmQueue = async ({ pubClient, logger }) => {
|
||||||
|
if (!fcmAddQueue || !fcmConsolidateQueue) {
|
||||||
|
const prefix = getBullMQPrefix();
|
||||||
|
const devKey = process.env?.NODE_ENV === "production" ? "prod" : "dev";
|
||||||
|
|
||||||
|
devDebugLogger(`Initializing Expo Push Queues with prefix: ${prefix}`);
|
||||||
|
|
||||||
|
fcmAddQueue = new Queue("fcmAdd", {
|
||||||
|
prefix,
|
||||||
|
connection: pubClient,
|
||||||
|
defaultJobOptions: { removeOnComplete: true, removeOnFail: true }
|
||||||
|
});
|
||||||
|
|
||||||
|
fcmConsolidateQueue = new Queue("fcmConsolidate", {
|
||||||
|
prefix,
|
||||||
|
connection: pubClient,
|
||||||
|
defaultJobOptions: { removeOnComplete: true, removeOnFail: true }
|
||||||
|
});
|
||||||
|
|
||||||
|
fcmAddWorker = new Worker(
|
||||||
|
"fcmAdd",
|
||||||
|
async (job) => {
|
||||||
|
const { jobId, jobRoNumber, bodyShopId, bodyShopName, scenarioKey, key, variables, body, recipients } =
|
||||||
|
job.data;
|
||||||
|
|
||||||
|
devDebugLogger(`Adding push notifications for jobId ${jobId}`);
|
||||||
|
|
||||||
|
const recipientsSetKey = `fcm:${devKey}:recipients:${jobId}`; // set of user emails
|
||||||
|
const metaKey = `fcm:${devKey}:meta:${jobId}`;
|
||||||
|
const redisKeyPrefix = `fcm:${devKey}:notifications:${jobId}`; // per-user list keys
|
||||||
|
|
||||||
|
// Store job-level metadata (always keep latest values)
|
||||||
|
await pubClient.hset(metaKey, "jobRoNumber", jobRoNumber || "");
|
||||||
|
await pubClient.hset(metaKey, "bodyShopId", bodyShopId || "");
|
||||||
|
await pubClient.hset(metaKey, "bodyShopName", bodyShopName || "");
|
||||||
|
await pubClient.expire(metaKey, seconds(NOTIFICATION_EXPIRATION));
|
||||||
|
|
||||||
|
for (const r of recipients || []) {
|
||||||
|
const user = r?.user;
|
||||||
|
const associationId = r?.associationId;
|
||||||
|
|
||||||
|
if (!user) continue;
|
||||||
|
|
||||||
|
const userKey = `${redisKeyPrefix}:${user}`;
|
||||||
|
const payload = JSON.stringify({
|
||||||
|
body: body || "",
|
||||||
|
scenarioKey: scenarioKey || "",
|
||||||
|
key: key || "",
|
||||||
|
variables: variables || {},
|
||||||
|
associationId: associationId ? String(associationId) : null,
|
||||||
|
ts: Date.now()
|
||||||
|
});
|
||||||
|
|
||||||
|
await pubClient.rpush(userKey, payload);
|
||||||
|
await pubClient.expire(userKey, seconds(NOTIFICATION_EXPIRATION));
|
||||||
|
|
||||||
|
await pubClient.sadd(recipientsSetKey, user);
|
||||||
|
await pubClient.expire(recipientsSetKey, seconds(NOTIFICATION_EXPIRATION));
|
||||||
|
}
|
||||||
|
|
||||||
|
const consolidateKey = `fcm:${devKey}:consolidate:${jobId}`;
|
||||||
|
const flagSet = await pubClient.setnx(consolidateKey, "pending");
|
||||||
|
|
||||||
|
if (flagSet) {
|
||||||
|
await fcmConsolidateQueue.add(
|
||||||
|
"consolidate-fcm",
|
||||||
|
{ jobId },
|
||||||
|
{
|
||||||
|
jobId: `consolidate-${jobId}`,
|
||||||
|
delay: FCM_CONSOLIDATION_DELAY,
|
||||||
|
attempts: 3,
|
||||||
|
backoff: BACKOFF_DELAY
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
await pubClient.expire(consolidateKey, seconds(CONSOLIDATION_KEY_EXPIRATION));
|
||||||
|
devDebugLogger(`Scheduled consolidation for jobId ${jobId}`);
|
||||||
|
} else {
|
||||||
|
devDebugLogger(`Consolidation already scheduled for jobId ${jobId}`);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ prefix, connection: pubClient, concurrency: 5 }
|
||||||
|
);
|
||||||
|
|
||||||
|
fcmConsolidateWorker = new Worker(
|
||||||
|
"fcmConsolidate",
|
||||||
|
async (job) => {
|
||||||
|
const { jobId } = job.data;
|
||||||
|
const devKey = process.env?.NODE_ENV === "production" ? "prod" : "dev";
|
||||||
|
|
||||||
|
const lockKey = `lock:${devKey}:fcmConsolidate:${jobId}`;
|
||||||
|
const lockAcquired = await pubClient.set(lockKey, "locked", "NX", "EX", seconds(LOCK_EXPIRATION));
|
||||||
|
|
||||||
|
if (!lockAcquired) {
|
||||||
|
devDebugLogger(`Skipped consolidation for jobId ${jobId} - lock held by another worker`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const recipientsSet = `fcm:${devKey}:recipients:${jobId}`;
|
||||||
|
const userEmails = await pubClient.smembers(recipientsSet);
|
||||||
|
|
||||||
|
if (!userEmails?.length) {
|
||||||
|
devDebugLogger(`No recipients found for jobId ${jobId}`);
|
||||||
|
await pubClient.del(`fcm:${devKey}:consolidate:${jobId}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load meta
|
||||||
|
const metaKey = `fcm:${devKey}:meta:${jobId}`;
|
||||||
|
const meta = await pubClient.hgetall(metaKey);
|
||||||
|
const jobRoNumber = meta?.jobRoNumber || "";
|
||||||
|
const bodyShopId = meta?.bodyShopId || "";
|
||||||
|
const bodyShopName = meta?.bodyShopName || "";
|
||||||
|
|
||||||
|
// Fetch tokens for all recipients (1 DB round-trip)
|
||||||
|
const usersResp = await gqlClient.request(GET_USERS_FCM_TOKENS_BY_EMAILS, { emails: userEmails });
|
||||||
|
|
||||||
|
// Map: email -> { raw, tokens }
|
||||||
|
const tokenMap = new Map(
|
||||||
|
(usersResp?.users || []).map((u) => [
|
||||||
|
String(u.email),
|
||||||
|
{ raw: u.fcmtokens, tokens: normalizeTokens(u.fcmtokens) }
|
||||||
|
])
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const userEmail of userEmails) {
|
||||||
|
const userKey = `fcm:${devKey}:notifications:${jobId}:${userEmail}`;
|
||||||
|
const raw = await pubClient.lrange(userKey, 0, -1);
|
||||||
|
|
||||||
|
if (!raw?.length) {
|
||||||
|
await pubClient.del(userKey);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsed = raw
|
||||||
|
.map((x) => {
|
||||||
|
try {
|
||||||
|
return JSON.parse(x);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.filter(Boolean);
|
||||||
|
|
||||||
|
const count = parsed.length;
|
||||||
|
const notificationBody = buildPushSummary({ count, jobRoNumber, bodyShopName });
|
||||||
|
|
||||||
|
// associationId should be stable for a user in a job’s bodyshop; take first non-null
|
||||||
|
const firstWithAssociation = parsed.find((p) => p?.associationId != null);
|
||||||
|
const associationId =
|
||||||
|
firstWithAssociation?.associationId != null ? String(firstWithAssociation.associationId) : "";
|
||||||
|
|
||||||
|
const tokenInfo = tokenMap.get(String(userEmail)) || { raw: null, tokens: [] };
|
||||||
|
const tokens = tokenInfo.tokens || [];
|
||||||
|
|
||||||
|
if (!tokens.length) {
|
||||||
|
devDebugLogger(`No Expo push tokens for ${userEmail}; skipping push for jobId ${jobId}`);
|
||||||
|
await pubClient.del(userKey);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build 1 message per device token
|
||||||
|
const messages = tokens.map((token) => ({
|
||||||
|
to: token,
|
||||||
|
title: "ImEX Online",
|
||||||
|
body: notificationBody,
|
||||||
|
priority: "high",
|
||||||
|
data: {
|
||||||
|
type: "job-notification",
|
||||||
|
jobId: String(jobId),
|
||||||
|
jobRoNumber: String(jobRoNumber || ""),
|
||||||
|
bodyShopId: String(bodyShopId || ""),
|
||||||
|
bodyShopName: String(bodyShopName || ""),
|
||||||
|
associationId: String(associationId || ""),
|
||||||
|
userEmail: String(userEmail),
|
||||||
|
count: String(count)
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
const { invalidTokens } = await sendExpoPush({ messages, logger });
|
||||||
|
|
||||||
|
// Opportunistic cleanup: remove invalid tokens from users.fcmtokens
|
||||||
|
if (invalidTokens?.length) {
|
||||||
|
try {
|
||||||
|
const nextFcmtokens = removeTokensFromFcmtokens(tokenInfo.raw, invalidTokens);
|
||||||
|
|
||||||
|
await gqlClient.request(UPDATE_USER_FCM_TOKENS_BY_EMAIL, {
|
||||||
|
email: String(userEmail),
|
||||||
|
fcmtokens: nextFcmtokens
|
||||||
|
});
|
||||||
|
|
||||||
|
devDebugLogger(`Cleaned ${invalidTokens.length} invalid Expo tokens for ${userEmail}`);
|
||||||
|
} catch (e) {
|
||||||
|
logger?.log?.("expo-push-token-cleanup-failed", "ERROR", "notifications", "api", {
|
||||||
|
userEmail: String(userEmail),
|
||||||
|
message: e?.message,
|
||||||
|
stack: e?.stack
|
||||||
|
});
|
||||||
|
// Do not throw: cleanup failure should not retry the whole consolidation and risk duplicate pushes.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
devDebugLogger(`Sent Expo push to ${userEmail} for jobId ${jobId} (${count} updates)`);
|
||||||
|
|
||||||
|
await pubClient.del(userKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
await pubClient.del(recipientsSet);
|
||||||
|
await pubClient.del(metaKey);
|
||||||
|
await pubClient.del(`fcm:${devKey}:consolidate:${jobId}`);
|
||||||
|
} catch (err) {
|
||||||
|
logger.log("fcm-queue-consolidation-error", "ERROR", "notifications", "api", {
|
||||||
|
message: err?.message,
|
||||||
|
stack: err?.stack
|
||||||
|
});
|
||||||
|
throw err;
|
||||||
|
} finally {
|
||||||
|
await pubClient.del(lockKey);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ prefix, connection: pubClient, concurrency: 1, limiter: { max: 1, duration: RATE_LIMITER_DURATION } }
|
||||||
|
);
|
||||||
|
|
||||||
|
fcmAddWorker.on("failed", (job, err) =>
|
||||||
|
logger.log("fcm-add-failed", "ERROR", "notifications", "api", { message: err?.message, stack: err?.stack })
|
||||||
|
);
|
||||||
|
|
||||||
|
fcmConsolidateWorker.on("failed", (job, err) =>
|
||||||
|
logger.log("fcm-consolidate-failed", "ERROR", "notifications", "api", {
|
||||||
|
message: err?.message,
|
||||||
|
stack: err?.stack
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
const shutdown = async () => {
|
||||||
|
devDebugLogger("Closing push queue workers...");
|
||||||
|
await Promise.all([fcmAddWorker.close(), fcmConsolidateWorker.close()]);
|
||||||
|
devDebugLogger("Push queue workers closed");
|
||||||
|
};
|
||||||
|
|
||||||
|
registerCleanupTask(shutdown);
|
||||||
|
}
|
||||||
|
|
||||||
|
return fcmAddQueue;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the add queue.
|
||||||
|
* @returns {*}
|
||||||
|
*/
|
||||||
|
const getQueue = () => {
|
||||||
|
if (!fcmAddQueue) throw new Error("FCM add queue not initialized. Ensure loadFcmQueue is called during bootstrap.");
|
||||||
|
return fcmAddQueue;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dispatch push notifications to the add queue.
|
||||||
|
* @param fcmsToDispatch
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
const dispatchFcmsToQueue = async ({ fcmsToDispatch }) => {
|
||||||
|
const queue = getQueue();
|
||||||
|
|
||||||
|
for (const fcm of fcmsToDispatch) {
|
||||||
|
const { jobId, jobRoNumber, bodyShopId, bodyShopName, scenarioKey, key, variables, body, recipients } = fcm;
|
||||||
|
|
||||||
|
if (!jobId || !recipients?.length) continue;
|
||||||
|
|
||||||
|
await queue.add(
|
||||||
|
"add-fcm-notification",
|
||||||
|
{ jobId, jobRoNumber, bodyShopId, bodyShopName, scenarioKey, key, variables, body, recipients },
|
||||||
|
{ jobId: `${jobId}-${Date.now()}` }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = { loadFcmQueue, getQueue, dispatchFcmsToQueue };
|
||||||
@@ -19,6 +19,8 @@ const buildNotification = (data, key, body, variables = {}) => {
|
|||||||
jobId: data.jobId,
|
jobId: data.jobId,
|
||||||
jobRoNumber: data.jobRoNumber,
|
jobRoNumber: data.jobRoNumber,
|
||||||
bodyShopId: data.bodyShopId,
|
bodyShopId: data.bodyShopId,
|
||||||
|
scenarioKey: data.scenarioKey,
|
||||||
|
scenarioTable: data.scenarioTable,
|
||||||
key,
|
key,
|
||||||
body,
|
body,
|
||||||
variables,
|
variables,
|
||||||
@@ -32,21 +34,47 @@ const buildNotification = (data, key, body, variables = {}) => {
|
|||||||
body,
|
body,
|
||||||
recipients: []
|
recipients: []
|
||||||
},
|
},
|
||||||
fcm: { recipients: [] }
|
fcm: {
|
||||||
|
jobId: data.jobId,
|
||||||
|
jobRoNumber: data.jobRoNumber,
|
||||||
|
bodyShopId: data.bodyShopId,
|
||||||
|
bodyShopName: data.bodyShopName,
|
||||||
|
bodyShopTimezone: data.bodyShopTimezone,
|
||||||
|
scenarioKey: data.scenarioKey,
|
||||||
|
scenarioTable: data.scenarioTable,
|
||||||
|
key,
|
||||||
|
body,
|
||||||
|
variables,
|
||||||
|
recipients: []
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Populate recipients from scenarioWatchers
|
// Populate recipients from scenarioWatchers
|
||||||
data.scenarioWatchers.forEach((recipients) => {
|
data.scenarioWatchers.forEach((recipients) => {
|
||||||
const { user, app, fcm, email, firstName, lastName, employeeId, associationId } = recipients;
|
const { user, app, fcm, email, firstName, lastName, employeeId, associationId } = recipients;
|
||||||
if (app === true)
|
|
||||||
|
if (app === true) {
|
||||||
result.app.recipients.push({
|
result.app.recipients.push({
|
||||||
user,
|
user,
|
||||||
bodyShopId: data.bodyShopId,
|
bodyShopId: data.bodyShopId,
|
||||||
employeeId,
|
employeeId,
|
||||||
associationId
|
associationId
|
||||||
});
|
});
|
||||||
if (fcm === true) result.fcm.recipients.push(user);
|
}
|
||||||
if (email === true) result.email.recipients.push({ user, firstName, lastName });
|
|
||||||
|
if (email === true) {
|
||||||
|
result.email.recipients.push({ user, firstName, lastName });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fcm === true) {
|
||||||
|
// Keep structure consistent and future-proof (token lookup is done server-side)
|
||||||
|
result.fcm.recipients.push({
|
||||||
|
user,
|
||||||
|
bodyShopId: data.bodyShopId,
|
||||||
|
employeeId,
|
||||||
|
associationId
|
||||||
|
});
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ const { isEmpty, isFunction } = require("lodash");
|
|||||||
const { getMatchingScenarios } = require("./scenarioMapper");
|
const { getMatchingScenarios } = require("./scenarioMapper");
|
||||||
const { dispatchEmailsToQueue } = require("./queues/emailQueue");
|
const { dispatchEmailsToQueue } = require("./queues/emailQueue");
|
||||||
const { dispatchAppsToQueue } = require("./queues/appQueue");
|
const { dispatchAppsToQueue } = require("./queues/appQueue");
|
||||||
|
const { dispatchFcmsToQueue } = require("./queues/fcmQueue"); // NEW
|
||||||
|
|
||||||
// If true, the user who commits the action will NOT receive notifications; if false, they will.
|
// If true, the user who commits the action will NOT receive notifications; if false, they will.
|
||||||
const FILTER_SELF_FROM_WATCHERS = process.env?.FILTER_SELF_FROM_WATCHERS !== "false";
|
const FILTER_SELF_FROM_WATCHERS = process.env?.FILTER_SELF_FROM_WATCHERS !== "false";
|
||||||
@@ -298,6 +299,16 @@ const scenarioParser = async (req, jobIdField) => {
|
|||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const fcmsToDispatch = scenariosToDispatch.map((scenario) => scenario?.fcm);
|
||||||
|
if (!isEmpty(fcmsToDispatch)) {
|
||||||
|
dispatchFcmsToQueue({ fcmsToDispatch, logger }).catch((e) =>
|
||||||
|
logger.log("Something went wrong dispatching FCMs to the FCM Notification Queue", "error", "queue", null, {
|
||||||
|
message: e?.message,
|
||||||
|
stack: e?.stack
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = scenarioParser;
|
module.exports = scenarioParser;
|
||||||
|
|||||||
@@ -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, markLastMessageUnread } = require("../sms/status");
|
const { status, markConversationRead } = require("../sms/status");
|
||||||
const validateFirebaseIdTokenMiddleware = require("../middleware/validateFirebaseIdTokenMiddleware");
|
const validateFirebaseIdTokenMiddleware = require("../middleware/validateFirebaseIdTokenMiddleware");
|
||||||
|
|
||||||
// Twilio Webhook Middleware for production
|
// Twilio Webhook Middleware for production
|
||||||
@@ -14,6 +14,5 @@ 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;
|
||||||
|
|||||||
@@ -61,8 +61,7 @@ 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 {
|
||||||
|
|||||||
@@ -8,46 +8,6 @@ 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
|
||||||
@@ -216,80 +176,7 @@ 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
|
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user