Compare commits

...

15 commits

Author SHA1 Message Date
fayazara
3c6abac5b2 Add new page for Search 2022-12-13 23:10:14 +05:30
Tejaswini Chile
60bb07923e fix: Added pg_trgm extension 2022-12-13 12:24:51 +05:30
Tejaswini Chile
443dbbbfd2 fix: unwanted changes and the comments 2022-12-13 09:39:05 +05:30
Tejaswini Chile
900e8501ca message json fix 2022-12-12 21:01:09 +05:30
Tejaswini Chile
e00e049fb7
Merge branch 'develop' into feat/5913-search-improvements 2022-12-12 20:13:00 +05:30
Tejaswini Chile
acb4b7ce04
Merge branch 'develop' into feat/5913-search-improvements 2022-12-12 14:55:47 +05:30
Tejaswini Chile
02148c5c64 fix: issue with current account not being present for some user 2022-12-12 13:16:27 +05:30
Tejaswini Chile
b456cec6a6 fix: migration for rebuilding multi model search 2022-12-12 11:57:01 +05:30
Tejaswini Chile
abbaeb7701 fix: specs 2022-12-12 11:12:29 +05:30
Tejaswini Chile
6e9a29ef56 fix: JSON format 2022-12-12 00:37:12 +05:30
Tejaswini Chile
e904a40254 fix: JSON format 2022-12-11 20:18:55 +05:30
Tejaswini Chile
8d09686baf fix: new endpoint for the text search 2022-12-11 20:05:27 +05:30
Tejaswini Chile
44c0c92f83 fix: new endpoint for the text search 2022-12-10 01:43:49 +05:30
Tejaswini Chile
4aec41bd72 fix: search improvements for multiple model with separate results 2022-12-10 01:42:07 +05:30
Tejaswini Chile
dd75db4196 feat: Search improvements 2022-12-10 01:42:07 +05:30
35 changed files with 1305 additions and 106 deletions

View file

@ -2,8 +2,8 @@ class Api::V1::Accounts::ConversationsController < Api::V1::Accounts::BaseContro
include Events::Types
include DateRangeHelper
before_action :conversation, except: [:index, :meta, :search, :create, :filter]
before_action :inbox, :contact, :contact_inbox, only: [:create]
before_action :conversation, except: [:index, :meta, :search, :create, :filter, :text_search]
before_action :inbox, :contact, :contact_inbox, :text_search, only: [:create]
def index
result = conversation_finder.perform
@ -11,6 +11,10 @@ class Api::V1::Accounts::ConversationsController < Api::V1::Accounts::BaseContro
@conversations_count = result[:count]
end
def text_search
@result = TextSearch.new(Current.user, params).perform
end
def meta
result = conversation_finder.perform
@conversations_count = result[:count]

View file

@ -0,0 +1,36 @@
class TextSearch
attr_reader :current_user, :current_account, :params
DEFAULT_STATUS = 'open'.freeze
def initialize(current_user, params)
@current_account = current_user.account || Current.account
@params = params
end
def perform
{
messages: filter_messages,
conversations: filter_conversations,
contacts: filter_contacts
}
end
private
def filter_conversations
conversation_ids = PgSearch.multisearch("#{@params[:q]}%").where(account_id: @current_account,
searchable_type: 'Conversation').pluck(:searchable_id)
@conversations = Conversation.where(id: conversation_ids)
end
def filter_messages
message_ids = PgSearch.multisearch("#{@params[:q]}%").where(account_id: @current_account, searchable_type: 'Message').pluck(:searchable_id)
@messages = Message.where(id: message_ids)
end
def filter_contacts
contact_ids = PgSearch.multisearch("#{@params[:q]}%").where(account_id: @current_account, searchable_type: 'Contact').pluck(:searchable_id)
@contacts = Contact.where(id: contact_ids)
end
end

View file

