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

View file

@ -1,6 +1,7 @@
<template>
<router
:show-unread-view="showUnreadView"
:show-campaign-view="showCampaignView"
:is-mobile="isMobile"
:has-fetched="hasFetched"
:unread-message-count="unreadMessageCount"
@ -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',
@ -26,6 +28,7 @@ export default {
data() {
return {
showUnreadView: false,
showCampaignView: false,
isMobile: false,
hideMessageBubble: false,
widgetPosition: 'right',
@ -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';
@ -49,6 +54,11 @@ export default {
return RNHelper.isRNWebView();
},
},
watch: {
activeCampaign() {
this.setCampaignView();
},
},
mounted() {
const { websiteToken, locale } = window.chatwootWebChannel;
this.setLocale(locale);
@ -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');
@ -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) {
@ -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') {
@ -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;
}
});
},

View file

@ -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(

View file

@ -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"
@ -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>
@ -38,6 +38,10 @@ export default {
type: Object,
default: () => {},
},
campaignId: {
type: Number,
default: null,
},
},
computed: {
companyName() {
@ -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>
@ -84,7 +93,9 @@ export default {
.chat-bubble {
max-width: 85%;
padding: $space-normal;
cursor: pointer;
}
.row--agent-block {
align-items: center;
display: flex;

View file

@ -1,5 +1,4 @@
import { triggerCampaign } from 'widget/api/campaign';
import store from '../store';
class CampaignTimer {
constructor() {
this.campaignTimers = [];
@ -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);
});
};

View file

@ -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,
@ -11,6 +11,7 @@ const state = {
isError: false,
hasFetched: false,
},
activeCampaign: {},
};
const resetCampaignTimers = (campaigns, currentURL) => {
@ -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 = {
@ -41,7 +43,7 @@ export const actions = {
commit('setHasFetched', true);
}
},
startCampaigns: async (
initCampaigns: async (
{ getters: { getCampaigns: campaigns }, dispatch },
{ currentURL, websiteToken }
) => {
@ -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);
},

View file

@ -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 => {

View file

@ -39,14 +39,14 @@ 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
);
@ -54,7 +54,7 @@ describe('#actions', () => {
expect(campaignTimer.initTimers).not.toHaveBeenCalled();
});
it('resets time if campaigns are available', async () => {
await actions.startCampaigns(
await actions.initCampaigns(
{ dispatch, getters: { getCampaigns: campaigns } },
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 { campaigns } from './data';
jest.mock('widget/store/index.js');
describe('#getters', () => {
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 { campaigns } from './data';
jest.mock('widget/store/index.js');
describe('#mutations', () => {
describe('#setCampaigns', () => {
it('set campaign records', () => {
@ -25,4 +25,12 @@ describe('#mutations', () => {
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
v-if="!showUnreadView"
v-if="showHomePage"
:has-fetched="hasFetched"
:unread-message-count="unreadMessageCount"
:show-popout-button="showPopoutButton"
/>
<unread
v-else
:show-unread-view="showUnreadView"
:has-fetched="hasFetched"
:unread-message-count="unreadMessageCount"
:hide-message-bubble="hideMessageBubble"
@ -50,6 +50,10 @@ export default {
type: Boolean,
default: false,
},
showCampaignView: {
type: Boolean,
default: false,
},
hideMessageBubble: {
type: Boolean,
default: false,
@ -63,5 +67,10 @@ export default {
default: false,
},
},
computed: {
showHomePage() {
return !this.showUnreadView && !this.showCampaignView;
},
},
};
</script>

View file

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

View file

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