feat: Add global message search (#1385)

* feat: Search messages by content

* Fix search UI

* Add specs

* chore: Filter search results

* Update highlight logic

* Rename query to searchTerm

Co-authored-by: Sojan <sojan@pepalo.com>
This commit is contained in:
Pranav Raj S 2020-11-08 01:46:45 +05:30 committed by GitHub
parent 22683cae66
commit 7718cf7d2c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
15 changed files with 399 additions and 30 deletions

View file

@ -25,7 +25,7 @@ class ConversationFinder
set_assignee_type
find_all_conversations
filter_by_status
filter_by_status unless params[:q]
filter_by_labels if params[:labels]
filter_by_query if params[:q]
@ -78,9 +78,11 @@ class ConversationFinder
end
def filter_by_query
@conversations = @conversations.joins(:messages).where('messages.content LIKE :search',
search: "%#{params[:q]}%").includes(:messages).where('messages.content LIKE :search',
search: "%#{params[:q]}%")
allowed_message_types = [Message.message_types[:incoming], Message.message_types[:outgoing]]
@conversations = conversations.joins(:messages).where('messages.content ILIKE :search', search: "%#{params[:q]}%")
.where(messages: { message_type: allowed_message_types }).includes(:messages)
.where('messages.content ILIKE :search', search: "%#{params[:q]}%")
.where(messages: { message_type: allowed_message_types })
end
def filter_by_status

View file

@ -18,6 +18,15 @@ class ConversationApi extends ApiClient {
});
}
search({ q }) {
return axios.get(`${this.url}/search`, {
params: {
q,
page: 1,
},
});
}
toggleStatus(conversationId) {
return axios.post(`${this.url}/${conversationId}/toggle_status`, {});
}

View file

