feat: Add CSAT reports (#2608)

This commit is contained in:
Pranav Raj S 2021-07-14 10:20:06 +05:30 committed by GitHub
parent b7806fc210
commit cb44eb2964
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
34 changed files with 1120 additions and 57 deletions

View file

@ -4,16 +4,33 @@ class Api::V1::Accounts::CsatSurveyResponsesController < Api::V1::Accounts::Base
RESULTS_PER_PAGE = 25 RESULTS_PER_PAGE = 25
before_action :check_authorization before_action :check_authorization
before_action :csat_survey_responses, only: [:index] before_action :set_csat_survey_responses, only: [:index, :metrics]
before_action :set_current_page, only: [:index]
before_action :set_current_page_surveys, only: [:index]
before_action :set_total_sent_messages_count, only: [:metrics]
def index; end def index; end
def metrics
@total_count = @csat_survey_responses.count
@ratings_count = @csat_survey_responses.group(:rating).count
end
private private
def csat_survey_responses def set_total_sent_messages_count
@csat_survey_responses = Current.account.csat_survey_responses @csat_messages = Current.account.messages.input_csat
@csat_messages = @csat_messages.where(created_at: range) if range.present?
@total_sent_messages_count = @csat_messages.count
end
def set_csat_survey_responses
@csat_survey_responses = Current.account.csat_survey_responses.includes([:conversation, :assigned_agent, :contact])
@csat_survey_responses = @csat_survey_responses.where(created_at: range) if range.present? @csat_survey_responses = @csat_survey_responses.where(created_at: range) if range.present?
@csat_survey_responses.page(@current_page).per(RESULTS_PER_PAGE) end
def set_current_page_surveys
@csat_survey_responses = @csat_survey_responses.page(@current_page).per(RESULTS_PER_PAGE)
end end
def set_current_page def set_current_page

View file

@ -0,0 +1,18 @@
/* global axios */
import ApiClient from './ApiClient';
class CSATReportsAPI extends ApiClient {
constructor() {
super('csat_survey_responses', { accountScoped: true });
}
get({ page } = {}) {
return axios.get(this.url, { params: { page } });
}
getMetrics() {
return axios.get(`${this.url}/metrics`);
}
}
export default new CSATReportsAPI();

View file

@ -0,0 +1,29 @@
import csatReportsAPI from '../csatReports';
import ApiClient from '../ApiClient';
import describeWithAPIMock from './apiSpecHelper';
describe('#Reports API', () => {
it('creates correct instance', () => {
expect(csatReportsAPI).toBeInstanceOf(ApiClient);
expect(csatReportsAPI.apiVersion).toBe('/api/v1');
expect(csatReportsAPI).toHaveProperty('get');
expect(csatReportsAPI).toHaveProperty('getMetrics');
});
describeWithAPIMock('API calls', context => {
it('#get', () => {
csatReportsAPI.get({ page: 1 });
expect(context.axiosMock.get).toHaveBeenCalledWith(
'/api/v1/csat_survey_responses',
{
params: { page: 1 },
}
);
});
it('#getMetrics', () => {
csatReportsAPI.getMetrics();
expect(context.axiosMock.get).toHaveBeenCalledWith(
'/api/v1/csat_survey_responses/metrics'
);
});
});
});

View file

@ -42,6 +42,10 @@ code {
white-space: nowrap; white-space: nowrap;
} }
.text-capitalize {
text-transform: capitalize;
}
.cursor-pointer { .cursor-pointer {
cursor: pointer; cursor: pointer;
} }

View file

