feat: Create campaign conversation only if user interacts with the bubble (#2335)

Co-authored-by: Pranav Raj S <pranav@chatwoot.com>
This commit is contained in:
Muhsin Keloth 2021-06-15 20:09:42 +05:30 committed by GitHub
parent 853db60f8e
commit fb2f3ff89f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
14 changed files with 211 additions and 18 deletions

View file

@ -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: () => { resetUnreadMode: () => {
IFrameHelper.sendMessage('unset-unread-view'); IFrameHelper.sendMessage('unset-unread-view');
IFrameHelper.events.removeUnreadClass(); IFrameHelper.events.removeUnreadClass();

View file

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

View file

@ -7,8 +7,7 @@ const getCampaigns = async websiteToken => {
return result; return result;
}; };
const triggerCampaign = async ({ campaignId }) => { const triggerCampaign = async ({ campaignId, websiteToken }) => {
const { websiteToken } = window.chatwootWebChannel;
const urlData = endPoints.triggerCampaign({ websiteToken, campaignId }); const urlData = endPoints.triggerCampaign({ websiteToken, campaignId });
await API.post( await API.post(

View file

@ -1,6 +1,6 @@
<template> <template>
<div class="chat-bubble-wrap"> <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"> <div v-if="showSender" class="row--agent-block">
<thumbnail <thumbnail
:src="avatarUrl" :src="avatarUrl"
@ -12,7 +12,7 @@
<span class="company--name"> {{ companyName }}</span> <span class="company--name"> {{ companyName }}</span>
</div> </div>
<div class="message-content" v-html="formatMessage(message, false)"></div> <div class="message-content" v-html="formatMessage(message, false)"></div>
</div> </button>
</div> </div>
</template> </template>
@ -38,6 +38,10 @@ export default {
type: Object, type: Object,
default: () => {}, default: () => {},
}, },
campaignId: {
type: Number,
default: null,
},
}, },
computed: { computed: {
companyName() { companyName() {
@ -76,6 +80,11 @@ export default {
isSenderExist(sender) { isSenderExist(sender) {
return sender && !isEmptyObject(sender); return sender && !isEmptyObject(sender);
}, },
onClickMessage() {
if (this.campaignId) {
bus.$emit('on-campaign-view-clicked', this.campaignId);
}
},
}, },
}; };
</script> </script>
@ -84,7 +93,9 @@ export default {
.chat-bubble { .chat-bubble {
max-width: 85%; max-width: 85%;
padding: $space-normal; padding: $space-normal;
cursor: pointer;
} }
.row--agent-block { .row--agent-block {
align-items: center; align-items: center;
display: flex; display: flex;

View file

@ -1,5 +1,4 @@
import { triggerCampaign } from 'widget/api/campaign'; import store from '../store';
class CampaignTimer { class CampaignTimer {
constructor() { constructor() {
this.campaignTimers = []; this.campaignTimers = [];
@ -10,7 +9,7 @@ class CampaignTimer {
campaigns.forEach(campaign => { campaigns.forEach(campaign => {
const { timeOnPage, id: campaignId } = campaign; const { timeOnPage, id: campaignId } = campaign;
this.campaignTimers[campaignId] = setTimeout(() => { this.campaignTimers[campaignId] = setTimeout(() => {
triggerCampaign({ campaignId }); store.dispatch('campaign/startCampaign', { campaignId });
}, timeOnPage * 1000); }, timeOnPage * 1000);
}); });
}; };

View file

@ -1,5 +1,5 @@
import Vue from 'vue'; import Vue from 'vue';
import { getCampaigns } from 'widget/api/campaign'; import { getCampaigns, triggerCampaign } from 'widget/api/campaign';
import campaignTimer from 'widget/helpers/campaignTimer'; import campaignTimer from 'widget/helpers/campaignTimer';
import { import {
formatCampaigns, formatCampaigns,
@ -11,6 +11,7 @@ const state = {
isError: false, isError: false,
hasFetched: false, hasFetched: false,
}, },
activeCampaign: {},
}; };
const resetCampaignTimers = (campaigns, currentURL) => { const resetCampaignTimers = (campaigns, currentURL) => {
@ -26,6 +27,7 @@ const resetCampaignTimers = (campaigns, currentURL) => {
export const getters = { export const getters = {
getHasFetched: $state => $state.uiFlags.hasFetched, getHasFetched: $state => $state.uiFlags.hasFetched,
getCampaigns: $state => $state.records, getCampaigns: $state => $state.records,
getActiveCampaign: $state => $state.activeCampaign,
}; };
export const actions = { export const actions = {
@ -41,7 +43,7 @@ export const actions = {
commit('setHasFetched', true); commit('setHasFetched', true);
} }
}, },
startCampaigns: async ( initCampaigns: async (
{ getters: { getCampaigns: campaigns }, dispatch }, { getters: { getCampaigns: campaigns }, dispatch },
{ currentURL, websiteToken } { currentURL, websiteToken }
) => { ) => {
@ -51,12 +53,31 @@ export const actions = {
resetCampaignTimers(campaigns, currentURL); 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 = { export const mutations = {
setCampaigns($state, data) { setCampaigns($state, data) {
Vue.set($state, 'records', data); Vue.set($state, 'records', data);
}, },
setActiveCampaign($state, data) {
Vue.set($state, 'activeCampaign', data);
},
setError($state, value) { setError($state, value) {
Vue.set($state.uiFlags, 'isError', value); Vue.set($state.uiFlags, 'isError', value);
}, },

View file

@ -27,6 +27,9 @@ export const getters = {
})); }));
}, },
getIsFetchingList: _state => _state.uiFlags.isFetchingList, getIsFetchingList: _state => _state.uiFlags.isFetchingList,
getMessageCount: _state => {
return Object.values(_state.conversations).length;
},
getUnreadMessageCount: _state => { getUnreadMessageCount: _state => {
const { userLastSeenAt } = _state.meta; const { userLastSeenAt } = _state.meta;
const count = Object.values(_state.conversations).filter(chat => { const count = Object.values(_state.conversations).filter(chat => {

View file

@ -39,14 +39,14 @@ describe('#actions', () => {
}); });
}); });
describe('#startCampaigns', () => { describe('#initCampaigns', () => {
const actionParams = { const actionParams = {
websiteToken: 'XDsafmADasd', websiteToken: 'XDsafmADasd',
currentURL: 'https://chatwoot.com', currentURL: 'https://chatwoot.com',
}; };
it('sends correct actions if campaigns are empty', async () => { it('sends correct actions if campaigns are empty', async () => {
await actions.startCampaigns( await actions.initCampaigns(
{ dispatch, getters: { getCampaigns: [] } }, { dispatch, getters: { getCampaigns: [] } },
actionParams actionParams
); );
@ -54,7 +54,7 @@ describe('#actions', () => {
expect(campaignTimer.initTimers).not.toHaveBeenCalled(); expect(campaignTimer.initTimers).not.toHaveBeenCalled();
}); });
it('resets time if campaigns are available', async () => { it('resets time if campaigns are available', async () => {
await actions.startCampaigns( await actions.initCampaigns(
{ dispatch, getters: { getCampaigns: campaigns } }, { dispatch, getters: { getCampaigns: campaigns } },
actionParams actionParams
); );
@ -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]]);
});
});
}); });

View file

@ -1,5 +1,6 @@
import { getters } from '../../campaign'; import { getters } from '../../campaign';
import { campaigns } from './data'; import { campaigns } from './data';
jest.mock('widget/store/index.js');
describe('#getters', () => { describe('#getters', () => {
it('getCampaigns', () => { it('getCampaigns', () => {
@ -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',
});
});
}); });

View file

@ -1,6 +1,6 @@
import { mutations } from '../../campaign'; import { mutations } from '../../campaign';
import { campaigns } from './data'; import { campaigns } from './data';
jest.mock('widget/store/index.js');
describe('#mutations', () => { describe('#mutations', () => {
describe('#setCampaigns', () => { describe('#setCampaigns', () => {
it('set campaign records', () => { it('set campaign records', () => {
@ -25,4 +25,12 @@ describe('#mutations', () => {
expect(state.uiFlags.hasFetched).toEqual(true); expect(state.uiFlags.hasFetched).toEqual(true);
}); });
}); });
describe('#setActiveCampaign', () => {
it('set active campaign', () => {
const state = { records: [] };
mutations.setActiveCampaign(state, campaigns[0]);
expect(state.activeCampaign).toEqual(campaigns[0]);
});
});
}); });

View file

@ -434,4 +434,15 @@ describe('#getters', () => {
]); ]);
}); });
}); });
it('getMessageCount', () => {
const state = {
conversations: {
1: {
content: 'hey, how are you?',
},
},
};
expect(getters.getMessageCount(state)).toEqual(1);
});
}); });

