Merge branch 'develop' into feat/onboarding

This commit is contained in:
Nithin David Thomas
2024-02-12 04:53:23 -08:00
committed by GitHub
63 changed files with 1401 additions and 509 deletions
+7
View File
@@ -0,0 +1,7 @@
## All javascript files should be reviewed by pranav before merging
*.js @pranavrajs
*.vue @pranavrajs
## All enterprise related files should be reviewed by sojan before merging
/enterprise/* @sojan-official
@@ -11,7 +11,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v2
uses: actions/checkout@v4
- name: Check for log lines and calculate percentage
run: |
+3 -3
View File
@@ -4,7 +4,7 @@
# # This action will try to install and setup
# # chatwoot on an Ubuntu 20.04 machine using
# # the linux installer script.
# #
# #
# # This is set to run daily at midnight.
# #
@@ -35,7 +35,7 @@ jobs:
run: |
sudo ./install.sh --install < input
# disabling http verify for now as http
# disabling http verify for now as http
# access to port 3000 fails in gh action env
# - name: Verify
# if: always()
@@ -45,7 +45,7 @@ jobs:
# curl http://localhost:3000/api
- name: Upload chatwoot setup log file as an artifact
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
if: always()
with:
name: chatwoot-setup-log-file
@@ -8,7 +8,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- name: Login to GitHub Container Registry
uses: docker/login-action@v1
+1 -1
View File
@@ -21,7 +21,7 @@ jobs:
GIT_REF: ${{ github.head_ref || github.ref_name }} # ref_name to get tags/branches
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v4
- name: Set up QEMU
uses: docker/setup-qemu-action@v1
+4 -4
View File
@@ -41,7 +41,7 @@ jobs:
options: --entrypoint redis-server
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.ref }}
repository: ${{ github.event.pull_request.head.repo.full_name }}
@@ -50,7 +50,7 @@ jobs:
with:
bundler-cache: true # runs 'bundle install' and caches installed gems automatically
- uses: actions/setup-node@v3
- uses: actions/setup-node@v4
with:
node-version: 20
cache: yarn
@@ -76,11 +76,11 @@ jobs:
- name: Run backend tests
run: |
bundle exec rspec --profile=10 --format documentation
env:
env:
NODE_OPTIONS: --openssl-legacy-provider
- name: Upload rails log folder
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
if: always()
with:
name: rails-log-folder
+3 -3
View File
@@ -40,7 +40,7 @@ jobs:
options: --entrypoint redis-server
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.ref }}
repository: ${{ github.event.pull_request.head.repo.full_name }}
@@ -49,7 +49,7 @@ jobs:
with:
bundler-cache: true # runs 'bundle install' and caches installed gems automatically
- uses: actions/setup-node@v3
- uses: actions/setup-node@v4
with:
node-version: 20
cache: yarn
@@ -77,7 +77,7 @@ jobs:
--format documentation
- name: Upload rails log folder
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
if: always()
with:
name: rails-log-folder
+3 -3
View File
@@ -10,7 +10,7 @@ jobs:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.ref }}
repository: ${{ github.event.pull_request.head.repo.full_name }}
@@ -19,7 +19,7 @@ jobs:
with:
bundler-cache: true # runs 'bundle install' and caches installed gems automatically
- uses: actions/setup-node@v3
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'yarn'
@@ -31,7 +31,7 @@ jobs:
run: |
rm -rf enterprise
rm -rf spec/enterprise
- name: Run asset compile
run: bundle exec rake assets:precompile
env:
+9 -9
View File
@@ -316,16 +316,16 @@ GEM
google-cloud-translate-v3 (0.6.0)
gapic-common (>= 0.17.1, < 2.a)
google-cloud-errors (~> 1.0)
google-protobuf (3.22.3)
google-protobuf (3.22.3-arm64-darwin)
google-protobuf (3.22.3-x86_64-darwin)
google-protobuf (3.22.3-x86_64-linux)
google-protobuf (3.25.2)
google-protobuf (3.25.2-arm64-darwin)
google-protobuf (3.25.2-x86_64-darwin)
google-protobuf (3.25.2-x86_64-linux)
googleapis-common-protos (1.4.0)
google-protobuf (~> 3.14)
googleapis-common-protos-types (~> 1.2)
grpc (~> 1.27)
googleapis-common-protos-types (1.6.0)
google-protobuf (~> 3.14)
googleapis-common-protos-types (1.11.0)
google-protobuf (~> 3.18)
googleauth (1.5.2)
faraday (>= 0.17.3, < 3.a)
jwt (>= 1.4, < 3.0)
@@ -335,13 +335,13 @@ GEM
signet (>= 0.16, < 2.a)
groupdate (6.2.1)
activesupport (>= 5.2)
grpc (1.54.0)
grpc (1.54.3)
google-protobuf (~> 3.21)
googleapis-common-protos-types (~> 1.0)
grpc (1.54.0-x86_64-darwin)
grpc (1.54.3-x86_64-darwin)
google-protobuf (~> 3.21)
googleapis-common-protos-types (~> 1.0)
grpc (1.54.0-x86_64-linux)
grpc (1.54.3-x86_64-linux)
google-protobuf (~> 3.21)
googleapis-common-protos-types (~> 1.0)
haikunator (1.1.1)
@@ -1,7 +1,8 @@
module AccessTokenAuthHelper
BOT_ACCESSIBLE_ENDPOINTS = {
'api/v1/accounts/conversations' => %w[toggle_status create],
'api/v1/accounts/conversations/messages' => ['create']
'api/v1/accounts/conversations' => %w[toggle_status toggle_priority create],
'api/v1/accounts/conversations/messages' => ['create'],
'api/v1/accounts/conversations/assignments' => ['create']
}.freeze
def ensure_access_token
@@ -25,6 +25,6 @@ module EnsureCurrentAccountHelper
end
def account_accessible_for_bot?(account)
render_unauthorized('You are not authorized to access this account') unless @resource.agent_bot_inboxes.find_by(account_id: account.id)
render_unauthorized('Bot is not authorized to access this account') unless @resource.agent_bot_inboxes.find_by(account_id: account.id)
end
end
@@ -28,8 +28,7 @@ class SuperAdmin::InstanceStatusesController < SuperAdmin::ApplicationController
end
def sha
sha = `git rev-parse HEAD`
@metrics['Git SHA'] = sha.presence || 'n/a'
@metrics['Git SHA'] = GIT_HASH
end
def postgres_status
+10 -10
View File
@@ -15,8 +15,8 @@ module Api::V2::Accounts::HeatmapHelper
dates = data.pluck(:date).uniq.sort
# add the dates as the first row, leave an empty cell for the hour column
# e.g. [nil, '2023-01-01', '2023-1-02', '2023-01-03']
result_arr << ([nil] + dates)
# e.g. ['Start of the hour', '2023-01-01', '2023-1-02', '2023-01-03']
result_arr << (['Start of the hour'] + dates)
# group the data by hour, we do not need to sort it, because the data is already sorted
# given it starts from the beginning of the day
@@ -25,7 +25,7 @@ module Api::V2::Accounts::HeatmapHelper
# value = [{date: 2023-01-01, value: 1}, {date: 2023-01-02, value: 1}, {date: 2023-01-03, value: 1}, ...]
data.group_by { |d| d[:hour] }.each do |hour, items|
# create a new row for each hour
row = [hour]
row = [format('%02d:00', hour)]
# group the items by date, so we can easily access the value for each date
# grouped values will be a hasg with the date as the key, and the value as the value
@@ -37,7 +37,7 @@ module Api::V2::Accounts::HeatmapHelper
row << (grouped_values[date][0][:value] if grouped_values[date].is_a?(Array))
end
# row will look like [22, 0, 0, 1, 4, 6, 7, 4]
# row will look like ['22:00', 0, 0, 1, 4, 6, 7, 4]
# add the row to the result array
result_arr << row
@@ -46,12 +46,12 @@ module Api::V2::Accounts::HeatmapHelper
# return the resultant array
# the result looks like this
# [
# [nil, '2023-01-01', '2023-1-02', '2023-01-03'],
# [0, 0, 0, 0],
# [1, 0, 0, 0],
# [2, 0, 0, 0],
# [3, 0, 0, 0],
# [4, 0, 0, 0],
# ['Start of the hour', '2023-01-01', '2023-1-02', '2023-01-03'],
# ['00:00', 0, 0, 0],
# ['01:00', 0, 0, 0],
# ['02:00', 0, 0, 0],
# ['03:00', 0, 0, 0],
# ['04:00', 0, 0, 0],
# ]
result_arr
end
@@ -6,8 +6,15 @@ class NotificationsAPI extends ApiClient {
super('notifications', { accountScoped: true });
}
get(page) {
return axios.get(`${this.url}?page=${page}`);
get({ page, status, type, sortOrder }) {
return axios.get(this.url, {
params: {
page,
status,
type,
sort_order: sortOrder,
},
});
}
getNotifications(contactId) {
@@ -28,10 +28,20 @@ describe('#NotificationAPI', () => {
});
it('#get', () => {
notificationsAPI.get(1);
expect(axiosMock.get).toHaveBeenCalledWith(
'/api/v1/notifications?page=1'
);
notificationsAPI.get({
page: 1,
status: 'read',
type: 'Conversation',
sortOrder: 'desc',
});
expect(axiosMock.get).toHaveBeenCalledWith('/api/v1/notifications', {
params: {
page: 1,
status: 'read',
type: 'Conversation',
sort_order: 'desc',
},
});
});
it('#getNotifications', () => {
@@ -65,5 +75,30 @@ describe('#NotificationAPI', () => {
'/api/v1/notifications/read_all'
);
});
it('#snooze', () => {
notificationsAPI.snooze({ id: 1, snoozedUntil: 12332211 });
expect(axiosMock.post).toHaveBeenCalledWith(
'/api/v1/notifications/1/snooze',
{
snoozed_until: 12332211,
}
);
});
it('#delete', () => {
notificationsAPI.delete(1);
expect(axiosMock.delete).toHaveBeenCalledWith('/api/v1/notifications/1');
});
it('#deleteAll', () => {
notificationsAPI.deleteAll({ type: 'all' });
expect(axiosMock.post).toHaveBeenCalledWith(
'/api/v1/notifications/destroy_all',
{
type: 'all',
}
);
});
});
});
@@ -46,6 +46,19 @@ export default {
},
EXAMPLE_URL: 'https://example.com',
EXAMPLE_WEBHOOK_URL: 'https://example/api/webhook',
INBOX_SORT_BY: {
NEWEST: 'desc',
OLDEST: 'asc',
},
INBOX_DISPLAY_BY: {
SNOOZED: 'snoozed',
READ: 'read',
},
INBOX_FILTER_TYPE: {
STATUS: 'status',
TYPE: 'type',
SORT_ORDER: 'sort_order',
},
};
export const DEFAULT_REDIRECT_URL = '/app/';
export const ONBOARDING_START_URL = '/app/start/setup-profile';
@@ -306,7 +306,7 @@ export default {
});
} else if (isAInboxViewRoute(this.$route.name)) {
this.$router.push({
name: 'inbox-view',
name: 'inbox_view',
});
} else if (this.$route.name !== 'contacts_dashboard') {
this.$router.push({
@@ -3,13 +3,13 @@
class="flex flex-col h-full w-full ltr:border-r border-slate-50 dark:border-slate-800/50"
:class="isOnExpandedLayout ? '' : 'min-w-[360px] max-w-[360px]'"
>
<inbox-list-header />
<inbox-list-header @filter="onFilterChange" />
<div
ref="notificationList"
class="flex flex-col w-full h-[calc(100%-56px)] overflow-x-hidden overflow-y-auto"
>
<inbox-card
v-for="notificationItem in records"
v-for="notificationItem in notifications"
:key="notificationItem.id"
:notification-item="notificationItem"
@mark-notification-as-read="markNotificationAsRead"
@@ -42,18 +42,20 @@
<script>
import { mapGetters } from 'vuex';
import wootConstants from 'dashboard/constants/globals';
import InboxCard from './components/InboxCard.vue';
import InboxListHeader from './components/InboxListHeader.vue';
import { INBOX_EVENTS } from 'dashboard/helper/AnalyticsHelper/events';
import IntersectionObserver from 'dashboard/components/IntersectionObserver.vue';
import alertMixin from 'shared/mixins/alertMixin';
import uiSettingsMixin from 'dashboard/mixins/uiSettings';
export default {
components: {
InboxCard,
InboxListHeader,
IntersectionObserver,
},
mixins: [alertMixin],
mixins: [alertMixin, uiSettingsMixin],
props: {
conversationId: {
type: [String, Number],
@@ -71,38 +73,64 @@ export default {
rootMargin: '100px 0px 100px 0px',
},
page: 1,
status: '',
type: '',
sortOrder: wootConstants.INBOX_SORT_BY.NEWEST,
};
},
computed: {
...mapGetters({
accountId: 'getCurrentAccountId',
meta: 'notifications/getMeta',
records: 'notifications/getNotifications',
uiFlags: 'notifications/getUIFlags',
notification: 'notifications/getFilteredNotifications',
}),
inboxFilters() {
return {
page: this.page,
status: this.status,
type: this.type,
sortOrder: this.sortOrder,
};
},
notifications() {
return this.notification(this.inboxFilters);
},
showEndOfList() {
return this.uiFlags.isAllNotificationsLoaded && !this.uiFlags.isFetching;
},
showEmptyState() {
return !this.uiFlags.isFetching && !this.records.length;
return !this.uiFlags.isFetching && !this.notifications.length;
},
showEndOfListMessage() {
return this.showEndOfList && this.records.length;
return this.showEndOfList && this.notifications.length;
},
},
mounted() {
this.$store.dispatch('notifications/clear');
this.$store.dispatch('notifications/index', { page: 1 });
this.setSavedFilter();
this.fetchNotifications();
},
methods: {
fetchNotifications() {
this.page = 1;
this.$store.dispatch('notifications/clear');
const filter = this.inboxFilters;
this.$store.dispatch('notifications/index', filter);
},
redirectToInbox() {
if (!this.conversationId) return;
if (this.$route.name === 'inbox-view') return;
this.$router.push({ name: 'inbox-view' });
if (this.$route.name === 'inbox_view') return;
this.$router.push({ name: 'inbox_view' });
},
loadMoreNotifications() {
if (this.uiFlags.isAllNotificationsLoaded) return;
this.$store.dispatch('notifications/index', { page: this.page + 1 });
this.$store.dispatch('notifications/index', {
page: this.page + 1,
status: this.status,
type: this.type,
sortOrder: this.sortOrder,
});
this.page += 1;
},
markNotificationAsRead(notification) {
@@ -148,6 +176,25 @@ export default {
this.showAlert(this.$t('INBOX.ALERTS.DELETE'));
});
},
onFilterChange(option) {
if (option.type === wootConstants.INBOX_FILTER_TYPE.STATUS) {
this.status = option.selected ? option.key : '';
}
if (option.type === wootConstants.INBOX_FILTER_TYPE.TYPE) {
this.type = option.selected ? option.key : '';
}
if (option.type === wootConstants.INBOX_FILTER_TYPE.SORT_ORDER) {
this.sortOrder = option.key;
}
this.fetchNotifications();
},
setSavedFilter() {
const { inbox_filter_by: filterBy = {} } = this.uiSettings;
const { status, type, sort_by: sortBy } = filterBy;
this.status = status;
this.type = type;
this.sortOrder = sortBy || wootConstants.INBOX_SORT_BY.NEWEST;
},
},
};
</script>
@@ -148,6 +148,7 @@ export default {
name: 'home',
});
}
this.$store.dispatch('agents/get');
},
methods: {
async fetchConversationById() {
@@ -29,7 +29,8 @@
v-if="assigneeMeta"
:src="assigneeMeta.thumbnail"
:username="assigneeMeta.name"
size="20px"
size="16px"
class="relative bottom-0.5"
/>
<div class="flex min-w-0">
<span
@@ -38,18 +38,17 @@
:key="option.key"
role="button"
class="flex rounded-[4px] h-5 w-full items-center justify-between p-0.5 gap-1"
:class="
activeSort === option.key ? 'bg-woot-50 dark:bg-woot-700/50' : ''
"
@click.stop="onSortOptionClick(option.key)"
:class="{
'bg-woot-50 dark:bg-woot-700/50': activeSort === option.key,
}"
@click.stop="onSortOptionClick(option)"
>
<span
class="text-xs font-medium hover:text-woot-600 dark:hover:text-woot-600"
:class="
activeSort === option.key
? 'text-woot-600 dark:text-woot-600'
: 'text-slate-600 dark:text-slate-300'
"
:class="{
'text-woot-600 dark:text-woot-600': activeSort === option.key,
'text-slate-600 dark:text-slate-300': activeSort !== option.key,
}"
>
{{ option.name }}
</span>
@@ -74,19 +73,19 @@
>
<div
v-for="option in displayOptions"
:key="option.id"
:key="option.key"
class="flex items-center px-3 py-2 gap-1.5 h-9"
>
<input
:id="option.value"
:id="option.key"
type="checkbox"
:name="option.value"
:name="option.key"
:checked="option.selected"
class="m-0 border-[1.5px] shadow border-slate-200 dark:border-slate-600 appearance-none rounded-[4px] w-4 h-4 dark:bg-slate-800 focus:ring-1 focus:ring-slate-100 dark:focus:ring-slate-700 checked:bg-woot-600 dark:checked:bg-woot-600 after:content-[''] after:text-white checked:after:content-['✓'] after:flex after:items-center after:justify-center checked:border-t checked:border-woot-700 dark:checked:border-woot-300 checked:border-b-0 checked:border-r-0 checked:border-l-0 after:text-center after:text-xs after:font-bold after:relative after:-top-[1.5px]"
@change="updateDisplayOption(option)"
/>
<label
:for="option.value"
:for="option.key"
class="text-xs font-medium text-slate-800 !ml-0 !mr-0 dark:text-slate-100"
>
{{ option.name }}
@@ -98,55 +97,101 @@
</template>
<script>
import wootConstants from 'dashboard/constants/globals';
import uiSettingsMixin from 'dashboard/mixins/uiSettings';
export default {
mixins: [uiSettingsMixin],
data() {
return {
showSortMenu: false,
displayOptions: [
{
id: 1,
name: this.$t('INBOX.DISPLAY_MENU.DISPLAY_OPTIONS.SNOOZED'),
value: 'snoozed',
key: wootConstants.INBOX_DISPLAY_BY.SNOOZED,
selected: false,
type: wootConstants.INBOX_FILTER_TYPE.STATUS,
},
{
id: 2,
name: this.$t('INBOX.DISPLAY_MENU.DISPLAY_OPTIONS.READ'),
value: 'read',
selected: true,
key: wootConstants.INBOX_DISPLAY_BY.READ,
selected: false,
type: wootConstants.INBOX_FILTER_TYPE.TYPE,
},
],
sortOptions: [
{
name: this.$t('INBOX.DISPLAY_MENU.SORT_OPTIONS.NEWEST'),
key: 'newest',
key: wootConstants.INBOX_SORT_BY.NEWEST,
type: wootConstants.INBOX_FILTER_TYPE.SORT_ORDER,
},
{
name: this.$t('INBOX.DISPLAY_MENU.SORT_OPTIONS.OLDEST'),
key: 'oldest',
key: wootConstants.INBOX_SORT_BY.OLDEST,
type: wootConstants.INBOX_FILTER_TYPE.SORT_ORDER,
},
],
activeSort: 'newest',
activeSort: wootConstants.INBOX_SORT_BY.NEWEST,
activeDisplayFilter: {
status: '',
type: '',
},
};
},
computed: {
activeSortOption() {
return this.sortOptions.find(option => option.key === this.activeSort)
.name;
return (
this.sortOptions.find(option => option.key === this.activeSort)?.name ||
''
);
},
},
mounted() {
this.setSavedFilter();
},
methods: {
updateDisplayOption(option) {
option.selected = !option.selected;
// TODO: Update the display options
this.displayOptions.forEach(displayOption => {
if (displayOption.key === option.key) {
displayOption.selected = !option.selected;
this.activeDisplayFilter[displayOption.type] = displayOption.selected
? displayOption.key
: '';
this.saveSelectedDisplayFilter();
this.$emit('filter', option);
}
});
},
openSortMenu() {
this.showSortMenu = !this.showSortMenu;
},
onSortOptionClick(key) {
this.activeSort = key;
onSortOptionClick(option) {
this.activeSort = option.key;
this.showSortMenu = false;
// TODO: Update the sort options
this.saveSelectedDisplayFilter();
this.$emit('filter', option);
},
saveSelectedDisplayFilter() {
this.updateUISettings({
inbox_filter_by: {
...this.activeDisplayFilter,
sort_by: this.activeSort || wootConstants.INBOX_SORT_BY.NEWEST,
},
});
},
setSavedFilter() {
const { inbox_filter_by: filterBy = {} } = this.uiSettings;
const { status, type, sort_by: sortBy } = filterBy;
this.activeSort = sortBy || wootConstants.INBOX_SORT_BY.NEWEST;
this.displayOptions.forEach(option => {
option.selected =
option.type === wootConstants.INBOX_FILTER_TYPE.STATUS
? option.key === status
: option.key === type;
this.activeDisplayFilter[option.type] = option.selected
? option.key
: '';
});
},
},
};
@@ -132,7 +132,7 @@ export default {
.then(() => {
this.showAlert(this.$t('INBOX.ALERTS.DELETE'));
});
this.$router.push({ name: 'inbox-view' });
this.$router.push({ name: 'inbox_view' });
},
onClickNext() {
this.$emit('next');
@@ -27,6 +27,7 @@
v-if="showInboxDisplayMenu"
v-on-clickaway="openInboxDisplayMenu"
class="absolute top-8"
@filter="onFilterChange"
/>
</div>
</div>
@@ -109,6 +110,12 @@ export default {
this.deleteAllRead();
}
},
onFilterChange(option) {
this.$emit('filter', option);
this.showInboxDisplayMenu = false;
if (this.$route.name === 'inbox_view') return;
this.$router.push({ name: 'inbox_view' });
},
},
};
</script>
@@ -9,7 +9,7 @@ export const actions = {
data: {
data: { payload, meta },
},
} = await NotificationsAPI.get(page);
} = await NotificationsAPI.get({ page });
commit(types.CLEAR_NOTIFICATIONS);
commit(types.SET_NOTIFICATIONS, payload);
commit(types.SET_NOTIFICATIONS_META, meta);
@@ -18,14 +18,19 @@ export const actions = {
commit(types.SET_NOTIFICATIONS_UI_FLAG, { isFetching: false });
}
},
index: async ({ commit }, { page = 1 } = {}) => {
index: async ({ commit }, { page = 1, status, type, sortOrder } = {}) => {
commit(types.SET_NOTIFICATIONS_UI_FLAG, { isFetching: true });
try {
const {
data: {
data: { payload, meta },
},
} = await NotificationsAPI.get(page);
} = await NotificationsAPI.get({
page,
status,
type,
sortOrder,
});
commit(types.SET_NOTIFICATIONS, payload);
commit(types.SET_NOTIFICATIONS_META, meta);
commit(types.SET_NOTIFICATIONS_UI_FLAG, { isFetching: false });
@@ -1,7 +1,19 @@
import { applyInboxPageFilters, sortComparator } from './helpers';
export const getters = {
getNotifications($state) {
return Object.values($state.records).sort((n1, n2) => n2.id - n1.id);
},
getFilteredNotifications: $state => filters => {
const sortOrder = filters.sortOrder === 'desc' ? 'newest' : 'oldest';
const filteredNotifications = Object.values($state.records).filter(
notification => applyInboxPageFilters(notification, filters)
);
const sortedNotifications = filteredNotifications.sort((a, b) =>
sortComparator(a, b, sortOrder)
);
return sortedNotifications;
},
getUIFlags($state) {
return $state.uiFlags;
},
@@ -0,0 +1,45 @@
export const filterByStatus = (snoozedUntil, filterStatus) =>
filterStatus === 'snoozed' ? !!snoozedUntil : !snoozedUntil;
export const filterByType = (readAt, filterType) =>
filterType === 'read' ? !!readAt : !readAt;
export const filterByTypeAndStatus = (
readAt,
snoozedUntil,
filterType,
filterStatus
) => {
const shouldFilterByStatus = filterByStatus(snoozedUntil, filterStatus);
const shouldFilterByType = filterByType(readAt, filterType);
return shouldFilterByStatus && shouldFilterByType;
};
export const applyInboxPageFilters = (notification, filters) => {
const { status, type } = filters;
const { read_at: readAt, snoozed_until: snoozedUntil } = notification;
if (status && type)
return filterByTypeAndStatus(readAt, snoozedUntil, type, status);
if (status && !type) return filterByStatus(snoozedUntil, status);
if (!status && type) return filterByType(readAt, type);
return true;
};
const INBOX_SORT_OPTIONS = {
newest: 'desc',
oldest: 'asc',
};
const sortConfig = {
newest: (a, b) => b.created_at - a.created_at,
oldest: (a, b) => a.created_at - b.created_at,
};
export const sortComparator = (a, b, sortOrder) => {
const sortDirection = INBOX_SORT_OPTIONS[sortOrder];
if (sortOrder === 'newest' || sortOrder === 'oldest') {
return sortConfig[sortOrder](a, b, sortDirection);
}
return 0;
};
@@ -16,6 +16,32 @@ describe('#getters', () => {
]);
});
it('getFilteredNotifications', () => {
const state = {
records: {
1: { id: 1, read_at: '2024-02-07T11:42:39.988Z', snoozed_until: null },
2: { id: 2, read_at: null, snoozed_until: null },
3: {
id: 3,
read_at: '2024-02-07T11:42:39.988Z',
snoozed_until: '2024-02-07T11:42:39.988Z',
},
},
};
const filters = {
type: 'read',
status: 'snoozed',
sortOrder: 'desc',
};
expect(getters.getFilteredNotifications(state)(filters)).toEqual([
{
id: 3,
read_at: '2024-02-07T11:42:39.988Z',
snoozed_until: '2024-02-07T11:42:39.988Z',
},
]);
});
it('getUIFlags', () => {
const state = {
uiFlags: {
@@ -0,0 +1,200 @@
import {
filterByStatus,
filterByType,
filterByTypeAndStatus,
applyInboxPageFilters,
sortComparator,
} from '../../notifications/helpers';
const notifications = [
{
id: 1,
read_at: '2024-02-07T11:42:39.988Z',
snoozed_until: null,
created_at: 1707328400,
},
{
id: 2,
read_at: null,
snoozed_until: null,
created_at: 1707233688,
},
{
id: 3,
read_at: '2024-01-07T11:42:39.988Z',
snoozed_until: null,
created_at: 1707233672,
},
{
id: 4,
read_at: null,
snoozed_until: '2024-02-08T03:30:00.000Z',
created_at: 1707233667,
},
{
id: 5,
read_at: '2024-02-07T10:42:39.988Z',
snoozed_until: '2024-02-08T03:30:00.000Z',
created_at: 1707233662,
},
{
id: 6,
read_at: null,
snoozed_until: '2024-02-08T03:30:00.000Z',
created_at: 1707233561,
},
];
describe('#filterByStatus', () => {
it('returns the notifications with snoozed status', () => {
const filters = { status: 'snoozed' };
notifications.forEach(notification => {
expect(
filterByStatus(notification.snoozed_until, filters.status)
).toEqual(notification.snoozed_until !== null);
});
});
it('returns true if the notification is snoozed', () => {
const filters = { status: 'snoozed' };
expect(
filterByStatus(notifications[3].snoozed_until, filters.status)
).toEqual(true);
});
it('returns false if the notification is not snoozed', () => {
const filters = { status: 'snoozed' };
expect(
filterByStatus(notifications[2].snoozed_until, filters.status)
).toEqual(false);
});
});
describe('#filterByType', () => {
it('returns the notifications with read status', () => {
const filters = { type: 'read' };
notifications.forEach(notification => {
expect(filterByType(notification.read_at, filters.type)).toEqual(
notification.read_at !== null
);
});
});
it('returns true if the notification is read', () => {
const filters = { type: 'read' };
expect(filterByType(notifications[0].read_at, filters.type)).toEqual(true);
});
it('returns false if the notification is not read', () => {
const filters = { type: 'read' };
expect(filterByType(notifications[1].read_at, filters.type)).toEqual(false);
});
});
describe('#filterByTypeAndStatus', () => {
it('returns the notifications with type and status', () => {
const filters = { type: 'read', status: 'snoozed' };
notifications.forEach(notification => {
expect(
filterByTypeAndStatus(
notification.read_at,
notification.snoozed_until,
filters.type,
filters.status
)
).toEqual(
notification.read_at !== null && notification.snoozed_until !== null
);
});
});
it('returns true if the notification is read and snoozed', () => {
const filters = { type: 'read', status: 'snoozed' };
expect(
filterByTypeAndStatus(
notifications[4].read_at,
notifications[4].snoozed_until,
filters.type,
filters.status
)
).toEqual(true);
});
it('returns false if the notification is not read and snoozed', () => {
const filters = { type: 'read', status: 'snoozed' };
expect(
filterByTypeAndStatus(
notifications[3].read_at,
notifications[3].snoozed_until,
filters.type,
filters.status
)
).toEqual(false);
});
});
describe('#applyInboxPageFilters', () => {
it('returns the notifications with type and status', () => {
const filters = { type: 'read', status: 'snoozed' };
notifications.forEach(notification => {
expect(applyInboxPageFilters(notification, filters)).toEqual(
filterByTypeAndStatus(
notification.read_at,
notification.snoozed_until,
filters.type,
filters.status
)
);
});
});
it('returns the notifications with type only', () => {
const filters = { type: 'read', status: null };
notifications.forEach(notification => {
expect(applyInboxPageFilters(notification, filters)).toEqual(
filterByType(notification.read_at, filters.type)
);
});
});
it('returns the notifications with status only', () => {
const filters = { type: null, status: 'snoozed' };
notifications.forEach(notification => {
expect(applyInboxPageFilters(notification, filters)).toEqual(
filterByStatus(notification.snoozed_until, filters.status)
);
});
});
it('returns true if there are no filters', () => {
const filters = { type: null, status: null };
notifications.forEach(notification => {
expect(applyInboxPageFilters(notification, filters)).toEqual(true);
});
});
});
describe('#sortComparator', () => {
it('returns the notifications sorted by newest', () => {
const sortOrder = 'newest';
const sortedNotifications = [...notifications].sort((a, b) =>
sortComparator(a, b, sortOrder)
);
const expectedOrder = [
notifications[0],
notifications[1],
notifications[2],
notifications[3],
notifications[4],
notifications[5],
].sort((a, b) => b.created_at - a.created_at);
expect(sortedNotifications).toEqual(expectedOrder);
});
it('returns the notifications sorted by oldest', () => {
const sortOrder = 'oldest';
const sortedNotifications = [...notifications].sort((a, b) =>
sortComparator(a, b, sortOrder)
);
const expectedOrder = [
notifications[0],
notifications[1],
notifications[2],
notifications[3],
notifications[4],
notifications[5],
].sort((a, b) => a.created_at - b.created_at);
expect(sortedNotifications).toEqual(expectedOrder);
});
});
+7 -127
View File
@@ -7,6 +7,7 @@ class Inboxes::FetchImapEmailsJob < MutexApplicationJob
return unless should_fetch_email?(channel)
key = format(::Redis::Alfred::EMAIL_MESSAGE_MUTEX, inbox_id: channel.inbox.id)
with_lock(key, 5.minutes) do
process_email_for_channel(channel)
end
@@ -28,128 +29,16 @@ class Inboxes::FetchImapEmailsJob < MutexApplicationJob
end
def process_email_for_channel(channel)
if channel.microsoft?
fetch_mail_for_ms_provider(channel)
else
fetch_mail_for_channel(channel)
end
# clearing old failures like timeouts since the mail is now successfully processed
channel.reauthorized!
end
def fetch_mail_for_channel(channel)
imap_client = build_imap_client(channel, channel.imap_password, 'PLAIN')
message_ids_with_seq = fetch_message_ids_with_sequence(imap_client, channel)
message_ids_with_seq.each do |message_id_with_seq|
process_message_id(channel, imap_client, message_id_with_seq)
end
end
def process_message_id(channel, imap_client, message_id_with_seq)
seq_no, message_id = message_id_with_seq
return if email_already_present?(channel, message_id)
if message_id.blank?
Rails.logger.info "[IMAP::FETCH_EMAIL_SERVICE] Empty message id for #{channel.email} with seq no. <#{seq_no}>."
return
end
# Fetch the original mail content using the sequence no
mail_str = imap_client.fetch(seq_no, 'RFC822')[0].attr['RFC822']
if mail_str.blank?
Rails.logger.info "[IMAP::FETCH_EMAIL_SERVICE] Fetch failed for #{channel.email} with message-id <#{message_id}>."
return
end
inbound_mail = build_mail_from_string(mail_str)
mail_info_logger(channel, inbound_mail, seq_no)
process_mail(inbound_mail, channel)
end
# Sends a FETCH command to retrieve data associated with a message in the mailbox.
# You can send batches of message sequence number in `.fetch` method.
def fetch_message_ids_with_sequence(imap_client, channel)
seq_nums = fetch_available_mail_sequence_numbers(imap_client)
Rails.logger.info "[IMAP::FETCH_EMAIL_SERVICE] Fetching mails from #{channel.email}, found #{seq_nums.length}."
message_ids_with_seq = []
seq_nums.each_slice(10).each do |batch|
# Fetch only message-id only without mail body or contents.
batch_message_ids = imap_client.fetch(batch, 'BODY.PEEK[HEADER]')
# .fetch returns an array of Net::IMAP::FetchData or nil
# (instead of an empty array) if there is no matching message.
# Check
if batch_message_ids.blank?
Rails.logger.info "[IMAP::FETCH_EMAIL_SERVICE] Fetching the batch failed for #{channel.email}."
next
end
batch_message_ids.each do |data|
message_id = build_mail_from_string(data.attr['BODY[HEADER]']).message_id
message_ids_with_seq.push([data.seqno, message_id])
end
end
message_ids_with_seq
end
# Sends a SEARCH command to search the mailbox for messages that were
# created between yesterday and today and returns message sequence numbers.
# Return <message set>
def fetch_available_mail_sequence_numbers(imap_client)
imap_client.search(['SINCE', yesterday])
end
def fetch_mail_for_ms_provider(channel)
return if channel.provider_config['access_token'].blank?
access_token = valid_access_token channel
return unless access_token
imap_client = build_imap_client(channel, access_token, 'XOAUTH2')
process_mails(imap_client, channel)
end
def process_mails(imap_client, channel)
fetch_available_mail_sequence_numbers(imap_client).each do |seq_no|
inbound_mail = Mail.read_from_string imap_client.fetch(seq_no, 'RFC822')[0].attr['RFC822']
mail_info_logger(channel, inbound_mail, seq_no)
next if channel.inbox.messages.find_by(source_id: inbound_mail.message_id).present?
inbound_emails = if channel.microsoft?
Imap::MicrosoftFetchEmailService.new(channel: channel).perform
else
Imap::FetchEmailService.new(channel: channel).perform
end
inbound_emails.map do |inbound_mail|
process_mail(inbound_mail, channel)
end
end
def mail_info_logger(channel, inbound_mail, uid)
return if Rails.env.test?
Rails.logger.info("
#{channel.provider} Email id: #{inbound_mail.from} - message_source_id: #{inbound_mail.message_id} - sequence id: #{uid}")
end
def build_imap_client(channel, access_token, auth_method)
imap = Net::IMAP.new(channel.imap_address, channel.imap_port, true)
imap.authenticate(auth_method, channel.imap_login, access_token)
imap.select('INBOX')
imap
end
def email_already_present?(channel, message_id)
channel.inbox.messages.find_by(source_id: message_id).present?
end
def build_mail_from_string(raw_email_content)
Mail.read_from_string(raw_email_content)
end
def process_mail(inbound_mail, channel)
Imap::ImapMailbox.new.process(inbound_mail, channel)
rescue StandardError => e
@@ -157,13 +46,4 @@ class Inboxes::FetchImapEmailsJob < MutexApplicationJob
Rails.logger.error("
#{channel.provider} Email dropped: #{inbound_mail.from} and message_source_id: #{inbound_mail.message_id}")
end
# Making sure the access token is valid for microsoft provider
def valid_access_token(channel)
Microsoft::RefreshOauthTokenService.new(channel: channel).access_token
end
def yesterday
(Time.zone.today - 1).strftime('%d-%b-%Y')
end
end
+2
View File
@@ -24,3 +24,5 @@ class TriggerScheduledItemsJob < ApplicationJob
Notification::RemoveOldNotificationJob.perform_later
end
end
TriggerScheduledItemsJob.prepend_mod_with('TriggerScheduledItemsJob')
@@ -0,0 +1,115 @@
require 'net/imap'
class Imap::BaseFetchEmailService
pattr_initialize [:channel!]
def perform
# Override this method
end
private
def authentication_type
# Override this method
end
def imap_password
# Override this method
end
def imap_client
@imap_client ||= build_imap_client
end
def mail_info_logger(inbound_mail, seq_no)
return if Rails.env.test?
Rails.logger.info("
#{channel.provider} Email id: #{inbound_mail.from} - message_source_id: #{inbound_mail.message_id} - sequence id: #{seq_no}")
end
def email_already_present?(channel, message_id)
channel.inbox.messages.find_by(source_id: message_id).present?
end
def fetch_mail_for_channel
message_ids_with_seq = fetch_message_ids_with_sequence
message_ids_with_seq.filter_map do |message_id_with_seq|
process_message_id(message_id_with_seq)
end
end
def process_message_id(message_id_with_seq)
seq_no, message_id = message_id_with_seq
if message_id.blank?
Rails.logger.info "[IMAP::FETCH_EMAIL_SERVICE] Empty message id for #{channel.email} with seq no. <#{seq_no}>."
return
end
return if email_already_present?(channel, message_id)
# Fetch the original mail content using the sequence no
mail_str = imap_client.fetch(seq_no, 'RFC822')[0].attr['RFC822']
if mail_str.blank?
Rails.logger.info "[IMAP::FETCH_EMAIL_SERVICE] Fetch failed for #{channel.email} with message-id <#{message_id}>."
return
end
inbound_mail = build_mail_from_string(mail_str)
mail_info_logger(inbound_mail, seq_no)
inbound_mail
end
# Sends a FETCH command to retrieve data associated with a message in the mailbox.
# You can send batches of message sequence number in `.fetch` method.
def fetch_message_ids_with_sequence
seq_nums = fetch_available_mail_sequence_numbers
Rails.logger.info "[IMAP::FETCH_EMAIL_SERVICE] Fetching mails from #{channel.email}, found #{seq_nums.length}."
message_ids_with_seq = []
seq_nums.each_slice(10).each do |batch|
# Fetch only message-id only without mail body or contents.
batch_message_ids = imap_client.fetch(batch, 'BODY.PEEK[HEADER]')
# .fetch returns an array of Net::IMAP::FetchData or nil
# (instead of an empty array) if there is no matching message.
# Check
if batch_message_ids.blank?
Rails.logger.info "[IMAP::FETCH_EMAIL_SERVICE] Fetching the batch failed for #{channel.email}."
next
end
batch_message_ids.each do |data|
message_id = build_mail_from_string(data.attr['BODY[HEADER]']).message_id
message_ids_with_seq.push([data.seqno, message_id])
end
end
message_ids_with_seq
end
# Sends a SEARCH command to search the mailbox for messages that were
# created between yesterday and today and returns message sequence numbers.
# Return <message set>
def fetch_available_mail_sequence_numbers
imap_client.search(['SINCE', yesterday])
end
def build_imap_client
imap = Net::IMAP.new(channel.imap_address, port: channel.imap_port, ssl: true)
imap.authenticate(authentication_type, channel.imap_login, imap_password)
imap.select('INBOX')
imap
end
def build_mail_from_string(raw_email_content)
Mail.read_from_string(raw_email_content)
end
def yesterday
(Time.zone.today - 1).strftime('%d-%b-%Y')
end
end
+15
View File
@@ -0,0 +1,15 @@
class Imap::FetchEmailService < Imap::BaseFetchEmailService
def perform
fetch_mail_for_channel
end
private
def authentication_type
'PLAIN'
end
def imap_password
channel.imap_password
end
end
@@ -0,0 +1,17 @@
class Imap::MicrosoftFetchEmailService < Imap::BaseFetchEmailService
def perform
return if channel.provider_config['access_token'].blank?
fetch_mail_for_channel
end
private
def authentication_type
'XOAUTH2'
end
def imap_password
Microsoft::RefreshOauthTokenService.new(channel: channel).access_token
end
end
@@ -1,4 +1,4 @@
<%= CSVSafe.generate_line [I18n.t('reports.conversation_traffic_csv.timezone'), @timezone] %>
<%= CSV.generate_line [I18n.t('reports.conversation_traffic_csv.timezone'), @timezone] %>
<% @report_data.each do |row| %>
<%= CSVSafe.generate_line row -%>
<% end %>
<% end %>
+1 -1
View File
@@ -1,6 +1,6 @@
# Define a method to fetch the git commit hash
def fetch_git_sha
sha = `git rev-parse HEAD`
sha = `git rev-parse HEAD` if File.directory?('.git')
if sha.present?
sha.strip
elsif File.exist?('.git_sha')
@@ -0,0 +1,6 @@
class ChangeAppliedSlaSlaStatusToEnum < ActiveRecord::Migration[7.0]
def change
remove_column :applied_slas, :sla_status, :string
add_column :applied_slas, :sla_status, :integer, default: 0
end
end
+2 -2
View File
@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[7.0].define(version: 2024_01_31_040316) do
ActiveRecord::Schema[7.0].define(version: 2024_02_07_103014) do
# These are extensions that must be enabled in order to support this database
enable_extension "pg_stat_statements"
enable_extension "pg_trgm"
@@ -119,9 +119,9 @@ ActiveRecord::Schema[7.0].define(version: 2024_01_31_040316) do
t.bigint "account_id", null: false
t.bigint "sla_policy_id", null: false
t.bigint "conversation_id", null: false
t.string "sla_status"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "sla_status", default: 0
t.index ["account_id"], name: "index_applied_slas_on_account_id"
t.index ["conversation_id"], name: "index_applied_slas_on_conversation_id"
t.index ["sla_policy_id"], name: "index_applied_slas_on_sla_policy_id"
@@ -0,0 +1,11 @@
module Enterprise::TriggerScheduledItemsJob
def perform
super
## Triggers Enterprise specific jobs
####################################
# Triggers Account Sla jobs
Sla::TriggerSlasForAccountsJob.perform_later
end
end
@@ -0,0 +1,9 @@
class Sla::ProcessAccountAppliedSlasJob < ApplicationJob
queue_as :medium
def perform(account)
account.applied_slas.where(sla_status: 'active').each do |applied_sla|
Sla::ProcessAppliedSlaJob.perform_later(applied_sla)
end
end
end
@@ -0,0 +1,7 @@
class Sla::ProcessAppliedSlaJob < ApplicationJob
queue_as :medium
def perform(applied_sla)
Sla::EvaluateAppliedSlaService.new(applied_sla: applied_sla).perform
end
end
@@ -0,0 +1,10 @@
class Sla::TriggerSlasForAccountsJob < ApplicationJob
queue_as :scheduled_jobs
def perform
Account.find_each do |account|
Rails.logger.info "Enqueuing ProcessAccountAppliedSlasJob for account #{account.id}"
Sla::ProcessAccountAppliedSlasJob.perform_later(account)
end
end
end
+3 -1
View File
@@ -3,7 +3,7 @@
# Table name: applied_slas
#
# id :bigint not null, primary key
# sla_status :string
# sla_status :integer default("active")
# created_at :datetime not null
# updated_at :datetime not null
# account_id :bigint not null
@@ -20,4 +20,6 @@ class AppliedSla < ApplicationRecord
belongs_to :account
belongs_to :sla_policy
belongs_to :conversation
enum sla_status: { active: 0, hit: 1, missed: 2 }
end
@@ -3,6 +3,7 @@ module Enterprise::Concerns::Account
included do
has_many :sla_policies, dependent: :destroy_async
has_many :applied_slas, dependent: :destroy_async
def self.add_response_related_associations
has_many :response_sources, dependent: :destroy_async
@@ -0,0 +1,78 @@
class Sla::EvaluateAppliedSlaService
pattr_initialize [:applied_sla!]
def perform
check_sla_thresholds
# We will calculate again in the next iteration
return unless applied_sla.conversation.resolved?
# No SLA missed, so marking as hit as conversation is resolved
handle_hit_sla(applied_sla) if applied_sla.active?
end
private
def check_sla_thresholds
[:first_response_time_threshold, :next_response_time_threshold, :resolution_time_threshold].each do |threshold|
next if applied_sla.sla_policy.send(threshold).blank?
send("check_#{threshold}", applied_sla, applied_sla.conversation, applied_sla.sla_policy)
end
end
def still_within_threshold?(threshold)
Time.zone.now.to_i < threshold
end
def check_first_response_time_threshold(applied_sla, conversation, sla_policy)
threshold = conversation.created_at.to_i + sla_policy.first_response_time_threshold.to_i
return if first_reply_was_within_threshold?(conversation, threshold)
return if still_within_threshold?(threshold)
handle_missed_sla(applied_sla)
end
def first_reply_was_within_threshold?(conversation, threshold)
conversation.first_reply_created_at.present? && conversation.first_reply_created_at.to_i <= threshold
end
def check_next_response_time_threshold(applied_sla, conversation, sla_policy)
# still waiting for first reply, so covered under first response time threshold
return if conversation.first_reply_created_at.blank?
# Waiting on customer response, no need to check next response time threshold
return if conversation.waiting_since.blank?
threshold = conversation.waiting_since.to_i + sla_policy.next_response_time_threshold.to_i
return if still_within_threshold?(threshold)
handle_missed_sla(applied_sla)
end
def check_resolution_time_threshold(applied_sla, conversation, sla_policy)
return if conversation.resolved?
threshold = conversation.created_at.to_i + sla_policy.resolution_time_threshold.to_i
return if still_within_threshold?(threshold)
handle_missed_sla(applied_sla)
end
def handle_missed_sla(applied_sla)
return unless applied_sla.active?
applied_sla.update!(sla_status: 'missed')
Rails.logger.warn "SLA missed for conversation #{applied_sla.conversation.id} " \
"in account #{applied_sla.account_id} " \
"for sla_policy #{applied_sla.sla_policy.id}"
end
def handle_hit_sla(applied_sla)
return unless applied_sla.active?
applied_sla.update!(sla_status: 'hit')
Rails.logger.info "SLA hit for conversation #{applied_sla.conversation.id} " \
"in account #{applied_sla.account_id} " \
"for sla_policy #{applied_sla.sla_policy.id}"
end
end
@@ -1,58 +0,0 @@
# frozen_string_literal: true
class Integrations::Widget::IncomingMessageBuilder
# params = {
# contact_id: 1,
# inbox_id: 1,
# content: "Hello world"
# }
attr_accessor :options, :message
def initialize(options)
@options = options
end
def perform
ActiveRecord::Base.transaction do
build_message
end
end
private
def inbox
@inbox ||= Inbox.find(options[:inbox_id])
end
def contact
@contact ||= Contact.find(options[:contact_id])
end
def conversation
@conversation ||= Conversation.find_by(conversation_params) || Conversation.create!(conversation_params)
end
def build_message
@message = conversation.messages.new(message_params)
@message.save!
end
def conversation_params
{
account_id: inbox.account_id,
inbox_id: inbox.id,
contact_id: options[:contact_id]
}
end
def message_params
{
account_id: conversation.account_id,
inbox_id: conversation.inbox_id,
message_type: 0,
content: options[:content],
sender: contact
}
end
end
@@ -1,52 +0,0 @@
# frozen_string_literal: true
class Integrations::Widget::OutgoingMessageBuilder
# params = {
# user_id: 1,
# inbox_id: 1,
# content: "Hello world",
# conversation_id: 2
# }
attr_accessor :options, :message
def initialize(options)
@options = options
end
def perform
ActiveRecord::Base.transaction do
conversation
build_message
end
end
private
def inbox
@inbox ||= Inbox.find(options[:inbox_id])
end
def user
@user ||= Contact.find(options[:user_id])
end
def conversation
@conversation ||= Conversation.find(options[:conversation_id])
end
def build_message
@message = conversation.messages.new(message_params)
@message.save!
end
def message_params
{
account_id: conversation.account_id,
inbox_id: conversation.inbox_id,
message_type: 1,
content: options[:content],
sender: user
}
end
end
@@ -14,6 +14,26 @@ RSpec.describe 'Conversation Assignment API', type: :request do
end
end
context 'when it is an authenticated bot with out access to the inbox' do
let(:agent_bot) { create(:agent_bot, account: account) }
let(:agent) { create(:user, account: account, role: :agent) }
before do
create(:inbox_member, inbox: conversation.inbox, user: agent)
end
it 'returns unauthorized' do
post "/api/v1/accounts/#{account.id}/conversations/#{conversation.display_id}/assignments",
headers: { api_access_token: agent_bot.access_token.token },
params: {
assignee_id: agent.id
},
as: :json
expect(response).to have_http_status(:unauthorized)
end
end
context 'when it is an authenticated user with access to the inbox' do
let(:agent) { create(:user, account: account, role: :agent) }
let(:team) { create(:team, account: account) }
@@ -52,6 +72,50 @@ RSpec.describe 'Conversation Assignment API', type: :request do
end
end
context 'when it is an authenticated bot with access to the inbox' do
let(:agent_bot) { create(:agent_bot, account: account) }
let(:agent) { create(:user, account: account, role: :agent) }
let(:team) { create(:team, account: account) }
before do
create(:agent_bot_inbox, inbox: conversation.inbox, agent_bot: agent_bot)
end
it 'assignment of an agent in the conversation by bot agent' do
create(:inbox_member, user: agent, inbox: conversation.inbox)
conversation.update!(assignee_id: nil)
expect(conversation.reload.assignee).to be_nil
post "/api/v1/accounts/#{account.id}/conversations/#{conversation.display_id}/assignments",
headers: { api_access_token: agent_bot.access_token.token },
params: {
assignee_id: agent.id
},
as: :json
expect(response).to have_http_status(:success)
expect(conversation.reload.assignee).to eq(agent)
end
it 'assignment of an team in the conversation by bot agent' do
create(:inbox_member, user: agent, inbox: conversation.inbox)
conversation.update!(team_id: nil)
expect(conversation.reload.team).to be_nil
post "/api/v1/accounts/#{account.id}/conversations/#{conversation.display_id}/assignments",
headers: { api_access_token: agent_bot.access_token.token },
params: {
team_id: team.id
},
as: :json
expect(response).to have_http_status(:success)
expect(conversation.reload.team).to eq(team)
end
end
context 'when conversation already has an assignee' do
let(:agent) { create(:user, account: account, role: :agent) }
@@ -466,7 +466,11 @@ RSpec.describe 'Conversations API', type: :request do
end
describe 'POST /api/v1/accounts/{account.id}/conversations/:id/toggle_priority' do
let(:inbox) { create(:inbox, account: account) }
let(:conversation) { create(:conversation, account: account) }
let(:pending_conversation) { create(:conversation, inbox: inbox, account: account, status: 'pending') }
let(:agent) { create(:user, account: account, role: :agent) }
let(:agent_bot) { create(:agent_bot, account: account) }
context 'when it is an unauthenticated user' do
it 'returns unauthorized' do
@@ -477,7 +481,6 @@ RSpec.describe 'Conversations API', type: :request do
end
context 'when it is an authenticated user' do
let(:agent) { create(:user, account: account, role: :agent) }
let(:administrator) { create(:user, account: account, role: :administrator) }
before do
@@ -509,6 +512,23 @@ RSpec.describe 'Conversations API', type: :request do
expect(conversation.reload.priority).to be_nil
end
end
context 'when it is an authenticated bot' do
it 'toggle the priority of the bot agent conversation' do
create(:agent_bot_inbox, inbox: inbox, agent_bot: agent_bot)
conversation.update!(priority: 'low')
expect(conversation.reload.priority).to eq('low')
post "/api/v1/accounts/#{account.id}/conversations/#{conversation.display_id}/toggle_priority",
headers: { api_access_token: agent_bot.access_token.token },
params: { priority: 'high' },
as: :json
expect(response).to have_http_status(:success)
expect(conversation.reload.priority).to eq('high')
end
end
end
describe 'POST /api/v1/accounts/{account.id}/conversations/:id/toggle_typing_status' do
@@ -17,8 +17,7 @@ RSpec.describe 'Super Admin Instance status', type: :request do
get '/super_admin/instance_status'
expect(response).to have_http_status(:success)
expect(response.body).to include('Chatwoot version')
sha = `git rev-parse HEAD`
expect(response.body).to include(sha)
expect(response.body).to include(GIT_HASH)
end
end
end
@@ -0,0 +1,10 @@
require 'rails_helper'
RSpec.describe TriggerScheduledItemsJob do
subject(:job) { described_class.perform_later }
it 'triggers Sla::TriggerSlasForAccountsJob' do
expect(Sla::TriggerSlasForAccountsJob).to receive(:perform_later).once
described_class.perform_now
end
end
@@ -0,0 +1,27 @@
require 'rails_helper'
RSpec.describe Sla::ProcessAccountAppliedSlasJob do
context 'when perform is called' do
let!(:account) { create(:account) }
let!(:sla_policy) { create(:sla_policy, first_response_time_threshold: 1.hour) }
let!(:applied_sla) { create(:applied_sla, account: account, sla_policy: sla_policy, sla_status: 'active') }
let!(:hit_applied_sla) { create(:applied_sla, account: account, sla_policy: sla_policy, sla_status: 'hit') }
let!(:miss_applied_sla) { create(:applied_sla, account: account, sla_policy: sla_policy, sla_status: 'missed') }
it 'enqueues the job' do
expect { described_class.perform_later }.to have_enqueued_job(described_class)
.on_queue('medium')
end
it 'calls the ProcessAppliedSlaJob' do
expect(Sla::ProcessAppliedSlaJob).to receive(:perform_later).with(applied_sla).and_call_original
described_class.perform_now(account)
end
it 'does not call the ProcessAppliedSlaJob for not active applied slas' do
expect(Sla::ProcessAppliedSlaJob).not_to receive(:perform_later).with(hit_applied_sla)
expect(Sla::ProcessAppliedSlaJob).not_to receive(:perform_later).with(miss_applied_sla)
described_class.perform_now(account)
end
end
end
@@ -0,0 +1,18 @@
require 'rails_helper'
RSpec.describe Sla::ProcessAppliedSlaJob do
context 'when perform is called' do
let(:account) { create(:account) }
it 'enqueues the job' do
expect { described_class.perform_later }.to have_enqueued_job(described_class)
.on_queue('medium')
end
it 'calls the EvaluateAppliedSlaService' do
applied_sla = create(:applied_sla)
expect(Sla::EvaluateAppliedSlaService).to receive(:new).with(applied_sla: applied_sla).and_call_original
described_class.perform_now(applied_sla)
end
end
end
@@ -0,0 +1,17 @@
require 'rails_helper'
RSpec.describe Sla::TriggerSlasForAccountsJob do
context 'when perform is called' do
let(:account) { create(:account) }
it 'enqueues the job' do
expect { described_class.perform_later }.to have_enqueued_job(described_class)
.on_queue('scheduled_jobs')
end
it 'calls the ProcessAccountAppliedSlasJob' do
expect(Sla::ProcessAccountAppliedSlasJob).to receive(:perform_later).with(account).and_call_original
described_class.perform_now
end
end
end
@@ -0,0 +1,141 @@
require 'rails_helper'
RSpec.describe Sla::EvaluateAppliedSlaService do
let!(:conversation) { create(:conversation, created_at: 6.hours.ago) }
let!(:sla_policy) do
create(:sla_policy, account: conversation.account,
first_response_time_threshold: nil,
next_response_time_threshold: nil,
resolution_time_threshold: nil)
end
let!(:applied_sla) { create(:applied_sla, conversation: conversation, sla_policy: sla_policy, sla_status: 'active') }
describe '#perform - SLA misses' do
context 'when first response SLA is missed' do
before { sla_policy.update(first_response_time_threshold: 1.hour) }
it 'updates the SLA status to missed and logs a warning' do
allow(Rails.logger).to receive(:warn)
described_class.new(applied_sla: applied_sla).perform
expect(Rails.logger).to have_received(:warn).with("SLA missed for conversation #{conversation.id} in account " \
"#{applied_sla.account_id} for sla_policy #{sla_policy.id}")
expect(applied_sla.reload.sla_status).to eq('missed')
end
end
context 'when next response SLA is missed' do
before do
sla_policy.update(next_response_time_threshold: 1.hour)
conversation.update(first_reply_created_at: 5.hours.ago, waiting_since: 5.hours.ago)
end
it 'updates the SLA status to missed and logs a warning' do
allow(Rails.logger).to receive(:warn)
described_class.new(applied_sla: applied_sla).perform
expect(Rails.logger).to have_received(:warn).with("SLA missed for conversation #{conversation.id} in account " \
"#{applied_sla.account_id} for sla_policy #{sla_policy.id}")
expect(applied_sla.reload.sla_status).to eq('missed')
end
end
context 'when resolution time SLA is missed' do
before { sla_policy.update(resolution_time_threshold: 1.hour) }
it 'updates the SLA status to missed and logs a warning' do
allow(Rails.logger).to receive(:warn)
described_class.new(applied_sla: applied_sla).perform
expect(Rails.logger).to have_received(:warn).with("SLA missed for conversation #{conversation.id} in account " \
"#{applied_sla.account_id} for sla_policy #{sla_policy.id}")
expect(applied_sla.reload.sla_status).to eq('missed')
end
end
# We will mark resolved miss only if while processing the SLA
# if the conversation is resolved and the resolution time is missed by small margins then we will not mark it as missed
context 'when resolved conversation with resolution time SLA is missed' do
before do
conversation.resolved!
sla_policy.update(resolution_time_threshold: 1.hour)
end
it 'does not update the SLA status to missed' do
described_class.new(applied_sla: applied_sla).perform
expect(applied_sla.reload.sla_status).to eq('hit')
end
end
context 'when multiple SLAs are missed' do
before do
sla_policy.update(first_response_time_threshold: 1.hour, next_response_time_threshold: 1.hour, resolution_time_threshold: 1.hour)
conversation.update(first_reply_created_at: 5.hours.ago, waiting_since: 5.hours.ago)
end
it 'updates the SLA status to missed and logs a warning' do
allow(Rails.logger).to receive(:warn)
described_class.new(applied_sla: applied_sla).perform
expect(Rails.logger).to have_received(:warn).with("SLA missed for conversation #{conversation.id} in account " \
"#{applied_sla.account_id} for sla_policy #{sla_policy.id}").exactly(1).time
expect(applied_sla.reload.sla_status).to eq('missed')
end
end
end
describe '#perform - SLA hits' do
context 'when first response SLA is hit' do
before do
sla_policy.update(first_response_time_threshold: 6.hours)
conversation.update(first_reply_created_at: 30.minutes.ago)
end
it 'sla remains active until conversation is resolved' do
described_class.new(applied_sla: applied_sla).perform
expect(applied_sla.reload.sla_status).to eq('active')
end
it 'updates the SLA status to hit and logs an info when conversations is resolved' do
conversation.resolved!
allow(Rails.logger).to receive(:info)
described_class.new(applied_sla: applied_sla).perform
expect(Rails.logger).to have_received(:info).with("SLA hit for conversation #{conversation.id} in account " \
"#{applied_sla.account_id} for sla_policy #{sla_policy.id}")
expect(applied_sla.reload.sla_status).to eq('hit')
end
end
context 'when next response SLA is hit' do
before do
sla_policy.update(next_response_time_threshold: 6.hours)
conversation.update(first_reply_created_at: 30.minutes.ago, waiting_since: nil)
end
it 'sla remains active until conversation is resolved' do
described_class.new(applied_sla: applied_sla).perform
expect(applied_sla.reload.sla_status).to eq('active')
end
it 'updates the SLA status to hit and logs an info when conversations is resolved' do
conversation.resolved!
allow(Rails.logger).to receive(:info)
described_class.new(applied_sla: applied_sla).perform
expect(Rails.logger).to have_received(:info).with("SLA hit for conversation #{conversation.id} in account " \
"#{applied_sla.account_id} for sla_policy #{sla_policy.id}")
expect(applied_sla.reload.sla_status).to eq('hit')
end
end
context 'when resolution time SLA is hit' do
before do
sla_policy.update(resolution_time_threshold: 8.hours)
conversation.resolved!
end
it 'updates the SLA status to hit and logs an info' do
allow(Rails.logger).to receive(:info)
described_class.new(applied_sla: applied_sla).perform
expect(Rails.logger).to have_received(:info).with("SLA hit for conversation #{conversation.id} in account " \
"#{applied_sla.account_id} for sla_policy #{sla_policy.id}")
expect(applied_sla.reload.sla_status).to eq('hit')
end
end
end
end
+4 -1
View File
@@ -1,8 +1,11 @@
FactoryBot.define do
factory :applied_sla do
account
sla_policy
conversation
sla_status { 'active' }
after(:build) do |applied_sla|
applied_sla.account ||= applied_sla.conversation&.account || create(:account)
end
end
end
+9
View File
@@ -25,5 +25,14 @@ FactoryBot.define do
end
provider { 'microsoft' }
end
trait :imap_email do
imap_enabled { true }
imap_address { 'imap.gmail.com' }
imap_port { 993 }
imap_login { 'email@example.com' }
imap_password { 'random-password' }
imap_enable_ssl { true }
end
end
end
+83 -138
View File
@@ -1,161 +1,106 @@
require 'rails_helper'
RSpec.describe Inboxes::FetchImapEmailsJob do
include ActiveJob::TestHelper
include ActionMailbox::TestHelper
let(:account) { create(:account) }
let(:imap_email_channel) do
create(:channel_email, imap_enabled: true, imap_address: 'imap.gmail.com', imap_port: 993, imap_login: 'imap@gmail.com',
imap_password: 'password', account: account)
end
let(:imap_email_channel) { create(:channel_email, :imap_email, account: account) }
let(:channel_with_imap_disabled) { create(:channel_email, :imap_email, imap_enabled: false, account: account) }
let(:microsoft_imap_email_channel) { create(:channel_email, :microsoft_email) }
let(:ms_email_inbox) { create(:inbox, channel: microsoft_imap_email_channel, account: account) }
let!(:conversation) { create(:conversation, inbox: imap_email_channel.inbox, account: account) }
let(:inbound_mail) { create_inbound_email_from_mail(from: 'testemail@gmail.com', to: 'imap@outlook.com', subject: 'Hello!') }
let(:inbound_mail_with_attachments) { create_inbound_email_from_fixture('multiple_attachments.eml') }
it 'enqueues the job' do
expect { described_class.perform_later }.to have_enqueued_job(described_class)
.on_queue('scheduled_jobs')
end
context 'when imap fetch new emails' do
it 'process the email' do
email = Mail.new do
to 'test@outlook.com'
from 'test@gmail.com'
subject :test.to_s
body 'hello'
end
imap_fetch_mail = Net::IMAP::FetchData.new
imap_fetch_mail.attr = { seqno: 1, RFC822: email }.with_indifferent_access
imap = double
allow(Net::IMAP).to receive(:new).and_return(imap)
allow(imap).to receive(:authenticate)
allow(imap).to receive(:select)
allow(imap).to receive(:search).and_return([1])
allow(imap).to receive(:fetch).and_return([imap_fetch_mail])
read_mail = Mail::Message.new(date: DateTime.now, from: 'testemail@gmail.com', to: 'imap@outlook.com', subject: 'Hello!')
allow(Mail).to receive(:read_from_string).and_return(inbound_mail.mail)
imap_mailbox = double
allow(Imap::ImapMailbox).to receive(:new).and_return(imap_mailbox)
expect(imap_mailbox).to receive(:process).with(read_mail, imap_email_channel).once
described_class.perform_now(imap_email_channel)
describe '#perform' do
it 'enqueues the job' do
expect do
described_class.perform_later
end.to have_enqueued_job(described_class).on_queue('scheduled_jobs')
end
it 'process the email with no date' do
fixture_path = Rails.root.join('spec/fixtures/files/mail_with_no_date.eml')
eml_content = File.read(fixture_path)
inbound_mail_with_no_date = create_inbound_email_from_fixture('mail_with_no_date.eml')
email_header = Net::IMAP::FetchData.new(1, 'BODY[HEADER]' => eml_content)
imap_fetch_mail = Net::IMAP::FetchData.new(1, 'RFC822' => eml_content)
imap = double
allow(Net::IMAP).to receive(:new).and_return(imap)
allow(imap).to receive(:authenticate)
allow(imap).to receive(:select)
allow(imap).to receive(:search).and_return([1])
allow(imap).to receive(:fetch).with([1], 'BODY.PEEK[HEADER]').and_return([email_header])
allow(imap).to receive(:fetch).with(1, 'RFC822').and_return([imap_fetch_mail])
imap_mailbox = double
allow(Imap::ImapMailbox).to receive(:new).and_return(imap_mailbox)
expect(imap_mailbox).to receive(:process).with(inbound_mail_with_no_date.mail, imap_email_channel).once
described_class.perform_now(imap_email_channel)
context 'when IMAP is disabled' do
it 'does not fetch emails' do
expect(Imap::FetchEmailService).not_to receive(:new)
expect(Imap::MicrosoftFetchEmailService).not_to receive(:new)
described_class.perform_now(channel_with_imap_disabled)
end
end
end
context 'when imap fetch new emails with more than 15 attachments' do
it 'process the email' do
email = Mail.new do
to 'test@outlook.com'
from 'test@gmail.com'
subject :test.to_s
body 'hello'
context 'when IMAP reauthorization is required' do
it 'does not fetch emails' do
10.times do
imap_email_channel.authorization_error!
end
expect(Imap::FetchEmailService).not_to receive(:new)
# Confirm the imap_enabled flag is true to avoid false positives.
expect(imap_email_channel.imap_enabled?).to be true
described_class.perform_now(imap_email_channel)
end
end
context 'when the channel is regular imap' do
it 'calls the imap fetch service' do
fetch_service = double
allow(Imap::FetchEmailService).to receive(:new).with(channel: imap_email_channel).and_return(fetch_service)
allow(fetch_service).to receive(:perform).and_return([])
described_class.perform_now(imap_email_channel)
expect(fetch_service).to have_received(:perform)
end
end
context 'when the channel is Microsoft' do
it 'calls the Microsoft fetch service' do
fetch_service = double
allow(Imap::MicrosoftFetchEmailService).to receive(:new).with(channel: microsoft_imap_email_channel).and_return(fetch_service)
allow(fetch_service).to receive(:perform).and_return([])
described_class.perform_now(microsoft_imap_email_channel)
expect(fetch_service).to have_received(:perform)
end
end
context 'when IMAP connection errors out' do
it 'mark the connection for authorization required' do
allow(Imap::FetchEmailService).to receive(:new).with(channel: imap_email_channel).and_raise(Errno::ECONNREFUSED)
allow(Redis::Alfred).to receive(:incr)
expect(Redis::Alfred).to receive(:incr).with("AUTHORIZATION_ERROR_COUNT:channel_email:#{imap_email_channel.id}")
described_class.perform_now(imap_email_channel)
end
end
context 'when the fetch service returns the email objects' do
let(:inbound_mail) { create_inbound_email_from_fixture('welcome.eml').mail }
let(:mailbox) { double }
let(:exception_tracker) { double }
let(:fetch_service) { double }
before do
allow(Imap::ImapMailbox).to receive(:new).and_return(mailbox)
allow(ChatwootExceptionTracker).to receive(:new).and_return(exception_tracker)
allow(Imap::FetchEmailService).to receive(:new).with(channel: imap_email_channel).and_return(fetch_service)
allow(fetch_service).to receive(:perform).and_return([inbound_mail])
end
imap_fetch_mail = Net::IMAP::FetchData.new
imap_fetch_mail.attr = { seqno: 1, RFC822: email }.with_indifferent_access
it 'calls the mailbox to create emails' do
allow(mailbox).to receive(:process)
imap = double
expect(Imap::FetchEmailService).to receive(:new).with(channel: imap_email_channel).and_return(fetch_service)
expect(fetch_service).to receive(:perform).and_return([inbound_mail])
expect(mailbox).to receive(:process).with(inbound_mail, imap_email_channel)
allow(Net::IMAP).to receive(:new).and_return(imap)
allow(imap).to receive(:authenticate)
allow(imap).to receive(:select)
allow(imap).to receive(:search).and_return([1])
allow(imap).to receive(:fetch).and_return([imap_fetch_mail])
inbound_mail_with_attachments.mail.date = DateTime.now
allow(Mail).to receive(:read_from_string).and_return(inbound_mail_with_attachments.mail)
imap_mailbox = Imap::ImapMailbox.new
allow(Imap::ImapMailbox).to receive(:new).and_return(imap_mailbox)
described_class.perform_now(imap_email_channel)
expect(Message.last.attachments.count).to eq(15)
end
end
context 'when imap fetch new emails for microsoft mailer' do
it 'fetch and process all emails' do
email = Mail.new do
to 'test@outlook.com'
from 'test@gmail.com'
subject :test.to_s
body 'hello'
end
imap_fetch_mail = Net::IMAP::FetchData.new
imap_fetch_mail.attr = { RFC822: email }.with_indifferent_access
ms_imap = double
allow(Net::IMAP).to receive(:new).and_return(ms_imap)
allow(ms_imap).to receive(:authenticate)
allow(ms_imap).to receive(:select)
allow(ms_imap).to receive(:search).and_return([1])
allow(ms_imap).to receive(:fetch).and_return([imap_fetch_mail])
allow(Mail).to receive(:read_from_string).and_return(inbound_mail)
ms_imap_email_inbox = double
allow(Imap::ImapMailbox).to receive(:new).and_return(ms_imap_email_inbox)
expect(ms_imap_email_inbox).to receive(:process).with(inbound_mail, microsoft_imap_email_channel).once
described_class.perform_now(microsoft_imap_email_channel)
end
end
context 'when imap fetch existing emails' do
it 'does not process the email' do
email = Mail.new do
to 'test@outlook.com'
from 'test@gmail.com'
subject :test.to_s
body 'hello'
message_id '<messageId@example.com>'
described_class.perform_now(imap_email_channel)
end
create(:message, message_type: 'incoming', source_id: email.message_id, account: account, inbox: imap_email_channel.inbox,
conversation: conversation)
it 'logs errors if mailbox returns errors' do
allow(mailbox).to receive(:process).and_raise(StandardError)
allow(Mail).to receive(:find).and_return([email])
imap_mailbox = double
allow(Imap::ImapMailbox).to receive(:new).and_return(imap_mailbox)
expect(imap_mailbox).not_to receive(:process).with(email, imap_email_channel)
expect(exception_tracker).to receive(:capture_exception)
described_class.perform_now(imap_email_channel)
described_class.perform_now(imap_email_channel)
end
end
end
end
+25 -25
View File
@@ -10,6 +10,31 @@ RSpec.describe TriggerScheduledItemsJob do
.on_queue('scheduled_jobs')
end
it 'triggers Conversations::ReopenSnoozedConversationsJob' do
expect(Conversations::ReopenSnoozedConversationsJob).to receive(:perform_later).once
described_class.perform_now
end
it 'triggers Notification::ReopenSnoozedNotificationsJob' do
expect(Notification::ReopenSnoozedNotificationsJob).to receive(:perform_later).once
described_class.perform_now
end
it 'triggers Account::ConversationsResolutionSchedulerJob' do
expect(Account::ConversationsResolutionSchedulerJob).to receive(:perform_later).once
described_class.perform_now
end
it 'triggers Channels::Whatsapp::TemplatesSyncSchedulerJob' do
expect(Channels::Whatsapp::TemplatesSyncSchedulerJob).to receive(:perform_later).once
described_class.perform_now
end
it 'triggers Notification::RemoveOldNotificationJob' do
expect(Notification::RemoveOldNotificationJob).to receive(:perform_later).once
described_class.perform_now
end
context 'when unexecuted Scheduled campaign jobs' do
let!(:twilio_sms) { create(:channel_twilio_sms) }
let!(:twilio_inbox) { create(:inbox, channel: twilio_sms) }
@@ -20,30 +45,5 @@ RSpec.describe TriggerScheduledItemsJob do
expect(Campaigns::TriggerOneoffCampaignJob).to receive(:perform_later).with(campaign).once
described_class.perform_now
end
it 'triggers Conversations::ReopenSnoozedConversationsJob' do
expect(Conversations::ReopenSnoozedConversationsJob).to receive(:perform_later).once
described_class.perform_now
end
it 'triggers Notification::ReopenSnoozedNotificationsJob' do
expect(Notification::ReopenSnoozedNotificationsJob).to receive(:perform_later).once
described_class.perform_now
end
it 'triggers Account::ConversationsResolutionSchedulerJob' do
expect(Account::ConversationsResolutionSchedulerJob).to receive(:perform_later).once
described_class.perform_now
end
it 'triggers Channels::Whatsapp::TemplatesSyncSchedulerJob' do
expect(Channels::Whatsapp::TemplatesSyncSchedulerJob).to receive(:perform_later).once
described_class.perform_now
end
it 'triggers Notification::RemoveOldNotificationJob' do
expect(Notification::RemoveOldNotificationJob).to receive(:perform_later).once
described_class.perform_now
end
end
end
+20 -8
View File
@@ -3,14 +3,10 @@ require 'rails_helper'
RSpec.describe Imap::ImapMailbox do
include ActionMailbox::TestHelper
describe 'add mail as a new conversation in the email inbox' do
describe '#process' do
let(:account) { create(:account) }
let(:agent) { create(:user, email: 'agent@example.com', account: account) }
let(:channel) do
create(:channel_email, imap_enabled: true, imap_address: 'imap.gmail.com',
imap_port: 993, imap_login: 'imap@gmail.com', imap_password: 'password',
account: account)
end
let(:channel) { create(:channel_email, :imap_email) }
let(:inbox) { channel.inbox }
let!(:contact) { create(:contact, email: 'email@gmail.com', phone_number: '+919584546666', account: account, identifier: '123') }
let(:conversation) { Conversation.where(inbox_id: channel.inbox).last }
@@ -20,17 +16,33 @@ RSpec.describe Imap::ImapMailbox do
create(:contact_inbox, contact_id: contact.id, inbox_id: channel.inbox.id)
end
context 'when a new email from non existing contact' do
context 'when the email is from a new contact' do
let(:inbound_mail) { create_inbound_email_from_mail(from: 'testemail@gmail.com', to: 'imap@gmail.com', subject: 'Hello!') }
it 'creates the contact and conversation with message' do
class_instance.process(inbound_mail.mail, channel)
expect do
class_instance.process(inbound_mail.mail, channel)
end.to change(Conversation, :count).by(1)
expect(conversation.contact.email).to eq(inbound_mail.mail.from.first)
expect(conversation.additional_attributes['source']).to eq('email')
expect(conversation.messages.empty?).to be false
end
end
context 'when the email has 15 or more attachments' do
let(:inbound_mail) { create_inbound_email_from_fixture('multiple_attachments.eml') }
it 'creates a converstation and a message properly' do
expect do
class_instance.process(inbound_mail.mail, channel)
end.to change(Conversation, :count).by(1)
expect(conversation.contact.email).to eq(inbound_mail.mail.from.first)
expect(conversation.messages.last.attachments.count).to be 15
end
end
context 'when a new email from existing contact' do
let(:inbound_mail) { create_inbound_email_from_mail(from: 'email@gmail.com', to: 'imap@gmail.com', subject: 'Hello!') }
@@ -0,0 +1,65 @@
require 'rails_helper'
RSpec.describe Imap::FetchEmailService do
include ActionMailbox::TestHelper
let(:logger) { instance_double(ActiveSupport::Logger, info: true, error: true) }
let(:account) { create(:account) }
let(:imap_email_channel) { create(:channel_email, :imap_email, account: account) }
let(:imap) { instance_double(Net::IMAP) }
let(:eml_content_with_message_id) { Rails.root.join('spec/fixtures/files/only_text.eml').read }
describe '#perform' do
before do
allow(Rails).to receive(:logger).and_return(logger)
allow(Net::IMAP).to receive(:new).with(
imap_email_channel.imap_address, port: imap_email_channel.imap_port, ssl: true
).and_return(imap)
allow(imap).to receive(:authenticate).with(
'PLAIN', imap_email_channel.imap_login, imap_email_channel.imap_password
)
allow(imap).to receive(:select).with('INBOX')
end
context 'when new emails are available in the mailbox' do
it 'fetches the emails and returns the emails that are not present in the db' do
travel_to '26.10.2020 10:00'.to_datetime do
email_object = create_inbound_email_from_fixture('only_text.eml')
email_header = Net::IMAP::FetchData.new(1, 'BODY[HEADER]' => eml_content_with_message_id)
imap_fetch_mail = Net::IMAP::FetchData.new(1, 'RFC822' => eml_content_with_message_id)
allow(imap).to receive(:search).with(%w[SINCE 25-Oct-2020]).and_return([1])
allow(imap).to receive(:fetch).with([1], 'BODY.PEEK[HEADER]').and_return([email_header])
allow(imap).to receive(:fetch).with(1, 'RFC822').and_return([imap_fetch_mail])
result = described_class.new(channel: imap_email_channel).perform
expect(result.length).to eq 1
expect(result[0].message_id).to eq email_object.message_id
expect(imap).to have_received(:search).with(%w[SINCE 25-Oct-2020])
expect(imap).to have_received(:fetch).with([1], 'BODY.PEEK[HEADER]')
expect(imap).to have_received(:fetch).with(1, 'RFC822')
expect(logger).to have_received(:info).with("[IMAP::FETCH_EMAIL_SERVICE] Fetching mails from #{imap_email_channel.email}, found 1.")
end
end
it 'fetches the emails and returns the mail objects that are not present in the db' do
travel_to '26.10.2020 10:00'.to_datetime do
email_object = create_inbound_email_from_fixture('only_text.eml')
create(:message, source_id: email_object.message_id, account: account, inbox: imap_email_channel.inbox)
email_header = Net::IMAP::FetchData.new(1, 'BODY[HEADER]' => eml_content_with_message_id)
allow(imap).to receive(:search).with(%w[SINCE 25-Oct-2020]).and_return([1])
allow(imap).to receive(:fetch).with([1], 'BODY.PEEK[HEADER]').and_return([email_header])
result = described_class.new(channel: imap_email_channel).perform
expect(result.length).to eq 0
expect(imap).to have_received(:search).with(%w[SINCE 25-Oct-2020])
expect(imap).to have_received(:fetch).with([1], 'BODY.PEEK[HEADER]')
expect(imap).not_to have_received(:fetch).with(1, 'RFC822')
end
end
end
end
end
@@ -0,0 +1,53 @@
require 'rails_helper'
RSpec.describe Imap::MicrosoftFetchEmailService do
include ActionMailbox::TestHelper
let(:logger) { instance_double(ActiveSupport::Logger, info: true, error: true) }
let(:account) { create(:account) }
let(:microsoft_channel) { create(:channel_email, :microsoft_email, account: account) }
let(:imap) { instance_double(Net::IMAP) }
let(:refresh_token_service) { double }
let(:eml_content_with_message_id) { Rails.root.join('spec/fixtures/files/only_text.eml').read }
describe '#perform' do
before do
allow(Rails).to receive(:logger).and_return(logger)
allow(Net::IMAP).to receive(:new).with(
microsoft_channel.imap_address, port: microsoft_channel.imap_port, ssl: true
).and_return(imap)
allow(imap).to receive(:authenticate).with(
'XOAUTH2', microsoft_channel.imap_login, microsoft_channel.provider_config['access_token']
)
allow(imap).to receive(:select).with('INBOX')
allow(Microsoft::RefreshOauthTokenService).to receive(:new).and_return(refresh_token_service)
allow(refresh_token_service).to receive(:access_token).and_return(microsoft_channel.provider_config['access_token'])
end
context 'when new emails are available in the mailbox' do
it 'fetches the emails and returns the emails that are not present in the db' do
travel_to '26.10.2020 10:00'.to_datetime do
email_object = create_inbound_email_from_fixture('only_text.eml')
email_header = Net::IMAP::FetchData.new(1, 'BODY[HEADER]' => eml_content_with_message_id)
imap_fetch_mail = Net::IMAP::FetchData.new(1, 'RFC822' => eml_content_with_message_id)
allow(imap).to receive(:search).with(%w[SINCE 25-Oct-2020]).and_return([1])
allow(imap).to receive(:fetch).with([1], 'BODY.PEEK[HEADER]').and_return([email_header])
allow(imap).to receive(:fetch).with(1, 'RFC822').and_return([imap_fetch_mail])
result = described_class.new(channel: microsoft_channel).perform
expect(refresh_token_service).to have_received(:access_token)
expect(result.length).to eq 1
expect(result[0].message_id).to eq email_object.message_id
expect(imap).to have_received(:search).with(%w[SINCE 25-Oct-2020])
expect(imap).to have_received(:fetch).with([1], 'BODY.PEEK[HEADER]')
expect(imap).to have_received(:fetch).with(1, 'RFC822')
expect(logger).to have_received(:info).with("[IMAP::FETCH_EMAIL_SERVICE] Fetching mails from #{microsoft_channel.email}, found 1.")
end
end
end
end
end
@@ -3,6 +3,9 @@ tags:
operationId: assign-a-conversation
summary: Assign Conversation
description: Assign a conversation to an agent or a team
security:
- userApiKey: []
- agentBotApiKey: []
parameters:
- name: data
in: body
+12
View File
@@ -3327,6 +3327,18 @@
"operationId": "assign-a-conversation",
"summary": "Assign Conversation",
"description": "Assign a conversation to an agent or a team",
"security": [
{
"userApiKey": [
]
},
{
"agentBotApiKey": [
]
}
],
"parameters": [
{
"name": "data",