diff --git a/app/models/conversation.rb b/app/models/conversation.rb index 6e3a91fb2421..7bdb30ede322 100644 --- a/app/models/conversation.rb +++ b/app/models/conversation.rb @@ -50,6 +50,8 @@ class Conversation < ApplicationRecord validates :account_id, presence: true validates :inbox_id, presence: true before_validation :validate_additional_attributes + validates :additional_attributes, jsonb_attributes_length: true + validates :custom_attributes, jsonb_attributes_length: true enum status: { open: 0, resolved: 1, pending: 2, snoozed: 3 } diff --git a/app/models/jsonb_attributes_length_validator.rb b/app/models/jsonb_attributes_length_validator.rb new file mode 100644 index 000000000000..2eda4a354f98 --- /dev/null +++ b/app/models/jsonb_attributes_length_validator.rb @@ -0,0 +1,21 @@ +class JsonbAttributesLengthValidator < ActiveModel::EachValidator + def validate_each(record, attribute, value) + return if value.empty? + + @attribute = attribute + @record = record + + value.each do |key, attribute_value| + validate_keys(key, attribute_value) + end + end + + def validate_keys(key, attribute_value) + case attribute_value.class.name + when 'String' + @record.errors.add @attribute, "#{key} length should be < 1500" if attribute_value.length > 1500 + when 'Integer' + @record.errors.add @attribute, "#{key} value should be < 9999999999" if attribute_value > 9_999_999_999 + end + end +end diff --git a/spec/models/conversation_spec.rb b/spec/models/conversation_spec.rb index d214b973b346..a1d67f7d09ec 100644 --- a/spec/models/conversation_spec.rb +++ b/spec/models/conversation_spec.rb @@ -58,6 +58,37 @@ end end + describe '.validate jsonb attributes' do + let(:account) { create(:account) } + let(:agent) { create(:user, email: 'agent1@example.com', account: account) } + let(:inbox) { create(:inbox, account: account) } + let(:conversation) do + create( + :conversation, + account: account, + contact: create(:contact, account: account), + inbox: inbox, + assignee: nil + ) + end + + it 'validate length of additional_attributes value' do + conversation.additional_attributes = { company_name: 'some_company' * 200, contact_number: 19_999_999_999 } + conversation.valid? + error_messages = conversation.errors.messages + expect(error_messages[:additional_attributes][0]).to eq('company_name length should be < 1500') + expect(error_messages[:additional_attributes][1]).to eq('contact_number value should be < 9999999999') + end + + it 'validate length of custom_attributes value' do + conversation.custom_attributes = { company_name: 'some_company' * 200, contact_number: 19_999_999_999 } + conversation.valid? + error_messages = conversation.errors.messages + expect(error_messages[:custom_attributes][0]).to eq('company_name length should be < 1500') + expect(error_messages[:custom_attributes][1]).to eq('contact_number value should be < 9999999999') + end + end + describe '.after_update' do let!(:account) { create(:account) } let!(:old_assignee) do