View file

@ -9,13 +9,13 @@
}" }"
> >
<home <home
v-if="!showUnreadView" v-if="showHomePage"
:has-fetched="hasFetched" :has-fetched="hasFetched"
:unread-message-count="unreadMessageCount" :unread-message-count="unreadMessageCount"
:show-popout-button="showPopoutButton" :show-popout-button="showPopoutButton"
/> />
<unread <unread
v-else :show-unread-view="showUnreadView"
:has-fetched="hasFetched" :has-fetched="hasFetched"
:unread-message-count="unreadMessageCount" :unread-message-count="unreadMessageCount"
:hide-message-bubble="hideMessageBubble" :hide-message-bubble="hideMessageBubble"
@ -50,6 +50,10 @@ export default {
type: Boolean, type: Boolean,
default: false, default: false,
}, },
showCampaignView: {
type: Boolean,
default: false,
},
hideMessageBubble: { hideMessageBubble: {
type: Boolean, type: Boolean,
default: false, default: false,
@ -63,5 +67,10 @@ export default {
default: false, default: false,
}, },
}, },
computed: {
showHomePage() {
return !this.showUnreadView && !this.showCampaignView;
},
},
}; };
</script> </script>

View file

@ -12,12 +12,14 @@
</div> </div>
<div class="unread-messages"> <div class="unread-messages">
<unread-message <unread-message
v-for="(message, index) in unreadMessages" v-for="(message, index) in allMessages"
:key="message.id" :key="message.id"
:message-type="message.messageType"
:message-id="message.id" :message-id="message.id"
:show-sender="!index" :show-sender="!index"
:sender="message.sender" :sender="message.sender"
:message="getMessageContent(message)" :message="getMessageContent(message)"
:campaign-id="message.campaignId"
/> />
</div> </div>
@ -60,10 +62,15 @@ export default {
type: Boolean, type: Boolean,
default: false, default: false,
}, },
showUnreadView: {
type: Boolean,
default: false,
},
}, },
computed: { computed: {
...mapGetters({ ...mapGetters({
unreadMessages: 'conversation/getUnreadTextMessages', unreadMessages: 'conversation/getUnreadTextMessages',
campaign: 'campaign/getActiveCampaign',
}), }),
showCloseButton() { showCloseButton() {
return this.unreadMessageCount && this.hideMessageBubble; return this.unreadMessageCount && this.hideMessageBubble;
@ -72,6 +79,19 @@ export default {
const [firstMessage] = this.unreadMessages; const [firstMessage] = this.unreadMessages;
return firstMessage.sender || {}; return firstMessage.sender || {};
}, },
allMessages() {
if (this.showUnreadView) {
return this.unreadMessages;
}
const { sender, id: campaignId, message: content } = this.campaign;
return [
{
content,
sender,
campaignId,
},
];
},
}, },
methods: { methods: {
openFullView() { openFullView() {

View file

@ -1,4 +1,6 @@
json.array! @campaigns do |campaign| json.array! @campaigns do |campaign|
json.id campaign.display_id json.id campaign.display_id
json.trigger_rules campaign.trigger_rules json.trigger_rules campaign.trigger_rules
json.message campaign.message
json.sender campaign.sender&.slice(:name, :avatar_url)
end end