Skip to content

Open-source live-chat, email support, omni-channel desk. An alternative to Intercom, Zendesk, Salesforce Service Cloud etc. 🔥💬

21.2 KB
Raw Blame
import types from '../../mutation-types';
import ConversationApi from '../../../api/inbox/conversation';
import MessageApi from '../../../api/inbox/message';
import { MESSAGE_STATUS, MESSAGE_TYPE } from 'shared/constants/messages';
import { createPendingMessage } from 'dashboard/helper/commons';
import filterQueryGenerator, {
  withTimestampTimezone,
} from 'dashboard/helper/filterQueryGenerator';
import {
  buildConversationList,
  isOnMentionsView,
  isOnParticipatingView,
  isOnUnattendedView,
  isOnFoldersView,
} from './helpers/actionHelpers';
import messageReadActions from './actions/messageReadActions';
import messageTranslateActions from './actions/messageTranslateActions';
import * as Sentry from '@sentry/vue';
import { useAbortableRequest } from 'dashboard/composables/useAbortableRequest';
import {
  handleVoiceCallCreated,
  handleVoiceCallUpdated,
  syncConversationCallVisibility,
} from 'dashboard/helper/voice';

// Page size MessageFinder uses when walking backwards through a conversation.
const MESSAGES_PER_PAGE = 20;

const pendingHistoryRequests = new Map();

const TERMINAL_CONTACT_INFO_REQUEST_STATES = ['shared', 'identity_conflict'];

const contactInfoSourceId = message =>
  message.conversation?.contact_inbox?.source_id;

const hasContactInfoSource = (conversation, sourceId) => {
  return (conversation.messages || []).some(message => {
    return contactInfoSourceId(message) === sourceId;
  });
};

const contactInfoRefreshConversationIds = (state, message) => {
  const conversationIds = new Set([message.conversation_id].filter(Boolean));
  const sourceId = contactInfoSourceId(message);
  if (!sourceId) return [...conversationIds];

  (state.allConversations || []).forEach(conversation => {
    if (hasContactInfoSource(conversation, sourceId)) {
      conversationIds.add(conversation.id);
    }
  });

  return [...conversationIds];
};

export const hasMessageFailedWithExternalError = pendingMessage => {
  // This helper is used to check if the message has failed with an external error.
  // We have two cases
  // 1. Messages that fail from the UI itself (due to large attachments or a failed network):
  //    In this case, the message will have a status of failed but no external error. So we need to create that message again
  // 2. Messages sent from Chatwoot but failed to deliver to the customer for some reason (user blocking or client system down):
  //    In this case, the message will have a status of failed and an external error. So we need to retry that message
  const { content_attributes: contentAttributes, status } = pendingMessage;
  const externalError = contentAttributes?.external_error ?? '';
  return status === MESSAGE_STATUS.FAILED && externalError !== '';
};

const conversationListRequest = useAbortableRequest();