@ -72,7 +72,7 @@
.chat-list__top {
@include flex;
@include padding($space-normal $zero $space-small $zero);
@include padding($zero $zero $space-small $zero);
align-items: center;
justify-content: space-between;

View file

@ -1,5 +1,6 @@
<template>
<div class="conversations-sidebar medium-4 columns">
<slot></slot>
<div class="chat-list__top">
<h1 class="page-title">
<woot-sidemenu-icon />
@ -54,9 +55,6 @@
</template>
<script>
/* eslint-env browser */
/* eslint no-console: 0 */
/* global bus */
import { mapGetters } from 'vuex';
import ChatFilter from './widgets/conversation/ChatFilter';

View file

@ -6,6 +6,13 @@
"NO_INBOX_1": "Hola! Looks like you haven't added any inboxes yet.",
"NO_INBOX_2": " to get started",
"NO_INBOX_AGENT": "Uh Oh! Looks like you are not part of any inbox. Please contact your administrator",
"SEARCH_MESSAGES": "Search for messages in conversations",
"SEARCH": {
"TITLE": "Search messages",
"LOADING_MESSAGE": "Crunching data...",
"PLACEHOLDER": "Type any text to search messages",
"NO_MATCHING_RESULTS": "There are no messages matching the search parameters."
},
"CLICK_HERE": "Click here",
"LOADING_INBOXES": "Loading inboxes",
"LOADING_CONVERSATIONS": "Loading Conversations",

View file

@ -1,6 +1,18 @@
<template>
<section class="app-content columns">
<chat-list :conversation-inbox="inboxId" :label="label"></chat-list>
<chat-list :conversation-inbox="inboxId" :label="label">
<button class="search--button" @click="onSearch">
<i class="ion-ios-search-strong search--icon" />
<div class="text-truncate">
{{ $t('CONVERSATION.SEARCH_MESSAGES') }}
</div>
</button>
<search
v-if="showSearchModal"
:show="showSearchModal"
:on-close="closeSearch"
/>
</chat-list>
<conversation-box
:inbox-id="inboxId"
:is-contact-panel-open="isContactPanelOpen"
@ -16,18 +28,19 @@
</template>
<script>
/* eslint no-console: 0 */
import { mapGetters } from 'vuex';
import ChatList from '../../../components/ChatList';
import ContactPanel from './ContactPanel';
import ConversationBox from '../../../components/widgets/conversation/ConversationBox';
import Search from './search/Search.vue';
export default {
components: {
ChatList,
ContactPanel,
ConversationBox,
Search,
},
props: {
inboxId: {
@ -47,6 +60,7 @@ export default {
data() {
return {
panelToggleState: true,
showSearchModal: false,
};
},
computed: {
@ -116,6 +130,32 @@ export default {
onToggleContactPanel() {
this.isContactPanelOpen = !this.isContactPanelOpen;
},
onSearch() {
this.showSearchModal = true;
},
closeSearch() {
this.showSearchModal = false;
},
},
};
</script>
<style scoped>
.search--button {
align-items: center;
border: 0;
color: var(--s-400);
cursor: pointer;
display: flex;
font-size: var(--font-size-small);
font-weight: 400;
padding: var(--space-normal);
text-align: left;
line-height: var(--font-size-large);
}
.search--icon {
color: var(--s-600);
font-size: var(--font-size-large);
padding-right: var(--space-small);
}
</style>

View file

@ -0,0 +1,173 @@
<template>
<woot-modal
class="message-search--modal"
:show.sync="show"
:on-close="onClose"
>
<woot-modal-header :header-title="$t('CONVERSATION.SEARCH.TITLE')" />
<div class="search--container">
<input
v-model="searchTerm"
v-focus
:placeholder="$t('CONVERSATION.SEARCH.PLACEHOLDER')"
type="text"
/>
<div v-if="uiFlags.isFetching" class="search--activity-message">
<woot-spinner size="" />
{{ $t('CONVERSATION.SEARCH.LOADING_MESSAGE') }}
</div>
<div
v-if="searchTerm && conversations.length && !uiFlags.isFetching"
class="search-results--container"
>
<div v-for="conversation in conversations" :key="conversation.id">
<button
v-for="message in conversation.messages"
:key="message.id"
class="search--messages"
@click="() => onClick(conversation)"
>
<div class="search--messages__metadata">
<span>#{{ conversation.id }}</span>
<span>{{ dynamicTime(message.created_at) }}</span>
</div>
<div v-html="prepareContent(message.content)" />
</button>
</div>
</div>
<div
v-else-if="
searchTerm &&
!conversations.length &&
!uiFlags.isFetching &&
hasSearched
"
class="search--activity-message"
>
{{ $t('CONVERSATION.SEARCH.NO_MATCHING_RESULTS') }}
</div>
</div>
</woot-modal>
</template>
<script>
import { mapGetters } from 'vuex';
import { frontendURL, conversationUrl } from '../../../../helper/URLHelper';
import timeMixin from '../../../../mixins/time';
export default {
directives: {
focus: {
inserted(el) {
el.focus();
},
},
},
mixins: [timeMixin],
props: {
show: {
type: Boolean,
default: false,
},
onClose: {
type: Function,
default: () => {},
},
},
data() {
return {
searchTerm: '',
hasSearched: false,
};
},
computed: {
...mapGetters({
conversations: 'conversationSearch/getConversations',
uiFlags: 'conversationSearch/getUIFlags',
accountId: 'getCurrentAccountId',
}),
},
watch: {
searchTerm(newValue) {
if (this.typingTimer) {
clearTimeout(this.typingTimer);
}
this.typingTimer = setTimeout(() => {
this.hasSearched = true;
this.$store.dispatch('conversationSearch/get', { q: newValue });
}, 1000);
},
},
mounted() {
this.$store.dispatch('conversationSearch/get', { q: '' });
},
methods: {
prepareContent(content = '') {
return content.replace(
new RegExp(`(${this.searchTerm})`, 'ig'),
'<span class="searchkey--highlight">$1</span>'
);
},
onClick(conversation) {
const path = conversationUrl({
accountId: this.accountId,
id: conversation.id,
});
window.location = frontendURL(path);
},
},
};
</script>
<style lang="scss">
.search--container {
font-size: var(--font-size-default);
padding: var(--space-normal) var(--space-large);
}
.search-results--container {
max-height: 300px;
overflow: scroll;
}
.searchkey--highlight {
background: var(--w-500);
color: var(--white);
}
.search--activity-message {
color: var(--s-800);
text-align: center;
}
.search--messages {
border-bottom: 1px solid var(--b-100);
color: var(--color-body);
cursor: pointer;
font-size: var(--font-size-small);
line-height: 1.5;
padding: var(--space-normal);
text-align: left;
width: 100%;
&:hover {
background: var(--w-50);
}
}
.message-search--modal .modal-container {
width: 800px;
min-height: 460px;
}
.search--messages__metadata {
display: flex;
justify-content: space-between;
margin-bottom: var(--space-small);
color: var(--s-500);
}
</style>

View file

@ -11,6 +11,7 @@ import conversationLabels from './modules/conversationLabels';
import conversationMetadata from './modules/conversationMetadata';
import conversationPage from './modules/conversationPage';
import conversations from './modules/conversations';
import conversationSearch from './modules/conversationSearch';
import conversationStats from './modules/conversationStats';
import conversationTypingStatus from './modules/conversationTypingStatus';
import globalConfig from 'shared/store/globalConfig';
@ -35,6 +36,7 @@ export default new Vuex.Store({
conversationMetadata,
conversationPage,
conversations,
conversationSearch,
conversationStats,
conversationTypingStatus,
globalConfig,

View file

@ -0,0 +1,54 @@
import ConversationAPI from '../../api/inbox/conversation';
import types from '../mutation-types';
export const initialState = {
records: [],
uiFlags: {
isFetching: false,
},
};
export const getters = {
getConversations(state) {
return state.records;
},
getUIFlags(state) {
return state.uiFlags;
},
};
export const actions = {
async get({ commit }, { q }) {
commit(types.SEARCH_CONVERSATIONS_SET, []);
if (!q) {
return;
}
commit(types.SEARCH_CONVERSATIONS_SET_UI_FLAG, { isFetching: true });
try {
const {
data: { payload },
} = await ConversationAPI.search({ q });
commit(types.SEARCH_CONVERSATIONS_SET, payload);
} catch (error) {
// Ignore error
} finally {
commit(types.SEARCH_CONVERSATIONS_SET_UI_FLAG, { isFetching: false });
}
},
};
export const mutations = {
[types.SEARCH_CONVERSATIONS_SET](state, records) {
state.records = records;
},
[types.SEARCH_CONVERSATIONS_SET_UI_FLAG](state, uiFlags) {
state.uiFlags = { ...state.uiFlags, ...uiFlags };
},
};
export default {
namespaced: true,
state: initialState,
getters,
actions,
mutations,
};

View file

@ -0,0 +1,44 @@
import { actions } from '../../conversationSearch';
import types from '../../../mutation-types';
import axios from 'axios';
const commit = jest.fn();
global.axios = axios;
jest.mock('axios');
describe('#actions', () => {
describe('#get', () => {
it('sends correct actions if no query param is provided', () => {
actions.get({ commit }, { q: '' });
expect(commit.mock.calls).toEqual([[types.SEARCH_CONVERSATIONS_SET, []]]);
});
it('sends correct actions if query param is provided and API call is success', async () => {
axios.get.mockResolvedValue({
data: {
payload: [{ messages: [{ id: 1, content: 'value testing' }], id: 1 }],
},
});
await actions.get({ commit }, { q: 'value' });
expect(commit.mock.calls).toEqual([
[types.SEARCH_CONVERSATIONS_SET, []],
[types.SEARCH_CONVERSATIONS_SET_UI_FLAG, { isFetching: true }],
[
types.SEARCH_CONVERSATIONS_SET,
[{ messages: [{ id: 1, content: 'value testing' }], id: 1 }],
],
[types.SEARCH_CONVERSATIONS_SET_UI_FLAG, { isFetching: false }],
]);
});
it('sends correct actions if query param is provided and API call is errored', async () => {
axios.get.mockRejectedValue({});
await actions.get({ commit }, { q: 'value' });
expect(commit.mock.calls).toEqual([
[types.SEARCH_CONVERSATIONS_SET, []],
[types.SEARCH_CONVERSATIONS_SET_UI_FLAG, { isFetching: true }],
[types.SEARCH_CONVERSATIONS_SET_UI_FLAG, { isFetching: false }],
]);
});
});
});

View file

@ -0,0 +1,19 @@
import { getters } from '../../conversationSearch';
describe('#getters', () => {
it('getConversations', () => {
const state = {
records: [{ id: 1, messages: [{ id: 1, content: 'value' }] }],
};
expect(getters.getConversations(state)).toEqual([
{ id: 1, messages: [{ id: 1, content: 'value' }] },
]);
});
it('getUIFlags', () => {
const state = {
uiFlags: { isFetching: false },
};
expect(getters.getUIFlags(state)).toEqual({ isFetching: false });
});
});

View file

@ -0,0 +1,22 @@
import types from '../../../mutation-types';
import { mutations } from '../../conversationSearch';
describe('#mutations', () => {
describe('#SEARCH_CONVERSATIONS_SET', () => {
it('set records correctly', () => {
const state = { records: [] };
mutations[types.SEARCH_CONVERSATIONS_SET](state, [{ id: 1 }]);
expect(state.records).toEqual([{ id: 1 }]);
});
});
describe('#SEARCH_CONVERSATIONS_SET', () => {
it('set uiFlags correctly', () => {
const state = { uiFlags: { isFetching: true } };
mutations[types.SEARCH_CONVERSATIONS_SET_UI_FLAG](state, {
isFetching: false,
});
expect(state.uiFlags).toEqual({ isFetching: false });
});
});
});

View file

@ -123,4 +123,8 @@ export default {
// User Typing
ADD_USER_TYPING_TO_CONVERSATION: 'ADD_USER_TYPING_TO_CONVERSATION',
REMOVE_USER_TYPING_FROM_CONVERSATION: 'REMOVE_USER_TYPING_FROM_CONVERSATION',
// Conversation Search
SEARCH_CONVERSATIONS_SET: 'SEARCH_CONVERSATIONS_SET',
SEARCH_CONVERSATIONS_SET_UI_FLAG: 'SEARCH_CONVERSATIONS_SET_UI_FLAG',
};

View file

@ -1,22 +1,17 @@
json.data do
json.meta do
json.mine_count @conversations_count[:mine_count]
json.unassigned_count @conversations_count[:unassigned_count]
json.all_count @conversations_count[:all_count]
end
json.payload do
json.array! @conversations do |conversation|
json.inbox_id conversation.inbox_id
json.messages conversation.messages
json.status conversation.status
json.muted conversation.muted?
json.can_reply conversation.can_reply?
json.timestamp conversation.last_activity_at.to_i
json.contact_last_seen_at conversation.contact_last_seen_at.to_i
json.agent_last_seen_at conversation.agent_last_seen_at.to_i
json.additional_attributes conversation.additional_attributes
json.account_id conversation.account_id
json.labels conversation.label_list
json.meta do
json.mine_count @conversations_count[:mine_count]
json.unassigned_count @conversations_count[:unassigned_count]
json.all_count @conversations_count[:all_count]
end
json.payload do
json.array! @conversations do |conversation|
json.id conversation.display_id
json.messages do
json.array! conversation.messages do |message|
json.content message.content
json.created_at message.created_at.to_i
end
end
json.account_id conversation.account_id
end
end

View file

@ -85,7 +85,7 @@ RSpec.describe 'Conversations API', type: :request do
as: :json
expect(response).to have_http_status(:success)
response_data = JSON.parse(response.body, symbolize_names: true)[:data]
response_data = JSON.parse(response.body, symbolize_names: true)
expect(response_data[:meta][:all_count]).to eq(1)
expect(response_data[:payload].first[:messages].first[:content]).to eq 'test1'
end