diff --git a/app/controllers/api/v1/accounts/conversations_controller.rb b/app/controllers/api/v1/accounts/conversations_controller.rb index 4301eaa4a..8220f7fa8 100644 --- a/app/controllers/api/v1/accounts/conversations_controller.rb +++ b/app/controllers/api/v1/accounts/conversations_controller.rb @@ -160,6 +160,9 @@ class Api::V1::Accounts::ConversationsController < Api::V1::Accounts::BaseContro def conversation @conversation ||= Current.account.conversations.find_by!(display_id: params[:id]) + # Return 404 if conversation has no valid contact or contact_inbox + raise ActiveRecord::RecordNotFound if @conversation.contact.blank? + authorize @conversation, :show? end diff --git a/app/finders/conversation_finder.rb b/app/finders/conversation_finder.rb index d43ed31e7..b2ec2beb1 100644 --- a/app/finders/conversation_finder.rb +++ b/app/finders/conversation_finder.rb @@ -63,6 +63,7 @@ class ConversationFinder set_assignee_type find_all_conversations + filter_orphan_conversations filter_by_status unless params[:q] filter_by_team filter_by_labels @@ -166,6 +167,12 @@ class ConversationFinder @conversations = @conversations.where(contact_inboxes: { source_id: params[:source_id] }) end + def filter_orphan_conversations + # Filter out conversations where the contact has been deleted + # Using INNER JOIN is most efficient - only returns conversations with existing contacts + @conversations = @conversations.joins(:contact) + end + def set_count_for_all_conversations [ @conversations.assigned_to(current_user).count, diff --git a/app/views/api/v1/conversations/partials/_conversation.json.jbuilder b/app/views/api/v1/conversations/partials/_conversation.json.jbuilder index 6036d91e0..4cb13f543 100644 --- a/app/views/api/v1/conversations/partials/_conversation.json.jbuilder +++ b/app/views/api/v1/conversations/partials/_conversation.json.jbuilder @@ -3,12 +3,8 @@ # Everywhere else we use conversation builder in partials folder json.meta do - if conversation.contact - json.sender do - json.partial! 'api/v1/models/contact', formats: [:json], resource: conversation.contact - end - else - json.sender nil + json.sender do + json.partial! 'api/v1/models/contact', formats: [:json], resource: conversation.contact end json.channel conversation.inbox.try(:channel_type) if conversation.assigned_entity.is_a?(AgentBot)