@ -45,6 +45,14 @@ class ConversationApi extends ApiClient {
});
}
fullSearch({ q }) {
return axios.get(`${this.url}/text_search`, {
params: {
q,
},
});
}
toggleStatus({ conversationId, status, snoozedUntil = null }) {
return axios.post(`${this.url}/${conversationId}/toggle_status`, {
status,

View file

@ -20,6 +20,7 @@ describe('#ConversationAPI', () => {
expect(conversationAPI).toHaveProperty('meta');
expect(conversationAPI).toHaveProperty('sendEmailTranscript');
expect(conversationAPI).toHaveProperty('filter');
expect(conversationAPI).toHaveProperty('fullSearch');
});
describeWithAPIMock('API calls', context => {
@ -64,6 +65,16 @@ describe('#ConversationAPI', () => {
);
});
it('#fullSearch', () => {
conversationAPI.fullSearch({ q: 'john' });
expect(context.axiosMock.get).toHaveBeenCalledWith(
'/api/v1/conversations/text_search',
{
params: { q: 'john' },
}
);
});
it('#toggleStatus', () => {
conversationAPI.toggleStatus({ conversationId: 12, status: 'online' });
expect(context.axiosMock.post).toHaveBeenCalledWith(

View file

@ -27,6 +27,7 @@ import settings from './settings.json';
import signup from './signup.json';
import teamsSettings from './teamsSettings.json';
import whatsappTemplates from './whatsappTemplates.json';
import search from './search.json';
export default {
...advancedFilters,
@ -58,4 +59,5 @@ export default {
...signup,
...teamsSettings,
...whatsappTemplates,
...search,
};

View file

@ -0,0 +1,17 @@
{
"SEARCH": {
"TABS": {
"ALL": "All",
"CONTACTS": "Contacts",
"CONVERSATIONS": "Conversations",
"MESSAGES": "Messages"
},
"SECTION": {
"CONTACTS": "CONTACTS",
"CONVERSATIONS": "CONVERSATIONS",
"MESSAGES": "MESSAGES"
},
"EMPTY_STATE": "No results found for this query",
"PLACEHOLDER_KEYBINDING": "/ to focus"
}
}

View file

@ -1,55 +1,18 @@
<template>
<div v-on-clickaway="closeSearch" class="search-wrap">
<div class="search-wrap">
<div class="search" :class="{ 'is-active': showSearchBox }">
<woot-sidemenu-icon />
<div class="icon">
<fluent-icon icon="search" class="search--icon" size="28" />
</div>
<input
v-model="searchTerm"
class="search--input"
:placeholder="$t('CONVERSATION.SEARCH_MESSAGES')"
@focus="onSearch"
/>
<router-link :to="searchUrl" class="search--link">
<div class="icon">
<fluent-icon icon="search" class="search--icon" size="28" />
</div>
<p class="search--label">{{ $t('CONVERSATION.SEARCH_MESSAGES') }}</p>
</router-link>
<switch-layout
:is-on-expanded-layout="isOnExpandedLayout"
@toggle="$emit('toggle-conversation-layout')"
/>
</div>
<div v-if="showSearchBox" class="results-wrap">
<div class="show-results">
<div>
<div class="result-view">
<div class="result">
{{ $t('CONVERSATION.SEARCH.RESULT_TITLE') }}
<span v-if="resultsCount" class="message-counter">
({{ resultsCount }})
</span>
</div>
<div v-if="uiFlags.isFetching" class="search--activity-message">
<woot-spinner size="" />
{{ $t('CONVERSATION.SEARCH.LOADING_MESSAGE') }}
</div>
</div>
<div v-if="showSearchResult" class="search-results--container">
<result-item
v-for="conversation in conversations"
:key="conversation.messageId"
:conversation-id="conversation.id"
:user-name="conversation.contact.name"
:timestamp="conversation.created_at"
:messages="conversation.messages"
:search-term="searchTerm"
:inbox-name="conversation.inbox.name"
/>
</div>
<div v-else-if="showEmptyResult" class="search--activity-no-message">
{{ $t('CONVERSATION.SEARCH.NO_MATCHING_RESULTS') }}
</div>
</div>
</div>
</div>
</div>
</template>
@ -57,15 +20,13 @@
import { mixin as clickaway } from 'vue-clickaway';
import { mapGetters } from 'vuex';
import timeMixin from '../../../../mixins/time';
import ResultItem from './ResultItem';
import messageFormatterMixin from 'shared/mixins/messageFormatterMixin';
import SwitchLayout from './SwitchLayout.vue';
import { frontendURL } from 'dashboard/helper/URLHelper';
export default {
components: {
ResultItem,
SwitchLayout,
},
directives: {
focus: {
inserted(el) {
@ -73,9 +34,7 @@ export default {
},
},
},
mixins: [timeMixin, messageFormatterMixin, clickaway],
props: {
isOnExpandedLayout: {
type: Boolean,
@ -92,59 +51,10 @@ export default {
computed: {
...mapGetters({
conversations: 'conversationSearch/getConversations',
uiFlags: 'conversationSearch/getUIFlags',
currentPage: 'conversationPage/getCurrentPage',
accountId: 'getCurrentAccountId',
}),
resultsCount() {
return this.conversations.length;
},
showSearchResult() {
return (
this.searchTerm && this.conversations.length && !this.uiFlags.isFetching
);
},
showEmptyResult() {
return (
this.searchTerm &&
!this.conversations.length &&
!this.uiFlags.isFetching
);
},
},
watch: {
searchTerm(newValue) {
if (this.typingTimer) {
clearTimeout(this.typingTimer);
}
this.typingTimer = setTimeout(() => {
this.hasSearched = true;
this.$store.dispatch('conversationSearch/get', { q: newValue });
}, 1000);
},
currentPage() {
this.clearSearchTerm();
},
},
mounted() {
this.$store.dispatch('conversationSearch/get', { q: '' });
bus.$on('clearSearchInput', () => {
this.clearSearchTerm();
});
},
methods: {
onSearch() {
this.showSearchBox = true;
},
closeSearch() {
this.showSearchBox = false;
},
clearSearchTerm() {
this.searchTerm = '';
searchUrl() {
return frontendURL(`accounts/${this.accountId}/search`);
},
},
};
@ -163,12 +73,24 @@ export default {
var(--space-normal);
&:hover {
.search--icon {
.search--icon,
.search--label {
color: var(--w-500);
}
}
}
.search--link {
display: inline-flex;
align-items: center;
flex: 1;
}
.search--label {
color: var(--color-body);
margin-bottom: 0;
}
.search--input {
align-items: center;
border: 0;

View file

@ -2,6 +2,7 @@ import AppContainer from './Dashboard';
import settings from './settings/settings.routes';
import conversation from './conversation/conversation.routes';
import { routes as contactRoutes } from './contacts/routes';
import { routes as searchRoutes } from './search/routes';
import { routes as notificationRoutes } from './notifications/routes';
import { frontendURL } from '../../helper/URLHelper';
import helpcenterRoutes from './helpcenter/helpcenter.routes';
@ -18,6 +19,7 @@ export default {
...conversation.routes,
...settings.routes,
...contactRoutes,
...searchRoutes,
...notificationRoutes,
],
},

View file

@ -0,0 +1,22 @@
<template>
<div />
</template>
<script>
export default {
mounted() {
this.handler = event => {
this.$emit('keyup', event);
};
window.addEventListener('keyup', this.handler);
},
beforeDestroy() {
window.removeEventListener('keyup', this.handler);
},
};
</script>
<style scoped>
div {
display: none;
}
</style>

View file

@ -0,0 +1,101 @@
<template>
<div>
<search-focus @keyup="focusSearch" />
<div class="input-container">
<div class="icon-container">
<fluent-icon icon="search" class="icon" aria-hidden="true" />
</div>
<input
ref="searchInput"
type="search"
placeholder="Search message content, contact name, email or phone or conversations"
:value="searchQuery"
@input="debounceSearch"
/>
<div class="key-binding">
<span>{{ $t('SEARCH.PLACEHOLDER_KEYBINDING') }}</span>
</div>
</div>
</div>
</template>
<script>
import SearchFocus from './SearchFocus.vue';
export default {
components: {
SearchFocus,
},
data() {
return {
searchQuery: '',
};
},
mounted() {
this.$refs.searchInput.focus();
},
methods: {
debounceSearch(e) {
this.searchQuery = e.target.value;
clearTimeout(this.debounce);
this.debounce = setTimeout(async () => {
this.$emit('search', this.searchQuery);
}, 500);
},
focusSearch(e) {
if (e.key === '/') this.$refs.searchInput.focus();
},
},
};
</script>
<style lang="scss" scoped>
.input-container {
position: relative;
border-radius: var(--border-radius-normal);
input[type='search'] {
width: 100%;
padding-left: calc(var(--space-large) + var(--space-small));
padding-right: var(--space-mega);
&:focus {
.icon {
color: var(--w-500) !important;
}
}
}
}
.icon-container {
padding-left: var(--space-slab);
display: flex;
align-items: center;
top: 0;
bottom: 0;
left: 0;
position: absolute;
.icon {
color: var(--s-400);
}
}
.key-binding {
position: absolute;
top: 0;
bottom: 0;
right: 0;
padding: var(--space-small) var(--space-small) 0 var(--space-small);
span {
color: var(--s-400);
font-weight: var(--font-weight-medium);
font-size: 1.4rem;
padding: 0 var(--space-small);
border: 1px solid var(--s-400);
border-radius: var(--border-radius-normal);
display: inline-flex;
align-items: center;
}
}
</style>

View file

@ -0,0 +1,81 @@
<template>
<router-link :to="navigateTo" class="contact-item">
<thumbnail :src="contact.thumbnail" size="42px" :username="contact.name" />
<div class="contact-details">
<p class="name">{{ contact.name }}</p>
<div class="details-meta">
<p v-if="contact.email" class="email">{{ contact.email }}</p>
<p v-if="contact.phone_number" class="separator">·</p>
<p v-if="contact.phone_number" class="phone_number">
{{ contact.phone_number }}
</p>
</div>
</div>
</router-link>
</template>
<script>
import Thumbnail from 'dashboard/components/widgets/Thumbnail.vue';
import { mapGetters } from 'vuex';
import { frontendURL } from 'dashboard/helper/URLHelper.js';
export default {
components: {
Thumbnail,
},
props: {
contact: {
type: Object,
default: () => ({}),
},
},
computed: {
...mapGetters({
accountId: 'getCurrentAccountId',
}),
navigateTo() {
return frontendURL(
`accounts/${this.accountId}/contacts/${this.contact.id}`
);
},
},
};
</script>
<style scoped lang="scss">
.contact-item {
width: 100%;
text-align: left;
display: flex;
cursor: pointer;
align-items: center;
padding: var(--space-small);
.contact-details {
margin-left: var(--space-slab);
.name {
margin: 0;
color: var(--s-700);
font-weight: var(--font-weight-bold);
font-size: var(--font-size-default);
}
.details-meta {
p {
margin: 0;
color: var(--s-500);
font-size: var(--font-size-small);
}
display: flex;
align-items: center;
}
.details-meta > :not([hidden]) ~ :not([hidden]) {
margin-right: calc(1rem * 0);
margin-left: calc(1rem * calc(1 - 0));
}
}
&:hover {
background-color: var(--s-50);
}
}
</style>

View file

@ -0,0 +1,29 @@
<template>
<search-result-section
:title="$t('SEARCH.SECTION.CONTACTS')"
:empty="!contacts.length"
>
<ul class="search-list">
<li v-for="contact in contacts" :key="contact.id">
<search-result-contact-item :contact="contact" />
</li>
</ul>
</search-result-section>
</template>
<script>
import SearchResultSection from './SearchResultSection.vue';
import SearchResultContactItem from './SearchResultContactItem.vue';
export default {
components: {
SearchResultSection,
SearchResultContactItem,
},
props: {
contacts: {
type: Array,
default: () => [],
},
},
};
</script>

View file

@ -0,0 +1,103 @@
<template>
<router-link :to="navigateTo" class="list-item">
<thumbnail size="42px" :username="conversation.contact.name" />
<div class="conversation-details">
<div class="conversation-meta">
<inbox-name :inbox="conversation.inbox" />
<span class="timestamp">
<time-ago :timestamp="conversation.created_at" />
</span>
</div>
<p class="name">{{ conversation.contact.name }}</p>
<div v-dompurify-html="messageContent" class="message-content" />
</div>
</router-link>
</template>
<script>
import Thumbnail from 'dashboard/components/widgets/Thumbnail.vue';
import messageFormatterMixin from 'shared/mixins/messageFormatterMixin';
import InboxName from 'dashboard/components/widgets/InboxName.vue';
import timeAgo from 'dashboard/components/ui/TimeAgo';
import { mapGetters } from 'vuex';
import { frontendURL } from 'dashboard/helper/URLHelper.js';
export default {
components: {
Thumbnail,
InboxName,
timeAgo,
},
mixins: [messageFormatterMixin],
props: {
conversation: {
type: Object,
default: () => ({}),
},
},
computed: {
messageContent() {
return (
this.formatMessage(
this.conversation.messages[this.conversation.messages.length - 1]
.content
) || ''
);
},
...mapGetters({
accountId: 'getCurrentAccountId',
}),
navigateTo() {
return frontendURL(
`accounts/${this.accountId}/conversations/${this.conversation.id}`
);
},
},
};
</script>
<style scoped lang="scss">
.list-item {
width: 100%;
text-align: left;
display: flex;
cursor: pointer;
align-items: start;
padding: var(--space-small);
&:hover {
background-color: var(--s-50);
}
.conversation-details {
margin-left: var(--space-slab);
flex-grow: 1;
.name {
margin: 0;
color: var(--s-700);
font-weight: var(--font-weight-bold);
font-size: var(--font-size-default);
}
.message-content {
margin: 0;
color: var(--s-500);
font-size: var(--font-size-small);
}
.details-meta > :not([hidden]) ~ :not([hidden]) {
margin-right: calc(1rem * 0);
margin-left: calc(1rem * calc(1 - 0));
}
}
.conversation-meta {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: var(--space-small);
.timestamp {
color: var(--s-500);
font-size: var(--font-size-small);
}
}
}
</style>

View file

@ -0,0 +1,29 @@
<template>
<search-result-section
:title="$t('SEARCH.SECTION.CONVERSATIONS')"
:empty="!conversations.length"
>
<ul class="search-list">
<li v-for="conversation in conversations" :key="conversation.id">
<search-result-conversation-item :conversation="conversation" />
</li>
</ul>
</search-result-section>
</template>
<script>
import SearchResultSection from './SearchResultSection.vue';
import SearchResultConversationItem from './SearchResultConversationItem.vue';
export default {
components: {
SearchResultSection,
SearchResultConversationItem,
},
props: {
conversations: {
type: Array,
default: () => [],
},
},
};
</script>

View file

@ -0,0 +1,86 @@
<template>
<router-link :to="navigateTo" class="list-item">
<thumbnail :src="getThumbnail" size="42px" :username="getName" />
<div class="message-details">
<p class="name">{{ getName }}</p>
<div v-dompurify-html="messageContent" class="message-content" />
</div>
</router-link>
</template>
<script>
import Thumbnail from 'dashboard/components/widgets/Thumbnail.vue';
import messageFormatterMixin from 'shared/mixins/messageFormatterMixin';
import { mapGetters } from 'vuex';
import { frontendURL } from 'dashboard/helper/URLHelper.js';
export default {
components: {
Thumbnail,
},
mixins: [messageFormatterMixin],
props: {
message: {
type: Object,
default: () => ({}),
},
},
computed: {
messageContent() {
return this.formatMessage(this.message.content);
},
...mapGetters({
accountId: 'getCurrentAccountId',
}),
navigateTo() {
return frontendURL(
`accounts/${this.accountId}/conversations/${this.message.conversation_id}`
);
},
getThumbnail() {
return this.message.sender && this.message.sender.thumbnail
? this.message.sender.thumbnail
: '';
},
getName() {
return this.message && this.message.sender && this.message.sender.name
? this.message.sender.name
: '';
},
},
};
</script>
<style scoped lang="scss">
.list-item {
width: 100%;
text-align: left;
display: flex;
cursor: pointer;
align-items: start;
padding: var(--space-small);
.message-details {
margin-left: var(--space-slab);
.name {
margin: 0;
color: var(--s-700);
font-weight: var(--font-weight-bold);
font-size: var(--font-size-default);
}
.message-content {
margin: 0;
color: var(--s-500);
font-size: var(--font-size-small);
}
.details-meta > :not([hidden]) ~ :not([hidden]) {
margin-right: calc(1rem * 0);
margin-left: calc(1rem * calc(1 - 0));
}
}
&:hover {
background-color: var(--s-50);
}
}
</style>

View file

@ -0,0 +1,29 @@
<template>
<search-result-section
:title="$t('SEARCH.SECTION.MESSAGES')"
:empty="!messages.length"
>
<ul class="search-list">
<li v-for="message in messages" :key="message.id">
<search-result-message-item :message="message" />
</li>
</ul>
</search-result-section>
</template>
<script>
import SearchResultSection from './SearchResultSection.vue';
import SearchResultMessageItem from './SearchResultMessageItem.vue';
export default {
components: {
SearchResultSection,
SearchResultMessageItem,
},
props: {
messages: {
type: Array,
default: () => [],
},
},
};
</script>

View file

@ -0,0 +1,70 @@
<template>
<section>
<div class="label-container">
<p>{{ title }}</p>
</div>
<slot />
<div v-if="empty" class="empty">
<fluent-icon icon="info" size="32px" class="icon" />
<p class="empty-state__text">
{{ $t('SEARCH.EMPTY_STATE') }}
</p>
</div>
</section>
</template>
<script>
export default {
props: {
title: {
type: String,
default: '',
},
empty: {
type: Boolean,
default: false,
},
},
};
</script>
<style scoped lang="scss">
.search-list {
list-style: none;
margin: 0;
padding: var(--spacing-normal) 0;
}
.label-container {
position: sticky;
top: 0;
padding: var(--space-small);
background-color: var(--s-25);
z-index: 50;
border-bottom-width: 1px;
border-top-width: 1px;
border-color: #dbdbdb;
border-style: solid;
border-left: 0;
border-right: 0;
p {
font-size: var(--font-size-small);
color: var(--b-600);
margin: 0;
}
}
.empty {
padding: var(--space-normal);
.icon {
font-size: 2rem;
color: var(--s-500);
margin: 0 auto;
display: block;
}
.empty-state__text {
text-align: center;
margin-top: var(--space-small);
color: var(--s-500);
}
}
</style>

View file

@ -0,0 +1,34 @@
<template>
<div class="tab-container">
<woot-tabs :index="activeTab" :border="false" @change="onTabChange">
<woot-tabs-item
v-for="item in tabs"
:key="item.key"
:name="item.name"
:count="item.count"
/>
</woot-tabs>
</div>
</template>
<script>
export default {
props: {
tabs: {
type: Array,
default: () => [],
},
},
data() {
return {
activeTab: 0,
};
},
methods: {
onTabChange(index) {
this.activeTab = index;
this.$emit('tab-change', this.tabs[index].key);
},
},
};
</script>

View file

@ -0,0 +1,148 @@
<template>
<section class="search-root">
<header>
<search-header @search="search" />
<search-tabs :tabs="tabs" @tab-change="tab => (selectedTab = tab)" />
</header>
<div class="search-results">
<woot-loading-state v-if="uiFlags.isFetching" :message="'Searching'" />
<div v-else>
<div v-if="all.length">
<search-result-contacts-list
v-if="filterContacts"
:contacts="contacts"
/>
<search-result-messages-list
v-if="filterMessages"
:messages="messages"
/>
<search-result-conversations-list
v-if="filterConversations"
:conversations="conversations"
/>
</div>
</div>
</div>
</section>
</template>
<script>
import SearchHeader from './SearchHeader.vue';
import SearchTabs from './SearchTabs.vue';
import SearchResultConversationsList from './SearchResultConversationsList.vue';
import SearchResultMessagesList from './SearchResultMessagesList.vue';
import SearchResultContactsList from './SearchResultContactsList.vue';
import { mapGetters } from 'vuex';
export default {
components: {
SearchHeader,
SearchTabs,
SearchResultContactsList,
SearchResultConversationsList,
SearchResultMessagesList,
},
data() {
return {
selectedTab: 'all',
query: '',
};
},
computed: {
...mapGetters({
fullSearchRecords: 'conversationSearch/getFullSearchRecords',
uiFlags: 'conversationSearch/getUIFlags',
}),
contacts() {
if (this.fullSearchRecords.contacts) {
return this.fullSearchRecords.contacts.map(contact => ({
...contact,
type: 'contact',
}));
}
return [];
},
conversations() {
if (this.fullSearchRecords.conversations) {
return this.fullSearchRecords.conversations.map(conversation => ({
...conversation,
type: 'conversation',
}));
}
return [];
},
messages() {
if (this.fullSearchRecords.messages) {
return this.fullSearchRecords.messages.map(message => ({
...message,
type: 'message',
}));
}
return [];
},
all() {
return [...this.contacts, ...this.conversations, ...this.messages];
},
filterContacts() {
return this.selectedTab === 'contacts' || this.selectedTab === 'all';
},
filterConversations() {
return this.selectedTab === 'conversations' || this.selectedTab === 'all';
},
filterMessages() {
return this.selectedTab === 'messages' || this.selectedTab === 'all';
},
tabs() {
return [
{
key: 'all',
name: this.$t('SEARCH.TABS.ALL'),
count:
this.contacts.length +
this.conversations.length +
this.messages.length,
},
{
key: 'contacts',
name: this.$t('SEARCH.TABS.CONTACTS'),
count: this.contacts.length,
},
{
key: 'conversations',
name: this.$t('SEARCH.TABS.CONVERSATIONS'),
count: this.conversations.length,
},
{
key: 'messages',
name: this.$t('SEARCH.TABS.MESSAGES'),
count: this.messages.length,
},
];
},
},
methods: {
search(q) {
this.$store.dispatch('conversationSearch/fullSearch', { q });
},
},
};
</script>
<style lang="scss" scoped>
header {
padding: var(--space-large) var(--space-normal) 0 var(--space-normal);
}
.search-root {
max-width: 800px;
width: 100%;
margin: 0 auto;
height: 100%;
display: flex;
flex-direction: column;
.search-results {
flex-grow: 1;
height: 100%;
overflow-y: auto;
}
}
</style>

View file

@ -0,0 +1,12 @@
/* eslint arrow-body-style: 0 */
import SearchView from './components/SearchView.vue';
import { frontendURL } from '../../../helper/URLHelper';
export const routes = [
{
path: frontendURL('accounts/:accountId/search'),
name: 'search',
roles: ['administrator', 'agent'],
component: SearchView,
},
];

View file

@ -2,6 +2,7 @@ import ConversationAPI from '../../api/inbox/conversation';
import types from '../mutation-types';
export const initialState = {
records: [],
fullSearchRecords: {},
uiFlags: {
isFetching: false,
},
@ -11,6 +12,9 @@ export const getters = {
getConversations(state) {
return state.records;
},
getFullSearchRecords(state) {
return state.fullSearchRecords;
},
getUIFlags(state) {
return state.uiFlags;
},
@ -34,15 +38,36 @@ export const actions = {
commit(types.SEARCH_CONVERSATIONS_SET_UI_FLAG, { isFetching: false });
}
},
async fullSearch({ commit }, { q }) {
commit(types.FULL_SEARCH_SET, []);
if (!q) {
return;
}
commit(types.FULL_SEARCH_SET_UI_FLAG, { isFetching: true });
try {
const { data } = await ConversationAPI.fullSearch({ q });
commit(types.FULL_SEARCH_SET, data.payload);
} catch (error) {
// Ignore error
} finally {
commit(types.FULL_SEARCH_SET_UI_FLAG, { isFetching: false });
}
},
};
export const mutations = {
[types.SEARCH_CONVERSATIONS_SET](state, records) {
state.records = records;
},
[types.FULL_SEARCH_SET](state, records) {
state.fullSearchRecords = records;
},
[types.SEARCH_CONVERSATIONS_SET_UI_FLAG](state, uiFlags) {
state.uiFlags = { ...state.uiFlags, ...uiFlags };
},
[types.FULL_SEARCH_SET_UI_FLAG](state, uiFlags) {
state.uiFlags = { ...state.uiFlags, ...uiFlags };
},
};
export default {

View file

@ -1,6 +1,7 @@
import { actions } from '../../conversationSearch';
import types from '../../../mutation-types';
import axios from 'axios';
import { fullSearchResponse } from './fixtures';
const commit = jest.fn();
global.axios = axios;
jest.mock('axios');
@ -41,4 +42,36 @@ describe('#actions', () => {
]);
});
});
describe('#fullSearch', () => {
it('sends correct actions if no query param is provided', () => {
actions.fullSearch({ commit }, { q: '' });
expect(commit.mock.calls).toEqual([[types.FULL_SEARCH_SET, []]]);
});
it('sends correct actions if query param is provided and API call is success', async () => {
axios.get.mockResolvedValue({
data: {
payload: fullSearchResponse,
},
});
await actions.fullSearch({ commit }, { q: 'value' });
expect(commit.mock.calls).toEqual([
[types.FULL_SEARCH_SET, []],
[types.FULL_SEARCH_SET_UI_FLAG, { isFetching: true }],
[types.FULL_SEARCH_SET, fullSearchResponse],
[types.FULL_SEARCH_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.fullSearch({ commit }, { q: 'value' });
expect(commit.mock.calls).toEqual([
[types.FULL_SEARCH_SET, []],
[types.FULL_SEARCH_SET_UI_FLAG, { isFetching: true }],
[types.FULL_SEARCH_SET_UI_FLAG, { isFetching: false }],
]);
});
});
});

View file

@ -0,0 +1,179 @@
export const fullSearchResponse = {
conversations: [
{
id: 93,
created_at: 1668756114,
contact: {
id: 168,
name: 'summer-wildflower-139',
},
inbox: {
id: 1,
name: 'Acme Support',
channel_type: 'Channel::WebWidget',
},
messages: [
{
content: 'Hello',
id: 1324,
sender_name: 'summer-wildflower-139',
message_type: 0,
created_at: 1668756114,
},
{
content: 'Hi There 👋',
id: 1325,
sender_name: 'Welcome Bot',
message_type: 1,
created_at: 1668756116,
},
{
content: '',
id: 1326,
sender_name: 'Welcome Bot',
message_type: 1,
created_at: 1668756118,
},
{
content: 'Enjoy the minion',
id: 1327,
sender_name: 'Welcome Bot',
message_type: 1,
created_at: 1668756118,
},
{
content: 'Do you like Pizza',
id: 1328,
sender_name: 'Welcome Bot',
message_type: 1,
created_at: 1668756118,
},
{
content: '',
id: 1329,
sender_name: 'Welcome Bot',
message_type: 1,
created_at: 1668756129,
},
{
content: "Here's some markdown for you",
id: 1330,
sender_name: 'Welcome Bot',
message_type: 1,
created_at: 1668756129,
},
{
content:
'[link text](https://google.com) **Some Bold text** # A large title',
id: 1331,
sender_name: 'Welcome Bot',
message_type: 1,
created_at: 1668756129,
},
{
content: 'Hi',
id: 1332,
sender_name: 'summer-wildflower-139',
message_type: 0,
created_at: 1668756133,
},
{
content: 'Hi',
id: 1333,
sender_name: 'Welcome Bot',
message_type: 1,
created_at: 1668756134,
},
{
content: 'Bye',
id: 1334,
sender_name: 'summer-wildflower-139',
message_type: 0,
created_at: 1668756141,
},
],
account_id: 1,
},
{
id: 96,
created_at: 1669368899,
contact: {
id: 6,
name: 'Fayaz',
},
inbox: {
id: 15,
name: 'Whatsapp',
channel_type: 'Channel::Whatsapp',
},
messages: [
{
content:
'Your package has been shipped. It will be delivered in 12 business days.',
id: 1351,
sender_name: 'Fayaz Ahmed',
message_type: 1,
created_at: 1669368899,
},
{
content: 'This is your flight confirmation for 123-123 on 123.',
id: 1352,
sender_name: 'Fayaz Ahmed',
message_type: 1,
created_at: 1669368988,
},
{
content: 'Esta é a sua confirmação de voo para das-zxc em qwe.',
id: 1353,
sender_name: 'Fayaz Ahmed',
message_type: 1,
created_at: 1669369021,
},
],
account_id: 1,
},
],
contacts: [
{
additional_attributes: {},
availability_status: 'offline',
email: null,
id: 94,
name: 'purple-hill-409',
phone_number: null,
identifier: null,
thumbnail: '',
custom_attributes: {},
last_activity_at: 1649918760,
},
],
messages: [
{
id: 1008,
content: 'Where can I download my invoices?',
inbox_id: 1,
conversation_id: 79,
message_type: 0,
content_type: 'text',
status: 'sent',
content_attributes: {},
created_at: 1663941027,
private: false,
source_id: null,
sender: {
additional_attributes: {},
custom_attributes: {
vfer: false,
xcvb: 'hello',
},
email: null,
id: 133,
identifier: null,
name: 'morning-violet-166',
phone_number: null,
thumbnail: '',
type: 'contact',
},
},
],
};

View file

@ -262,4 +262,8 @@ export default {
SET_CONVERSATION_WATCHERS_UI_FLAG: 'SET_CONVERSATION_WATCHERS_UI_FLAG',
SET_CONVERSATION_WATCHERS: 'SET_CONVERSATION_WATCHERS',
// Full Search
FULL_SEARCH_SET: 'FULL_SEARCH_SET',
FULL_SEARCH_SET_UI_FLAG: 'FULL_SEARCH_SET_UI_FLAG',
};

View file

@ -0,0 +1,49 @@
module MultiSearchableHelpers
extend ActiveSupport::Concern
included do
PgSearch.multisearch_options = {
using: {
# trigram: {},
tsearch: {
prefix: true,
any_word: true,
normalization: 3
}
}
}
def update_contact_search_document
return if contact_pg_search_record.present?
initialize_contact_pg_search_record.update!(
content: "#{contact.id} #{contact.email} #{contact.name} #{contact.phone_number} #{contact.account_id}",
conversation_id: id
)
end
end
def contact_pg_search_record
contacts_pg_search_records.find_by(conversation_id: id)
end
def initialize_contact_pg_search_record
record = contacts_pg_search_records.find_by(conversation_id: nil)
return record if record.present?
PgSearch::Document.new(
searchable_type: 'Contact',
searchable_id: contact_id,
account_id: account_id
)
end
def contacts_pg_search_records
PgSearch::Document.where(
searchable_type: 'Contact',
searchable_id: contact_id,
account_id: account_id
)
end
end

View file

@ -26,6 +26,13 @@ class Contact < ApplicationRecord
include Avatarable
include AvailabilityStatusable
include Labelable
include PgSearch::Model
include MultiSearchableHelpers
multisearchable(
against: [:id, :email, :name, :phone_number],
additional_attributes: ->(contact) { { conversation_id: nil, account_id: contact.account_id } }
)
validates :account_id, presence: true
validates :email, allow_blank: true, uniqueness: { scope: [:account_id], case_sensitive: false },
@ -140,6 +147,24 @@ class Contact < ApplicationRecord
email_format
end
def self.rebuild_pg_search_documents
return super unless name == 'Contact'
connection.execute <<~SQL.squish
INSERT INTO pg_search_documents (searchable_type, searchable_id, content, account_id, conversation_id, created_at, updated_at)
SELECT 'Contact' AS searchable_type,
contacts.id AS searchable_id,
CONCAT_WS(' ', contacts.id, contacts.email, contacts.name, contacts.phone_number, contacts.account_id) AS content,
contacts.account_id::int AS account_id,
conversations.id AS conversation_id,
now() AS created_at,
now() AS updated_at
FROM contacts
LEFT OUTER JOIN conversations
ON conversations.contact_id = contacts.id
SQL
end
private
def ip_lookup

View file

@ -48,7 +48,13 @@ class Conversation < ApplicationRecord
include ActivityMessageHandler
include UrlHelper
include SortHandler
include PgSearch::Model
include MultiSearchableHelpers
multisearchable(
against: [:display_id],
additional_attributes: ->(conversation) { { conversation_id: conversation.id, account_id: conversation.account_id } }
)
validates :account_id, presence: true
validates :inbox_id, presence: true
before_validation :validate_additional_attributes
@ -93,6 +99,7 @@ class Conversation < ApplicationRecord
after_update_commit :execute_after_update_commit_callbacks
after_create_commit :notify_conversation_creation
after_create_commit :update_contact_search_document, if: :contact_id?
after_commit :set_display_id, unless: :display_id?
delegate :auto_resolve_duration, to: :account

View file

@ -33,6 +33,14 @@
class Message < ApplicationRecord
include MessageFilterHelpers
NUMBER_OF_PERMITTED_ATTACHMENTS = 15
include PgSearch::Model
include MultiSearchableHelpers
multisearchable(
against: [:content],
if: :allowed_message_types?,
additional_attributes: ->(message) { { conversation_id: message.conversation_id, account_id: message.account_id } }
)
before_validation :ensure_content_type
@ -274,4 +282,8 @@ class Message < ApplicationRecord
conversation.update_columns(last_activity_at: created_at)
# rubocop:enable Rails/SkipsModelValidations
end
def allowed_message_types?
incoming? || outgoing?
end
end

View file

@ -0,0 +1,19 @@
json.payload do
json.conversations do
json.array! @result[:conversations] do |conversation|
json.partial! 'api/v1/models/conversation', formats: [:json], conversation: conversation
end
end
json.contacts do
json.array! @result[:contacts] do |contact|
json.partial! 'api/v1/models/contact', formats: [:json], resource: contact
end
end
json.messages do
json.array! @result[:messages] do |message|
json.partial! 'api/v1/models/message', formats: [:json], message: message
end
end
end

View file

@ -2,7 +2,8 @@ json.id message.id
json.content message.content
json.inbox_id message.inbox_id
json.echo_id message.echo_id if message.echo_id
json.conversation_id message.conversation.display_id
# For deleted conversation, messages are not yet deleted [because of destroy_async] for this we added try block
json.conversation_id message.conversation.try(:display_id)
json.message_type message.message_type_before_type_cast
json.content_type message.content_type
json.status message.status

View file

@ -71,6 +71,7 @@ Rails.application.routes.draw do
get :meta
get :search
post :filter
get :text_search
end
scope module: :conversations do
resources :messages, only: [:index, :create, :destroy]

View file

@ -0,0 +1,21 @@
class CreatePgSearchDocuments < ActiveRecord::Migration[6.1]
def up
say_with_time('Creating table for pg_search multisearch') do
create_table :pg_search_documents do |t|
t.text :content
t.bigint 'conversation_id'
t.bigint 'account_id'
t.belongs_to :searchable, polymorphic: true, index: true
t.timestamps null: false
end
add_index :pg_search_documents, :account_id
add_index :pg_search_documents, :conversation_id
end
end
def down
say_with_time('Dropping table for pg_search multisearch') do
drop_table :pg_search_documents
end
end
end

View file

@ -0,0 +1,12 @@
class EnableMultiSearchable < ActiveRecord::Migration[6.1]
def up
Contact.rebuild_pg_search_documents
PgSearch::Multisearch.rebuild(Conversation)
PgSearch::Multisearch.rebuild(Message)
# execute 'create extension pg_trgm;'
end
def down
PgSearch::Document.delete_all
end
end

View file

@ -10,10 +10,11 @@
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2022_11_16_000514) do
ActiveRecord::Schema.define(version: 2022_12_12_061802) do
# These are extensions that must be enabled in order to support this database
enable_extension "pg_stat_statements"
enable_extension "pg_trgm"
enable_extension "pgcrypto"
enable_extension "plpgsql"
@ -674,6 +675,19 @@ ActiveRecord::Schema.define(version: 2022_11_16_000514) do
t.index ["user_id"], name: "index_notifications_on_user_id"
end
create_table "pg_search_documents", force: :cascade do |t|
t.text "content"
t.bigint "conversation_id"
t.bigint "account_id"
t.string "searchable_type"
t.bigint "searchable_id"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["account_id"], name: "index_pg_search_documents_on_account_id"
t.index ["conversation_id"], name: "index_pg_search_documents_on_conversation_id"
t.index ["searchable_type", "searchable_id"], name: "index_pg_search_documents_on_searchable"
end
create_table "platform_app_permissibles", force: :cascade do |t|
t.bigint "platform_app_id", null: false
t.string "permissible_type", null: false

View file

@ -0,0 +1,51 @@
require 'rails_helper'
describe ::TextSearch do
subject(:text_search) { described_class.new(user_1, params) }
let!(:account) { create(:account) }
let!(:user_1) { create(:user, account: account) }
let!(:user_2) { create(:user, account: account) }
let!(:inbox) { create(:inbox, account: account, enable_auto_assignment: false) }
before do
create(:inbox_member, user: user_1, inbox: inbox)
create(:inbox_member, user: user_2, inbox: inbox)
create(:contact, name: '1223', account_id: account.id)
create(:contact, name: 'Potter', account_id: account.id)
contact_2 = create(:contact, name: 'Harry Potter', account_id: account.id)
conversation_1 = create(:conversation, account: account, inbox: inbox, assignee: user_1, display_id: 121)
conversation_2 = create(:conversation, account: account, inbox: inbox, assignee: user_1, display_id: 122)
create(:conversation, account: account, inbox: inbox, assignee: user_1, status: 'resolved', display_id: 13, contact_id: contact_2.id)
create(:conversation, account: account, inbox: inbox, assignee: user_2, display_id: 14)
create(:conversation, account: account, inbox: inbox, display_id: 15)
Current.account = account
create(:message, conversation_id: conversation_1.id, account_id: account.id, content: 'Ask Lisa')
create(:message, conversation_id: conversation_1.id, account_id: account.id, content: 'message_12')
create(:message, conversation_id: conversation_1.id, account_id: account.id, content: 'message_13')
create(:message, conversation_id: conversation_2.id, account_id: account.id, content: 'Pottery Barn order')
create(:message, conversation_id: conversation_2.id, account_id: account.id, content: 'message_22')
create(:message, conversation_id: conversation_2.id, account_id: account.id, content: 'message_23')
end
describe '#perform' do
context 'with text search' do
it 'filter conversations by number' do
params = { q: '12' }
result = described_class.new(user_1, params).perform
expect(result[:conversations].length).to be 2
expect(result[:contacts].length).to be 1
end
it 'filter conversations by string' do
params = { q: 'pot' }
result = described_class.new(user_1, params).perform
expect(result[:messages].length).to be 1
expect(result[:contacts].length).to be 2
end
end
end
end