feat: Custom Attributes for contacts (#1158)

Co-authored-by: Pranav Raj Sreepuram <pranavrajs@gmail.com>
This commit is contained in:
Sojan Jose 2020-08-21 19:30:27 +05:30 committed by GitHub
parent 507b40a51d
commit cdd385b269
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
18 changed files with 182 additions and 21 deletions

View file

@ -33,7 +33,8 @@ class ContactIdentifyAction
end end
def update_contact def update_contact
@contact.update!(params.slice(:name, :email, :identifier)) custom_attributes = params[:custom_attributes] ? @contact.custom_attributes.merge(params[:custom_attributes]) : @contact.custom_attributes
@contact.update!(params.slice(:name, :email, :identifier).merge({ custom_attributes: custom_attributes }))
ContactAvatarJob.perform_later(@contact, params[:avatar_url]) if params[:avatar_url].present? ContactAvatarJob.perform_later(@contact, params[:avatar_url]) if params[:avatar_url].present?
end end

View file

@ -12,14 +12,14 @@ class Api::V1::Accounts::ContactsController < Api::V1::Accounts::BaseController
def create def create
ActiveRecord::Base.transaction do ActiveRecord::Base.transaction do
@contact = Current.account.contacts.new(contact_create_params) @contact = Current.account.contacts.new(contact_params)
@contact.save! @contact.save!
@contact_inbox = build_contact_inbox @contact_inbox = build_contact_inbox
end end
end end
def update def update
@contact.update!(contact_params) @contact.update!(contact_update_params)
end end
def search def search
@ -43,14 +43,21 @@ class Api::V1::Accounts::ContactsController < Api::V1::Accounts::BaseController
end end
def contact_params def contact_params
params.require(:contact).permit(:name, :email, :phone_number) params.require(:contact).permit(:name, :email, :phone_number, custom_attributes: {})
end
def contact_custom_attributes
return @contact.custom_attributes.merge(contact_params[:custom_attributes]) if contact_params[:custom_attributes]
@contact.custom_attributes
end
def contact_update_params
# we want the merged custom attributes not the original one
contact_params.except(:custom_attributes).merge({ custom_attributes: contact_custom_attributes })
end end
def fetch_contact def fetch_contact
@contact = Current.account.contacts.find(params[:id]) @contact = Current.account.contacts.find(params[:id])
end end
def contact_create_params
params.require(:contact).permit(:name, :email, :phone_number)
end
end end

View file

@ -10,6 +10,6 @@ class Api::V1::Widget::ContactsController < Api::V1::Widget::BaseController
private private
def permitted_params def permitted_params
params.permit(:website_token, :identifier, :email, :name, :avatar_url) params.permit(:website_token, :identifier, :email, :name, :avatar_url, custom_attributes: {})
end end
end end

View file

@ -9,6 +9,9 @@
"NO_RECORDS_FOUND": "There are no previous conversations associated to this contact.", "NO_RECORDS_FOUND": "There are no previous conversations associated to this contact.",
"TITLE": "Previous Conversations" "TITLE": "Previous Conversations"
}, },
"CUSTOM_ATTRIBUTES": {
"TITLE": "Custom Attributes"
},
"LABELS": { "LABELS": {
"TITLE": "Conversation Labels", "TITLE": "Conversation Labels",
"MODAL": { "MODAL": {

View file

@ -0,0 +1,59 @@
<template>
<div class="custom-attributes--panel">
<contact-details-item
:title="$t('CONTACT_PANEL.CUSTOM_ATTRIBUTES.TITLE')"
icon="ion-code"
/>
<div
v-for="attribute in listOfAttributes"
:key="attribute"
class="custom-attribute--row"
>
<div class="custom-attribute--row__attribute">
{{ attribute }}
</div>
<div>
{{ customAttributes[attribute] }}
</div>
</div>
</div>
</template>
<script>
import ContactDetailsItem from './ContactDetailsItem.vue';
export default {
components: {
ContactDetailsItem,
},
props: {
customAttributes: {
type: Object,
default: () => ({}),
},
},
computed: {
listOfAttributes() {
return Object.keys(this.customAttributes).filter(key => {
const value = this.customAttributes[key];
return value !== null && value !== undefined && value !== '';
});
},
},
};
</script>
<style scoped>
.custom-attributes--panel {
border-top: 1px solid var(--b-100);
padding: var(--space-normal);
}
.custom-attribute--row {
margin-bottom: var(--space-small);
}
.custom-attribute--row__attribute {
font-weight: 500;
}
</style>

View file

@ -36,7 +36,7 @@ export default {
@import '~dashboard/assets/scss/mixins'; @import '~dashboard/assets/scss/mixins';
.conv-details--item { .conv-details--item {
padding-bottom: $space-normal; padding-bottom: var(--space-slab);
&:last-child { &:last-child {
padding-bottom: 0; padding-bottom: 0;

View file

@ -84,6 +84,10 @@
icon="ion-clock" icon="ion-clock"
/> />
</div> </div>
<contact-custom-attributes
v-if="hasContactAttributes"
:custom-attributes="contact.custom_attributes"
/>
<conversation-labels :conversation-id="conversationId" /> <conversation-labels :conversation-id="conversationId" />
<contact-conversations <contact-conversations
v-if="contact.id" v-if="contact.id"
@ -99,9 +103,11 @@ import Thumbnail from 'dashboard/components/widgets/Thumbnail.vue';
import ContactConversations from './ContactConversations.vue'; import ContactConversations from './ContactConversations.vue';
import ContactDetailsItem from './ContactDetailsItem.vue'; import ContactDetailsItem from './ContactDetailsItem.vue';
import ConversationLabels from './labels/LabelBox.vue'; import ConversationLabels from './labels/LabelBox.vue';
import ContactCustomAttributes from './ContactCustomAttributes';
export default { export default {
components: { components: {
ContactCustomAttributes,
ContactConversations, ContactConversations,
ContactDetailsItem, ContactDetailsItem,
ConversationLabels, ConversationLabels,
@ -129,6 +135,10 @@ export default {
additionalAttributes() { additionalAttributes() {
return this.currentConversationMetaData.additional_attributes || {}; return this.currentConversationMetaData.additional_attributes || {};
}, },
hasContactAttributes() {
const { custom_attributes: customAttributes } = this.contact;
return customAttributes && Object.keys(customAttributes).length;
},
browser() { browser() {
return this.additionalAttributes.browser || {}; return this.additionalAttributes.browser || {};
}, },

View file

@ -32,6 +32,24 @@ const runSDK = ({ baseUrl, websiteToken }) => {
} }
}, },
setCustomAttributes(customAttributes = {}) {
if (!customAttributes || !Object.keys(customAttributes).length) {
throw new Error('Custom attributes should have atleast one key');
} else {
IFrameHelper.sendMessage('set-custom-attributes', { customAttributes });
}
},
deleteCustomAttribute(customAttribute = '') {
if (!customAttribute) {
throw new Error('Custom attribute is required');
} else {
IFrameHelper.sendMessage('delete-custom-attribute', {
customAttribute,
});
}
},
setLabel(label = '') { setLabel(label = '') {
IFrameHelper.sendMessage('set-label', { label }); IFrameHelper.sendMessage('set-label', { label });
}, },

View file

@ -15,8 +15,6 @@
</template> </template>
<script> <script>
/* global bus */
import Vue from 'vue'; import Vue from 'vue';
import { mapGetters, mapActions } from 'vuex'; import { mapGetters, mapActions } from 'vuex';
import { setHeader } from 'widget/helpers/axios'; import { setHeader } from 'widget/helpers/axios';
@ -99,6 +97,15 @@ export default {
this.$store.dispatch('conversationLabels/destroy', message.label); this.$store.dispatch('conversationLabels/destroy', message.label);
} else if (message.event === 'set-user') { } else if (message.event === 'set-user') {
this.$store.dispatch('contacts/update', message); this.$store.dispatch('contacts/update', message);
} else if (message.event === 'set-custom-attributes') {
this.$store.dispatch(
'contacts/setCustomAttributes',
message.customAttributes
);
} else if (message.event === 'delete-custom-attribute') {
this.$store.dispatch('contacts/setCustomAttributes', {
[message.customAttribute]: null,
});
} else if (message.event === 'set-locale') { } else if (message.event === 'set-locale') {
this.setLocale(message.locale); this.setLocale(message.locale);
this.setBubbleLabel(); this.setBubbleLabel();

View file

@ -9,4 +9,9 @@ export default {
...userObject, ...userObject,
}); });
}, },
setCustomAttibutes(customAttributes = {}) {
return API.patch(buildUrl('widget/contact'), {
custom_attributes: customAttributes,
});
},
}; };

View file

@ -17,6 +17,13 @@ export const actions = {
// Ingore error // Ingore error
} }
}, },
setCustomAttributes: async (_, customAttributes = {}) => {
try {
await ContactsAPI.setCustomAttibutes(customAttributes);
} catch (error) {
// Ingore error
}
},
}; };
export default { export default {

View file

@ -4,6 +4,7 @@
# #
# id :integer not null, primary key # id :integer not null, primary key
# additional_attributes :jsonb # additional_attributes :jsonb
# custom_attributes :jsonb
# email :string # email :string
# identifier :string # identifier :string
# name :string # name :string
@ -68,12 +69,12 @@ class Contact < ApplicationRecord
} }
end end
private
def downcase_email def downcase_email
email.downcase! if email.present? email.downcase! if email.present?
end end
private
def dispatch_create_event def dispatch_create_event
Rails.configuration.dispatcher.dispatch(CONTACT_CREATED, Time.zone.now, contact: self) Rails.configuration.dispatcher.dispatch(CONTACT_CREATED, Time.zone.now, contact: self)
end end

