From 30920ae2e80c7fbb1d4afaf5b6c5728b6ed27129 Mon Sep 17 00:00:00 2001 From: Muhsin Date: Sun, 27 Dec 2020 10:11:00 +0530 Subject: [PATCH] Add conversation group by helpers --- app/javascript/dashboard/helper/commons.js | 43 +++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/app/javascript/dashboard/helper/commons.js b/app/javascript/dashboard/helper/commons.js index afd71fefe..02e27ee6f 100644 --- a/app/javascript/dashboard/helper/commons.js +++ b/app/javascript/dashboard/helper/commons.js @@ -1,5 +1,7 @@ /* eslint no-param-reassign: 0 */ - +const groupBy = require('lodash.groupby'); +import { formatUnixDate } from 'shared/helpers/DateHelper'; +import { isASubmittedFormMessage } from 'shared/helpers/MessageTypeHelper'; import getUuid from 'widget/helpers/uuid'; import { MESSAGE_STATUS, MESSAGE_TYPE } from 'shared/constants/messages'; @@ -67,3 +69,42 @@ export const createPendingAttachment = data => { }; return pendingMessage; }; + +const getSenderName = message => (message.sender ? message.sender.name : ''); + +const shouldShowAvatar = (message, nextMessage) => { + const currentSender = getSenderName(message); + const nextSender = getSenderName(nextMessage); + + return ( + currentSender !== nextSender || + message.message_type !== nextMessage.message_type || + isASubmittedFormMessage(nextMessage) + ); +}; + +const groupConversationBySender = conversationsForADate => + conversationsForADate.map((message, index) => { + let showAvatar = false; + const isLastMessage = index === conversationsForADate.length - 1; + if (isASubmittedFormMessage(message)) { + showAvatar = false; + } else if (isLastMessage) { + showAvatar = true; + } else { + const nextMessage = conversationsForADate[index + 1]; + showAvatar = shouldShowAvatar(message, nextMessage); + } + return { showAvatar, ...message }; + }); + +export const getGroupedConversation = ({ conversations }) => { + const conversationGroupedByDate = groupBy( + Object.values(conversations), + message => formatUnixDate(message.created_at) + ); + return Object.keys(conversationGroupedByDate).map(date => ({ + date, + messages: groupConversationBySender(conversationGroupedByDate[date]), + })); +};