// actions
const actions = {
  getConversation: async ({ commit, dispatch }, conversationId) => {
    try {
      const response = await ConversationApi.show(conversationId);
      // API refreshes can run in the background after reconnecting. Use the
      // list merge to preserve local message state without moving the agent's
      // scroll position or marking messages as read.
      commit(types.SET_ALL_CONVERSATION, [response.data]);
      commit(`contacts/${types.SET_CONTACT_ITEM}`, response.data.meta.sender);
      dispatch('conversationLabels/setConversationLabel', {
        id: response.data.id,
        data: response.data.labels,
      });
    } catch (error) {
      // Ignore error
    }
  },

  fetchAllConversations: async (
    { commit, state, dispatch },
    { replaceExisting = false } = {}
  ) => {
    return conversationListRequest.run(async signal => {
      const params = state.conversationFilters;
      const countRequest = await dispatch(
        'conversationStats/onListRequestStarted',
        params
      );
      if (signal.aborted) return;
      commit(types.SET_LIST_LOADING_STATUS);
      try {
        const {
          data: { data },
        } = await ConversationApi.get(params, { signal });

        if (signal.aborted) return;

        buildConversationList(
          { commit, dispatch },
          params,
          data,
          params.assigneeType,
          { replaceExisting, countRequest }
        );
      } catch (error) {
        if (!signal.aborted) {
          commit(types.CLEAR_LIST_LOADING_STATUS);
        }
      }
    });
  },

  fetchFilteredConversations: async ({ commit, dispatch, state }, params) => {
    return conversationListRequest.run(async signal => {
      const {
        replaceExisting = false,
        sortBy = state.chatSortFilter,
        ...requestParams
      } = params;
      // The contact scope pins its own order to match the in-thread navigation.
      const filterRequestParams = {
        ...requestParams,
        sortBy: state.appliedFiltersSortBy || sortBy,
      };
      const countRequest = await dispatch(
        'conversationStats/onListRequestStarted',
        filterRequestParams
      );
      if (signal.aborted) return;
      commit(types.SET_LIST_LOADING_STATUS);
      try {
        const { data } = await ConversationApi.filter(filterRequestParams, {
          signal,
        });

        if (signal.aborted) return;

        buildConversationList(
          { commit, dispatch },
          filterRequestParams,
          data,
          'appliedFilters',
          { replaceExisting, countRequest }
        );
      } catch (error) {
        if (signal.aborted) return;

        commit(types.CLEAR_LIST_LOADING_STATUS);
        throw error;
      }
    });
  },

  emptyAllConversations({ commit }) {
    commit(types.EMPTY_ALL_CONVERSATION);
  },

  clearSelectedState({ commit }) {
    commit(types.CLEAR_CURRENT_CHAT_WINDOW);
  },

  fetchPreviousMessages: ({ commit, dispatch }, data) => {
    const requestKey = JSON.stringify([
      MessageApi.url,
      data.conversationId,
      data.before,
      data.after,
    ]);
    if (pendingHistoryRequests.has(requestKey)) {
      return pendingHistoryRequests.get(requestKey);
    }

    const request = MessageApi.getPreviousMessages(data)
      .then(({ data: { meta, payload } }) => {
        commit(`conversationMetadata/${types.SET_CONVERSATION_METADATA}`, {
          id: data.conversationId,
          data: meta,
        });
        commit(types.SET_PREVIOUS_CONVERSATIONS, {
          id: data.conversationId,
          data: payload,
        });
        dispatch('autoTranslateMessages', data.conversationId);
        // A short backward page means the start is reached; `after` requests only prove it when empty.
        const hasReachedFirstMessage = data.after
          ? !payload.length
          : payload.length < MESSAGES_PER_PAGE;
        if (hasReachedFirstMessage) {
          commit(types.SET_ALL_MESSAGES_LOADED, data.conversationId);
        }
      })
      .finally(() => pendingHistoryRequests.delete(requestKey));

    pendingHistoryRequests.set(requestKey, request);
    return request;
  },

  fetchAllAttachments: async ({ commit }, conversationId) => {
    let attachments = [];

    try {
      const { data } = await ConversationApi.getAllAttachments(conversationId);
      attachments = data.payload;
    } catch (error) {
      // in case of error, log the error and continue
      Sentry.setContext('Conversation', {
        id: conversationId,
      });
      Sentry.captureException(error);
    } finally {
      // we run the commit even if the request fails
      // this ensures that the `attachment` variable is always present on chat
      commit(types.SET_ALL_ATTACHMENTS, {
        id: conversationId,
        data: attachments,
      });
    }
  },

  syncActiveConversationMessages: async (
    { commit, state, dispatch },
    { conversationId }
  ) => {
    const { allConversations, syncConversationsMessages } = state;
    const lastMessageId = syncConversationsMessages[conversationId];
    const selectedChat = allConversations.find(
      conversation => conversation.id === conversationId
    );
    if (!selectedChat) return;
    try {
      const { messages } = selectedChat;
      // Fetch all the messages after the last message id
      const {
        data: { meta, payload },
      } = await MessageApi.getPreviousMessages({
        conversationId,
        after: lastMessageId,
      });
      commit(`conversationMetadata/${types.SET_CONVERSATION_METADATA}`, {
        id: conversationId,
        data: meta,
      });
      // Find the messages that are not already present in the store
      const missingMessages = payload.filter(
        message => !messages.find(item => item.id === message.id)
      );
      selectedChat.messages.push(...missingMessages);
      // Sort the messages by created_at
      const sortedMessages = selectedChat.messages.sort((a, b) => {
        return new Date(a.created_at) - new Date(b.created_at);
      });
      commit(types.SET_MISSING_MESSAGES, {
        id: conversationId,
        data: sortedMessages,
      });
      commit(types.SET_LAST_MESSAGE_ID_IN_SYNC_CONVERSATION, {
        conversationId,
        messageId: null,
      });
      dispatch('autoTranslateMessages', conversationId);
      dispatch('markMessagesRead', { id: conversationId }, { root: true });
    } catch (error) {
      // Handle error
    }
  },

  setConversationLastMessageId: async (
    { commit, state },
    { conversationId }
  ) => {
    const { allConversations } = state;
    const selectedChat = allConversations.find(
      conversation => conversation.id === conversationId
    );
    if (!selectedChat) return;
    const { messages } = selectedChat;
    const lastMessage = messages.last();
    if (!lastMessage) return;
    commit(types.SET_LAST_MESSAGE_ID_IN_SYNC_CONVERSATION, {
      conversationId,
      messageId: lastMessage.id,
    });
  },

  async setActiveChat({ commit, dispatch }, { data, after }) {
    commit(types.SET_CURRENT_CHAT_WINDOW, data);
    if (data.dataFetched === undefined) {
      // Reset only when refetching — a re-activated short conversation has no scroll to earn it back.
      commit(types.CLEAR_ALL_MESSAGES_LOADED, data.id);
      try {
        await dispatch('fetchPreviousMessages', {
          after,
          // A conversation created without an initial message has nothing to anchor on.
          before: data.messages[0]?.id,
          conversationId: data.id,
        });
        commit(types.SET_CHAT_DATA_FETCHED, data.id);
      } catch (error) {
        // Ignore error
      }
    }
  },

  assignAgent: async (
    { dispatch },
    { conversationId, agentId, assigneeType }
  ) => {
    try {
      const response = await ConversationApi.assignAgent({
        conversationId,
        agentId,
        assigneeType,
      });
      dispatch('setCurrentChatAssignee', {
        conversationId,
        assignee: response.data,
        assigneeType,
      });
    } catch (error) {
      // Handle error
    }
  },

  setCurrentChatAssignee(
    { commit },
    { conversationId, assignee, assigneeType }
  ) {
    commit(types.ASSIGN_AGENT, { conversationId, assignee, assigneeType });
  },

  assignTeam: async ({ dispatch }, { conversationId, teamId }) => {
    try {
      const response = await ConversationApi.assignTeam({
        conversationId,
        teamId,
      });
      dispatch('setCurrentChatTeam', { team: response.data, conversationId });
    } catch (error) {
      // Handle error
    }
  },

  setCurrentChatTeam({ commit }, { team, conversationId }) {
    commit(types.ASSIGN_TEAM, { team, conversationId });
  },

  toggleStatus: async (
    { commit },
    { conversationId, status, snoozedUntil = null, customAttributes = null }
  ) => {
    try {
      // Update custom attributes first if provided
      if (customAttributes) {
        await ConversationApi.updateCustomAttributes({
          conversationId,
          customAttributes,
        });
        commit(types.UPDATE_CONVERSATION_CUSTOM_ATTRIBUTES, {
          conversationId,
          customAttributes,
        });
      }

      const {
        data: {
          payload: {
            current_status: updatedStatus,
            snoozed_until: updatedSnoozedUntil,
          } = {},
        } = {},
      } = await ConversationApi.toggleStatus({
        conversationId,
        status,
        snoozedUntil,
      });
      commit(types.CHANGE_CONVERSATION_STATUS, {
        conversationId,
        status: updatedStatus,
        snoozedUntil: updatedSnoozedUntil,
      });
    } catch (error) {
      // Handle error
    }
  },

  createPendingMessageAndSend: async ({ dispatch }, data) => {
    const pendingMessage = createPendingMessage(data);
    dispatch('sendMessageWithData', pendingMessage);
  },

  sendMessageWithData: async ({ commit }, pendingMessage) => {
    const { conversation_id: conversationId, id } = pendingMessage;
    try {
      commit(types.ADD_MESSAGE, {
        ...pendingMessage,
        status: MESSAGE_STATUS.PROGRESS,
      });
      const response = hasMessageFailedWithExternalError(pendingMessage)
        ? await MessageApi.retry(conversationId, id)
        : await MessageApi.create(pendingMessage);
      commit(types.ADD_MESSAGE, {
        ...response.data,
        status: MESSAGE_STATUS.SENT,
      });
      commit(types.ADD_CONVERSATION_ATTACHMENTS, {
        ...response.data,
        status: MESSAGE_STATUS.SENT,
      });
    } catch (error) {
      const errorMessage = error.response
        ? error.response.data.error
        : undefined;
      commit(types.ADD_MESSAGE, {
        ...pendingMessage,
        meta: {
          error: errorMessage,
        },
        status: MESSAGE_STATUS.FAILED,
      });
      throw error;
    }
  },

  getContactInfoRequestAvailability: async (_, { conversationId, signal }) => {
    const { data } = await ConversationApi.getContactInfoRequestAvailability(
      conversationId,
      {
        signal,
      }
    );
    return data;
  },

  requestContactInfo: async ({ commit }, conversationId) => {
    const { data } = await ConversationApi.requestContactInfo(conversationId);
    commit(types.ADD_MESSAGE, data);
    return data;
  },

  addMessage({ commit, dispatch, rootGetters }, message) {
    commit(types.ADD_MESSAGE, message);
    if (message.message_type === MESSAGE_TYPE.INCOMING) {
      commit(types.SET_CONVERSATION_CAN_REPLY, {
        conversationId: message.conversation_id,
        canReply: true,
      });
      commit(types.ADD_CONVERSATION_ATTACHMENTS, message);
      dispatch('autoTranslateMessages', message.conversation_id);
    }
    handleVoiceCallCreated(
      message,
      rootGetters?.getCurrentUserID,
      rootGetters?.getCurrentUserAvailability
    );
  },

  updateMessage({ commit, dispatch, rootGetters, state }, message) {
    commit(types.ADD_MESSAGE, message);

    const contactInfoRequest =
      message.content_attributes?.whatsapp_contact_info;
    const isTerminalContactInfoRequest =
      contactInfoRequest?.type === 'request' &&
      (message.status === MESSAGE_STATUS.FAILED ||
        TERMINAL_CONTACT_INFO_REQUEST_STATES.includes(
          contactInfoRequest.state
        ));
    if (isTerminalContactInfoRequest) {
      contactInfoRefreshConversationIds(state, message).forEach(
        conversationId => {
          dispatch('getConversation', conversationId);
        }
      );
    }

    handleVoiceCallUpdated(
      commit,
      message,
      rootGetters?.getCurrentUserID,
      rootGetters?.getCurrentUserAvailability
    );
  },

  deleteMessage: async function deleteLabels(
    { commit },
    { conversationId, messageId }
  ) {
    try {
      const { data } = await MessageApi.delete(conversationId, messageId);
      commit(types.ADD_MESSAGE, data);
      commit(types.DELETE_CONVERSATION_ATTACHMENTS, data);
    } catch (error) {
      throw new Error(error);
    }
  },

  deleteConversation: async ({ commit, dispatch }, conversationId) => {
    try {
      await ConversationApi.delete(conversationId);
      commit(types.DELETE_CONVERSATION, conversationId);
      dispatch('conversationStats/get');
    } catch (error) {
      throw new Error(error);
    }
  },

  addConversation({ commit, state, dispatch, rootState }, conversation) {
    const { currentInbox, appliedFilters } = state;
    const {
      inbox_id: inboxId,
      meta: { sender },
    } = conversation;
    const hasAppliedFilters = !!appliedFilters.length;
    const isMatchingInboxFilter =
      !currentInbox || Number(currentInbox) === inboxId;
    if (
      !hasAppliedFilters &&
      !isOnFoldersView(rootState) &&
      !isOnMentionsView(rootState) &&
      !isOnParticipatingView(rootState) &&
      !isOnUnattendedView(rootState) &&
      isMatchingInboxFilter
    ) {
      commit(types.ADD_CONVERSATION, conversation);
      dispatch('contacts/setContact', sender);
    }
  },

  addMentions({ dispatch, rootState }, conversation) {
    if (isOnMentionsView(rootState)) {
      dispatch('updateConversation', conversation);
    }
  },

  addUnattended({ dispatch, rootState }, conversation) {
    if (isOnUnattendedView(rootState)) {
      dispatch('updateConversation', conversation);
    }
  },

  updateConversation({ commit, dispatch, rootGetters }, conversation) {
    const sender = conversation.meta?.sender;

    commit(types.UPDATE_CONVERSATION, conversation);
    syncConversationCallVisibility(conversation, rootGetters?.getCurrentUserID);
    // The contact language can change after a message arrived; the action skips anything already handled.
    dispatch('autoTranslateMessages', conversation.id);

    dispatch('conversationLabels/setConversationLabel', {
      id: conversation.id,
      data: conversation.labels,
    });

    if (sender) dispatch('contacts/setContact', sender);
  },

  updateConversationLastActivity(
    { commit },
    { conversationId, lastActivityAt }
  ) {
    commit(types.UPDATE_CONVERSATION_LAST_ACTIVITY, {
      lastActivityAt,
      conversationId,
    });
  },

  setChatStatusFilter({ commit }, data) {
    commit(types.CHANGE_CHAT_STATUS_FILTER, data);
  },

  setChatSortFilter({ commit }, data) {
    commit(types.CHANGE_CHAT_SORT_FILTER, data);
  },

  updateAssignee({ commit }, data) {
    commit(types.UPDATE_ASSIGNEE, data);
  },

  updateConversationContact({ commit }, data) {
    if (data.id) {
      commit(`contacts/${types.SET_CONTACT_ITEM}`, data);
    }
    commit(types.UPDATE_CONVERSATION_CONTACT, data);
  },

  setActiveInbox({ commit }, inboxId) {
    commit(types.SET_ACTIVE_INBOX, inboxId);
  },

  muteConversation: async ({ commit }, conversationId) => {
    try {
      await ConversationApi.mute(conversationId);
      commit(types.MUTE_CONVERSATION);
    } catch (error) {
      //
    }
  },

  unmuteConversation: async ({ commit }, conversationId) => {
    try {
      await ConversationApi.unmute(conversationId);
      commit(types.UNMUTE_CONVERSATION);
    } catch (error) {
      //
    }
  },

  sendEmailTranscript: async (_, { conversationId, email }) => {
    await ConversationApi.sendEmailTranscript({ conversationId, email });
  },

  updateCustomAttributes: async (
    { commit },
    { conversationId, customAttributes }
  ) => {
    try {
      const response = await ConversationApi.updateCustomAttributes({
        conversationId,
        customAttributes,
      });
      const { custom_attributes } = response.data;
      commit(types.UPDATE_CONVERSATION_CUSTOM_ATTRIBUTES, {
        conversationId,
        customAttributes: custom_attributes,
      });
    } catch (error) {
      throw new Error(error);
    }
  },

  setConversationFilters({ commit }, data) {
    commit(types.SET_CONVERSATION_FILTERS, data);
  },

  // Replaces the list with page 1 of the snake_case filters; sortBy overrides the activity order.
  applyConversationFilters: (
    { commit, dispatch },
    { filters, sortBy = null }
  ) => {
    const appliedFilters = filters.map(withTimestampTimezone);
    commit(types.SET_CONVERSATION_FILTERS, appliedFilters);
    commit(types.SET_CONVERSATION_FILTERS_SORT, sortBy);
    commit(types.EMPTY_ALL_CONVERSATION);
    dispatch('conversationPage/reset', {}, { root: true });

    return dispatch('fetchFilteredConversations', {
      queryData: filterQueryGenerator(appliedFilters),
      page: 1,
    });
  },

  clearConversationFilters({ commit }) {
    commit(types.CLEAR_CONVERSATION_FILTERS);
  },

  setChatListFilters({ commit }, data) {
    commit(types.SET_CHAT_LIST_FILTERS, data);
  },

  updateChatListFilters({ commit }, data) {
    commit(types.UPDATE_CHAT_LIST_FILTERS, data);
  },

  invalidateConversationListRequests({ commit }) {
    conversationListRequest.abort();
    commit(types.CLEAR_LIST_LOADING_STATUS);
  },

  assignPriority: async ({ dispatch }, { conversationId, priority }) => {
    try {
      await ConversationApi.togglePriority({
        conversationId,
        priority,
      });

      dispatch('setCurrentChatPriority', {
        priority,
        conversationId,
      });
    } catch (error) {
      // Handle error
    }
  },

  setCurrentChatPriority({ commit }, { priority, conversationId }) {
    commit(types.ASSIGN_PRIORITY, { priority, conversationId });
  },

  setContextMenuChatId({ commit }, chatId) {
    commit(types.SET_CONTEXT_MENU_CHAT_ID, chatId);
  },

  getInboxCaptainAssistantById: async ({ commit }, conversationId) => {
    try {
      const response = await ConversationApi.getInboxAssistant(conversationId);
      commit(types.SET_INBOX_CAPTAIN_ASSISTANT, response.data);
    } catch (error) {
      // Handle error
    }
  },

  ...messageReadActions,
  ...messageTranslateActions,
};

export default actions;