View file

@ -5,6 +5,7 @@ json.id resource.id
json.name resource.name json.name resource.name
json.phone_number resource.phone_number json.phone_number resource.phone_number
json.thumbnail resource.avatar_url json.thumbnail resource.avatar_url
json.custom_attributes resource.custom_attributes
# we only want to output contact inbox when its /contacts endpoints # we only want to output contact inbox when its /contacts endpoints
if defined?(with_contact_inboxes) && with_contact_inboxes.present? if defined?(with_contact_inboxes) && with_contact_inboxes.present?

View file

@ -0,0 +1,5 @@
class AddCustomAttributesToContacts < ActiveRecord::Migration[6.0]
def change
add_column :contacts, :custom_attributes, :jsonb, default: {}
end
end

View file

@ -10,7 +10,7 @@
# #
# It's strongly recommended that you check this file into your version control system. # It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2020_08_02_170002) do ActiveRecord::Schema.define(version: 2020_08_19_190629) do
# These are extensions that must be enabled in order to support this database # These are extensions that must be enabled in order to support this database
enable_extension "pg_stat_statements" enable_extension "pg_stat_statements"
@ -204,6 +204,7 @@ ActiveRecord::Schema.define(version: 2020_08_02_170002) do
t.string "pubsub_token" t.string "pubsub_token"
t.jsonb "additional_attributes" t.jsonb "additional_attributes"
t.string "identifier" t.string "identifier"
t.jsonb "custom_attributes", default: {}
t.index ["account_id"], name: "index_contacts_on_account_id" t.index ["account_id"], name: "index_contacts_on_account_id"
t.index ["email", "account_id"], name: "uniq_email_per_account_contact", unique: true t.index ["email", "account_id"], name: "uniq_email_per_account_contact", unique: true
t.index ["identifier", "account_id"], name: "uniq_identifier_per_account_contact", unique: true t.index ["identifier", "account_id"], name: "uniq_identifier_per_account_contact", unique: true

