Skip to content

Commit

Permalink
feat: Create campaign conversation only if user interacts with the bu…
Browse files Browse the repository at this point in the history
…bble (chatwoot#2335)

Co-authored-by: Pranav Raj S <pranav@chatwoot.com>
  • Loading branch information
muhsin-k and pranavrajs committed Jun 15, 2021
1 parent 853db60 commit fb2f3ff
Show file tree
Hide file tree
Showing 14 changed files with 211 additions and 18 deletions.
10 changes: 10 additions & 0 deletions app/javascript/sdk/IFrameHelper.js
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,16 @@ export const IFrameHelper = {
}
},

setCampaignMode: () => {
const { isOpen } = window.$chatwoot;
const toggleValue = true;
if (!isOpen) {
onBubbleClick({ toggleValue });
const holderEl = document.querySelector('.woot-widget-holder');
addClass(holderEl, 'has-unread-view');
}
},

resetUnreadMode: () => {
IFrameHelper.sendMessage('unset-unread-view');
IFrameHelper.events.removeUnreadClass();
Expand Down
38 changes: 36 additions & 2 deletions app/javascript/widget/App.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<template>
<router
:show-unread-view="showUnreadView"
:show-campaign-view="showCampaignView"
:is-mobile="isMobile"
:has-fetched="hasFetched"
:unread-message-count="unreadMessageCount"
Expand All @@ -17,6 +18,7 @@ import { IFrameHelper, RNHelper } from 'widget/helpers/utils';
import Router from './views/Router';
import { getLocale } from './helpers/urlParamsHelper';
import { BUS_EVENTS } from 'shared/constants/busEvents';
import { isEmptyObject } from 'widget/helpers/utils';
export default {
name: 'App',
Expand All @@ -26,6 +28,7 @@ export default {
data() {
return {
showUnreadView: false,
showCampaignView: false,
isMobile: false,
hideMessageBubble: false,
widgetPosition: 'right',
Expand All @@ -35,8 +38,10 @@ export default {
computed: {
...mapGetters({
hasFetched: 'agent/getHasFetched',
messageCount: 'conversation/getMessageCount',
unreadMessageCount: 'conversation/getUnreadMessageCount',
campaigns: 'campaign/getCampaigns',
activeCampaign: 'campaign/getActiveCampaign',
}),
isLeftAligned() {
const isLeft = this.widgetPosition === 'left';
Expand All @@ -49,6 +54,11 @@ export default {
return RNHelper.isRNWebView();
},
},
watch: {
activeCampaign() {
this.setCampaignView();
},
},
mounted() {
const { websiteToken, locale } = window.chatwootWebChannel;
this.setLocale(locale);
Expand All @@ -69,11 +79,12 @@ export default {
this.$store.dispatch('conversationAttributes/get');
this.setWidgetColor(window.chatwootWebChannel);
this.registerUnreadEvents();
this.registerCampaignEvents();
},
methods: {
...mapActions('appConfig', ['setWidgetColor']),
...mapActions('conversation', ['fetchOldConversations', 'setUserLastSeen']),
...mapActions('campaign', ['startCampaigns']),
...mapActions('campaign', ['initCampaigns', 'executeCampaign']),
...mapActions('agent', ['fetchAvailableAgents']),
scrollConversationToBottom() {
const container = this.$el.querySelector('.conversation-wrap');
Expand Down Expand Up @@ -110,9 +121,30 @@ export default {
this.setUserLastSeen();
});
},
registerCampaignEvents() {
bus.$on('on-campaign-view-clicked', campaignId => {
const { websiteToken } = window.chatwootWebChannel;
this.showCampaignView = false;
this.showUnreadView = false;
this.unsetUnreadView();
this.setUserLastSeen();
this.executeCampaign({ campaignId, websiteToken });
});
},
setPopoutDisplay(showPopoutButton) {
this.showPopoutButton = showPopoutButton;
},
setCampaignView() {
const { messageCount, activeCampaign } = this;
const isCampaignReadyToExecute =
!isEmptyObject(activeCampaign) && !messageCount;
if (this.isIFrame && isCampaignReadyToExecute) {
this.showCampaignView = true;
IFrameHelper.sendMessage({
event: 'setCampaignMode',
});
}
},
setUnreadView() {
const { unreadMessageCount } = this;
if (this.isIFrame && unreadMessageCount > 0) {
Expand Down Expand Up @@ -156,7 +188,7 @@ export default {
this.scrollConversationToBottom();
} else if (message.event === 'change-url') {
const { referrerURL, referrerHost } = message;
this.startCampaigns({ currentURL: referrerURL, websiteToken });
this.initCampaigns({ currentURL: referrerURL, websiteToken });
window.referrerURL = referrerURL;
bus.$emit(BUS_EVENTS.SET_REFERRER_HOST, referrerHost);
} else if (message.event === 'toggle-close-button') {
Expand All @@ -183,8 +215,10 @@ export default {
this.setBubbleLabel();
} else if (message.event === 'set-unread-view') {
this.showUnreadView = true;
this.showCampaignView = false;
} else if (message.event === 'unset-unread-view') {
this.showUnreadView = false;
this.showCampaignView = false;
}
});
},
Expand Down
3 changes: 1 addition & 2 deletions app/javascript/widget/api/campaign.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ const getCampaigns = async websiteToken => {
return result;
};

const triggerCampaign = async ({ campaignId }) => {
const { websiteToken } = window.chatwootWebChannel;
const triggerCampaign = async ({ campaignId, websiteToken }) => {
const urlData = endPoints.triggerCampaign({ websiteToken, campaignId });

await API.post(
Expand Down
15 changes: 13 additions & 2 deletions app/javascript/widget/components/UnreadMessage.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<template>
<div class="chat-bubble-wrap">
<div class="chat-bubble agent">
<button class="chat-bubble agent" @click="onClickMessage">
<div v-if="showSender" class="row--agent-block">
<thumbnail
:src="avatarUrl"
Expand All @@ -12,7 +12,7 @@
<span class="company--name"> {{ companyName }}</span>
</div>
<div class="message-content" v-html="formatMessage(message, false)"></div>
</div>
</button>
</div>
</template>

Expand All @@ -38,6 +38,10 @@ export default {
type: Object,
default: () => {},
},
campaignId: {
type: Number,
default: null,
},
},
computed: {
companyName() {
Expand Down Expand Up @@ -76,6 +80,11 @@ export default {
isSenderExist(sender) {
return sender && !isEmptyObject(sender);
},
onClickMessage() {
if (this.campaignId) {
bus.$emit('on-campaign-view-clicked', this.campaignId);
}
},
},
};
</script>
Expand All @@ -84,7 +93,9 @@ export default {
.chat-bubble {
max-width: 85%;
padding: $space-normal;
cursor: pointer;
}
.row--agent-block {
align-items: center;
display: flex;
Expand Down
5 changes: 2 additions & 3 deletions app/javascript/widget/helpers/campaignTimer.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { triggerCampaign } from 'widget/api/campaign';

import store from '../store';
class CampaignTimer {
constructor() {
this.campaignTimers = [];
Expand All @@ -10,7 +9,7 @@ class CampaignTimer {
campaigns.forEach(campaign => {
const { timeOnPage, id: campaignId } = campaign;
this.campaignTimers[campaignId] = setTimeout(() => {
triggerCampaign({ campaignId });
store.dispatch('campaign/startCampaign', { campaignId });
}, timeOnPage * 1000);
});
};
Expand Down
25 changes: 23 additions & 2 deletions app/javascript/widget/store/modules/campaign.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import Vue from 'vue';
import { getCampaigns } from 'widget/api/campaign';
import { getCampaigns, triggerCampaign } from 'widget/api/campaign';
import campaignTimer from 'widget/helpers/campaignTimer';
import {
formatCampaigns,
Expand All @@ -11,6 +11,7 @@ const state = {
isError: false,
hasFetched: false,
},
activeCampaign: {},
};

const resetCampaignTimers = (campaigns, currentURL) => {
Expand All @@ -26,6 +27,7 @@ const resetCampaignTimers = (campaigns, currentURL) => {
export const getters = {
getHasFetched: $state => $state.uiFlags.hasFetched,
getCampaigns: $state => $state.records,
getActiveCampaign: $state => $state.activeCampaign,
};

export const actions = {
Expand All @@ -41,7 +43,7 @@ export const actions = {
commit('setHasFetched', true);
}
},
startCampaigns: async (
initCampaigns: async (
{ getters: { getCampaigns: campaigns }, dispatch },
{ currentURL, websiteToken }
) => {
Expand All @@ -51,12 +53,31 @@ export const actions = {
resetCampaignTimers(campaigns, currentURL);
}
},
startCampaign: async (
{ getters: { getCampaigns: campaigns }, commit },
{ campaignId }
) => {
const campaign = campaigns.find(item => item.id === campaignId);
commit('setActiveCampaign', campaign);
},

executeCampaign: async ({ commit }, { campaignId, websiteToken }) => {
try {
await triggerCampaign({ campaignId, websiteToken });
commit('setActiveCampaign', {});
} catch (error) {
commit('setError', true);
}
},
};

export const mutations = {
setCampaigns($state, data) {
Vue.set($state, 'records', data);
},
setActiveCampaign($state, data) {
Vue.set($state, 'activeCampaign', data);
},
setError($state, value) {
Vue.set($state.uiFlags, 'isError', value);
},
Expand Down
3 changes: 3 additions & 0 deletions app/javascript/widget/store/modules/conversation/getters.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ export const getters = {
}));
},
getIsFetchingList: _state => _state.uiFlags.isFetchingList,
getMessageCount: _state => {
return Object.values(_state.conversations).length;
},
getUnreadMessageCount: _state => {
const { userLastSeenAt } = _state.meta;
const count = Object.values(_state.conversations).filter(chat => {
Expand Down
36 changes: 33 additions & 3 deletions app/javascript/widget/store/modules/specs/campaign/actions.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,22 +39,22 @@ describe('#actions', () => {
});
});

describe('#startCampaigns', () => {
describe('#initCampaigns', () => {
const actionParams = {
websiteToken: 'XDsafmADasd',
currentURL: 'https://chatwoot.com',
};

it('sends correct actions if campaigns are empty', async () => {
await actions.startCampaigns(
await actions.initCampaigns(
{ dispatch, getters: { getCampaigns: [] } },
actionParams
);
expect(dispatch.mock.calls).toEqual([['fetchCampaigns', actionParams]]);
expect(campaignTimer.initTimers).not.toHaveBeenCalled();
});
it('resets time if campaigns are available', async () => {
await actions.startCampaigns(
await actions.initCampaigns(
{ dispatch, getters: { getCampaigns: campaigns } },
actionParams
);
Expand All @@ -64,4 +64,34 @@ describe('#actions', () => {
});
});
});
describe('#startCampaign', () => {
it('reset campaign if campaign id is not present in the campaign list', async () => {
await actions.startCampaign(
{ dispatch, getters: { getCampaigns: campaigns }, commit },
{ campaignId: 32 }
);
expect(commit.mock.calls).toEqual([['setActiveCampaign', undefined]]);
});
it('start campaign if campaign id passed', async () => {
await actions.startCampaign(
{ dispatch, getters: { getCampaigns: campaigns }, commit },
{ campaignId: 1 }
);
expect(commit.mock.calls).toEqual([['setActiveCampaign', campaigns[0]]]);
});
});
describe('#executeCampaign', () => {
it('sends correct actions if execute campaign API is success', async () => {
const params = { campaignId: 12, websiteToken: 'XDsafmADasd' };
API.post.mockResolvedValue({});
await actions.executeCampaign({ commit }, params);
expect(commit.mock.calls).toEqual([['setActiveCampaign', {}]]);
});
it('sends correct actions if execute campaign API is failed', async () => {
const params = { campaignId: 12, websiteToken: 'XDsafmADasd' };
API.post.mockRejectedValue({ message: 'Authentication required' });
await actions.executeCampaign({ commit }, params);
expect(commit.mock.calls).toEqual([['setError', true]]);
});
});
});
36 changes: 36 additions & 0 deletions app/javascript/widget/store/modules/specs/campaign/getters.spec.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { getters } from '../../campaign';
import { campaigns } from './data';
jest.mock('widget/store/index.js');

describe('#getters', () => {
it('getCampaigns', () => {
Expand Down Expand Up @@ -93,4 +94,39 @@ describe('#getters', () => {
},
]);
});

it('getActiveCampaign', () => {
const state = {
records: campaigns[0],
};
expect(getters.getCampaigns(state)).toEqual({
id: 1,
title: 'Welcome',
description: null,
account_id: 1,
inbox: {
id: 37,
channel_id: 1,
name: 'Chatwoot',
channel_type: 'Channel::WebWidget',
},
sender: {
account_id: 1,
availability_status: 'offline',
confirmed: true,
email: 'sojan@chatwoot.com',
available_name: 'Sojan',
id: 10,
name: 'Sojan',
},
message: 'Hey, What brings you today',
enabled: true,
trigger_rules: {
url: 'https://github.com',
time_on_page: 10,
},
created_at: '2021-05-03T04:53:36.354Z',
updated_at: '2021-05-03T04:53:36.354Z',
});
});
});
Loading

0 comments on commit fb2f3ff

Please sign in to comment.