@ -1,7 +1,6 @@
.report-card { .report-card {
@include padding($space-normal $space-small $space-normal $space-two); @include padding($space-normal $space-small $space-normal $space-two);
@include margin($zero); @include margin($zero);
@include background-light;
cursor: pointer; cursor: pointer;
@include custom-border-top(3px, transparent); @include custom-border-top(3px, transparent);

View file

@ -1,14 +1,14 @@
/* eslint no-plusplus: 0 */ /* eslint no-plusplus: 0 */
/* eslint-env browser */
import AvatarUploader from './widgets/forms/AvatarUploader.vue'; import AvatarUploader from './widgets/forms/AvatarUploader.vue';
import Bar from './widgets/chart/BarChart'; import Bar from './widgets/chart/BarChart';
import Button from './ui/WootButton'; import Button from './ui/WootButton';
import Code from './Code'; import Code from './Code';
import ColorPicker from './widgets/ColorPicker'; import ColorPicker from './widgets/ColorPicker';
import DeleteModal from './widgets/modal/DeleteModal.vue';
import ConfirmDeleteModal from './widgets/modal/ConfirmDeleteModal.vue'; import ConfirmDeleteModal from './widgets/modal/ConfirmDeleteModal.vue';
import DeleteModal from './widgets/modal/DeleteModal.vue';
import DropdownItem from 'shared/components/ui/dropdown/DropdownItem'; import DropdownItem from 'shared/components/ui/dropdown/DropdownItem';
import DropdownMenu from 'shared/components/ui/dropdown/DropdownMenu'; import DropdownMenu from 'shared/components/ui/dropdown/DropdownMenu';
import HorizontalBar from './widgets/chart/HorizontalBarChart';
import Input from './widgets/forms/Input.vue'; import Input from './widgets/forms/Input.vue';
import Label from './ui/Label'; import Label from './ui/Label';
import LoadingState from './widgets/LoadingState'; import LoadingState from './widgets/LoadingState';
@ -28,12 +28,14 @@ const WootUIKit = {
Button, Button,
Code, Code,
ColorPicker, ColorPicker,
ConfirmDeleteModal,
DeleteModal, DeleteModal,
DropdownItem, DropdownItem,
DropdownMenu, DropdownMenu,
HorizontalBar,
Input, Input,
LoadingState,
Label, Label,
LoadingState,
Modal, Modal,
ModalHeader, ModalHeader,
ReportStatsCard, ReportStatsCard,
@ -43,7 +45,6 @@ const WootUIKit = {
Tabs, Tabs,
TabsItem, TabsItem,
Thumbnail, Thumbnail,
ConfirmDeleteModal,
install(Vue) { install(Vue) {
const keys = Object.keys(this); const keys = Object.keys(this);
keys.pop(); // remove 'install' from keys keys.pop(); // remove 'install' from keys

View file

@ -1,12 +1,21 @@
<template> <template>
<div class="small-2 report-card" :class="{ 'active': selected }" v-on:click="onClick(index)"> <div
<h3 class="heading">{{heading}}</h3> class="small-2 report-card"
<h4 class="metric">{{point}}</h4> :class="{ active: selected }"
<p class="desc">{{desc}}</p> @click="onClick(index)"
>
<h3 class="heading">
{{ heading }}
</h3>
<h4 class="metric">
{{ point }}
</h4>
<p class="desc">
{{ desc }}
</p>
</div> </div>
</template> </template>
<script> <script>
export default { export default {
props: { props: {
heading: String, heading: String,

View file

@ -1,36 +1,37 @@
<template> <template>
<div class="row--user-block"> <div class="row--user-block">
<Thumbnail <thumbnail
:src="sender.thumbnail" :src="user.thumbnail"
size="20px" :size="size"
:username="sender.name" :username="user.name"
:status="sender.availability_status" :status="user.availability_status"
/> />
<div> <h6 class="text-block-title text-truncate text-capitalize">
<h6 class="text-block-title text-truncate"> {{ user.name }}
{{ sender.name }} </h6>
</h6>
</div>
</div> </div>
</template> </template>
<script> <script>
import Thumbnail from 'dashboard/components/widgets/Thumbnail.vue'; import Thumbnail from 'dashboard/components/widgets/Thumbnail.vue';
export default { export default {
components: { components: {
Thumbnail, Thumbnail,
}, },
props: { props: {
sender: { user: {
type: Object, type: Object,
default: () => {}, default: () => {},
}, },
size: {
type: String,
default: '20px',
},
}, },
}; };
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
@import '~dashboard/assets/scss/mixins';
.row--user-block { .row--user-block {
align-items: center; align-items: center;
display: flex; display: flex;

View file

@ -0,0 +1,54 @@
import { HorizontalBar } from 'vue-chartjs';
const chartOptions = {
responsive: true,
legend: {
display: false,
},
title: {
display: false,
},
tooltips: {
enabled: false,
},
scales: {
xAxes: [
{
gridLines: {
offsetGridLines: false,
},
display: false,
stacked: true,
},
],
yAxes: [
{
gridLines: {
offsetGridLines: false,
},
display: false,
stacked: true,
},
],
},
};
export default {
extends: HorizontalBar,
props: {
collection: {
type: Object,
default: () => {},
},
chartOptions: {
type: Object,
default: () => {},
},
},
mounted() {
this.renderChart(this.collection, {
...chartOptions,
...this.chartOptions,
});
},
};

View file

@ -8,7 +8,6 @@ export const getSidebarItems = accountId => ({
'inbox_conversation', 'inbox_conversation',
'conversation_through_inbox', 'conversation_through_inbox',
'notifications_dashboard', 'notifications_dashboard',
'settings_account_reports',
'profile_settings', 'profile_settings',
'profile_settings_index', 'profile_settings_index',
'label_conversations', 'label_conversations',
@ -80,6 +79,32 @@ export const getSidebarItems = accountId => ({
}, },
}, },
}, },
reports: {
routes: ['settings_account_reports', 'csat_reports'],
menuItems: {
back: {
icon: 'ion-ios-arrow-back',
label: 'HOME',
hasSubMenu: false,
toStateName: 'home',
toState: frontendURL(`accounts/${accountId}/dashboard`),
},
reportOverview: {
icon: 'ion-arrow-graph-up-right',
label: 'REPORTS_OVERVIEW',
hasSubMenu: false,
toState: frontendURL(`accounts/${accountId}/reports/overview`),
toStateName: 'settings_account_reports',
},
csatReports: {
icon: 'ion-happy',
label: 'CSAT',
hasSubMenu: false,
toState: frontendURL(`accounts/${accountId}/reports/csat`),
toStateName: 'csat_reports',
},
},
},
settings: { settings: {
routes: [ routes: [
'agent_list', 'agent_list',

View file

@ -1,6 +1,6 @@
{ {
"REPORT": { "REPORT": {
"HEADER": "Reports", "HEADER": "Overview",
"LOADING_CHART": "Loading chart data...", "LOADING_CHART": "Loading chart data...",
"NO_ENOUGH_DATA": "We've not received enough data points to generate report, Please try again later.", "NO_ENOUGH_DATA": "We've not received enough data points to generate report, Please try again later.",
"DOWNLOAD_AGENT_REPORTS": "Download agent reports", "DOWNLOAD_AGENT_REPORTS": "Download agent reports",
@ -60,5 +60,31 @@
"CONFIRM": "Apply", "CONFIRM": "Apply",
"PLACEHOLDER": "Select date range" "PLACEHOLDER": "Select date range"
} }
},
"CSAT_REPORTS": {
"HEADER": "CSAT Reports",
"NO_RECORDS": "There are no CSAT survey responses available.",
"TABLE": {
"HEADER": {
"CONTACT_NAME": "Contact",
"AGENT_NAME": "Assigned agent",
"RATING": "Rating",
"FEEDBACK_TEXT": "Feedback comment"
}
},
"METRIC": {
"TOTAL_RESPONSES": {
"LABEL": "Total responses",
"TOOLTIP": "Total number of responses collected"
},
"SATISFACTION_SCORE": {
"LABEL": "Satisfaction score",
"TOOLTIP": "Total number of positive responses / Total number of responses * 100"
},
"RESPONSE_RATE": {
"LABEL": "Response rate",
"TOOLTIP": "Total number of responses / Total number of CSAT survey messages sent * 100"
}
}
} }
} }

View file

@ -139,7 +139,9 @@
"LABELS": "Labels", "LABELS": "Labels",
"TEAMS": "Teams", "TEAMS": "Teams",
"ALL_CONTACTS": "All Contacts", "ALL_CONTACTS": "All Contacts",
"TAGGED_WITH": "Tagged with" "TAGGED_WITH": "Tagged with",
"REPORTS_OVERVIEW": "Overview",
"CSAT": "CSAT"
}, },
"CREATE_ACCOUNT": { "CREATE_ACCOUNT": {
"NEW_ACCOUNT": "New Account", "NEW_ACCOUNT": "New Account",

View file

@ -22,7 +22,7 @@ import Spinner from 'shared/components/Spinner.vue';
import Label from 'dashboard/components/ui/Label'; import Label from 'dashboard/components/ui/Label';
import EmptyState from 'dashboard/components/widgets/EmptyState.vue'; import EmptyState from 'dashboard/components/widgets/EmptyState.vue';
import WootButton from 'dashboard/components/ui/WootButton.vue'; import WootButton from 'dashboard/components/ui/WootButton.vue';
import CampaignSender from './CampaignSender'; import UserAvatarWithName from 'dashboard/components/widgets/UserAvatarWithName';
export default { export default {
components: { components: {
@ -95,7 +95,7 @@ export default {
title: this.$t('CAMPAIGN.LIST.TABLE_HEADER.SENDER'), title: this.$t('CAMPAIGN.LIST.TABLE_HEADER.SENDER'),
align: 'left', align: 'left',
renderBodyCell: ({ row }) => { renderBodyCell: ({ row }) => {
if (row.sender) return <CampaignSender sender={row.sender} />; if (row.sender) return <UserAvatarWithName user={row.sender} />;
return this.$t('CAMPAIGN.LIST.SENDER.BOT'); return this.$t('CAMPAIGN.LIST.SENDER.BOT');
}, },
}, },

View file

@ -0,0 +1,33 @@
<template>
<div class="column content-box">
<csat-metrics />
<csat-table :page-index="pageIndex" @page-change="onPageNumberChange" />
</div>
</template>
<script>
import CsatMetrics from './components/CsatMetrics';
import CsatTable from './components/CsatTable';
export default {
name: 'CsatResponses',
components: {
CsatMetrics,
CsatTable,
},
data() {
return { pageIndex: 1 };
},
mounted() {
this.$store.dispatch('csat/getMetrics');
this.getData();
},
methods: {
getData() {
this.$store.dispatch('csat/get', { page: this.pageIndex });
},
onPageNumberChange(pageIndex) {
this.pageIndex = pageIndex;
this.getData();
},
},
};
</script>

View file

@ -0,0 +1,43 @@
import Vue from 'vue';
import VTooltip from 'v-tooltip';
import CsatMetricCard from './CsatMetricCard';
Vue.use(VTooltip, { defaultHtml: false });
export default {
title: 'Components/CSAT/Metrics Card',
component: CsatMetricCard,
argTypes: {
label: {
defaultValue: '',
control: {
type: 'text',
},
},
value: {
defaultValue: '',
control: {
type: 'text',
},
},
infoText: {
defaultValue: '',
control: {
type: 'text',
},
},
},
};
const Template = (_, { argTypes }) => ({
props: Object.keys(argTypes),
components: { CsatMetricCard },
template: '<csat-metric-card v-bind="$props" />',
});
export const CsatMetricCardTemplate = Template.bind({});
CsatMetricCardTemplate.args = {
infoText: 'No. of responses / No. of survey messages sent * 100',
label: 'Satisfaction Score',
value: '98.5',
};

View file

@ -0,0 +1,55 @@
<template>
<div class="medium-2 small-6 csat--metric-card">
<h3 class="heading">
<span>{{ label }}</span>
<i v-tooltip="infoText" class="csat--icon ion-ios-information" />
</h3>
<h4 class="metric">
{{ value }}
</h4>
</div>
</template>
<script>
export default {
props: {
label: {
type: String,
required: true,
},
value: {
type: String,
required: true,
},
infoText: {
type: String,
required: true,
},
},
};
</script>
<style lang="scss" scoped>
.csat--metric-card {
margin: 0;
padding: var(--space-normal) var(--space-small) var(--space-normal)
var(--space-two);
.heading {
color: var(--color-heading);
font-size: var(--font-size-small);
font-weight: var(--font-weight-bold);
margin: 0;
}
.metric {
font-size: var(--font-size-bigger);
font-weight: var(--font-weight-feather);
margin-bottom: 0;
margin-top: var(--space-smaller);
}
}
.csat--icon {
color: var(--b-400);
margin-left: var(--space-micro);
}
</style>

View file

@ -0,0 +1,108 @@
<template>
<div class="row csat--metrics-container">
<csat-metric-card
:label="$t('CSAT_REPORTS.METRIC.TOTAL_RESPONSES.LABEL')"
:info-text="$t('CSAT_REPORTS.METRIC.TOTAL_RESPONSES.TOOLTIP')"
:value="responseCount"
/>
<csat-metric-card
:label="$t('CSAT_REPORTS.METRIC.SATISFACTION_SCORE.LABEL')"
:info-text="$t('CSAT_REPORTS.METRIC.SATISFACTION_SCORE.TOOLTIP')"
:value="formatToPercent(satisfactionScore)"
/>
<csat-metric-card
:label="$t('CSAT_REPORTS.METRIC.RESPONSE_RATE.LABEL')"
:info-text="$t('CSAT_REPORTS.METRIC.RESPONSE_RATE.TOOLTIP')"
:value="formatToPercent(responseRate)"
/>
<div v-if="metrics.totalResponseCount" class="medium-6 report-card">
<h3 class="heading">
<div class="emoji--distribution">
<div
v-for="(rating, key, index) in ratingPercentage"
:key="rating + key + index"
class="emoji--distribution-item"
>
<span class="emoji--distribution-key">{{
csatRatings[key - 1].emoji
}}</span>
<span>{{ formatToPercent(rating) }}</span>
</div>
</div>
</h3>
<div class="emoji--distribution-chart">
<woot-horizontal-bar :collection="chartData" :height="24" />
</div>
</div>
</div>
</template>
<script>
import { mapGetters } from 'vuex';
import CsatMetricCard from './CsatMetricCard';
import { CSAT_RATINGS } from 'shared/constants/messages';
export default {
components: {
CsatMetricCard,
},
data() {
return {
csatRatings: CSAT_RATINGS,
};
},
computed: {
...mapGetters({
metrics: 'csat/getMetrics',
ratingPercentage: 'csat/getRatingPercentage',
satisfactionScore: 'csat/getSatisfactionScore',
responseRate: 'csat/getResponseRate',
}),
chartData() {
return {
labels: ['Rating'],
datasets: CSAT_RATINGS.map((rating, index) => ({
label: rating.emoji,
data: [this.ratingPercentage[index + 1]],
backgroundColor: rating.color,
})),
};
},
responseCount() {
return this.metrics.totalResponseCount
? this.metrics.totalResponseCount.toLocaleString()
: '--';
},
},
methods: {
formatToPercent(value) {
return value ? `${value}%` : '--';
},
},
};
</script>
<style lang="scss" scoped>
.csat--metrics-container {
background: var(--white);
margin-bottom: var(--space-two);
border-radius: var(--border-radius-normal);
border: 1px solid var(--color-border);
padding: var(--space-normal);
}
.emoji--distribution {
display: flex;
justify-content: flex-end;
.emoji--distribution-item {
padding-left: var(--space-normal);
}
}
.emoji--distribution-chart {
margin-top: var(--space-small);
}
.emoji--distribution-key {
margin-right: var(--space-micro);
}
</style>

View file

@ -0,0 +1,191 @@
<template>
<div class="csat--table-container">
<ve-table
max-height="calc(100vh - 30rem)"
:fixed-header="true"
:columns="columns"
:table-data="tableData"
/>
<div v-show="!tableData.length" class="csat--empty-records">
{{ $t('CSAT_REPORTS.NO_RECORDS') }}
</div>
<div v-if="metrics.totalResponseCount" class="table-pagination">
<ve-pagination
:total="metrics.totalResponseCount"
:page-index="pageIndex"
:page-size="25"
:page-size-option="[25]"
@on-page-number-change="onPageNumberChange"
/>
</div>
</div>
</template>
<script>
import { VeTable, VePagination } from 'vue-easytable';
import UserAvatarWithName from 'dashboard/components/widgets/UserAvatarWithName';
import { CSAT_RATINGS } from 'shared/constants/messages';
import { mapGetters } from 'vuex';
export default {
components: {
VeTable,
VePagination,
},
props: {
pageIndex: {
type: Number,
default: 1,
},
},
computed: {
...mapGetters({
uiFlags: 'csat/getUIFlags',
csatResponses: 'csat/getCSATResponses',
metrics: 'csat/getMetrics',
}),
columns() {
return [
{
field: 'contact',
key: 'contact',
title: this.$t('CSAT_REPORTS.TABLE.HEADER.CONTACT_NAME'),
align: 'left',
width: 200,
renderBodyCell: ({ row }) => {
if (row.contact) {
return <UserAvatarWithName size="24px" user={row.contact} />;
}
return '---';
},
},
{
field: 'assignedAgent',
key: 'assignedAgent',
title: this.$t('CSAT_REPORTS.TABLE.HEADER.AGENT_NAME'),
align: 'left',
width: 200,
renderBodyCell: ({ row }) => {
if (row.assignedAgent) {
return (
<UserAvatarWithName size="24px" user={row.assignedAgent} />
);
}
return '---';
},
},
{
field: 'rating',
key: 'rating',
title: this.$t('CSAT_REPORTS.TABLE.HEADER.RATING'),
align: 'center',
width: 80,
renderBodyCell: ({ row }) => {
const [ratingObject = {}] = CSAT_RATINGS.filter(
rating => rating.value === row.rating
);
return (
<span class="emoji-response">{ratingObject.emoji || '---'}</span>
);
},
},
{
field: 'feedbackText',
key: 'feedbackText',
title: this.$t('CSAT_REPORTS.TABLE.HEADER.FEEDBACK_TEXT'),
align: 'left',
},
{
field: 'converstionId',
key: 'converstionId',
title: '',
align: 'left',
width: 100,
renderBodyCell: ({ row }) => {
const routerParams = {
name: 'inbox_conversation',
params: { conversation_id: row.conversationId },
};
return (
<router-link to={routerParams}>
{`#${row.conversationId}`}
</router-link>
);
},
},
];
},
tableData() {
return this.csatResponses.map(response => ({
contact: response.contact,
assignedAgent: response.assigned_agent,
rating: response.rating,
feedbackText: response.feedback_message || '---',
conversationId: response.conversation_id,
}));
},
},
methods: {
onPageNumberChange(pageIndex) {
this.$emit('page-change', pageIndex);
},
},
};
</script>
<style lang="scss" scoped>
.csat--table-container {
display: flex;
flex-direction: column;
flex: 1;
.ve-table {
background: var(--white);
&::v-deep {
.ve-table-container {
border-radius: var(--border-radius-normal);
border: 1px solid var(--color-border) !important;
}
th.ve-table-header-th {
font-size: var(--font-size-mini) !important;
padding: var(--space-normal) !important;
}
td.ve-table-body-td {
padding: var(--space-small) var(--space-normal) !important;
}
}
}
&::v-deep .ve-pagination {
background-color: transparent;
}
&::v-deep .ve-pagination-select {
display: none;
}
.emoji-response {
font-size: var(--font-size-large);
}
.table-pagination {
margin-top: var(--space-normal);
text-align: right;
}
}
.csat--empty-records {
align-items: center;
background-color: var(--white);
border: 1px solid var(--color-border);
border-top: 0;
color: var(--b-600);
display: flex;
font-size: var(--font-size-small);
height: 20rem;
justify-content: center;
margin-top: -1px;
width: 100%;
}
</style>

View file

@ -1,4 +1,5 @@
import Index from './Index'; import Index from './Index';
import CsatResponses from './CsatResponses';
import SettingsContent from '../Wrapper'; import SettingsContent from '../Wrapper';
import { frontendURL } from '../../../../helper/URLHelper'; import { frontendURL } from '../../../../helper/URLHelper';
@ -9,17 +10,36 @@ export default {
component: SettingsContent, component: SettingsContent,
props: { props: {
headerTitle: 'REPORT.HEADER', headerTitle: 'REPORT.HEADER',
headerButtonText: 'REPORT.HEADER_BTN_TXT',
icon: 'ion-arrow-graph-up-right', icon: 'ion-arrow-graph-up-right',
}, },
children: [ children: [
{ {
path: '', path: '',
redirect: 'overview',
},
{
path: 'overview',
name: 'settings_account_reports', name: 'settings_account_reports',
roles: ['administrator'], roles: ['administrator'],
component: Index, component: Index,
}, },
], ],
}, },
{
path: frontendURL('accounts/:accountId/reports'),
component: SettingsContent,
props: {
headerTitle: 'CSAT_REPORTS.HEADER',
icon: 'ion-happy-outline',
},
children: [
{
path: 'csat',
name: 'csat_reports',
roles: ['administrator'],
component: CsatResponses,
},
],
},
], ],
}; };

View file

@ -4,11 +4,12 @@ import Vuex from 'vuex';
import accounts from './modules/accounts'; import accounts from './modules/accounts';
import agents from './modules/agents'; import agents from './modules/agents';
import auth from './modules/auth'; import auth from './modules/auth';
import campaigns from './modules/campaigns';
import cannedResponse from './modules/cannedResponse'; import cannedResponse from './modules/cannedResponse';
import contactConversations from './modules/contactConversations'; import contactConversations from './modules/contactConversations';
import contacts from './modules/contacts';
import contactLabels from './modules/contactLabels'; import contactLabels from './modules/contactLabels';
import notifications from './modules/notifications'; import contactNotes from './modules/contactNotes';
import contacts from './modules/contacts';
import conversationLabels from './modules/conversationLabels'; import conversationLabels from './modules/conversationLabels';
import conversationMetadata from './modules/conversationMetadata'; import conversationMetadata from './modules/conversationMetadata';
import conversationPage from './modules/conversationPage'; import conversationPage from './modules/conversationPage';
@ -16,19 +17,19 @@ import conversations from './modules/conversations';
import conversationSearch from './modules/conversationSearch'; import conversationSearch from './modules/conversationSearch';
import conversationStats from './modules/conversationStats'; import conversationStats from './modules/conversationStats';
import conversationTypingStatus from './modules/conversationTypingStatus'; import conversationTypingStatus from './modules/conversationTypingStatus';
import csat from './modules/csat';
import globalConfig from 'shared/store/globalConfig'; import globalConfig from 'shared/store/globalConfig';
import inboxAssignableAgents from './modules/inboxAssignableAgents';
import inboxes from './modules/inboxes'; import inboxes from './modules/inboxes';
import inboxMembers from './modules/inboxMembers'; import inboxMembers from './modules/inboxMembers';
import inboxAssignableAgents from './modules/inboxAssignableAgents';
import integrations from './modules/integrations'; import integrations from './modules/integrations';
import labels from './modules/labels'; import labels from './modules/labels';
import notifications from './modules/notifications';
import reports from './modules/reports'; import reports from './modules/reports';
import teamMembers from './modules/teamMembers';
import teams from './modules/teams';
import userNotificationSettings from './modules/userNotificationSettings'; import userNotificationSettings from './modules/userNotificationSettings';
import webhooks from './modules/webhooks'; import webhooks from './modules/webhooks';
import teams from './modules/teams';
import teamMembers from './modules/teamMembers';
import campaigns from './modules/campaigns';
import contactNotes from './modules/contactNotes';
Vue.use(Vuex); Vue.use(Vuex);
export default new Vuex.Store({ export default new Vuex.Store({
@ -36,11 +37,12 @@ export default new Vuex.Store({
accounts, accounts,
agents, agents,
auth, auth,
campaigns,
cannedResponse, cannedResponse,
contactConversations, contactConversations,
contacts,
contactLabels, contactLabels,
notifications, contactNotes,
contacts,
conversationLabels, conversationLabels,
conversationMetadata, conversationMetadata,
conversationPage, conversationPage,
@ -48,18 +50,18 @@ export default new Vuex.Store({
conversationSearch, conversationSearch,
conversationStats, conversationStats,
conversationTypingStatus, conversationTypingStatus,
csat,
globalConfig, globalConfig,
inboxAssignableAgents,
inboxes, inboxes,
inboxMembers, inboxMembers,
inboxAssignableAgents,
integrations, integrations,
labels, labels,
notifications,
reports, reports,
teamMembers,
teams,
userNotificationSettings, userNotificationSettings,
webhooks, webhooks,
teams,
teamMembers,
campaigns,
contactNotes,
}, },
}); });

View file

@ -0,0 +1,144 @@
import * as MutationHelpers from 'shared/helpers/vuex/mutationHelpers';
import types from '../mutation-types';
import CSATReports from '../../api/csatReports';
const computeDistribution = (value, total) =>
((value * 100) / total).toFixed(2);
export const state = {
records: [],
metrics: {
totalResponseCount: 0,
ratingsCount: {
1: 0,
2: 0,
3: 0,
4: 0,
5: 0,
},
totalSentMessagesCount: 0,
},
uiFlags: {
isFetching: false,
isFetchingMetrics: false,
},
};
export const getters = {
getCSATResponses(_state) {
return _state.records;
},
getMetrics(_state) {
return _state.metrics;
},
getUIFlags(_state) {
return _state.uiFlags;
},
getSatisfactionScore(_state) {
if (!_state.metrics.totalResponseCount) {
return 0;
}
return computeDistribution(
_state.metrics.ratingsCount[4] + _state.metrics.ratingsCount[5],
_state.metrics.totalResponseCount
);
},
getResponseRate(_state) {
if (!_state.metrics.totalSentMessagesCount) {
return 0;
}
return computeDistribution(
_state.metrics.totalResponseCount,
_state.metrics.totalSentMessagesCount
);
},
getRatingPercentage(_state) {
if (!_state.metrics.totalResponseCount) {
return { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 };
}
return {
1: computeDistribution(
_state.metrics.ratingsCount[1],
_state.metrics.totalResponseCount
),
2: computeDistribution(
_state.metrics.ratingsCount[2],
_state.metrics.totalResponseCount
),
3: computeDistribution(
_state.metrics.ratingsCount[3],
_state.metrics.totalResponseCount
),
4: computeDistribution(
_state.metrics.ratingsCount[4],
_state.metrics.totalResponseCount
),
5: computeDistribution(
_state.metrics.ratingsCount[5],
_state.metrics.totalResponseCount
),
};
},
};
export const actions = {
get: async function getResponses({ commit }, { page = 1 } = {}) {
commit(types.SET_CSAT_RESPONSE_UI_FLAG, { isFetching: true });
try {
const response = await CSATReports.get({ page });
commit(types.SET_CSAT_RESPONSE, response.data);
} catch (error) {
// Ignore error
} finally {
commit(types.SET_CSAT_RESPONSE_UI_FLAG, { isFetching: false });
}
},
getMetrics: async function getMetrics({ commit }) {
commit(types.SET_CSAT_RESPONSE_UI_FLAG, { isFetchingMetrics: true });
try {
const response = await CSATReports.getMetrics();
commit(types.SET_CSAT_RESPONSE_METRICS, response.data);
} catch (error) {
// Ignore error
} finally {
commit(types.SET_CSAT_RESPONSE_UI_FLAG, { isFetchingMetrics: false });
}
},
};
export const mutations = {
[types.SET_CSAT_RESPONSE_UI_FLAG](_state, data) {
_state.uiFlags = {
..._state.uiFlags,
...data,
};
},
[types.SET_CSAT_RESPONSE]: MutationHelpers.set,
[types.SET_CSAT_RESPONSE_METRICS](
_state,
{
total_count: totalResponseCount,
ratings_count: ratingsCount,
total_sent_messages_count: totalSentMessagesCount,
}
) {
_state.metrics.totalResponseCount = totalResponseCount || 0;
_state.metrics.ratingsCount = {
1: ratingsCount['1'] || 0,
2: ratingsCount['2'] || 0,
3: ratingsCount['3'] || 0,
4: ratingsCount['4'] || 0,
5: ratingsCount['5'] || 0,
};
_state.metrics.totalSentMessagesCount = totalSentMessagesCount || 0;
},
};
export default {
namespaced: true,
state,
getters,
actions,
mutations,
};

View file

@ -0,0 +1,64 @@
import axios from 'axios';
import { actions } from '../../csat';
import types from '../../../mutation-types';
const commit = jest.fn();
global.axios = axios;
jest.mock('axios');
describe('#actions', () => {
describe('#get', () => {
it('sends correct mutations if API is success', async () => {
axios.get.mockResolvedValue({
data: [{ id: 1, rating: 1, feedback_text: 'Bad' }],
});
await actions.get({ commit }, { page: 1 });
expect(commit.mock.calls).toEqual([
[types.SET_CSAT_RESPONSE_UI_FLAG, { isFetching: true }],
[types.SET_CSAT_RESPONSE, [{ id: 1, rating: 1, feedback_text: 'Bad' }]],
[types.SET_CSAT_RESPONSE_UI_FLAG, { isFetching: false }],
]);
});
it('sends correct actions if API is error', async () => {
axios.get.mockRejectedValue({ message: 'Incorrect header' });
await actions.get({ commit }, { page: 1 });
expect(commit.mock.calls).toEqual([
[types.SET_CSAT_RESPONSE_UI_FLAG, { isFetching: true }],
[types.SET_CSAT_RESPONSE_UI_FLAG, { isFetching: false }],
]);
});
});
describe('#getMetrics', () => {
it('sends correct mutations if API is success', async () => {
axios.get.mockResolvedValue({
data: {
total_count: 29,
ratings_count: { 1: 10, 2: 10, 3: 3, 4: 3, 5: 3 },
total_sent_messages_count: 120,
},
});
await actions.getMetrics({ commit }, { page: 1 });
expect(commit.mock.calls).toEqual([
[types.SET_CSAT_RESPONSE_UI_FLAG, { isFetchingMetrics: true }],
[
types.SET_CSAT_RESPONSE_METRICS,
{
total_count: 29,
ratings_count: { 1: 10, 2: 10, 3: 3, 4: 3, 5: 3 },
total_sent_messages_count: 120,
},
],
[types.SET_CSAT_RESPONSE_UI_FLAG, { isFetchingMetrics: false }],
]);
});
it('sends correct actions if API is error', async () => {
axios.get.mockRejectedValue({ message: 'Incorrect header' });
await actions.getMetrics({ commit }, { page: 1 });
expect(commit.mock.calls).toEqual([
[types.SET_CSAT_RESPONSE_UI_FLAG, { isFetchingMetrics: true }],
[types.SET_CSAT_RESPONSE_UI_FLAG, { isFetchingMetrics: false }],
]);
});
});
});

View file

@ -0,0 +1,89 @@
import { getters } from '../../csat';
describe('#getters', () => {
it('getUIFlags', () => {
const state = { uiFlags: { isFetching: false } };
expect(getters.getUIFlags(state)).toEqual({ isFetching: false });
});
it('getCSATResponses', () => {
const state = { records: [{ id: 1, raring: 1, feedback_text: 'Bad' }] };
expect(getters.getCSATResponses(state)).toEqual([
{ id: 1, raring: 1, feedback_text: 'Bad' },
]);
});
it('getMetrics', () => {
const state = {
metrics: {
totalResponseCount: 0,
ratingsCount: { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 },
},
};
expect(getters.getMetrics(state)).toEqual(state.metrics);
});
it('getRatingPercentage', () => {
let state = {
metrics: {
totalResponseCount: 0,
ratingsCount: { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 },
},
};
expect(getters.getRatingPercentage(state)).toEqual({
1: 0,
2: 0,
3: 0,
4: 0,
5: 0,
});
state = {
metrics: {
totalResponseCount: 50,
ratingsCount: { 1: 10, 2: 20, 3: 15, 4: 3, 5: 2 },
},
};
expect(getters.getRatingPercentage(state)).toEqual({
1: '20.00',
2: '40.00',
3: '30.00',
4: '6.00',
5: '4.00',
});
});
it('getResponseRate', () => {
expect(
getters.getResponseRate({
metrics: { totalResponseCount: 0, totalSentMessagesCount: 0 },
})
).toEqual(0);
expect(
getters.getResponseRate({
metrics: { totalResponseCount: 20, totalSentMessagesCount: 50 },
})
).toEqual('40.00');
});
it('getSatisfactionScore', () => {
expect(
getters.getSatisfactionScore({
metrics: {
totalResponseCount: 0,
ratingsCount: { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 },
},
})
).toEqual(0);
expect(
getters.getSatisfactionScore({
metrics: {
totalResponseCount: 54,
ratingsCount: { 1: 0, 2: 0, 3: 0, 4: 12, 5: 15 },
},
})
).toEqual('50.00');
});
});

View file

@ -0,0 +1,52 @@
import types from '../../../mutation-types';
import { mutations } from '../../csat';
describe('#mutations', () => {
describe('#SET_CSAT_RESPONSE_UI_FLAG', () => {
it('set uiFlags correctly', () => {
const state = { uiFlags: { isFetching: true } };
mutations[types.SET_CSAT_RESPONSE_UI_FLAG](state, { isFetching: false });
expect(state.uiFlags).toEqual({ isFetching: false });
});
});
describe('#SET_CSAT_RESPONSE', () => {
it('set records correctly', () => {
const state = { records: [] };
mutations[types.SET_CSAT_RESPONSE](state, [
{ id: 1, rating: 1, feedback_text: 'Bad' },
]);
expect(state.records).toEqual([
{ id: 1, rating: 1, feedback_text: 'Bad' },
]);
});
});
describe('#SET_CSAT_RESPONSE_METRICS', () => {
it('set metrics correctly', () => {
const state = { metrics: {} };
mutations[types.SET_CSAT_RESPONSE_METRICS](state, {
total_count: 29,
ratings_count: { 1: 10, 2: 10, 3: 3, 4: 3, 5: 3 },
total_sent_messages_count: 120,
});
expect(state.metrics).toEqual({
totalResponseCount: 29,
ratingsCount: { 1: 10, 2: 10, 3: 3, 4: 3, 5: 3 },
totalSentMessagesCount: 120,
});
});
it('set ratingsCount correctly', () => {
const state = { metrics: {} };
mutations[types.SET_CSAT_RESPONSE_METRICS](state, {
ratings_count: { 1: 5 },
});
expect(state.metrics).toEqual({
totalResponseCount: 0,
ratingsCount: { 1: 5, 2: 0, 3: 0, 4: 0, 5: 0 },
totalSentMessagesCount: 0,
});
});
});
});

View file

@ -167,4 +167,9 @@ export default {
ADD_CONTACT_NOTE: 'ADD_CONTACT_NOTE', ADD_CONTACT_NOTE: 'ADD_CONTACT_NOTE',
EDIT_CONTACT_NOTE: 'EDIT_CONTACT_NOTE', EDIT_CONTACT_NOTE: 'EDIT_CONTACT_NOTE',
DELETE_CONTACT_NOTE: 'DELETE_CONTACT_NOTE', DELETE_CONTACT_NOTE: 'DELETE_CONTACT_NOTE',
// CSAT Responses
SET_CSAT_RESPONSE_UI_FLAG: 'SET_CSAT_RESPONSE_UI_FLAG',
SET_CSAT_RESPONSE: 'SET_CSAT_RESPONSE',
SET_CSAT_RESPONSE_METRICS: 'SET_CSAT_RESPONSE_METRICS',
}; };

View file

@ -18,25 +18,30 @@ export const CSAT_RATINGS = [
key: 'disappointed', key: 'disappointed',
emoji: '😞', emoji: '😞',
value: 1, value: 1,
color: '#FDAD2A',
}, },
{ {
key: 'expressionless', key: 'expressionless',
emoji: '😑', emoji: '😑',
value: 2, value: 2,
color: '#FFC532',
}, },
{ {
key: 'neutral', key: 'neutral',
emoji: '😐', emoji: '😐',
value: 3, value: 3,
color: '#FCEC56',
}, },
{ {
key: 'grinning', key: 'grinning',
emoji: '😀', emoji: '😀',
value: 4, value: 4,
color: '#6FD86F',
}, },
{ {
key: 'smiling', key: 'smiling',
emoji: '😍', emoji: '😍',
value: 5, value: 5,
color: '#44CE4B',
}, },
]; ];

View file

@ -86,7 +86,7 @@ class Message < ApplicationRecord
after_create_commit :execute_after_create_commit_callbacks after_create_commit :execute_after_create_commit_callbacks
after_update :dispatch_update_event after_update_commit :dispatch_update_event
def channel_token def channel_token
@token ||= inbox.channel.try(:page_access_token) @token ||= inbox.channel.try(:page_access_token)

View file

@ -2,4 +2,8 @@ class CsatSurveyResponsePolicy < ApplicationPolicy
def index? def index?
@account_user.administrator? @account_user.administrator?
end end
def metrics?
@account_user.administrator?
end
end end

View file

@ -0,0 +1,3 @@
json.total_count @total_count
json.ratings_count @ratings_count
json.total_sent_messages_count @total_sent_messages_count

View file

@ -3,7 +3,15 @@ json.rating resource.rating
json.feedback_message resource.feedback_message json.feedback_message resource.feedback_message
json.account_id resource.account_id json.account_id resource.account_id
json.message_id resource.message_id json.message_id resource.message_id
json.contact resource.contact if resource.contact
json.contact do
json.partial! 'api/v1/models/contact.json.jbuilder', resource: resource.contact
end
end
json.conversation_id resource.conversation.display_id json.conversation_id resource.conversation.display_id
json.assigned_agent resource.assigned_agent if resource.assigned_agent
json.assigned_agent do
json.partial! 'api/v1/models/agent.json.jbuilder', resource: resource.assigned_agent
end
end
json.created_at resource.created_at json.created_at resource.created_at

View file

@ -87,7 +87,11 @@ Rails.application.routes.draw do
resources :labels, only: [:create, :index] resources :labels, only: [:create, :index]
end end
end end
resources :csat_survey_responses, only: [:index] resources :csat_survey_responses, only: [:index] do
collection do
get :metrics
end
end
resources :custom_filters, only: [:index, :show, :create, :update, :destroy] resources :custom_filters, only: [:index, :show, :create, :update, :destroy]
resources :inboxes, only: [:index, :create, :update, :destroy] do resources :inboxes, only: [:index, :create, :update, :destroy] do
get :assignable_agents, on: :member get :assignable_agents, on: :member

View file

@ -55,7 +55,7 @@
"vue-chartjs": "3.5.1", "vue-chartjs": "3.5.1",
"vue-clickaway": "~2.1.0", "vue-clickaway": "~2.1.0",
"vue-color": "2.8.1", "vue-color": "2.8.1",
"vue-easytable": "2.5.1", "vue-easytable": "2.5.5",
"vue-i18n": "8.24.3", "vue-i18n": "8.24.3",
"vue-loader": "15.9.6", "vue-loader": "15.9.6",
"vue-multiselect": "~2.1.6", "vue-multiselect": "~2.1.6",

View file

@ -33,7 +33,7 @@ RSpec.describe 'CSAT Survey Responses API', type: :request do
expect(JSON.parse(response.body).first['feedback_message']).to eq(csat_survey_response.feedback_message) expect(JSON.parse(response.body).first['feedback_message']).to eq(csat_survey_response.feedback_message)
end end
it 'filters csat responsed based on a date range' do it 'filters csat responses based on a date range' do
csat_10_days_ago = create(:csat_survey_response, account: account, created_at: 10.days.ago) csat_10_days_ago = create(:csat_survey_response, account: account, created_at: 10.days.ago)
csat_3_days_ago = create(:csat_survey_response, account: account, created_at: 3.days.ago) csat_3_days_ago = create(:csat_survey_response, account: account, created_at: 3.days.ago)
@ -49,4 +49,52 @@ RSpec.describe 'CSAT Survey Responses API', type: :request do
end end
end end
end end
describe 'GET /api/v1/accounts/{account.id}/csat_survey_responses/metrics' do
context 'when it is an unauthenticated user' do
it 'returns unauthorized' do
get "/api/v1/accounts/#{account.id}/csat_survey_responses/metrics"
expect(response).to have_http_status(:unauthorized)
end
end
context 'when it is an authenticated user' do
it 'returns unauthorized for agents' do
get "/api/v1/accounts/#{account.id}/csat_survey_responses/metrics",
headers: agent.create_new_auth_token,
as: :json
expect(response).to have_http_status(:unauthorized)
end
it 'returns csat metrics for administrators' do
get "/api/v1/accounts/#{account.id}/csat_survey_responses/metrics",
headers: administrator.create_new_auth_token,
as: :json
expect(response).to have_http_status(:success)
response_data = JSON.parse(response.body)
expect(response_data['total_count']).to eq 1
expect(response_data['total_sent_messages_count']).to eq 0
expect(response_data['ratings_count']).to eq({ '1' => 1 })
end
it 'filters csat metrics based on a date range' do
create(:csat_survey_response, account: account, created_at: 10.days.ago)
create(:csat_survey_response, account: account, created_at: 3.days.ago)
get "/api/v1/accounts/#{account.id}/csat_survey_responses/metrics",
params: { since: 5.days.ago.to_time.to_i.to_s, until: Time.zone.today.to_time.to_i.to_s },
headers: administrator.create_new_auth_token,
as: :json
expect(response).to have_http_status(:success)
response_data = JSON.parse(response.body)
expect(response_data['total_count']).to eq 1
expect(response_data['total_sent_messages_count']).to eq 0
expect(response_data['ratings_count']).to eq({ '1' => 1 })
end
end
end
end end

View file

@ -14966,10 +14966,10 @@ vue-docgen-loader@^1.5.0:
loader-utils "^1.2.3" loader-utils "^1.2.3"
querystring "^0.2.0" querystring "^0.2.0"
vue-easytable@2.5.1: vue-easytable@2.5.5:
version "2.5.1" version "2.5.5"
resolved "https://registry.yarnpkg.com/vue-easytable/-/vue-easytable-2.5.1.tgz#2d27a9926edbf79d766465f890f4c75a9848c630" resolved "https://registry.yarnpkg.com/vue-easytable/-/vue-easytable-2.5.5.tgz#0d0ac244beb853859c76191c117311b5cf9654b5"
integrity sha512-HyqcwgV828eQ0DmmHTFedZznjPkS6T2AQHPGsUS59KsHBHs0ZDb7nNs5o+9fOsbYbWt/BkG9B96u2p5iG6Hy5g== integrity sha512-2dp2+OWYgCn8+g6p+7tNoCuU85OGHqk1hnQ7QnS4HUyPFVAN1n4mmG+6WkIuRKrc5wsFpsg7ZiFxHQnplos3jw==
dependencies: dependencies:
lodash "^4.17.20" lodash "^4.17.20"
resize-observer-polyfill "^1.5.1" resize-observer-polyfill "^1.5.1"