View file

@ -66,6 +66,31 @@ window.$chatwoot.setUser('identifier_key', {
Make sure that you reset the session when the user logs out of your app. Make sure that you reset the session when the user logs out of your app.
### Set custom attributes
Inorder to set additional information about the customer you can use customer attributes field.
To set a custom attributes call `setCustomAttributes` as follows
```js
window.$chatwoot.setCustomAttributes({
accountId: 1,
pricingPlan: 'paid',
// You can pass any key value pair here.
// Value should either be a string or a number.
// You need to flatten nested JSON structure while using this function
});
```
You can view these information in the sidepanel of a conversation.
To delete a custom attribute, use `deleteCustomAttribute` as follows
```js
window.$chatwoot.deleteCustomAttribute('attribute-name');
```
### To set language manually ### To set language manually
```js ```js

View file

@ -4,14 +4,17 @@ describe ::ContactIdentifyAction do
subject(:contact_identify) { described_class.new(contact: contact, params: params).perform } subject(:contact_identify) { described_class.new(contact: contact, params: params).perform }
let!(:account) { create(:account) } let!(:account) { create(:account) }
let!(:contact) { create(:contact, account: account) } let(:custom_attributes) { { test: 'test', test1: 'test1' } }
let(:params) { { name: 'test', identifier: 'test_id' } } let!(:contact) { create(:contact, account: account, custom_attributes: custom_attributes) }
let(:params) { { name: 'test', identifier: 'test_id', custom_attributes: { test: 'new test', test2: 'test2' } } }
describe '#perform' do describe '#perform' do
it 'updates the contact' do it 'updates the contact' do
expect(ContactAvatarJob).not_to receive(:perform_later).with(contact, params[:avatar_url]) expect(ContactAvatarJob).not_to receive(:perform_later).with(contact, params[:avatar_url])
contact_identify contact_identify
expect(contact.reload.name).to eq 'test' expect(contact.reload.name).to eq 'test'
# custom attributes are merged properly without overwritting existing ones
expect(contact.custom_attributes).to eq({ 'test' => 'new test', 'test1' => 'test1', 'test2' => 'test2' })
expect(contact.reload.identifier).to eq 'test_id' expect(contact.reload.identifier).to eq 'test_id'
end end

View file

@ -83,7 +83,8 @@ RSpec.describe 'Contacts API', type: :request do
end end
describe 'POST /api/v1/accounts/{account.id}/contacts' do describe 'POST /api/v1/accounts/{account.id}/contacts' do
let(:valid_params) { { contact: { name: 'test' } } } let(:custom_attributes) { { test: 'test', test1: 'test1' } }
let(:valid_params) { { contact: { name: 'test', custom_attributes: custom_attributes } } }
context 'when it is an unauthenticated user' do context 'when it is an unauthenticated user' do
it 'returns unauthorized' do it 'returns unauthorized' do
@ -104,6 +105,10 @@ RSpec.describe 'Contacts API', type: :request do
end.to change(Contact, :count).by(1) end.to change(Contact, :count).by(1)
expect(response).to have_http_status(:success) expect(response).to have_http_status(:success)
# custom attributes are updated
json_response = JSON.parse(response.body)
expect(json_response['payload']['contact']['custom_attributes']).to eq({ 'test' => 'test', 'test1' => 'test1' })
end end
it 'creates the contact identifier when inbox id is passed' do it 'creates the contact identifier when inbox id is passed' do
@ -118,8 +123,9 @@ RSpec.describe 'Contacts API', type: :request do
end end
describe 'PATCH /api/v1/accounts/{account.id}/contacts/:id' do describe 'PATCH /api/v1/accounts/{account.id}/contacts/:id' do
let!(:contact) { create(:contact, account: account) } let(:custom_attributes) { { test: 'test', test1: 'test1' } }
let(:valid_params) { { contact: { name: 'Test Blub' } } } let!(:contact) { create(:contact, account: account, custom_attributes: custom_attributes) }
let(:valid_params) { { name: 'Test Blub', custom_attributes: { test: 'new test', test2: 'test2' } } }
context 'when it is an unauthenticated user' do context 'when it is an unauthenticated user' do
it 'returns unauthorized' do it 'returns unauthorized' do
@ -140,7 +146,9 @@ RSpec.describe 'Contacts API', type: :request do
as: :json as: :json
expect(response).to have_http_status(:success) expect(response).to have_http_status(:success)
expect(Contact.last.name).to eq('Test Blub') expect(contact.reload.name).to eq('Test Blub')
# custom attributes are merged properly without overwritting existing ones
expect(contact.custom_attributes).to eq({ 'test' => 'new test', 'test1' => 'test1', 'test2' => 'test2' })
end end
it 'prevents the update of contact of another account' do it 'prevents the update of contact of another account' do