Merge remote-tracking branch 'origin/assignment_v2/assignment_service' into assignment_v2/assignment_service
This commit is contained in:
@@ -0,0 +1,169 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe Email::FromBuilder do
|
||||
let(:account) { create(:account, support_email: 'support@example.com') }
|
||||
let(:agent) { create(:user, account: account) }
|
||||
let(:conversation) { create(:conversation, account: account) }
|
||||
let(:current_message) { create(:message, conversation: conversation, sender: agent, message_type: :outgoing) }
|
||||
|
||||
describe '#build' do
|
||||
context 'when inbox is not an email channel' do
|
||||
let(:channel) { create(:channel_api, account: account) }
|
||||
let(:inbox) { create(:inbox, channel: channel, account: account) }
|
||||
|
||||
it 'returns account support email with sender name formatting' do
|
||||
builder = described_class.new(inbox: inbox, message: current_message)
|
||||
result = builder.build
|
||||
|
||||
expect(result).to include('support@example.com')
|
||||
end
|
||||
|
||||
context 'with friendly inbox' do
|
||||
let(:inbox) { create(:inbox, channel: channel, account: account, sender_name_type: :friendly) }
|
||||
|
||||
it 'returns friendly formatted sender name with support email' do
|
||||
builder = described_class.new(inbox: inbox, message: current_message)
|
||||
result = builder.build
|
||||
|
||||
expect(result).to include(agent.available_name)
|
||||
expect(result).to include('support@example.com')
|
||||
end
|
||||
end
|
||||
|
||||
context 'with professional inbox' do
|
||||
let(:inbox) { create(:inbox, channel: channel, account: account, sender_name_type: :professional) }
|
||||
|
||||
it 'returns professional formatted sender name with support email' do
|
||||
builder = described_class.new(inbox: inbox, message: current_message)
|
||||
result = builder.build
|
||||
|
||||
expect(result).to include('support@example.com')
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
context 'when inbox is an email channel' do
|
||||
let(:channel) { create(:channel_email, email: 'care@example.com', account: account) }
|
||||
let(:inbox) { create(:inbox, channel: channel, account: account) }
|
||||
|
||||
context 'with standard IMAP/SMTP configuration' do
|
||||
before do
|
||||
channel.update!(
|
||||
imap_enabled: true,
|
||||
smtp_enabled: true,
|
||||
imap_address: 'imap.example.com',
|
||||
smtp_address: 'smtp.example.com'
|
||||
)
|
||||
end
|
||||
|
||||
it 'returns channel email with sender name formatting' do
|
||||
builder = described_class.new(inbox: inbox, message: current_message)
|
||||
result = builder.build
|
||||
|
||||
expect(result).to include('care@example.com')
|
||||
end
|
||||
end
|
||||
|
||||
context 'with Google OAuth configuration' do
|
||||
before do
|
||||
channel.update!(
|
||||
provider: 'google',
|
||||
imap_enabled: true,
|
||||
provider_config: { access_token: 'token', refresh_token: 'refresh' }
|
||||
)
|
||||
end
|
||||
|
||||
it 'returns channel email with sender name formatting' do
|
||||
builder = described_class.new(inbox: inbox, message: current_message)
|
||||
result = builder.build
|
||||
|
||||
expect(result).to include('care@example.com')
|
||||
end
|
||||
end
|
||||
|
||||
context 'with Microsoft OAuth configuration' do
|
||||
before do
|
||||
channel.update!(
|
||||
provider: 'microsoft',
|
||||
imap_enabled: true,
|
||||
provider_config: { access_token: 'token', refresh_token: 'refresh' }
|
||||
)
|
||||
end
|
||||
|
||||
it 'returns channel email with sender name formatting' do
|
||||
builder = described_class.new(inbox: inbox, message: current_message)
|
||||
result = builder.build
|
||||
|
||||
expect(result).to include('care@example.com')
|
||||
end
|
||||
end
|
||||
|
||||
context 'with forwarding and own SMTP configuration' do
|
||||
before do
|
||||
channel.update!(
|
||||
imap_enabled: false,
|
||||
smtp_enabled: true,
|
||||
smtp_address: 'smtp.example.com'
|
||||
)
|
||||
end
|
||||
|
||||
it 'returns channel email with sender name formatting' do
|
||||
builder = described_class.new(inbox: inbox, message: current_message)
|
||||
result = builder.build
|
||||
|
||||
expect(result).to include('care@example.com')
|
||||
end
|
||||
end
|
||||
|
||||
context 'with IMAP enabled and Chatwoot SMTP and channel is verified_for_sending' do
|
||||
before do
|
||||
channel.update!(verified_for_sending: true, imap_enabled: true, smtp_enabled: false)
|
||||
end
|
||||
|
||||
it 'returns channel email with sender name formatting' do
|
||||
builder = described_class.new(inbox: inbox, message: current_message)
|
||||
result = builder.build
|
||||
|
||||
expect(result).to include('care@example.com')
|
||||
end
|
||||
end
|
||||
|
||||
context 'with IMAP enabled and Chatwoot SMTP and channel is not verified_for_sending' do
|
||||
before do
|
||||
channel.update!(verified_for_sending: false, imap_enabled: true, smtp_enabled: false)
|
||||
end
|
||||
|
||||
it 'returns account support email with sender name formatting' do
|
||||
builder = described_class.new(inbox: inbox, message: current_message)
|
||||
result = builder.build
|
||||
|
||||
expect(result).to include('support@example.com')
|
||||
end
|
||||
end
|
||||
|
||||
context 'with forwarding and Chatwoot SMTP and channel is verified_for_sending' do
|
||||
before do
|
||||
channel.update!(verified_for_sending: true, imap_enabled: false, smtp_enabled: false)
|
||||
end
|
||||
|
||||
it 'returns channel email with sender name formatting' do
|
||||
builder = described_class.new(inbox: inbox, message: current_message)
|
||||
result = builder.build
|
||||
|
||||
expect(result).to include('care@example.com')
|
||||
end
|
||||
end
|
||||
|
||||
context 'with forwarding and Chatwoot SMTP and channel is not verified_for_sending' do
|
||||
before { channel.update!(verified_for_sending: false, imap_enabled: false, smtp_enabled: false) }
|
||||
|
||||
it 'returns account support email with sender name formatting' do
|
||||
builder = described_class.new(inbox: inbox, message: current_message)
|
||||
result = builder.build
|
||||
|
||||
expect(result).to include('support@example.com')
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,108 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe Email::ReplyToBuilder do
|
||||
let(:account) { create(:account, domain: 'mail.example.com', support_email: 'support@example.com') }
|
||||
let(:agent) { create(:user, account: account) }
|
||||
let(:conversation) { create(:conversation, account: account) }
|
||||
let(:current_message) { create(:message, conversation: conversation, sender: agent, message_type: :outgoing) }
|
||||
let(:inbox) { create(:inbox, account: account) }
|
||||
|
||||
describe '#build' do
|
||||
context 'when inbox is an email channel' do
|
||||
let(:channel) { create(:channel_email, email: 'care@example.com', account: account) }
|
||||
let(:inbox) { create(:inbox, channel: channel, account: account) }
|
||||
|
||||
it 'returns the channel email with sender name formatting' do
|
||||
builder = described_class.new(inbox: inbox, message: current_message)
|
||||
result = builder.build
|
||||
|
||||
expect(result).to include('care@example.com')
|
||||
end
|
||||
|
||||
context 'with friendly inbox' do
|
||||
let(:inbox) do
|
||||
create(:inbox, channel: channel, account: account, greeting_enabled: true, greeting_message: 'Hello', sender_name_type: :friendly)
|
||||
end
|
||||
|
||||
it 'returns friendly formatted sender name' do
|
||||
builder = described_class.new(inbox: inbox, message: current_message)
|
||||
result = builder.build
|
||||
|
||||
expect(result).to include(agent.available_name)
|
||||
expect(result).to include('care@example.com')
|
||||
end
|
||||
end
|
||||
|
||||
context 'with professional inbox' do
|
||||
let(:inbox) { create(:inbox, channel: channel, account: account, sender_name_type: :professional) }
|
||||
|
||||
it 'returns professional formatted sender name' do
|
||||
builder = described_class.new(inbox: inbox, message: current_message)
|
||||
result = builder.build
|
||||
|
||||
expect(result).to include('care@example.com')
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
context 'when inbox is not an email channel' do
|
||||
let(:channel) { create(:channel_api, account: account) }
|
||||
let(:inbox) { create(:inbox, channel: channel, account: account) }
|
||||
|
||||
context 'with inbound email enabled' do
|
||||
before do
|
||||
account.enable_features('inbound_emails')
|
||||
account.update!(domain: 'mail.example.com', support_email: 'support@example.com')
|
||||
end
|
||||
|
||||
it 'returns reply email with conversation uuid' do
|
||||
builder = described_class.new(inbox: inbox, message: current_message)
|
||||
result = builder.build
|
||||
|
||||
expect(result).to include("reply+#{conversation.uuid}@mail.example.com")
|
||||
end
|
||||
end
|
||||
|
||||
context 'when support_email has display name format and inbound emails are disabled' do
|
||||
before do
|
||||
account.disable_features('inbound_emails')
|
||||
account.update!(support_email: 'Support <support@example.com>')
|
||||
end
|
||||
|
||||
it 'returns account support email with display name' do
|
||||
builder = described_class.new(inbox: inbox, message: current_message)
|
||||
result = builder.build
|
||||
|
||||
expect(result).to include("#{inbox.name} <support@example.com>")
|
||||
end
|
||||
end
|
||||
|
||||
context 'when feature is disabled' do
|
||||
before do
|
||||
account.disable_features('inbound_emails')
|
||||
end
|
||||
|
||||
it 'returns account support email' do
|
||||
builder = described_class.new(inbox: inbox, message: current_message)
|
||||
result = builder.build
|
||||
|
||||
expect(result).to include('support@example.com')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when inbound email domain is missing' do
|
||||
before do
|
||||
account.enable_features('inbound_emails')
|
||||
account.update!(domain: nil)
|
||||
end
|
||||
|
||||
it 'returns account support email' do
|
||||
builder = described_class.new(inbox: inbox, message: current_message)
|
||||
result = builder.build
|
||||
|
||||
expect(result).to include('support@example.com')
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -179,6 +179,50 @@ describe Messages::MessageBuilder do
|
||||
expect(message.content_attributes[:cc_emails]).to eq ['test1@test.com', 'test2@test.com', 'test3@test.com']
|
||||
expect(message.content_attributes[:bcc_emails]).to eq ['test1@test.com', 'test2@test.com', 'test3@test.com']
|
||||
end
|
||||
|
||||
context 'when custom email content is provided' do
|
||||
before do
|
||||
account.enable_features('quoted_email_reply')
|
||||
end
|
||||
|
||||
it 'creates message with custom HTML email content' do
|
||||
params = ActionController::Parameters.new({
|
||||
content: 'Regular message content',
|
||||
email_html_content: '<p>Custom <strong>HTML</strong> content</p>'
|
||||
})
|
||||
|
||||
message = described_class.new(user, conversation, params).perform
|
||||
|
||||
expect(message.content_attributes.dig('email', 'html_content', 'full')).to eq '<p>Custom <strong>HTML</strong> content</p>'
|
||||
expect(message.content_attributes.dig('email', 'html_content', 'reply')).to eq '<p>Custom <strong>HTML</strong> content</p>'
|
||||
expect(message.content_attributes.dig('email', 'text_content', 'full')).to eq 'Regular message content'
|
||||
expect(message.content_attributes.dig('email', 'text_content', 'reply')).to eq 'Regular message content'
|
||||
end
|
||||
|
||||
it 'does not process custom email content for private messages' do
|
||||
params = ActionController::Parameters.new({
|
||||
content: 'Regular message content',
|
||||
email_html_content: '<p>Custom HTML content</p>',
|
||||
private: true
|
||||
})
|
||||
|
||||
message = described_class.new(user, conversation, params).perform
|
||||
|
||||
expect(message.content_attributes.dig('email', 'html_content')).to be_nil
|
||||
expect(message.content_attributes.dig('email', 'text_content')).to be_nil
|
||||
end
|
||||
|
||||
it 'falls back to default behavior when no custom email content is provided' do
|
||||
params = ActionController::Parameters.new({
|
||||
content: 'Regular **markdown** content'
|
||||
})
|
||||
|
||||
message = described_class.new(user, conversation, params).perform
|
||||
|
||||
expect(message.content_attributes.dig('email', 'html_content', 'full')).to include('<strong>markdown</strong>')
|
||||
expect(message.content_attributes.dig('email', 'text_content', 'full')).to eq 'Regular **markdown** content'
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -120,8 +120,38 @@ describe V2::ReportBuilder do
|
||||
builder = described_class.new(account, params)
|
||||
metrics = builder.timeseries
|
||||
|
||||
# 4 conversations are resolved
|
||||
expect(metrics[Time.zone.today]).to be 4
|
||||
# 5 resolution events occurred (even though 1 was later reopened)
|
||||
expect(metrics[Time.zone.today]).to be 5
|
||||
expect(metrics[Time.zone.today - 2.days]).to be 0
|
||||
end
|
||||
end
|
||||
|
||||
it 'return resolutions count with multiple resolutions of same conversation' do
|
||||
travel_to(Time.zone.today) do
|
||||
params = {
|
||||
metric: 'resolutions_count',
|
||||
type: :account,
|
||||
since: (Time.zone.today - 3.days).to_time.to_i.to_s,
|
||||
until: Time.zone.today.end_of_day.to_time.to_i.to_s
|
||||
}
|
||||
|
||||
conversations = account.conversations.where('created_at < ?', 1.day.ago)
|
||||
perform_enqueued_jobs do
|
||||
# Resolve all 5 conversations (first round)
|
||||
conversations.each(&:resolved!)
|
||||
|
||||
# Reopen 2 conversations and resolve them again
|
||||
conversations.first(2).each do |conversation|
|
||||
conversation.open!
|
||||
conversation.resolved!
|
||||
end
|
||||
end
|
||||
|
||||
builder = described_class.new(account, params)
|
||||
metrics = builder.timeseries
|
||||
|
||||
# 7 total resolution events: 5 initial + 2 re-resolutions
|
||||
expect(metrics[Time.zone.today]).to be 7
|
||||
expect(metrics[Time.zone.today - 2.days]).to be 0
|
||||
end
|
||||
end
|
||||
@@ -153,10 +183,10 @@ describe V2::ReportBuilder do
|
||||
metrics = builder.timeseries
|
||||
summary = builder.bot_summary
|
||||
|
||||
# 4 conversations are resolved
|
||||
expect(metrics[Time.zone.today]).to be 4
|
||||
# 5 bot resolution events occurred (even though 1 was later reopened)
|
||||
expect(metrics[Time.zone.today]).to be 5
|
||||
expect(metrics[Time.zone.today - 2.days]).to be 0
|
||||
expect(summary[:bot_resolutions_count]).to be 4
|
||||
expect(summary[:bot_resolutions_count]).to be 5
|
||||
end
|
||||
end
|
||||
|
||||
@@ -339,8 +369,40 @@ describe V2::ReportBuilder do
|
||||
builder = described_class.new(account, params)
|
||||
metrics = builder.timeseries
|
||||
|
||||
# this should count only 4 since the last conversation was reopened
|
||||
expect(metrics[Time.zone.today]).to be 4
|
||||
# this should count all 5 resolution events (even though 1 was later reopened)
|
||||
expect(metrics[Time.zone.today]).to be 5
|
||||
expect(metrics[Time.zone.today - 2.days]).to be 0
|
||||
end
|
||||
end
|
||||
|
||||
it 'return resolutions count with multiple resolutions of same conversation' do
|
||||
travel_to(Time.zone.today) do
|
||||
params = {
|
||||
metric: 'resolutions_count',
|
||||
type: :label,
|
||||
id: label_2.id,
|
||||
since: (Time.zone.today - 3.days).to_time.to_i.to_s,
|
||||
until: (Time.zone.today + 1.day).to_time.to_i.to_s
|
||||
}
|
||||
|
||||
conversations = account.conversations.where('created_at < ?', 1.day.ago)
|
||||
|
||||
perform_enqueued_jobs do
|
||||
# Resolve all 5 conversations (first round)
|
||||
conversations.each(&:resolved!)
|
||||
|
||||
# Reopen 3 conversations and resolve them again
|
||||
conversations.first(3).each do |conversation|
|
||||
conversation.open!
|
||||
conversation.resolved!
|
||||
end
|
||||
end
|
||||
|
||||
builder = described_class.new(account, params)
|
||||
metrics = builder.timeseries
|
||||
|
||||
# 8 total resolution events: 5 initial + 3 re-resolutions
|
||||
expect(metrics[Time.zone.today]).to be 8
|
||||
expect(metrics[Time.zone.today - 2.days]).to be 0
|
||||
end
|
||||
end
|
||||
|
||||
@@ -313,5 +313,61 @@ RSpec.describe V2::Reports::LabelSummaryBuilder do
|
||||
expect(label_1_report[:avg_first_response_time]).to eq(1800.0)
|
||||
end
|
||||
end
|
||||
|
||||
context 'with resolution count with multiple resolutions of same conversation' do
|
||||
let(:business_hours) { false }
|
||||
let(:account2) { create(:account) }
|
||||
let(:unique_label_name) { SecureRandom.uuid }
|
||||
let(:test_label) { create(:label, title: unique_label_name, account: account2) }
|
||||
let(:test_date) { Date.new(2025, 6, 15) }
|
||||
let(:account2_builder) do
|
||||
described_class.new(account: account2, params: {
|
||||
business_hours: false,
|
||||
since: test_date.to_time.to_i.to_s,
|
||||
until: test_date.end_of_day.to_time.to_i.to_s,
|
||||
timezone_offset: 0
|
||||
})
|
||||
end
|
||||
|
||||
before do
|
||||
# Ensure test_label is created
|
||||
test_label
|
||||
|
||||
travel_to(test_date) do
|
||||
user = create(:user, account: account2)
|
||||
inbox = create(:inbox, account: account2)
|
||||
create(:inbox_member, user: user, inbox: inbox)
|
||||
|
||||
gravatar_url = 'https://www.gravatar.com'
|
||||
stub_request(:get, /#{gravatar_url}.*/).to_return(status: 404)
|
||||
|
||||
perform_enqueued_jobs do
|
||||
conversation = create(:conversation, account: account2,
|
||||
inbox: inbox, assignee: user,
|
||||
created_at: test_date)
|
||||
conversation.update_labels(unique_label_name)
|
||||
conversation.label_list
|
||||
conversation.save!
|
||||
|
||||
# First resolution
|
||||
conversation.resolved!
|
||||
|
||||
# Reopen conversation
|
||||
conversation.open!
|
||||
|
||||
# Second resolution
|
||||
conversation.resolved!
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
it 'counts multiple resolution events for same conversation' do
|
||||
report = account2_builder.build
|
||||
|
||||
test_label_report = report.find { |r| r[:name] == unique_label_name }
|
||||
expect(test_label_report).not_to be_nil
|
||||
expect(test_label_report[:resolved_conversations_count]).to eq(2)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
require 'rails_helper'
|
||||
|
||||
describe V2::Reports::Timeseries::CountReportBuilder do
|
||||
subject { described_class.new(account, params) }
|
||||
|
||||
let(:account) { create(:account) }
|
||||
let(:account2) { create(:account) }
|
||||
let(:user) { create(:user, email: 'agent1@example.com') }
|
||||
let(:inbox) { create(:inbox, account: account) }
|
||||
let(:inbox2) { create(:inbox, account: account2) }
|
||||
let(:current_time) { Time.current }
|
||||
|
||||
let(:params) do
|
||||
{
|
||||
type: 'agent',
|
||||
metric: 'resolutions_count',
|
||||
since: (current_time - 1.day).beginning_of_day.to_i.to_s,
|
||||
until: current_time.end_of_day.to_i.to_s,
|
||||
id: user.id.to_s
|
||||
}
|
||||
end
|
||||
|
||||
before do
|
||||
travel_to current_time
|
||||
|
||||
# Add the same user to both accounts
|
||||
create(:account_user, account: account, user: user)
|
||||
create(:account_user, account: account2, user: user)
|
||||
|
||||
# Create conversations in account1
|
||||
conversation1 = create(:conversation, account: account, inbox: inbox, assignee: user)
|
||||
conversation2 = create(:conversation, account: account, inbox: inbox, assignee: user)
|
||||
|
||||
# Create conversations in account2
|
||||
conversation3 = create(:conversation, account: account2, inbox: inbox2, assignee: user)
|
||||
conversation4 = create(:conversation, account: account2, inbox: inbox2, assignee: user)
|
||||
|
||||
# User resolves 2 conversations in account1
|
||||
create(:reporting_event,
|
||||
name: 'conversation_resolved',
|
||||
account: account,
|
||||
user: user,
|
||||
conversation: conversation1,
|
||||
created_at: current_time - 12.hours)
|
||||
|
||||
create(:reporting_event,
|
||||
name: 'conversation_resolved',
|
||||
account: account,
|
||||
user: user,
|
||||
conversation: conversation2,
|
||||
created_at: current_time - 6.hours)
|
||||
|
||||
# Same user resolves 3 conversations in account2 - these should NOT be counted for account1
|
||||
create(:reporting_event,
|
||||
name: 'conversation_resolved',
|
||||
account: account2,
|
||||
user: user,
|
||||
conversation: conversation3,
|
||||
created_at: current_time - 8.hours)
|
||||
|
||||
create(:reporting_event,
|
||||
name: 'conversation_resolved',
|
||||
account: account2,
|
||||
user: user,
|
||||
conversation: conversation4,
|
||||
created_at: current_time - 4.hours)
|
||||
|
||||
# Create another conversation in account2 for testing
|
||||
conversation5 = create(:conversation, account: account2, inbox: inbox2, assignee: user)
|
||||
create(:reporting_event,
|
||||
name: 'conversation_resolved',
|
||||
account: account2,
|
||||
user: user,
|
||||
conversation: conversation5,
|
||||
created_at: current_time - 2.hours)
|
||||
end
|
||||
|
||||
describe '#aggregate_value' do
|
||||
it 'returns only resolutions performed by the user in the specified account' do
|
||||
# User should have 2 resolutions in account1, not 5 (total across both accounts)
|
||||
expect(subject.aggregate_value).to eq(2)
|
||||
end
|
||||
|
||||
context 'when querying account2' do
|
||||
subject { described_class.new(account2, params) }
|
||||
|
||||
it 'returns only resolutions for account2' do
|
||||
# User should have 3 resolutions in account2
|
||||
expect(subject.aggregate_value).to eq(3)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe '#timeseries' do
|
||||
it 'filters resolutions by account' do
|
||||
result = subject.timeseries
|
||||
# Should only count the 2 resolutions from account1
|
||||
total_count = result.sum { |r| r[:value] }
|
||||
expect(total_count).to eq(2)
|
||||
end
|
||||
end
|
||||
|
||||
describe 'account isolation' do
|
||||
it 'does not leak data between accounts' do
|
||||
# If account isolation works correctly, the counts should be different
|
||||
account1_count = described_class.new(account, params).aggregate_value
|
||||
account2_count = described_class.new(account2, params).aggregate_value
|
||||
|
||||
expect(account1_count).to eq(2)
|
||||
expect(account2_count).to eq(3)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -5,6 +5,29 @@ RSpec.describe 'API Base', type: :request do
|
||||
let!(:user) { create(:user, account: account) }
|
||||
|
||||
describe 'request with api_access_token for user' do
|
||||
context 'when accessing an account scoped resource' do
|
||||
let!(:admin) { create(:user, :administrator, account: account) }
|
||||
let!(:conversation) { create(:conversation, account: account) }
|
||||
|
||||
it 'sets Current attributes for the request and then returns the response' do
|
||||
# expect Current.account_user is set to the admin's account_user
|
||||
allow(Current).to receive(:user=).and_call_original
|
||||
allow(Current).to receive(:account=).and_call_original
|
||||
allow(Current).to receive(:account_user=).and_call_original
|
||||
|
||||
get "/api/v1/accounts/#{account.id}/conversations/#{conversation.display_id}",
|
||||
headers: { api_access_token: admin.access_token.token },
|
||||
as: :json
|
||||
|
||||
expect(Current).to have_received(:user=).with(admin).at_least(:once)
|
||||
expect(Current).to have_received(:account=).with(account).at_least(:once)
|
||||
expect(Current).to have_received(:account_user=).with(admin.account_users.first).at_least(:once)
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
expect(response.parsed_body['id']).to eq(conversation.display_id)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when it is an invalid api_access_token' do
|
||||
it 'returns unauthorized' do
|
||||
get '/api/v1/profile',
|
||||
|
||||
@@ -225,4 +225,49 @@ RSpec.describe 'Api::V1::Accounts::BulkActionsController', type: :request do
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'POST /api/v1/accounts/{account.id}/bulk_actions (contacts)' do
|
||||
context 'when it is an authenticated user' do
|
||||
let!(:agent) { create(:user, account: account, role: :agent) }
|
||||
|
||||
it 'enqueues Contacts::BulkActionJob with permitted params' do
|
||||
contact_one = create(:contact, account: account)
|
||||
contact_two = create(:contact, account: account)
|
||||
|
||||
expect do
|
||||
post "/api/v1/accounts/#{account.id}/bulk_actions",
|
||||
headers: agent.create_new_auth_token,
|
||||
params: {
|
||||
type: 'Contact',
|
||||
ids: [contact_one.id, contact_two.id],
|
||||
labels: { add: %w[vip support] },
|
||||
extra: 'ignored'
|
||||
}
|
||||
end.to have_enqueued_job(Contacts::BulkActionJob).with(
|
||||
account.id,
|
||||
agent.id,
|
||||
hash_including(
|
||||
'ids' => [contact_one.id.to_s, contact_two.id.to_s],
|
||||
'labels' => hash_including('add' => %w[vip support])
|
||||
)
|
||||
)
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
end
|
||||
|
||||
it 'returns unauthorized for delete action when user is not admin' do
|
||||
contact = create(:contact, account: account)
|
||||
|
||||
post "/api/v1/accounts/#{account.id}/bulk_actions",
|
||||
headers: agent.create_new_auth_token,
|
||||
params: {
|
||||
type: 'Contact',
|
||||
ids: [contact.id],
|
||||
action_name: 'delete'
|
||||
}
|
||||
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -93,9 +93,9 @@ RSpec.describe 'Custom Filters API', type: :request do
|
||||
expect(json_response['name']).to eq 'vip-customers'
|
||||
end
|
||||
|
||||
it 'gives the error for 51st record' do
|
||||
it 'gives the error for 1001st record' do
|
||||
CustomFilter.delete_all
|
||||
CustomFilter::MAX_FILTER_PER_USER.times do
|
||||
Limits::MAX_CUSTOM_FILTERS_PER_USER.times do
|
||||
create(:custom_filter, user: user, account: account)
|
||||
end
|
||||
|
||||
@@ -107,7 +107,7 @@ RSpec.describe 'Custom Filters API', type: :request do
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
json_response = response.parsed_body
|
||||
expect(json_response['message']).to include(
|
||||
'Account Limit reached. The maximum number of allowed custom filters for a user per account is 50.'
|
||||
'Account Limit reached. The maximum number of allowed custom filters for a user per account is 1000.'
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -980,4 +980,153 @@ RSpec.describe 'Inboxes API', type: :request do
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'GET /api/v1/accounts/{account.id}/inboxes/{inbox.id}/health' do
|
||||
let(:whatsapp_channel) do
|
||||
create(:channel_whatsapp, account: account, provider: 'whatsapp_cloud', sync_templates: false, validate_provider_config: false)
|
||||
end
|
||||
let(:whatsapp_inbox) { create(:inbox, account: account, channel: whatsapp_channel) }
|
||||
let(:non_whatsapp_inbox) { create(:inbox, account: account) }
|
||||
let(:health_service) { instance_double(Whatsapp::HealthService) }
|
||||
let(:health_data) do
|
||||
{
|
||||
display_phone_number: '+1234567890',
|
||||
verified_name: 'Test Business',
|
||||
name_status: 'APPROVED',
|
||||
quality_rating: 'GREEN',
|
||||
messaging_limit_tier: 'TIER_1000',
|
||||
account_mode: 'LIVE',
|
||||
business_id: 'business123'
|
||||
}
|
||||
end
|
||||
|
||||
before do
|
||||
allow(Whatsapp::HealthService).to receive(:new).and_return(health_service)
|
||||
allow(health_service).to receive(:fetch_health_status).and_return(health_data)
|
||||
end
|
||||
|
||||
context 'when it is an unauthenticated user' do
|
||||
it 'returns unauthorized' do
|
||||
get "/api/v1/accounts/#{account.id}/inboxes/#{whatsapp_inbox.id}/health"
|
||||
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when it is an authenticated user' do
|
||||
context 'with WhatsApp inbox' do
|
||||
it 'returns health data for administrator' do
|
||||
get "/api/v1/accounts/#{account.id}/inboxes/#{whatsapp_inbox.id}/health",
|
||||
headers: admin.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
json_response = response.parsed_body
|
||||
expect(json_response).to include(
|
||||
'display_phone_number' => '+1234567890',
|
||||
'verified_name' => 'Test Business',
|
||||
'name_status' => 'APPROVED',
|
||||
'quality_rating' => 'GREEN',
|
||||
'messaging_limit_tier' => 'TIER_1000',
|
||||
'account_mode' => 'LIVE',
|
||||
'business_id' => 'business123'
|
||||
)
|
||||
end
|
||||
|
||||
it 'returns health data for agent with inbox access' do
|
||||
create(:inbox_member, user: agent, inbox: whatsapp_inbox)
|
||||
|
||||
get "/api/v1/accounts/#{account.id}/inboxes/#{whatsapp_inbox.id}/health",
|
||||
headers: agent.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
json_response = response.parsed_body
|
||||
expect(json_response['display_phone_number']).to eq('+1234567890')
|
||||
end
|
||||
|
||||
it 'returns unauthorized for agent without inbox access' do
|
||||
get "/api/v1/accounts/#{account.id}/inboxes/#{whatsapp_inbox.id}/health",
|
||||
headers: agent.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
|
||||
it 'calls the health service with correct channel' do
|
||||
expect(Whatsapp::HealthService).to receive(:new).with(whatsapp_channel).and_return(health_service)
|
||||
expect(health_service).to receive(:fetch_health_status)
|
||||
|
||||
get "/api/v1/accounts/#{account.id}/inboxes/#{whatsapp_inbox.id}/health",
|
||||
headers: admin.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
end
|
||||
|
||||
it 'handles service errors gracefully' do
|
||||
allow(health_service).to receive(:fetch_health_status).and_raise(StandardError, 'API Error')
|
||||
|
||||
get "/api/v1/accounts/#{account.id}/inboxes/#{whatsapp_inbox.id}/health",
|
||||
headers: admin.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
json_response = response.parsed_body
|
||||
expect(json_response['error']).to include('API Error')
|
||||
end
|
||||
end
|
||||
|
||||
context 'with non-WhatsApp inbox' do
|
||||
it 'returns bad request error for administrator' do
|
||||
get "/api/v1/accounts/#{account.id}/inboxes/#{non_whatsapp_inbox.id}/health",
|
||||
headers: admin.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:bad_request)
|
||||
json_response = response.parsed_body
|
||||
expect(json_response['error']).to eq('Health data only available for WhatsApp Cloud API channels')
|
||||
end
|
||||
|
||||
it 'returns bad request error for agent' do
|
||||
create(:inbox_member, user: agent, inbox: non_whatsapp_inbox)
|
||||
|
||||
get "/api/v1/accounts/#{account.id}/inboxes/#{non_whatsapp_inbox.id}/health",
|
||||
headers: agent.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:bad_request)
|
||||
json_response = response.parsed_body
|
||||
expect(json_response['error']).to eq('Health data only available for WhatsApp Cloud API channels')
|
||||
end
|
||||
end
|
||||
|
||||
context 'with WhatsApp non-cloud inbox' do
|
||||
let(:whatsapp_default_channel) do
|
||||
create(:channel_whatsapp, account: account, provider: 'default', sync_templates: false, validate_provider_config: false)
|
||||
end
|
||||
let(:whatsapp_default_inbox) { create(:inbox, account: account, channel: whatsapp_default_channel) }
|
||||
|
||||
it 'returns bad request error for non-cloud provider' do
|
||||
get "/api/v1/accounts/#{account.id}/inboxes/#{whatsapp_default_inbox.id}/health",
|
||||
headers: admin.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:bad_request)
|
||||
json_response = response.parsed_body
|
||||
expect(json_response['error']).to eq('Health data only available for WhatsApp Cloud API channels')
|
||||
end
|
||||
end
|
||||
|
||||
context 'with non-existent inbox' do
|
||||
it 'returns not found error' do
|
||||
get "/api/v1/accounts/#{account.id}/inboxes/999999/health",
|
||||
headers: admin.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:not_found)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -154,6 +154,25 @@ RSpec.describe 'Api::V1::Accounts::Portals', type: :request do
|
||||
portal.reload
|
||||
expect(portal.archived).to be_truthy
|
||||
end
|
||||
|
||||
it 'clears associated web widget when inbox selection is blank' do
|
||||
web_widget_inbox = create(:inbox, account: account)
|
||||
portal.update!(channel_web_widget: web_widget_inbox.channel)
|
||||
|
||||
expect(portal.channel_web_widget_id).to eq(web_widget_inbox.channel.id)
|
||||
|
||||
put "/api/v1/accounts/#{account.id}/portals/#{portal.slug}",
|
||||
params: {
|
||||
portal: { name: portal.name },
|
||||
inbox_id: ''
|
||||
},
|
||||
headers: admin.create_new_auth_token
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
portal.reload
|
||||
expect(portal.channel_web_widget_id).to be_nil
|
||||
expect(response.parsed_body['inbox']).to be_nil
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
@@ -16,31 +16,7 @@ RSpec.describe 'WhatsApp Authorization API', type: :request do
|
||||
let(:agent) { create(:user, account: account, role: :agent) }
|
||||
let(:administrator) { create(:user, account: account, role: :administrator) }
|
||||
|
||||
context 'when feature is not enabled' do
|
||||
before do
|
||||
account.disable_features!(:whatsapp_embedded_signup)
|
||||
end
|
||||
|
||||
it 'returns forbidden' do
|
||||
post "/api/v1/accounts/#{account.id}/whatsapp/authorization",
|
||||
params: {
|
||||
code: 'test_code',
|
||||
business_id: 'test_business_id',
|
||||
waba_id: 'test_waba_id'
|
||||
},
|
||||
headers: agent.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:forbidden)
|
||||
expect(response.parsed_body['error']).to eq('WhatsApp embedded signup is not enabled for this account')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when feature is enabled' do
|
||||
before do
|
||||
account.enable_features!(:whatsapp_embedded_signup)
|
||||
end
|
||||
|
||||
context 'when authenticated user makes request' do
|
||||
it 'returns unprocessable entity when code is missing' do
|
||||
post "/api/v1/accounts/#{account.id}/whatsapp/authorization",
|
||||
params: {
|
||||
@@ -246,10 +222,6 @@ RSpec.describe 'WhatsApp Authorization API', type: :request do
|
||||
context 'when user is not authorized for the account' do
|
||||
let(:other_account) { create(:account) }
|
||||
|
||||
before do
|
||||
account.enable_features!(:whatsapp_embedded_signup)
|
||||
end
|
||||
|
||||
it 'returns unauthorized' do
|
||||
post "/api/v1/accounts/#{other_account.id}/whatsapp/authorization",
|
||||
params: {
|
||||
@@ -265,10 +237,6 @@ RSpec.describe 'WhatsApp Authorization API', type: :request do
|
||||
end
|
||||
|
||||
context 'when user is an administrator' do
|
||||
before do
|
||||
account.enable_features!(:whatsapp_embedded_signup)
|
||||
end
|
||||
|
||||
it 'allows channel creation' do
|
||||
embedded_signup_service = instance_double(Whatsapp::EmbeddedSignupService)
|
||||
whatsapp_channel = create(:channel_whatsapp, account: account, validate_provider_config: false, sync_templates: false)
|
||||
@@ -321,10 +289,6 @@ RSpec.describe 'WhatsApp Authorization API', type: :request do
|
||||
context 'when user is an administrator' do
|
||||
let(:administrator) { create(:user, account: account, role: :administrator) }
|
||||
|
||||
before do
|
||||
account.enable_features!(:whatsapp_embedded_signup)
|
||||
end
|
||||
|
||||
context 'with valid parameters' do
|
||||
let(:valid_params) do
|
||||
{
|
||||
@@ -489,7 +453,6 @@ RSpec.describe 'WhatsApp Authorization API', type: :request do
|
||||
let(:agent) { create(:user, account: account, role: :agent) }
|
||||
|
||||
before do
|
||||
account.enable_features!(:whatsapp_embedded_signup)
|
||||
create(:inbox_member, inbox: whatsapp_inbox, user: agent)
|
||||
end
|
||||
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe Api::V2::Accounts::ReportsController, type: :request do
|
||||
let(:account) { create(:account) }
|
||||
let(:admin) { create(:user, account: account, role: :administrator) }
|
||||
let(:agent) { create(:user, account: account, role: :agent) }
|
||||
let(:inbox) { create(:inbox, account: account) }
|
||||
|
||||
describe 'GET /api/v2/accounts/{account.id}/reports' do
|
||||
context 'when authenticated and authorized' do
|
||||
before do
|
||||
# Create conversations across 24 hours at different times
|
||||
base_time = Time.utc(2024, 1, 14, 23, 0) # Start at 23:00 to span 2 days
|
||||
|
||||
# Create conversations every 4 hours across 24 hours
|
||||
6.times do |i|
|
||||
time = base_time + (i * 4).hours
|
||||
travel_to time do
|
||||
conversation = create(:conversation, account: account, inbox: inbox, assignee: agent)
|
||||
create(:message, account: account, conversation: conversation, message_type: :outgoing)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
it 'timezone_offset affects data grouping and timestamps correctly' do
|
||||
travel_to Time.utc(2024, 1, 15, 12, 0) do
|
||||
Time.use_zone('UTC') do
|
||||
base_time = Time.utc(2024, 1, 14, 23, 0) # Start at 23:00 to span 2 days
|
||||
base_params = {
|
||||
metric: 'conversations_count',
|
||||
type: 'account',
|
||||
since: (base_time - 1.day).to_i.to_s,
|
||||
until: (base_time + 2.days).to_i.to_s,
|
||||
group_by: 'day'
|
||||
}
|
||||
|
||||
responses = [0, -8, 9].map do |offset|
|
||||
get "/api/v2/accounts/#{account.id}/reports",
|
||||
params: base_params.merge(timezone_offset: offset),
|
||||
headers: admin.create_new_auth_token, as: :json
|
||||
response.parsed_body
|
||||
end
|
||||
|
||||
data_entries = responses.map { |r| r.select { |e| e['value'] > 0 } }
|
||||
totals = responses.map { |r| r.sum { |e| e['value'] } }
|
||||
timestamps = responses.map { |r| r.map { |e| e['timestamp'] } }
|
||||
|
||||
# Data conservation and redistribution
|
||||
expect(totals.uniq).to eq([6])
|
||||
expect(data_entries[0].map { |e| e['value'] }).to eq([1, 5])
|
||||
expect(data_entries[1].map { |e| e['value'] }).to eq([3, 3])
|
||||
expect(data_entries[2].map { |e| e['value'] }).to eq([4, 2])
|
||||
|
||||
# Timestamp differences
|
||||
expect(timestamps.uniq.size).to eq(3)
|
||||
timestamps[0].zip(timestamps[1]).each { |utc, pst| expect(utc - pst).to eq(-28_800) }
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'timezone_offset does not affect summary report totals' do
|
||||
let(:base_time) { Time.utc(2024, 1, 15, 12, 0) }
|
||||
let(:summary_params) do
|
||||
{
|
||||
type: 'account',
|
||||
since: (base_time - 1.day).to_i.to_s,
|
||||
until: (base_time + 1.day).to_i.to_s
|
||||
}
|
||||
end
|
||||
|
||||
let(:jst_params) do
|
||||
# For JST: User wants "Jan 15 JST" which translates to:
|
||||
# Jan 14 15:00 UTC to Jan 15 15:00 UTC (event NOT included)
|
||||
{
|
||||
type: 'account',
|
||||
since: (Time.utc(2024, 1, 15, 0, 0) - 9.hours).to_i.to_s, # Jan 14 15:00 UTC
|
||||
until: (Time.utc(2024, 1, 16, 0, 0) - 9.hours).to_i.to_s # Jan 15 15:00 UTC
|
||||
}
|
||||
end
|
||||
let(:utc_params) do
|
||||
# For UTC: Jan 15 00:00 UTC to Jan 16 00:00 UTC (event included)
|
||||
{
|
||||
type: 'account',
|
||||
since: Time.utc(2024, 1, 15, 0, 0).to_i.to_s,
|
||||
until: Time.utc(2024, 1, 16, 0, 0).to_i.to_s
|
||||
}
|
||||
end
|
||||
|
||||
it 'returns identical conversation counts across timezones' do
|
||||
Time.use_zone('UTC') do
|
||||
summaries = [-8, 0, 9].map do |offset|
|
||||
get "/api/v2/accounts/#{account.id}/reports/summary",
|
||||
params: summary_params.merge(timezone_offset: offset),
|
||||
headers: admin.create_new_auth_token, as: :json
|
||||
response.parsed_body
|
||||
end
|
||||
|
||||
conversation_counts = summaries.map { |s| s['conversations_count'] }
|
||||
expect(conversation_counts.uniq).to eq([6])
|
||||
end
|
||||
end
|
||||
|
||||
it 'returns identical message counts across timezones' do
|
||||
Time.use_zone('UTC') do
|
||||
get "/api/v2/accounts/#{account.id}/reports/summary",
|
||||
params: summary_params.merge(timezone_offset: 0),
|
||||
headers: admin.create_new_auth_token, as: :json
|
||||
utc_summary = response.parsed_body
|
||||
|
||||
get "/api/v2/accounts/#{account.id}/reports/summary",
|
||||
params: summary_params.merge(timezone_offset: -8),
|
||||
headers: admin.create_new_auth_token, as: :json
|
||||
pst_summary = response.parsed_body
|
||||
|
||||
expect(utc_summary['incoming_messages_count']).to eq(pst_summary['incoming_messages_count'])
|
||||
expect(utc_summary['outgoing_messages_count']).to eq(pst_summary['outgoing_messages_count'])
|
||||
end
|
||||
end
|
||||
|
||||
it 'returns consistent resolution counts across timezones' do
|
||||
Time.use_zone('UTC') do
|
||||
get "/api/v2/accounts/#{account.id}/reports/summary",
|
||||
params: summary_params.merge(timezone_offset: 0),
|
||||
headers: admin.create_new_auth_token, as: :json
|
||||
utc_summary = response.parsed_body
|
||||
|
||||
get "/api/v2/accounts/#{account.id}/reports/summary",
|
||||
params: summary_params.merge(timezone_offset: 9),
|
||||
headers: admin.create_new_auth_token, as: :json
|
||||
jst_summary = response.parsed_body
|
||||
|
||||
expect(utc_summary['resolutions_count']).to eq(jst_summary['resolutions_count'])
|
||||
end
|
||||
end
|
||||
|
||||
it 'returns consistent previous period data across timezones' do
|
||||
Time.use_zone('UTC') do
|
||||
get "/api/v2/accounts/#{account.id}/reports/summary",
|
||||
params: summary_params.merge(timezone_offset: 0),
|
||||
headers: admin.create_new_auth_token, as: :json
|
||||
utc_summary = response.parsed_body
|
||||
|
||||
get "/api/v2/accounts/#{account.id}/reports/summary",
|
||||
params: summary_params.merge(timezone_offset: -8),
|
||||
headers: admin.create_new_auth_token, as: :json
|
||||
pst_summary = response.parsed_body
|
||||
|
||||
expect(utc_summary['previous']['conversations_count']).to eq(pst_summary['previous']['conversations_count']) if utc_summary['previous']
|
||||
end
|
||||
end
|
||||
|
||||
it 'summary reports work when frontend sends correct timezone boundaries' do
|
||||
Time.use_zone('UTC') do
|
||||
# Create a resolution event right at timezone boundary
|
||||
boundary_time = Time.utc(2024, 1, 15, 23, 30) # 11:30 PM UTC on Jan 15
|
||||
gravatar_url = 'https://www.gravatar.com'
|
||||
stub_request(:get, /#{gravatar_url}.*/).to_return(status: 404)
|
||||
|
||||
travel_to boundary_time do
|
||||
perform_enqueued_jobs do
|
||||
conversation = create(:conversation, account: account, inbox: inbox, assignee: agent)
|
||||
conversation.resolved!
|
||||
end
|
||||
end
|
||||
|
||||
get "/api/v2/accounts/#{account.id}/reports/summary",
|
||||
params: jst_params.merge(timezone_offset: 9),
|
||||
headers: admin.create_new_auth_token, as: :json
|
||||
jst_summary = response.parsed_body
|
||||
|
||||
get "/api/v2/accounts/#{account.id}/reports/summary",
|
||||
params: utc_params.merge(timezone_offset: 0),
|
||||
headers: admin.create_new_auth_token, as: :json
|
||||
utc_summary = response.parsed_body
|
||||
|
||||
expect(jst_summary['resolutions_count']).to eq(0)
|
||||
expect(utc_summary['resolutions_count']).to eq(1)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
context 'when unauthenticated' do
|
||||
it 'returns unauthorized' do
|
||||
get "/api/v2/accounts/#{account.id}/reports"
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when authenticated but not authorized' do
|
||||
it 'returns forbidden' do
|
||||
get "/api/v2/accounts/#{account.id}/reports",
|
||||
headers: agent.create_new_auth_token,
|
||||
as: :json
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,166 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe DeviseOverrides::SessionsController, type: :controller do
|
||||
include Devise::Test::ControllerHelpers
|
||||
|
||||
before do
|
||||
request.env['devise.mapping'] = Devise.mappings[:user]
|
||||
end
|
||||
|
||||
describe 'POST #create' do
|
||||
let(:user) { create(:user, password: 'Test@123456') }
|
||||
|
||||
context 'with standard authentication' do
|
||||
it 'authenticates with valid credentials' do
|
||||
post :create, params: { email: user.email, password: 'Test@123456' }
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
end
|
||||
|
||||
it 'rejects invalid credentials' do
|
||||
post :create, params: { email: user.email, password: 'wrong' }
|
||||
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
end
|
||||
|
||||
context 'with MFA authentication' do
|
||||
before do
|
||||
skip('Skipping since MFA is not configured in this environment') unless Chatwoot.encryption_configured?
|
||||
user.enable_two_factor!
|
||||
user.update!(otp_required_for_login: true)
|
||||
end
|
||||
|
||||
it 'requires MFA verification after successful password authentication' do
|
||||
post :create, params: { email: user.email, password: 'Test@123456' }
|
||||
|
||||
expect(response).to have_http_status(:partial_content)
|
||||
json_response = response.parsed_body
|
||||
expect(json_response['mfa_required']).to be(true)
|
||||
expect(json_response['mfa_token']).to be_present
|
||||
end
|
||||
|
||||
it 'does not return authentication tokens before MFA verification' do
|
||||
post :create, params: { email: user.email, password: 'Test@123456' }
|
||||
|
||||
expect(response).to have_http_status(:partial_content)
|
||||
|
||||
# Check that no authentication headers are present
|
||||
expect(response.headers['access-token']).to be_nil
|
||||
expect(response.headers['uid']).to be_nil
|
||||
expect(response.headers['client']).to be_nil
|
||||
expect(response.headers['Authorization']).to be_nil
|
||||
|
||||
# Check that no bearer token is present in any form
|
||||
response.headers.each do |key, value|
|
||||
expect(value.to_s).not_to include('Bearer') if key.downcase.include?('auth')
|
||||
end
|
||||
|
||||
json_response = response.parsed_body
|
||||
expect(json_response['data']).to be_nil
|
||||
end
|
||||
|
||||
context 'when verifying MFA' do
|
||||
let(:mfa_token) { Mfa::TokenService.new(user: user).generate_token }
|
||||
|
||||
it 'authenticates with valid OTP' do
|
||||
post :create, params: {
|
||||
mfa_token: mfa_token,
|
||||
otp_code: user.current_otp
|
||||
}
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
end
|
||||
|
||||
it 'authenticates with valid backup code' do
|
||||
backup_codes = user.generate_backup_codes!
|
||||
|
||||
post :create, params: {
|
||||
mfa_token: mfa_token,
|
||||
backup_code: backup_codes.first
|
||||
}
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
end
|
||||
|
||||
it 'rejects invalid OTP' do
|
||||
post :create, params: {
|
||||
mfa_token: mfa_token,
|
||||
otp_code: '000000'
|
||||
}
|
||||
|
||||
expect(response).to have_http_status(:bad_request)
|
||||
expect(response.parsed_body['error']).to eq(I18n.t('errors.mfa.invalid_code'))
|
||||
end
|
||||
|
||||
it 'rejects invalid backup code' do
|
||||
user.generate_backup_codes!
|
||||
|
||||
post :create, params: {
|
||||
mfa_token: mfa_token,
|
||||
backup_code: 'invalid'
|
||||
}
|
||||
|
||||
expect(response).to have_http_status(:bad_request)
|
||||
expect(response.parsed_body['error']).to eq(I18n.t('errors.mfa.invalid_code'))
|
||||
end
|
||||
|
||||
it 'rejects expired MFA token' do
|
||||
expired_token = JWT.encode(
|
||||
{ user_id: user.id, exp: 1.minute.ago.to_i },
|
||||
Rails.application.secret_key_base,
|
||||
'HS256'
|
||||
)
|
||||
|
||||
post :create, params: {
|
||||
mfa_token: expired_token,
|
||||
otp_code: user.current_otp
|
||||
}
|
||||
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
expect(response.parsed_body['error']).to eq(I18n.t('errors.mfa.invalid_token'))
|
||||
end
|
||||
|
||||
it 'requires either OTP or backup code' do
|
||||
post :create, params: { mfa_token: mfa_token }
|
||||
|
||||
expect(response).to have_http_status(:bad_request)
|
||||
expect(response.parsed_body['error']).to eq(I18n.t('errors.mfa.invalid_code'))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
context 'with SSO authentication' do
|
||||
it 'authenticates with valid SSO token' do
|
||||
sso_token = user.generate_sso_auth_token
|
||||
|
||||
post :create, params: {
|
||||
email: user.email,
|
||||
sso_auth_token: sso_token
|
||||
}
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
end
|
||||
|
||||
it 'rejects invalid SSO token' do
|
||||
post :create, params: {
|
||||
email: user.email,
|
||||
sso_auth_token: 'invalid'
|
||||
}
|
||||
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'GET #new' do
|
||||
it 'redirects to frontend login page' do
|
||||
allow(ENV).to receive(:fetch).and_call_original
|
||||
allow(ENV).to receive(:fetch).with('FRONTEND_URL', nil).and_return('/frontend')
|
||||
|
||||
get :new
|
||||
|
||||
expect(response).to redirect_to('/frontend/app/login?error=access-denied')
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -16,6 +16,17 @@ RSpec.describe 'Public Inbox Contact Conversations API', type: :request do
|
||||
expect(data.first['uuid']).to eq contact_inbox.conversations.first.uuid
|
||||
end
|
||||
|
||||
it 'return the conversations when hmac_verified is true' do
|
||||
contact_inbox.update(hmac_verified: true)
|
||||
create(:conversation, contact: contact)
|
||||
get "/public/api/v1/inboxes/#{api_channel.identifier}/contacts/#{contact_inbox.source_id}/conversations"
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
data = response.parsed_body
|
||||
expect(data.length).to eq 1
|
||||
expect(data.first['uuid']).to eq contact.conversations.first.uuid
|
||||
end
|
||||
|
||||
it 'does not return any private or activity message' do
|
||||
conversation = create(:conversation, contact_inbox: contact_inbox)
|
||||
create(:message, account: conversation.account, inbox: conversation.inbox, conversation: conversation, content: 'message-1')
|
||||
|
||||
@@ -66,4 +66,38 @@ RSpec.describe 'Super Admin Users API', type: :request do
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'PATCH /super_admin/users/:id' do
|
||||
let!(:user) { create(:user) }
|
||||
let(:request_path) { "/super_admin/users/#{user.id}" }
|
||||
|
||||
before { sign_in(super_admin, scope: :super_admin) }
|
||||
|
||||
it 'skips reconfirmation when confirmed_at is provided' do
|
||||
ActiveJob::Base.queue_adapter.enqueued_jobs.clear
|
||||
patch request_path, params: { user: { email: 'updated@example.com', confirmed_at: Time.current } }
|
||||
|
||||
expect(response).to have_http_status(:redirect)
|
||||
expect(user.reload.email).to eq('updated@example.com')
|
||||
expect(user.reload.unconfirmed_email).to be_nil
|
||||
|
||||
mail_jobs = ActiveJob::Base.queue_adapter.enqueued_jobs.select do |job|
|
||||
job[:job].to_s == 'ActionMailer::MailDeliveryJob'
|
||||
end
|
||||
expect(mail_jobs.count).to eq(0)
|
||||
end
|
||||
|
||||
it 'does not skip reconfirmation when confirmed_at is blank' do
|
||||
ActiveJob::Base.queue_adapter.enqueued_jobs.clear
|
||||
patch request_path, params: { user: { email: 'updated-again@example.com' } }
|
||||
|
||||
expect(response).to have_http_status(:redirect)
|
||||
expect(user.reload.unconfirmed_email).to eq('updated-again@example.com')
|
||||
|
||||
mail_jobs = ActiveJob::Base.queue_adapter.enqueued_jobs.select do |job|
|
||||
job[:job].to_s == 'ActionMailer::MailDeliveryJob'
|
||||
end
|
||||
expect(mail_jobs.count).to be >= 1
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe AgentBuilder do
|
||||
let(:email) { 'agent@example.com' }
|
||||
let(:name) { 'Test Agent' }
|
||||
let(:account) { create(:account) }
|
||||
let!(:inviter) { create(:user, account: account, role: 'administrator') }
|
||||
let(:builder) do
|
||||
described_class.new(
|
||||
email: email,
|
||||
name: name,
|
||||
account: account,
|
||||
inviter: inviter
|
||||
)
|
||||
end
|
||||
|
||||
describe '#perform with SAML enabled' do
|
||||
let(:saml_settings) do
|
||||
create(:account_saml_settings, account: account)
|
||||
end
|
||||
|
||||
before { saml_settings }
|
||||
|
||||
context 'when user does not exist' do
|
||||
it 'creates a new user with SAML provider' do
|
||||
expect { builder.perform }.to change(User, :count).by(1)
|
||||
|
||||
user = User.from_email(email)
|
||||
expect(user.provider).to eq('saml')
|
||||
end
|
||||
|
||||
it 'creates user with correct attributes' do
|
||||
user = builder.perform
|
||||
|
||||
expect(user.email).to eq(email)
|
||||
expect(user.name).to eq(name)
|
||||
expect(user.provider).to eq('saml')
|
||||
expect(user.encrypted_password).to be_present
|
||||
end
|
||||
|
||||
it 'adds user to the account with correct role' do
|
||||
user = builder.perform
|
||||
account_user = AccountUser.find_by(user: user, account: account)
|
||||
|
||||
expect(account_user).to be_present
|
||||
expect(account_user.role).to eq('agent')
|
||||
expect(account_user.inviter).to eq(inviter)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when user already exists with email provider' do
|
||||
let!(:existing_user) { create(:user, email: email, provider: 'email') }
|
||||
|
||||
it 'does not create a new user' do
|
||||
expect { builder.perform }.not_to change(User, :count)
|
||||
end
|
||||
|
||||
it 'converts existing user to SAML provider' do
|
||||
expect(existing_user.provider).to eq('email')
|
||||
|
||||
builder.perform
|
||||
|
||||
expect(existing_user.reload.provider).to eq('saml')
|
||||
end
|
||||
|
||||
it 'adds existing user to the account' do
|
||||
user = builder.perform
|
||||
account_user = AccountUser.find_by(user: user, account: account)
|
||||
|
||||
expect(account_user).to be_present
|
||||
expect(account_user.inviter).to eq(inviter)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when user already exists with SAML provider' do
|
||||
let!(:existing_user) { create(:user, email: email, provider: 'saml') }
|
||||
|
||||
it 'does not change the provider' do
|
||||
expect { builder.perform }.not_to(change { existing_user.reload.provider })
|
||||
end
|
||||
|
||||
it 'still adds user to the account' do
|
||||
user = builder.perform
|
||||
account_user = AccountUser.find_by(user: user, account: account)
|
||||
|
||||
expect(account_user).to be_present
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe '#perform without SAML' do
|
||||
context 'when user does not exist' do
|
||||
it 'creates a new user with email provider (default behavior)' do
|
||||
expect { builder.perform }.to change(User, :count).by(1)
|
||||
|
||||
user = User.from_email(email)
|
||||
expect(user.provider).to eq('email')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when user already exists' do
|
||||
let!(:existing_user) { create(:user, email: email, provider: 'email') }
|
||||
|
||||
it 'does not change the existing user provider' do
|
||||
expect { builder.perform }.not_to(change { existing_user.reload.provider })
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe '#perform with different account configurations' do
|
||||
context 'when account has no SAML settings' do
|
||||
# No saml_settings created for this account
|
||||
|
||||
it 'treats account as non-SAML enabled' do
|
||||
user = builder.perform
|
||||
expect(user.provider).to eq('email')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when SAML settings are deleted after user creation' do
|
||||
let(:saml_settings) do
|
||||
create(:account_saml_settings, account: account)
|
||||
end
|
||||
let(:existing_user) { create(:user, email: email, provider: 'saml') }
|
||||
|
||||
before do
|
||||
saml_settings
|
||||
existing_user
|
||||
end
|
||||
|
||||
it 'does not affect existing SAML users when adding to account' do
|
||||
saml_settings.destroy!
|
||||
|
||||
user = builder.perform
|
||||
expect(user.provider).to eq('saml') # Unchanged
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,264 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe SamlUserBuilder do
|
||||
let(:email) { 'saml.user@example.com' }
|
||||
let(:auth_hash) do
|
||||
{
|
||||
'provider' => 'saml',
|
||||
'uid' => 'saml-uid-123',
|
||||
'info' => {
|
||||
'email' => email,
|
||||
'name' => 'SAML User',
|
||||
'first_name' => 'SAML',
|
||||
'last_name' => 'User'
|
||||
},
|
||||
'extra' => {
|
||||
'raw_info' => {
|
||||
'groups' => %w[Administrators Users]
|
||||
}
|
||||
}
|
||||
}
|
||||
end
|
||||
let(:account) { create(:account) }
|
||||
let(:builder) { described_class.new(auth_hash, account.id) }
|
||||
|
||||
describe '#perform' do
|
||||
context 'when user does not exist' do
|
||||
it 'creates a new user' do
|
||||
expect { builder.perform }.to change(User, :count).by(1)
|
||||
end
|
||||
|
||||
it 'creates user with correct attributes' do
|
||||
user = builder.perform
|
||||
|
||||
expect(user.email).to eq(email)
|
||||
expect(user.name).to eq('SAML User')
|
||||
expect(user.display_name).to eq('SAML')
|
||||
expect(user.provider).to eq('saml')
|
||||
expect(user.uid).to eq(email) # User model sets uid to email in before_validation callback
|
||||
expect(user.confirmed_at).to be_present
|
||||
end
|
||||
|
||||
it 'creates user with a random password' do
|
||||
user = builder.perform
|
||||
expect(user.encrypted_password).to be_present
|
||||
end
|
||||
|
||||
it 'adds user to the account' do
|
||||
user = builder.perform
|
||||
expect(user.accounts).to include(account)
|
||||
end
|
||||
|
||||
it 'sets default role as agent' do
|
||||
user = builder.perform
|
||||
account_user = AccountUser.find_by(user: user, account: account)
|
||||
expect(account_user.role).to eq('agent')
|
||||
end
|
||||
|
||||
context 'when name is not provided' do
|
||||
let(:auth_hash) do
|
||||
{
|
||||
'provider' => 'saml',
|
||||
'uid' => 'saml-uid-123',
|
||||
'info' => {
|
||||
'email' => email
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
it 'derives name from email' do
|
||||
user = builder.perform
|
||||
expect(user.name).to eq('saml.user')
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
context 'when user already exists' do
|
||||
let!(:existing_user) { create(:user, email: email) }
|
||||
|
||||
it 'does not create a new user' do
|
||||
expect { builder.perform }.not_to change(User, :count)
|
||||
end
|
||||
|
||||
it 'returns the existing user' do
|
||||
user = builder.perform
|
||||
expect(user).to eq(existing_user)
|
||||
end
|
||||
|
||||
it 'adds existing user to the account if not already added' do
|
||||
user = builder.perform
|
||||
expect(user.accounts).to include(account)
|
||||
end
|
||||
|
||||
it 'converts existing user to SAML' do
|
||||
expect(existing_user.provider).not_to eq('saml')
|
||||
|
||||
builder.perform
|
||||
|
||||
expect(existing_user.reload.provider).to eq('saml')
|
||||
end
|
||||
|
||||
it 'does not change provider if user is already SAML' do
|
||||
existing_user.update!(provider: 'saml')
|
||||
|
||||
expect { builder.perform }.not_to(change { existing_user.reload.provider })
|
||||
end
|
||||
|
||||
it 'does not duplicate account association' do
|
||||
existing_user.account_users.create!(account: account, role: 'agent')
|
||||
|
||||
expect { builder.perform }.not_to change(AccountUser, :count)
|
||||
end
|
||||
|
||||
context 'when user is not confirmed' do
|
||||
let(:unconfirmed_email) { 'unconfirmed_saml_user@example.com' }
|
||||
let(:unconfirmed_auth_hash) do
|
||||
{
|
||||
'provider' => 'saml',
|
||||
'uid' => 'saml-uid-123',
|
||||
'info' => {
|
||||
'email' => unconfirmed_email,
|
||||
'name' => 'SAML User',
|
||||
'first_name' => 'SAML',
|
||||
'last_name' => 'User'
|
||||
},
|
||||
'extra' => {
|
||||
'raw_info' => {
|
||||
'groups' => %w[Administrators Users]
|
||||
}
|
||||
}
|
||||
}
|
||||
end
|
||||
let(:unconfirmed_builder) { described_class.new(unconfirmed_auth_hash, account.id) }
|
||||
let!(:existing_user) do
|
||||
user = build(:user, email: unconfirmed_email)
|
||||
user.confirmed_at = nil
|
||||
user.save!(validate: false)
|
||||
user
|
||||
end
|
||||
|
||||
it 'confirms unconfirmed user after SAML authentication' do
|
||||
expect(existing_user.confirmed?).to be false
|
||||
|
||||
unconfirmed_builder.perform
|
||||
|
||||
expect(existing_user.reload.confirmed?).to be true
|
||||
end
|
||||
end
|
||||
|
||||
context 'when user is already confirmed' do
|
||||
let!(:existing_user) { create(:user, email: email, confirmed_at: Time.current) }
|
||||
|
||||
it 'keeps already confirmed user confirmed' do
|
||||
expect(existing_user.confirmed?).to be true
|
||||
original_confirmed_at = existing_user.confirmed_at
|
||||
|
||||
builder.perform
|
||||
|
||||
expect(existing_user.reload.confirmed?).to be true
|
||||
expect(existing_user.reload.confirmed_at).to be_within(2.seconds).of(original_confirmed_at)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
context 'with role mappings' do
|
||||
let(:saml_settings) do
|
||||
create(:account_saml_settings,
|
||||
account: account,
|
||||
role_mappings: {
|
||||
'Administrators' => { 'role' => 'administrator' },
|
||||
'Agents' => { 'role' => 'agent' }
|
||||
})
|
||||
end
|
||||
|
||||
before { saml_settings }
|
||||
|
||||
it 'applies administrator role based on SAML groups' do
|
||||
user = builder.perform
|
||||
account_user = AccountUser.find_by(user: user, account: account)
|
||||
expect(account_user.role).to eq('administrator')
|
||||
end
|
||||
|
||||
context 'with custom role mapping' do
|
||||
let!(:custom_role) { create(:custom_role, account: account) }
|
||||
let(:saml_settings) do
|
||||
create(:account_saml_settings,
|
||||
account: account,
|
||||
role_mappings: {
|
||||
'Administrators' => { 'custom_role_id' => custom_role.id }
|
||||
})
|
||||
end
|
||||
|
||||
before { saml_settings }
|
||||
|
||||
it 'applies custom role based on SAML groups' do
|
||||
user = builder.perform
|
||||
account_user = AccountUser.find_by(user: user, account: account)
|
||||
expect(account_user.custom_role_id).to eq(custom_role.id)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when user is not in any mapped groups' do
|
||||
let(:auth_hash) do
|
||||
{
|
||||
'provider' => 'saml',
|
||||
'uid' => 'saml-uid-123',
|
||||
'info' => {
|
||||
'email' => email,
|
||||
'name' => 'SAML User'
|
||||
},
|
||||
'extra' => {
|
||||
'raw_info' => {
|
||||
'groups' => ['UnmappedGroup']
|
||||
}
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
it 'keeps default agent role' do
|
||||
user = builder.perform
|
||||
account_user = AccountUser.find_by(user: user, account: account)
|
||||
expect(account_user.role).to eq('agent')
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
context 'with different group attribute names' do
|
||||
let(:auth_hash) do
|
||||
{
|
||||
'provider' => 'saml',
|
||||
'uid' => 'saml-uid-123',
|
||||
'info' => {
|
||||
'email' => email,
|
||||
'name' => 'SAML User'
|
||||
},
|
||||
'extra' => {
|
||||
'raw_info' => {
|
||||
'memberOf' => ['CN=Administrators,OU=Groups,DC=example,DC=com']
|
||||
}
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
it 'reads groups from memberOf attribute' do
|
||||
builder_instance = described_class.new(auth_hash, account_id: account.id)
|
||||
allow(builder_instance).to receive(:saml_groups).and_return(['CN=Administrators,OU=Groups,DC=example,DC=com'])
|
||||
user = builder_instance.perform
|
||||
expect(user).to be_persisted
|
||||
end
|
||||
end
|
||||
|
||||
context 'when there are errors' do
|
||||
it 'returns unsaved user object when user creation fails' do
|
||||
allow(User).to receive(:create).and_return(User.new(email: email))
|
||||
user = builder.perform
|
||||
expect(user.persisted?).to be false
|
||||
end
|
||||
|
||||
it 'does not create account association for failed user' do
|
||||
allow(User).to receive(:create).and_return(User.new(email: email))
|
||||
expect { builder.perform }.not_to change(AccountUser, :count)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -152,7 +152,7 @@ RSpec.describe 'Applied SLAs API', type: :request do
|
||||
body = JSON.parse(response.body)
|
||||
expect(body['payload'].size).to eq(1)
|
||||
expect(body['payload'].first).to include('applied_sla')
|
||||
expect(body['payload'].first['conversation']['id']).to eq(conversation2.id)
|
||||
expect(body['payload'].first['conversation']['id']).to eq(conversation2.display_id)
|
||||
expect(body['meta']).to include('count' => 1)
|
||||
end
|
||||
|
||||
|
||||
+47
@@ -90,6 +90,53 @@ RSpec.describe 'Api::V1::Accounts::Captain::AssistantResponses', type: :request
|
||||
expect(json_response[:payload][0][:documentable][:id]).to eq(document.id)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when searching' do
|
||||
before do
|
||||
create(:captain_assistant_response,
|
||||
account: account,
|
||||
assistant: assistant,
|
||||
question: 'How to reset password?',
|
||||
answer: 'Click forgot password')
|
||||
create(:captain_assistant_response,
|
||||
account: account,
|
||||
assistant: assistant,
|
||||
question: 'How to change email?',
|
||||
answer: 'Go to settings')
|
||||
end
|
||||
|
||||
it 'finds responses by question text' do
|
||||
get "/api/v1/accounts/#{account.id}/captain/assistant_responses",
|
||||
params: { search: 'password' },
|
||||
headers: agent.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(json_response[:payload].length).to eq(1)
|
||||
expect(json_response[:payload][0][:question]).to include('password')
|
||||
end
|
||||
|
||||
it 'finds responses by answer text' do
|
||||
get "/api/v1/accounts/#{account.id}/captain/assistant_responses",
|
||||
params: { search: 'settings' },
|
||||
headers: agent.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(json_response[:payload].length).to eq(1)
|
||||
expect(json_response[:payload][0][:answer]).to include('settings')
|
||||
end
|
||||
|
||||
it 'returns empty when no matches' do
|
||||
get "/api/v1/accounts/#{account.id}/captain/assistant_responses",
|
||||
params: { search: 'nonexistent' },
|
||||
headers: agent.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(json_response[:payload].length).to eq(0)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'GET /api/v1/accounts/:account_id/captain/assistant_responses/:id' do
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe 'Api::V1::Accounts::Captain::CustomTools', type: :request do
|
||||
let(:account) { create(:account) }
|
||||
let(:admin) { create(:user, account: account, role: :administrator) }
|
||||
let(:agent) { create(:user, account: account, role: :agent) }
|
||||
|
||||
def json_response
|
||||
JSON.parse(response.body, symbolize_names: true)
|
||||
end
|
||||
|
||||
describe 'GET /api/v1/accounts/{account.id}/captain/custom_tools' do
|
||||
context 'when it is an un-authenticated user' do
|
||||
it 'returns unauthorized status' do
|
||||
get "/api/v1/accounts/#{account.id}/captain/custom_tools"
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when it is an agent' do
|
||||
it 'returns success status' do
|
||||
create_list(:captain_custom_tool, 3, account: account)
|
||||
get "/api/v1/accounts/#{account.id}/captain/custom_tools",
|
||||
headers: agent.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
expect(json_response[:payload].length).to eq(3)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when it is an admin' do
|
||||
it 'returns success status and custom tools' do
|
||||
create_list(:captain_custom_tool, 5, account: account)
|
||||
get "/api/v1/accounts/#{account.id}/captain/custom_tools",
|
||||
headers: admin.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
expect(json_response[:payload].length).to eq(5)
|
||||
end
|
||||
|
||||
it 'returns only enabled custom tools' do
|
||||
create(:captain_custom_tool, account: account, enabled: true)
|
||||
create(:captain_custom_tool, account: account, enabled: false)
|
||||
get "/api/v1/accounts/#{account.id}/captain/custom_tools",
|
||||
headers: admin.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
expect(json_response[:payload].length).to eq(1)
|
||||
expect(json_response[:payload].first[:enabled]).to be(true)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'GET /api/v1/accounts/{account.id}/captain/custom_tools/{id}' do
|
||||
let(:custom_tool) { create(:captain_custom_tool, account: account) }
|
||||
|
||||
context 'when it is an un-authenticated user' do
|
||||
it 'returns unauthorized status' do
|
||||
get "/api/v1/accounts/#{account.id}/captain/custom_tools/#{custom_tool.id}"
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when it is an agent' do
|
||||
it 'returns success status and custom tool' do
|
||||
get "/api/v1/accounts/#{account.id}/captain/custom_tools/#{custom_tool.id}",
|
||||
headers: agent.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
expect(json_response[:id]).to eq(custom_tool.id)
|
||||
expect(json_response[:title]).to eq(custom_tool.title)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when custom tool does not exist' do
|
||||
it 'returns not found status' do
|
||||
get "/api/v1/accounts/#{account.id}/captain/custom_tools/999999",
|
||||
headers: agent.create_new_auth_token
|
||||
|
||||
expect(response).to have_http_status(:not_found)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'POST /api/v1/accounts/{account.id}/captain/custom_tools' do
|
||||
let(:valid_attributes) do
|
||||
{
|
||||
custom_tool: {
|
||||
title: 'Fetch Order Status',
|
||||
description: 'Fetches order status from external API',
|
||||
endpoint_url: 'https://api.example.com/orders/{{ order_id }}',
|
||||
http_method: 'GET',
|
||||
enabled: true,
|
||||
param_schema: [
|
||||
{ name: 'order_id', type: 'string', description: 'The order ID', required: true }
|
||||
]
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
context 'when it is an un-authenticated user' do
|
||||
it 'returns unauthorized status' do
|
||||
post "/api/v1/accounts/#{account.id}/captain/custom_tools",
|
||||
params: valid_attributes
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when it is an agent' do
|
||||
it 'returns unauthorized status' do
|
||||
post "/api/v1/accounts/#{account.id}/captain/custom_tools",
|
||||
params: valid_attributes,
|
||||
headers: agent.create_new_auth_token
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when it is an admin' do
|
||||
it 'creates a new custom tool and returns success status' do
|
||||
post "/api/v1/accounts/#{account.id}/captain/custom_tools",
|
||||
params: valid_attributes,
|
||||
headers: admin.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
expect(json_response[:title]).to eq('Fetch Order Status')
|
||||
expect(json_response[:description]).to eq('Fetches order status from external API')
|
||||
expect(json_response[:enabled]).to be(true)
|
||||
expect(json_response[:slug]).to eq('custom_fetch_order_status')
|
||||
expect(json_response[:param_schema]).to eq([
|
||||
{ name: 'order_id', type: 'string', description: 'The order ID', required: true }
|
||||
])
|
||||
end
|
||||
|
||||
context 'with invalid parameters' do
|
||||
let(:invalid_attributes) do
|
||||
{
|
||||
custom_tool: {
|
||||
title: '',
|
||||
endpoint_url: ''
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
it 'returns unprocessable entity status' do
|
||||
post "/api/v1/accounts/#{account.id}/captain/custom_tools",
|
||||
params: invalid_attributes,
|
||||
headers: admin.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
end
|
||||
end
|
||||
|
||||
context 'with invalid endpoint URL' do
|
||||
let(:invalid_url_attributes) do
|
||||
{
|
||||
custom_tool: {
|
||||
title: 'Test Tool',
|
||||
endpoint_url: 'http://localhost/api',
|
||||
http_method: 'GET'
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
it 'returns unprocessable entity status' do
|
||||
post "/api/v1/accounts/#{account.id}/captain/custom_tools",
|
||||
params: invalid_url_attributes,
|
||||
headers: admin.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'PATCH /api/v1/accounts/{account.id}/captain/custom_tools/{id}' do
|
||||
let(:custom_tool) { create(:captain_custom_tool, account: account) }
|
||||
let(:update_attributes) do
|
||||
{
|
||||
custom_tool: {
|
||||
title: 'Updated Tool Title',
|
||||
enabled: false
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
context 'when it is an un-authenticated user' do
|
||||
it 'returns unauthorized status' do
|
||||
patch "/api/v1/accounts/#{account.id}/captain/custom_tools/#{custom_tool.id}",
|
||||
params: update_attributes
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when it is an agent' do
|
||||
it 'returns unauthorized status' do
|
||||
patch "/api/v1/accounts/#{account.id}/captain/custom_tools/#{custom_tool.id}",
|
||||
params: update_attributes,
|
||||
headers: agent.create_new_auth_token
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when it is an admin' do
|
||||
it 'updates the custom tool and returns success status' do
|
||||
patch "/api/v1/accounts/#{account.id}/captain/custom_tools/#{custom_tool.id}",
|
||||
params: update_attributes,
|
||||
headers: admin.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
expect(json_response[:title]).to eq('Updated Tool Title')
|
||||
expect(json_response[:enabled]).to be(false)
|
||||
end
|
||||
|
||||
context 'with invalid parameters' do
|
||||
let(:invalid_attributes) do
|
||||
{
|
||||
custom_tool: {
|
||||
title: ''
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
it 'returns unprocessable entity status' do
|
||||
patch "/api/v1/accounts/#{account.id}/captain/custom_tools/#{custom_tool.id}",
|
||||
params: invalid_attributes,
|
||||
headers: admin.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'DELETE /api/v1/accounts/{account.id}/captain/custom_tools/{id}' do
|
||||
let!(:custom_tool) { create(:captain_custom_tool, account: account) }
|
||||
|
||||
context 'when it is an un-authenticated user' do
|
||||
it 'returns unauthorized status' do
|
||||
delete "/api/v1/accounts/#{account.id}/captain/custom_tools/#{custom_tool.id}"
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when it is an agent' do
|
||||
it 'returns unauthorized status' do
|
||||
delete "/api/v1/accounts/#{account.id}/captain/custom_tools/#{custom_tool.id}",
|
||||
headers: agent.create_new_auth_token
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when it is an admin' do
|
||||
it 'deletes the custom tool and returns no content status' do
|
||||
expect do
|
||||
delete "/api/v1/accounts/#{account.id}/captain/custom_tools/#{custom_tool.id}",
|
||||
headers: admin.create_new_auth_token
|
||||
end.to change(Captain::CustomTool, :count).by(-1)
|
||||
|
||||
expect(response).to have_http_status(:no_content)
|
||||
end
|
||||
|
||||
context 'when custom tool does not exist' do
|
||||
it 'returns not found status' do
|
||||
delete "/api/v1/accounts/#{account.id}/captain/custom_tools/999999",
|
||||
headers: admin.create_new_auth_token
|
||||
|
||||
expect(response).to have_http_status(:not_found)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,141 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe 'Companies API', type: :request do
|
||||
let(:account) { create(:account) }
|
||||
|
||||
describe 'GET /api/v1/accounts/{account.id}/companies' do
|
||||
context 'when it is an unauthenticated user' do
|
||||
it 'returns unauthorized' do
|
||||
get "/api/v1/accounts/#{account.id}/companies"
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when it is an authenticated user' do
|
||||
let(:admin) { create(:user, account: account, role: :administrator) }
|
||||
let!(:company1) { create(:company, name: 'Company 1', account: account) }
|
||||
let!(:company2) { create(:company, account: account) }
|
||||
|
||||
it 'returns all companies' do
|
||||
get "/api/v1/accounts/#{account.id}/companies",
|
||||
headers: admin.create_new_auth_token,
|
||||
as: :json
|
||||
expect(response).to have_http_status(:success)
|
||||
response_body = response.parsed_body
|
||||
expect(response_body['payload'].size).to eq(2)
|
||||
expect(response_body['payload'].map { |c| c['name'] }).to contain_exactly(company1.name, company2.name)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'GET /api/v1/accounts/{account.id}/companies/{id}' do
|
||||
context 'when it is an authenticated user' do
|
||||
let(:admin) { create(:user, account: account, role: :administrator) }
|
||||
let(:company) { create(:company, account: account) }
|
||||
|
||||
it 'returns the company' do
|
||||
get "/api/v1/accounts/#{account.id}/companies/#{company.id}",
|
||||
headers: admin.create_new_auth_token,
|
||||
as: :json
|
||||
expect(response).to have_http_status(:success)
|
||||
response_body = response.parsed_body
|
||||
expect(response_body['payload']['name']).to eq(company.name)
|
||||
expect(response_body['payload']['id']).to eq(company.id)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'POST /api/v1/accounts/{account.id}/companies' do
|
||||
context 'when it is an authenticated user' do
|
||||
let(:admin) { create(:user, account: account, role: :administrator) }
|
||||
let(:valid_params) do
|
||||
{
|
||||
company: {
|
||||
name: 'New Company',
|
||||
domain: 'newcompany.com',
|
||||
description: 'A new company'
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
it 'creates a new company' do
|
||||
expect do
|
||||
post "/api/v1/accounts/#{account.id}/companies",
|
||||
params: valid_params,
|
||||
headers: admin.create_new_auth_token,
|
||||
as: :json
|
||||
end.to change(Company, :count).by(1)
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
response_body = response.parsed_body
|
||||
expect(response_body['payload']['name']).to eq('New Company')
|
||||
expect(response_body['payload']['domain']).to eq('newcompany.com')
|
||||
end
|
||||
|
||||
it 'returns error for invalid params' do
|
||||
invalid_params = { company: { name: '' } }
|
||||
|
||||
post "/api/v1/accounts/#{account.id}/companies",
|
||||
params: invalid_params,
|
||||
headers: admin.create_new_auth_token,
|
||||
as: :json
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'PATCH /api/v1/accounts/{account.id}/companies/{id}' do
|
||||
context 'when it is an authenticated user' do
|
||||
let(:admin) { create(:user, account: account, role: :administrator) }
|
||||
let(:company) { create(:company, account: account) }
|
||||
let(:update_params) do
|
||||
{
|
||||
company: {
|
||||
name: 'Updated Company Name',
|
||||
domain: 'updated.com'
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
it 'updates the company' do
|
||||
patch "/api/v1/accounts/#{account.id}/companies/#{company.id}",
|
||||
params: update_params,
|
||||
headers: admin.create_new_auth_token,
|
||||
as: :json
|
||||
expect(response).to have_http_status(:success)
|
||||
response_body = response.parsed_body
|
||||
expect(response_body['payload']['name']).to eq('Updated Company Name')
|
||||
expect(response_body['payload']['domain']).to eq('updated.com')
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'DELETE /api/v1/accounts/{account.id}/companies/{id}' do
|
||||
context 'when it is an authenticated administrator' do
|
||||
let(:admin) { create(:user, account: account, role: :administrator) }
|
||||
let(:company) { create(:company, account: account) }
|
||||
|
||||
it 'deletes the company' do
|
||||
company
|
||||
expect do
|
||||
delete "/api/v1/accounts/#{account.id}/companies/#{company.id}",
|
||||
headers: admin.create_new_auth_token,
|
||||
as: :json
|
||||
end.to change(Company, :count).by(-1)
|
||||
expect(response).to have_http_status(:ok)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when it is a regular agent' do
|
||||
let(:agent) { create(:user, account: account, role: :agent) }
|
||||
let(:company) { create(:company, account: account) }
|
||||
|
||||
it 'returns unauthorized' do
|
||||
delete "/api/v1/accounts/#{account.id}/companies/#{company.id}",
|
||||
headers: agent.create_new_auth_token,
|
||||
as: :json
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -30,5 +30,76 @@ RSpec.describe 'Conversations API', type: :request do
|
||||
expect(response.parsed_body.keys).not_to include('applied_sla')
|
||||
expect(response.parsed_body.keys).not_to include('sla_events')
|
||||
end
|
||||
|
||||
context 'when agent has team access' do
|
||||
let(:agent) { create(:user, account: account, role: :agent) }
|
||||
let(:team) { create(:team, account: account) }
|
||||
let(:conversation) { create(:conversation, account: account, team: team) }
|
||||
|
||||
before do
|
||||
create(:team_member, team: team, user: agent)
|
||||
end
|
||||
|
||||
it 'allows accessing the conversation via team membership' do
|
||||
get "/api/v1/accounts/#{account.id}/conversations/#{conversation.display_id}", headers: agent.create_new_auth_token
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(response.parsed_body['id']).to eq(conversation.display_id)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when agent has a custom role' do
|
||||
let(:agent) { create(:user, account: account, role: :agent) }
|
||||
let(:conversation) { create(:conversation, account: account) }
|
||||
|
||||
before do
|
||||
create(:inbox_member, user: agent, inbox: conversation.inbox)
|
||||
end
|
||||
|
||||
it 'returns unauthorized for unassigned conversation without permission' do
|
||||
custom_role = create(:custom_role, account: account, permissions: ['conversation_participating_manage'])
|
||||
account.account_users.find_by(user_id: agent.id).update!(custom_role: custom_role)
|
||||
|
||||
get "/api/v1/accounts/#{account.id}/conversations/#{conversation.display_id}", headers: agent.create_new_auth_token
|
||||
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
|
||||
it 'returns the conversation when permission allows managing unassigned conversations, including when assigned to agent' do
|
||||
custom_role = create(:custom_role, account: account, permissions: ['conversation_unassigned_manage'])
|
||||
account_user = account.account_users.find_by(user_id: agent.id)
|
||||
account_user.update!(custom_role: custom_role)
|
||||
conversation.update!(assignee: agent)
|
||||
|
||||
get "/api/v1/accounts/#{account.id}/conversations/#{conversation.display_id}", headers: agent.create_new_auth_token
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(response.parsed_body['id']).to eq(conversation.display_id)
|
||||
end
|
||||
|
||||
it 'returns the conversation when permission allows managing assigned conversations' do
|
||||
custom_role = create(:custom_role, account: account, permissions: ['conversation_participating_manage'])
|
||||
account_user = account.account_users.find_by(user_id: agent.id)
|
||||
account_user.update!(custom_role: custom_role)
|
||||
conversation.update!(assignee: agent)
|
||||
|
||||
get "/api/v1/accounts/#{account.id}/conversations/#{conversation.display_id}", headers: agent.create_new_auth_token
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(response.parsed_body['id']).to eq(conversation.display_id)
|
||||
end
|
||||
|
||||
it 'returns the conversation when permission allows managing participating conversations' do
|
||||
custom_role = create(:custom_role, account: account, permissions: ['conversation_participating_manage'])
|
||||
account_user = account.account_users.find_by(user_id: agent.id)
|
||||
account_user.update!(custom_role: custom_role)
|
||||
create(:conversation_participant, conversation: conversation, account: account, user: agent)
|
||||
|
||||
get "/api/v1/accounts/#{account.id}/conversations/#{conversation.display_id}", headers: agent.create_new_auth_token
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(response.parsed_body['id']).to eq(conversation.display_id)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe 'Api::V1::Accounts::SamlSettings', type: :request do
|
||||
let(:account) { create(:account) }
|
||||
let(:agent) { create(:user, account: account, role: :agent) }
|
||||
let(:administrator) { create(:user, account: account, role: :administrator) }
|
||||
|
||||
before do
|
||||
account.enable_features('saml')
|
||||
account.save!
|
||||
end
|
||||
|
||||
def json_response
|
||||
JSON.parse(response.body, symbolize_names: true)
|
||||
end
|
||||
|
||||
describe 'GET /api/v1/accounts/{account.id}/saml_settings' do
|
||||
context 'when unauthenticated' do
|
||||
it 'returns unauthorized' do
|
||||
get "/api/v1/accounts/#{account.id}/saml_settings"
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when authenticated as administrator' do
|
||||
context 'when SAML settings exist' do
|
||||
let(:saml_settings) do
|
||||
create(:account_saml_settings,
|
||||
account: account,
|
||||
sso_url: 'https://idp.example.com/saml/sso',
|
||||
role_mappings: { 'Admins' => { 'role' => 1 } })
|
||||
end
|
||||
|
||||
before do
|
||||
saml_settings # Ensure the record exists
|
||||
end
|
||||
|
||||
it 'returns the SAML settings' do
|
||||
get "/api/v1/accounts/#{account.id}/saml_settings",
|
||||
headers: administrator.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
expect(json_response[:sso_url]).to eq('https://idp.example.com/saml/sso')
|
||||
expect(json_response[:role_mappings]).to eq({ Admins: { role: 1 } })
|
||||
end
|
||||
end
|
||||
|
||||
context 'when SAML settings do not exist' do
|
||||
it 'returns default SAML settings' do
|
||||
get "/api/v1/accounts/#{account.id}/saml_settings",
|
||||
headers: administrator.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
expect(json_response[:role_mappings]).to eq({})
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
context 'when authenticated as agent' do
|
||||
it 'returns unauthorized' do
|
||||
get "/api/v1/accounts/#{account.id}/saml_settings",
|
||||
headers: agent.create_new_auth_token
|
||||
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when SAML feature is not enabled' do
|
||||
before do
|
||||
account.disable_features('saml')
|
||||
account.save!
|
||||
end
|
||||
|
||||
it 'returns forbidden with feature not enabled message' do
|
||||
get "/api/v1/accounts/#{account.id}/saml_settings",
|
||||
headers: administrator.create_new_auth_token
|
||||
|
||||
expect(response).to have_http_status(:forbidden)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'POST /api/v1/accounts/{account.id}/saml_settings' do
|
||||
let(:valid_params) do
|
||||
key = OpenSSL::PKey::RSA.new(2048)
|
||||
cert = OpenSSL::X509::Certificate.new
|
||||
cert.version = 2
|
||||
cert.serial = 1
|
||||
cert.subject = OpenSSL::X509::Name.parse('/C=US/ST=Test/L=Test/O=Test/CN=test.example.com')
|
||||
cert.issuer = cert.subject
|
||||
cert.public_key = key.public_key
|
||||
cert.not_before = Time.zone.now
|
||||
cert.not_after = cert.not_before + (365 * 24 * 60 * 60)
|
||||
cert.sign(key, OpenSSL::Digest.new('SHA256'))
|
||||
|
||||
{
|
||||
saml_settings: {
|
||||
sso_url: 'https://idp.example.com/saml/sso',
|
||||
certificate: cert.to_pem,
|
||||
idp_entity_id: 'https://idp.example.com/saml/metadata',
|
||||
role_mappings: { 'Admins' => { 'role' => 1 }, 'Users' => { 'role' => 0 } }
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
context 'when unauthenticated' do
|
||||
it 'returns unauthorized' do
|
||||
post "/api/v1/accounts/#{account.id}/saml_settings", params: valid_params
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when authenticated as administrator' do
|
||||
context 'with valid parameters' do
|
||||
it 'creates SAML settings' do
|
||||
expect do
|
||||
post "/api/v1/accounts/#{account.id}/saml_settings",
|
||||
params: valid_params,
|
||||
headers: administrator.create_new_auth_token,
|
||||
as: :json
|
||||
end.to change(AccountSamlSettings, :count).by(1)
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
|
||||
saml_settings = AccountSamlSettings.find_by(account: account)
|
||||
expect(saml_settings.sso_url).to eq('https://idp.example.com/saml/sso')
|
||||
expect(saml_settings.role_mappings).to eq({ 'Admins' => { 'role' => 1 }, 'Users' => { 'role' => 0 } })
|
||||
end
|
||||
end
|
||||
|
||||
context 'with invalid parameters' do
|
||||
let(:invalid_params) do
|
||||
valid_params.tap do |params|
|
||||
params[:saml_settings][:sso_url] = nil
|
||||
end
|
||||
end
|
||||
|
||||
it 'returns unprocessable entity' do
|
||||
post "/api/v1/accounts/#{account.id}/saml_settings",
|
||||
params: invalid_params,
|
||||
headers: administrator.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
expect(AccountSamlSettings.count).to eq(0)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
context 'when authenticated as agent' do
|
||||
it 'returns unauthorized' do
|
||||
post "/api/v1/accounts/#{account.id}/saml_settings",
|
||||
params: valid_params,
|
||||
headers: agent.create_new_auth_token
|
||||
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
expect(AccountSamlSettings.count).to eq(0)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'PUT /api/v1/accounts/{account.id}/saml_settings' do
|
||||
let(:saml_settings) do
|
||||
create(:account_saml_settings,
|
||||
account: account,
|
||||
sso_url: 'https://old.example.com/saml')
|
||||
end
|
||||
let(:update_params) do
|
||||
key = OpenSSL::PKey::RSA.new(2048)
|
||||
cert = OpenSSL::X509::Certificate.new
|
||||
cert.version = 2
|
||||
cert.serial = 3
|
||||
cert.subject = OpenSSL::X509::Name.parse('/C=US/ST=Test/L=Test/O=Test/CN=update.example.com')
|
||||
cert.issuer = cert.subject
|
||||
cert.public_key = key.public_key
|
||||
cert.not_before = Time.zone.now
|
||||
cert.not_after = cert.not_before + (365 * 24 * 60 * 60)
|
||||
cert.sign(key, OpenSSL::Digest.new('SHA256'))
|
||||
|
||||
{
|
||||
saml_settings: {
|
||||
sso_url: 'https://new.example.com/saml/sso',
|
||||
certificate: cert.to_pem,
|
||||
role_mappings: { 'NewGroup' => { 'custom_role_id' => 5 } }
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
before do
|
||||
saml_settings # Ensure the record exists
|
||||
end
|
||||
|
||||
context 'when unauthenticated' do
|
||||
it 'returns unauthorized' do
|
||||
put "/api/v1/accounts/#{account.id}/saml_settings", params: update_params
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when authenticated as administrator' do
|
||||
it 'updates SAML settings' do
|
||||
put "/api/v1/accounts/#{account.id}/saml_settings",
|
||||
params: update_params,
|
||||
headers: administrator.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
|
||||
saml_settings.reload
|
||||
expect(saml_settings.sso_url).to eq('https://new.example.com/saml/sso')
|
||||
expect(saml_settings.role_mappings).to eq({ 'NewGroup' => { 'custom_role_id' => 5 } })
|
||||
end
|
||||
end
|
||||
|
||||
context 'when authenticated as agent' do
|
||||
it 'returns unauthorized' do
|
||||
put "/api/v1/accounts/#{account.id}/saml_settings",
|
||||
params: update_params,
|
||||
headers: agent.create_new_auth_token
|
||||
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'DELETE /api/v1/accounts/{account.id}/saml_settings' do
|
||||
let(:saml_settings) { create(:account_saml_settings, account: account) }
|
||||
|
||||
before do
|
||||
saml_settings # Ensure the record exists
|
||||
end
|
||||
|
||||
context 'when unauthenticated' do
|
||||
it 'returns unauthorized' do
|
||||
delete "/api/v1/accounts/#{account.id}/saml_settings"
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when authenticated as administrator' do
|
||||
it 'destroys SAML settings' do
|
||||
expect do
|
||||
delete "/api/v1/accounts/#{account.id}/saml_settings",
|
||||
headers: administrator.create_new_auth_token
|
||||
end.to change(AccountSamlSettings, :count).by(-1)
|
||||
|
||||
expect(response).to have_http_status(:no_content)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when authenticated as agent' do
|
||||
it 'returns unauthorized' do
|
||||
delete "/api/v1/accounts/#{account.id}/saml_settings",
|
||||
headers: agent.create_new_auth_token
|
||||
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
expect(AccountSamlSettings.count).to eq(1)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,137 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe 'Api::V1::Auth', type: :request do
|
||||
let(:account) { create(:account) }
|
||||
let(:user) { create(:user, email: 'user@example.com') }
|
||||
|
||||
before do
|
||||
account.enable_features('saml')
|
||||
account.save!
|
||||
allow(ENV).to receive(:fetch).and_call_original
|
||||
allow(ENV).to receive(:fetch).with('FRONTEND_URL', nil).and_return('http://www.example.com')
|
||||
end
|
||||
|
||||
describe 'POST /api/v1/auth/saml_login' do
|
||||
context 'when email is blank' do
|
||||
it 'returns bad request' do
|
||||
post '/api/v1/auth/saml_login', params: { email: '' }
|
||||
|
||||
expect(response).to have_http_status(:bad_request)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when email is nil' do
|
||||
it 'returns bad request' do
|
||||
post '/api/v1/auth/saml_login', params: {}
|
||||
|
||||
expect(response).to have_http_status(:bad_request)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when user does not exist' do
|
||||
it 'redirects to SSO login page with error' do
|
||||
post '/api/v1/auth/saml_login', params: { email: 'nonexistent@example.com' }
|
||||
|
||||
expect(response.location).to eq('http://www.example.com/app/login/sso?error=saml-authentication-failed')
|
||||
end
|
||||
|
||||
it 'redirects to mobile deep link with error when target is mobile' do
|
||||
post '/api/v1/auth/saml_login', params: { email: 'nonexistent@example.com', target: 'mobile' }
|
||||
|
||||
expect(response.location).to eq('chatwootapp://auth/saml?error=saml-authentication-failed')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when user exists but has no SAML enabled accounts' do
|
||||
before do
|
||||
create(:account_user, user: user, account: account)
|
||||
end
|
||||
|
||||
it 'redirects to SSO login page with error' do
|
||||
post '/api/v1/auth/saml_login', params: { email: user.email }
|
||||
|
||||
expect(response.location).to eq('http://www.example.com/app/login/sso?error=saml-authentication-failed')
|
||||
end
|
||||
|
||||
it 'redirects to mobile deep link with error when target is mobile' do
|
||||
post '/api/v1/auth/saml_login', params: { email: user.email, target: 'mobile' }
|
||||
|
||||
expect(response.location).to eq('chatwootapp://auth/saml?error=saml-authentication-failed')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when user has account without SAML feature enabled' do
|
||||
let(:saml_settings) { create(:account_saml_settings, account: account) }
|
||||
|
||||
before do
|
||||
saml_settings
|
||||
create(:account_user, user: user, account: account)
|
||||
account.disable_features('saml')
|
||||
account.save!
|
||||
end
|
||||
|
||||
it 'redirects to SSO login page with error' do
|
||||
post '/api/v1/auth/saml_login', params: { email: user.email }
|
||||
|
||||
expect(response.location).to eq('http://www.example.com/app/login/sso?error=saml-authentication-failed')
|
||||
end
|
||||
|
||||
it 'redirects to mobile deep link with error when target is mobile' do
|
||||
post '/api/v1/auth/saml_login', params: { email: user.email, target: 'mobile' }
|
||||
|
||||
expect(response.location).to eq('chatwootapp://auth/saml?error=saml-authentication-failed')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when user has valid SAML configuration' do
|
||||
let(:saml_settings) do
|
||||
create(:account_saml_settings, account: account)
|
||||
end
|
||||
|
||||
before do
|
||||
saml_settings
|
||||
create(:account_user, user: user, account: account)
|
||||
end
|
||||
|
||||
it 'redirects to SAML initiation URL' do
|
||||
post '/api/v1/auth/saml_login', params: { email: user.email }
|
||||
|
||||
expect(response.location).to include("/auth/saml?account_id=#{account.id}")
|
||||
end
|
||||
|
||||
it 'redirects to SAML initiation URL with mobile relay state' do
|
||||
post '/api/v1/auth/saml_login', params: { email: user.email, target: 'mobile' }
|
||||
|
||||
expect(response.location).to include("/auth/saml?account_id=#{account.id}&RelayState=mobile")
|
||||
end
|
||||
end
|
||||
|
||||
context 'when user has multiple accounts with SAML' do
|
||||
let(:account2) { create(:account) }
|
||||
let(:saml_settings1) do
|
||||
create(:account_saml_settings, account: account)
|
||||
end
|
||||
let(:saml_settings2) do
|
||||
create(:account_saml_settings, account: account2)
|
||||
end
|
||||
|
||||
before do
|
||||
account2.enable_features('saml')
|
||||
account2.save!
|
||||
saml_settings1
|
||||
saml_settings2
|
||||
create(:account_user, user: user, account: account)
|
||||
create(:account_user, user: user, account: account2)
|
||||
end
|
||||
|
||||
it 'redirects to the first SAML enabled account' do
|
||||
post '/api/v1/auth/saml_login', params: { email: user.email }
|
||||
|
||||
returned_account_id = response.location.match(/account_id=(\d+)/)[1].to_i
|
||||
expect([account.id, account2.id]).to include(returned_account_id)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe 'Enterprise SAML OmniAuth Callbacks', type: :request do
|
||||
let!(:account) { create(:account) }
|
||||
let(:saml_settings) { create(:account_saml_settings, account: account) }
|
||||
|
||||
def set_saml_config(email = 'test@example.com')
|
||||
OmniAuth.config.test_mode = true
|
||||
OmniAuth.config.mock_auth[:saml] = OmniAuth::AuthHash.new(
|
||||
provider: 'saml',
|
||||
uid: '123545',
|
||||
info: {
|
||||
name: 'Test User',
|
||||
email: email
|
||||
}
|
||||
)
|
||||
end
|
||||
|
||||
before do
|
||||
allow(ChatwootApp).to receive(:enterprise?).and_return(true)
|
||||
account.enable_features!('saml')
|
||||
saml_settings
|
||||
end
|
||||
|
||||
describe '#saml callback' do
|
||||
it 'creates new user and logs them in' do
|
||||
with_modified_env FRONTEND_URL: 'http://www.example.com' do
|
||||
set_saml_config('new_user@example.com')
|
||||
|
||||
get "/omniauth/saml/callback?account_id=#{account.id}"
|
||||
|
||||
# expect a 302 redirect to auth/saml/callback
|
||||
expect(response).to redirect_to('http://www.example.com/auth/saml/callback')
|
||||
follow_redirect!
|
||||
|
||||
# expect redirect to login with SSO token
|
||||
expect(response).to redirect_to(%r{/app/login\?email=.+&sso_auth_token=.+$})
|
||||
|
||||
# verify user was created
|
||||
user = User.from_email('new_user@example.com')
|
||||
expect(user).to be_present
|
||||
expect(user.provider).to eq('saml')
|
||||
end
|
||||
end
|
||||
|
||||
it 'logs in existing user' do
|
||||
with_modified_env FRONTEND_URL: 'http://www.example.com' do
|
||||
create(:user, email: 'existing@example.com', account: account)
|
||||
set_saml_config('existing@example.com')
|
||||
|
||||
get "/omniauth/saml/callback?account_id=#{account.id}"
|
||||
|
||||
# expect a 302 redirect to auth/saml/callback
|
||||
expect(response).to redirect_to('http://www.example.com/auth/saml/callback')
|
||||
follow_redirect!
|
||||
|
||||
expect(response).to redirect_to(%r{/app/login\?email=.+&sso_auth_token=.+$})
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,36 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe 'Enterprise Passwords Controller', type: :request do
|
||||
let!(:account) { create(:account) }
|
||||
|
||||
describe 'POST /auth/password' do
|
||||
context 'with SAML user email' do
|
||||
let!(:saml_user) { create(:user, email: 'saml@example.com', provider: 'saml', account: account) }
|
||||
|
||||
it 'prevents password reset and returns forbidden with custom error message' do
|
||||
params = { email: saml_user.email, redirect_url: 'http://test.host' }
|
||||
|
||||
post user_password_path, params: params, as: :json
|
||||
|
||||
expect(response).to have_http_status(:forbidden)
|
||||
json_response = JSON.parse(response.body)
|
||||
expect(json_response['success']).to be(false)
|
||||
expect(json_response['errors']).to include(I18n.t('messages.reset_password_saml_user'))
|
||||
end
|
||||
end
|
||||
|
||||
context 'with non-SAML user email' do
|
||||
let!(:regular_user) { create(:user, email: 'regular@example.com', provider: 'email', account: account) }
|
||||
|
||||
it 'allows password reset for non-SAML users' do
|
||||
params = { email: regular_user.email, redirect_url: 'http://test.host' }
|
||||
|
||||
post user_password_path, params: params, as: :json
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
json_response = JSON.parse(response.body)
|
||||
expect(json_response['message']).to be_present
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
+64
-21
@@ -5,32 +5,75 @@ RSpec.describe 'Enterprise Audit API', type: :request do
|
||||
let!(:user) { create(:user, password: 'Password1!', account: account) }
|
||||
|
||||
describe 'POST /sign_in' do
|
||||
it 'creates a sign_in audit event wwith valid credentials' do
|
||||
params = { email: user.email, password: 'Password1!' }
|
||||
context 'with SAML user attempting password login' do
|
||||
let(:saml_settings) { create(:account_saml_settings, account: account) }
|
||||
let(:saml_user) { create(:user, email: 'saml@example.com', provider: 'saml', account: account) }
|
||||
|
||||
expect do
|
||||
post new_user_session_url,
|
||||
params: params,
|
||||
as: :json
|
||||
end.to change(Enterprise::AuditLog, :count).by(1)
|
||||
before do
|
||||
saml_settings
|
||||
saml_user
|
||||
end
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
expect(response.body).to include(user.email)
|
||||
it 'prevents login and returns SAML authentication error' do
|
||||
params = { email: saml_user.email, password: 'Password1!' }
|
||||
|
||||
# Check if the sign_in event is created
|
||||
user.reload
|
||||
expect(user.audits.last.action).to eq('sign_in')
|
||||
expect(user.audits.last.associated_id).to eq(account.id)
|
||||
expect(user.audits.last.associated_type).to eq('Account')
|
||||
post new_user_session_url, params: params, as: :json
|
||||
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
json_response = JSON.parse(response.body)
|
||||
expect(json_response['success']).to be(false)
|
||||
expect(json_response['errors']).to include(I18n.t('messages.login_saml_user'))
|
||||
end
|
||||
|
||||
it 'allows login with valid SSO token' do
|
||||
valid_token = saml_user.generate_sso_auth_token
|
||||
params = { email: saml_user.email, sso_auth_token: valid_token, password: 'Password1!' }
|
||||
|
||||
expect do
|
||||
post new_user_session_url, params: params, as: :json
|
||||
end.to change(Enterprise::AuditLog, :count).by(1)
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
expect(response.body).to include(saml_user.email)
|
||||
end
|
||||
end
|
||||
|
||||
it 'will not create a sign_in audit event with invalid credentials' do
|
||||
params = { email: user.email, password: 'invalid' }
|
||||
expect do
|
||||
post new_user_session_url,
|
||||
params: params,
|
||||
as: :json
|
||||
end.not_to change(Enterprise::AuditLog, :count)
|
||||
context 'with regular user credentials' do
|
||||
it 'creates a sign_in audit event wwith valid credentials' do
|
||||
params = { email: user.email, password: 'Password1!' }
|
||||
|
||||
expect do
|
||||
post new_user_session_url,
|
||||
params: params,
|
||||
as: :json
|
||||
end.to change(Enterprise::AuditLog, :count).by(1)
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
expect(response.body).to include(user.email)
|
||||
|
||||
# Check if the sign_in event is created
|
||||
user.reload
|
||||
expect(user.audits.last.action).to eq('sign_in')
|
||||
expect(user.audits.last.associated_id).to eq(account.id)
|
||||
expect(user.audits.last.associated_type).to eq('Account')
|
||||
end
|
||||
|
||||
it 'will not create a sign_in audit event with invalid credentials' do
|
||||
params = { email: user.email, password: 'invalid' }
|
||||
expect do
|
||||
post new_user_session_url,
|
||||
params: params,
|
||||
as: :json
|
||||
end.not_to change(Enterprise::AuditLog, :count)
|
||||
end
|
||||
end
|
||||
|
||||
context 'with blank email' do
|
||||
it 'skips SAML check and processes normally' do
|
||||
params = { email: '', password: 'Password1!' }
|
||||
post new_user_session_url, params: params, as: :json
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe 'Twilio::VoiceController', type: :request do
|
||||
let(:account) { create(:account) }
|
||||
let(:channel) { create(:channel_voice, account: account, phone_number: '+15551230003') }
|
||||
let(:inbox) { channel.inbox }
|
||||
let(:digits) { channel.phone_number.delete_prefix('+') }
|
||||
|
||||
before do
|
||||
allow(Twilio::VoiceWebhookSetupService).to receive(:new)
|
||||
.and_return(instance_double(Twilio::VoiceWebhookSetupService, perform: "AP#{SecureRandom.hex(16)}"))
|
||||
end
|
||||
|
||||
describe 'POST /twilio/voice/call/:phone' do
|
||||
let(:call_sid) { 'CA_test_call_sid_123' }
|
||||
let(:from_number) { '+15550003333' }
|
||||
let(:to_number) { channel.phone_number }
|
||||
|
||||
it 'invokes Voice::InboundCallBuilder with expected params and renders its TwiML' do
|
||||
builder_double = instance_double(Voice::InboundCallBuilder)
|
||||
expect(Voice::InboundCallBuilder).to receive(:new).with(
|
||||
hash_including(
|
||||
account: account,
|
||||
inbox: inbox,
|
||||
from_number: from_number,
|
||||
to_number: to_number,
|
||||
call_sid: call_sid
|
||||
)
|
||||
).and_return(builder_double)
|
||||
expect(builder_double).to receive(:perform).and_return(builder_double)
|
||||
expect(builder_double).to receive(:twiml_response).and_return('<Response/>')
|
||||
|
||||
post "/twilio/voice/call/#{digits}", params: {
|
||||
'CallSid' => call_sid,
|
||||
'From' => from_number,
|
||||
'To' => to_number
|
||||
}
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(response.body).to eq('<Response/>')
|
||||
end
|
||||
|
||||
it 'raises not found when inbox is not present' do
|
||||
expect(Voice::InboundCallBuilder).not_to receive(:new)
|
||||
post '/twilio/voice/call/19998887777', params: {
|
||||
'CallSid' => call_sid,
|
||||
'From' => from_number,
|
||||
'To' => to_number
|
||||
}
|
||||
expect(response).to have_http_status(:not_found)
|
||||
end
|
||||
end
|
||||
|
||||
describe 'POST /twilio/voice/status/:phone' do
|
||||
let(:call_sid) { 'CA_status_sid_456' }
|
||||
|
||||
it 'invokes Voice::StatusUpdateService with expected params' do
|
||||
service_double = instance_double(Voice::StatusUpdateService, perform: nil)
|
||||
expect(Voice::StatusUpdateService).to receive(:new).with(
|
||||
hash_including(
|
||||
account: account,
|
||||
call_sid: call_sid,
|
||||
call_status: 'completed'
|
||||
)
|
||||
).and_return(service_double)
|
||||
expect(service_double).to receive(:perform)
|
||||
|
||||
post "/twilio/voice/status/#{digits}", params: {
|
||||
'CallSid' => call_sid,
|
||||
'CallStatus' => 'completed'
|
||||
}
|
||||
|
||||
expect(response).to have_http_status(:no_content)
|
||||
end
|
||||
|
||||
it 'raises not found when inbox is not present' do
|
||||
expect(Voice::StatusUpdateService).not_to receive(:new)
|
||||
post '/twilio/voice/status/18005550101', params: {
|
||||
'CallSid' => call_sid,
|
||||
'CallStatus' => 'busy'
|
||||
}
|
||||
expect(response).to have_http_status(:not_found)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,8 +1,6 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe Captain::InboxPendingConversationsResolutionJob, type: :job do
|
||||
include ActiveJob::TestHelper
|
||||
|
||||
let!(:inbox) { create(:inbox) }
|
||||
|
||||
let!(:resolvable_pending_conversation) { create(:conversation, inbox: inbox, last_activity_at: 2.hours.ago, status: :pending) }
|
||||
@@ -14,6 +12,7 @@ RSpec.describe Captain::InboxPendingConversationsResolutionJob, type: :job do
|
||||
before do
|
||||
create(:captain_inbox, inbox: inbox, captain_assistant: captain_assistant)
|
||||
stub_const('Limits::BULK_ACTIONS_LIMIT', 2)
|
||||
inbox.reload
|
||||
end
|
||||
|
||||
it 'queues the job' do
|
||||
@@ -22,7 +21,7 @@ RSpec.describe Captain::InboxPendingConversationsResolutionJob, type: :job do
|
||||
end
|
||||
|
||||
it 'resolves only the eligible pending conversations' do
|
||||
perform_enqueued_jobs { described_class.perform_later(inbox) }
|
||||
described_class.perform_now(inbox)
|
||||
|
||||
expect(resolvable_pending_conversation.reload.status).to eq('resolved')
|
||||
expect(recent_pending_conversation.reload.status).to eq('pending')
|
||||
@@ -34,7 +33,7 @@ RSpec.describe Captain::InboxPendingConversationsResolutionJob, type: :job do
|
||||
captain_assistant.update!(config: { 'resolution_message' => custom_message })
|
||||
|
||||
expect do
|
||||
perform_enqueued_jobs { described_class.perform_later(inbox) }
|
||||
described_class.perform_now(inbox)
|
||||
end.to change { resolvable_pending_conversation.messages.outgoing.reload.count }.by(1)
|
||||
|
||||
outgoing_message = resolvable_pending_conversation.messages.outgoing.last
|
||||
@@ -44,7 +43,7 @@ RSpec.describe Captain::InboxPendingConversationsResolutionJob, type: :job do
|
||||
it 'creates an outgoing message with default auto resolution message if not configured' do
|
||||
captain_assistant.update!(config: {})
|
||||
|
||||
perform_enqueued_jobs { described_class.perform_later(inbox) }
|
||||
described_class.perform_now(inbox)
|
||||
outgoing_message = resolvable_pending_conversation.messages.outgoing.last
|
||||
expect(outgoing_message.content).to eq(
|
||||
I18n.t('conversations.activity.auto_resolution_message')
|
||||
@@ -52,11 +51,17 @@ RSpec.describe Captain::InboxPendingConversationsResolutionJob, type: :job do
|
||||
end
|
||||
|
||||
it 'adds the correct activity message after resolution by Captain' do
|
||||
perform_enqueued_jobs { described_class.perform_later(inbox) }
|
||||
activity_message = resolvable_pending_conversation.messages.activity.last
|
||||
expect(activity_message).not_to be_nil
|
||||
expect(activity_message.content).to eq(
|
||||
I18n.t('conversations.activity.captain.resolved', user_name: captain_assistant.name)
|
||||
)
|
||||
described_class.perform_now(inbox)
|
||||
expected_content = I18n.t('conversations.activity.captain.resolved', user_name: captain_assistant.name)
|
||||
expect(Conversations::ActivityMessageJob)
|
||||
.to have_been_enqueued.with(
|
||||
resolvable_pending_conversation,
|
||||
{
|
||||
account_id: resolvable_pending_conversation.account_id,
|
||||
inbox_id: resolvable_pending_conversation.inbox_id,
|
||||
message_type: :activity,
|
||||
content: expected_content
|
||||
}
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -23,7 +23,7 @@ RSpec.describe Captain::Tools::FirecrawlParserJob, type: :job do
|
||||
expect(document).to have_attributes(
|
||||
content: payload[:markdown],
|
||||
name: payload[:metadata]['title'],
|
||||
external_link: payload[:metadata]['url'],
|
||||
external_link: 'https://www.firecrawl.dev',
|
||||
status: 'available'
|
||||
)
|
||||
end
|
||||
@@ -32,7 +32,7 @@ RSpec.describe Captain::Tools::FirecrawlParserJob, type: :job do
|
||||
existing_document = create(:captain_document,
|
||||
assistant: assistant,
|
||||
account: assistant.account,
|
||||
external_link: payload[:metadata]['url'],
|
||||
external_link: 'https://www.firecrawl.dev',
|
||||
content: 'old content',
|
||||
name: 'old title',
|
||||
status: :in_progress)
|
||||
@@ -42,7 +42,9 @@ RSpec.describe Captain::Tools::FirecrawlParserJob, type: :job do
|
||||
end.not_to change(assistant.documents, :count)
|
||||
|
||||
existing_document.reload
|
||||
# Payload URL ends with '/', but we persist the canonical URL without it.
|
||||
expect(existing_document).to have_attributes(
|
||||
external_link: 'https://www.firecrawl.dev',
|
||||
content: payload[:markdown],
|
||||
name: payload[:metadata]['title'],
|
||||
status: 'available'
|
||||
|
||||
@@ -3,7 +3,7 @@ require 'rails_helper'
|
||||
RSpec.describe Captain::Tools::SimplePageCrawlParserJob, type: :job do
|
||||
describe '#perform' do
|
||||
let(:assistant) { create(:captain_assistant) }
|
||||
let(:page_link) { 'https://example.com/page' }
|
||||
let(:page_link) { 'https://example.com/page/' }
|
||||
let(:page_title) { 'Example Page Title' }
|
||||
let(:content) { 'Some page content here' }
|
||||
let(:crawler) { instance_double(Captain::Tools::SimplePageCrawlService) }
|
||||
@@ -24,7 +24,7 @@ RSpec.describe Captain::Tools::SimplePageCrawlParserJob, type: :job do
|
||||
end.to change(assistant.documents, :count).by(1)
|
||||
|
||||
document = assistant.documents.last
|
||||
expect(document.external_link).to eq(page_link)
|
||||
expect(document.external_link).to eq('https://example.com/page')
|
||||
expect(document.name).to eq(page_title)
|
||||
expect(document.content).to eq(content)
|
||||
expect(document.status).to eq('available')
|
||||
@@ -33,7 +33,7 @@ RSpec.describe Captain::Tools::SimplePageCrawlParserJob, type: :job do
|
||||
it 'updates existing document if one exists' do
|
||||
existing_document = create(:captain_document,
|
||||
assistant: assistant,
|
||||
external_link: page_link,
|
||||
external_link: 'https://example.com/page',
|
||||
name: 'Old Title',
|
||||
content: 'Old content')
|
||||
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe Migration::CompanyAccountBatchJob, type: :job do
|
||||
let(:account) { create(:account) }
|
||||
|
||||
describe '#perform' do
|
||||
before do
|
||||
# Stub EmailProvideInfo to control behavior in tests
|
||||
allow(EmailProviderInfo).to receive(:call) do |email|
|
||||
domain = email.split('@').last&.downcase
|
||||
case domain
|
||||
when 'gmail.com', 'yahoo.com', 'hotmail.com', 'uol.com.br'
|
||||
'free_provider' # generic free provider name
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
context 'when contact has business email' do
|
||||
let!(:contact) { create(:contact, account: account, email: 'user@acme.com') }
|
||||
|
||||
it 'creates a company and associates the contact' do
|
||||
# Clean up companies created by Part 2's callback
|
||||
Company.delete_all
|
||||
# rubocop:disable Rails/SkipsModelValidations
|
||||
contact.update_column(:company_id, nil)
|
||||
# rubocop:enable Rails/SkipsModelValidations
|
||||
|
||||
expect do
|
||||
described_class.perform_now(account)
|
||||
end.to change(Company, :count).by(1)
|
||||
contact.reload
|
||||
expect(contact.company).to be_present
|
||||
expect(contact.company.domain).to eq('acme.com')
|
||||
expect(contact.company.name).to eq('Acme')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when contact has free email' do
|
||||
let!(:contact) { create(:contact, account: account, email: 'user@gmail.com') }
|
||||
|
||||
it 'does not create a company' do
|
||||
expect do
|
||||
described_class.perform_now(account)
|
||||
end.not_to change(Company, :count)
|
||||
contact.reload
|
||||
expect(contact.company_id).to be_nil
|
||||
end
|
||||
end
|
||||
|
||||
context 'when contact has company_name in additional_attributes' do
|
||||
let!(:contact) do
|
||||
create(:contact, account: account, email: 'user@acme.com', additional_attributes: { 'company_name' => 'Acme Corporation' })
|
||||
end
|
||||
|
||||
it 'uses the saved company name' do
|
||||
described_class.perform_now(account)
|
||||
contact.reload
|
||||
expect(contact.company.name).to eq('Acme Corporation')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when contact already has a company' do
|
||||
let!(:existing_company) { create(:company, account: account, domain: 'existing.com') }
|
||||
let!(:contact) do
|
||||
create(:contact, account: account, email: 'user@acme.com', company: existing_company)
|
||||
end
|
||||
|
||||
it 'does not change the existing company' do
|
||||
described_class.perform_now(account)
|
||||
contact.reload
|
||||
expect(contact.company_id).to eq(existing_company.id)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when multiple contacts have the same domain' do
|
||||
let!(:contact1) { create(:contact, account: account, email: 'user1@acme.com') }
|
||||
let!(:contact2) { create(:contact, account: account, email: 'user2@acme.com') }
|
||||
|
||||
it 'creates only one company for the domain' do
|
||||
# Clean up companies created by Part 2's callback
|
||||
Company.delete_all
|
||||
# rubocop:disable Rails/SkipsModelValidations
|
||||
contact1.update_column(:company_id, nil)
|
||||
contact2.update_column(:company_id, nil)
|
||||
# rubocop:enable Rails/SkipsModelValidations
|
||||
|
||||
expect do
|
||||
described_class.perform_now(account)
|
||||
end.to change(Company, :count).by(1)
|
||||
contact1.reload
|
||||
contact2.reload
|
||||
expect(contact1.company_id).to eq(contact2.company_id)
|
||||
expect(contact1.company.domain).to eq('acme.com')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when contact has no email' do
|
||||
let!(:contact) { create(:contact, account: account, email: nil) }
|
||||
|
||||
it 'skips the contact' do
|
||||
expect do
|
||||
described_class.perform_now(account)
|
||||
end.not_to change(Company, :count)
|
||||
contact.reload
|
||||
expect(contact.company_id).to be_nil
|
||||
end
|
||||
end
|
||||
|
||||
context 'when processing large batch' do
|
||||
before do
|
||||
contacts_data = Array.new(2000) do |i|
|
||||
{
|
||||
account_id: account.id,
|
||||
email: "user#{i}@company#{i % 100}.com",
|
||||
name: "User #{i}",
|
||||
created_at: Time.current,
|
||||
updated_at: Time.current
|
||||
}
|
||||
end
|
||||
# rubocop:disable Rails/SkipsModelValidations
|
||||
Contact.insert_all(contacts_data)
|
||||
# rubocop:enable Rails/SkipsModelValidations
|
||||
end
|
||||
|
||||
it 'processes all contacts in batches' do
|
||||
expect do
|
||||
described_class.perform_now(account)
|
||||
end.to change(Company, :count).by(100)
|
||||
expect(account.contacts.where.not(company_id: nil).count).to eq(2000)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,31 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe Migration::CompanyBackfillJob, type: :job do
|
||||
describe '#perform' do
|
||||
it 'enqueues the job' do
|
||||
expect { described_class.perform_later }
|
||||
.to have_enqueued_job(described_class)
|
||||
.on_queue('low')
|
||||
end
|
||||
|
||||
context 'when accounts exist' do
|
||||
let!(:account1) { create(:account) }
|
||||
let!(:account2) { create(:account) }
|
||||
|
||||
it 'enqueues CompanyAccountBatchJob for each account' do
|
||||
expect do
|
||||
described_class.perform_now
|
||||
end.to have_enqueued_job(Migration::CompanyAccountBatchJob)
|
||||
.with(account1)
|
||||
.and have_enqueued_job(Migration::CompanyAccountBatchJob)
|
||||
.with(account2)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when no accounts exist' do
|
||||
it 'completes without error' do
|
||||
expect { described_class.perform_now }.not_to raise_error
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,65 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe Saml::UpdateAccountUsersProviderJob, type: :job do
|
||||
let(:account) { create(:account) }
|
||||
let!(:user1) { create(:user, accounts: [account], provider: 'email') }
|
||||
let!(:user2) { create(:user, accounts: [account], provider: 'email') }
|
||||
let!(:user3) { create(:user, accounts: [account], provider: 'google') }
|
||||
|
||||
describe '#perform' do
|
||||
context 'when setting provider to saml' do
|
||||
it 'updates all account users to saml provider' do
|
||||
described_class.new.perform(account.id, 'saml')
|
||||
|
||||
expect(user1.reload.provider).to eq('saml')
|
||||
expect(user2.reload.provider).to eq('saml')
|
||||
expect(user3.reload.provider).to eq('saml')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when resetting provider to email' do
|
||||
before do
|
||||
# rubocop:disable Rails/SkipsModelValidations
|
||||
user1.update_column(:provider, 'saml')
|
||||
user2.update_column(:provider, 'saml')
|
||||
user3.update_column(:provider, 'saml')
|
||||
# rubocop:enable Rails/SkipsModelValidations
|
||||
end
|
||||
|
||||
context 'when users have no other SAML accounts' do
|
||||
it 'updates all account users to email provider' do
|
||||
described_class.new.perform(account.id, 'email')
|
||||
|
||||
expect(user1.reload.provider).to eq('email')
|
||||
expect(user2.reload.provider).to eq('email')
|
||||
expect(user3.reload.provider).to eq('email')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when users belong to other accounts with SAML enabled' do
|
||||
let(:other_account) { create(:account) }
|
||||
|
||||
before do
|
||||
create(:account_saml_settings, account: other_account)
|
||||
user1.account_users.create!(account: other_account, role: :agent)
|
||||
end
|
||||
|
||||
it 'preserves SAML provider for users with other SAML accounts' do
|
||||
described_class.new.perform(account.id, 'email')
|
||||
|
||||
expect(user1.reload.provider).to eq('saml')
|
||||
expect(user2.reload.provider).to eq('email')
|
||||
expect(user3.reload.provider).to eq('email')
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
context 'when account does not exist' do
|
||||
it 'raises ActiveRecord::RecordNotFound' do
|
||||
expect do
|
||||
described_class.new.perform(999_999, 'saml')
|
||||
end.to raise_error(ActiveRecord::RecordNotFound)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,241 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe Captain::Tools::HttpTool, type: :model do
|
||||
let(:account) { create(:account) }
|
||||
let(:assistant) { create(:captain_assistant, account: account) }
|
||||
let(:custom_tool) { create(:captain_custom_tool, account: account) }
|
||||
let(:tool) { described_class.new(assistant, custom_tool) }
|
||||
let(:tool_context) { Struct.new(:state).new({}) }
|
||||
|
||||
describe '#active?' do
|
||||
it 'returns true when custom tool is enabled' do
|
||||
custom_tool.update!(enabled: true)
|
||||
|
||||
expect(tool.active?).to be true
|
||||
end
|
||||
|
||||
it 'returns false when custom tool is disabled' do
|
||||
custom_tool.update!(enabled: false)
|
||||
|
||||
expect(tool.active?).to be false
|
||||
end
|
||||
end
|
||||
|
||||
describe '#perform' do
|
||||
context 'with GET request' do
|
||||
before do
|
||||
custom_tool.update!(
|
||||
http_method: 'GET',
|
||||
endpoint_url: 'https://example.com/orders/123',
|
||||
response_template: nil
|
||||
)
|
||||
stub_request(:get, 'https://example.com/orders/123')
|
||||
.to_return(status: 200, body: '{"status": "success"}')
|
||||
end
|
||||
|
||||
it 'executes GET request and returns response body' do
|
||||
result = tool.perform(tool_context)
|
||||
|
||||
expect(result).to eq('{"status": "success"}')
|
||||
expect(WebMock).to have_requested(:get, 'https://example.com/orders/123')
|
||||
end
|
||||
end
|
||||
|
||||
context 'with POST request' do
|
||||
before do
|
||||
custom_tool.update!(
|
||||
http_method: 'POST',
|
||||
endpoint_url: 'https://example.com/orders',
|
||||
request_template: '{"order_id": "{{ order_id }}"}',
|
||||
response_template: nil
|
||||
)
|
||||
stub_request(:post, 'https://example.com/orders')
|
||||
.with(body: '{"order_id": "123"}', headers: { 'Content-Type' => 'application/json' })
|
||||
.to_return(status: 200, body: '{"created": true}')
|
||||
end
|
||||
|
||||
it 'executes POST request with rendered body' do
|
||||
result = tool.perform(tool_context, order_id: '123')
|
||||
|
||||
expect(result).to eq('{"created": true}')
|
||||
expect(WebMock).to have_requested(:post, 'https://example.com/orders')
|
||||
.with(body: '{"order_id": "123"}')
|
||||
end
|
||||
end
|
||||
|
||||
context 'with template variables in URL' do
|
||||
before do
|
||||
custom_tool.update!(
|
||||
endpoint_url: 'https://example.com/orders/{{ order_id }}',
|
||||
response_template: nil
|
||||
)
|
||||
stub_request(:get, 'https://example.com/orders/456')
|
||||
.to_return(status: 200, body: '{"order_id": "456"}')
|
||||
end
|
||||
|
||||
it 'renders URL template with params' do
|
||||
result = tool.perform(tool_context, order_id: '456')
|
||||
|
||||
expect(result).to eq('{"order_id": "456"}')
|
||||
expect(WebMock).to have_requested(:get, 'https://example.com/orders/456')
|
||||
end
|
||||
end
|
||||
|
||||
context 'with bearer token authentication' do
|
||||
before do
|
||||
custom_tool.update!(
|
||||
auth_type: 'bearer',
|
||||
auth_config: { 'token' => 'secret_bearer_token' },
|
||||
endpoint_url: 'https://example.com/data',
|
||||
response_template: nil
|
||||
)
|
||||
stub_request(:get, 'https://example.com/data')
|
||||
.with(headers: { 'Authorization' => 'Bearer secret_bearer_token' })
|
||||
.to_return(status: 200, body: '{"authenticated": true}')
|
||||
end
|
||||
|
||||
it 'adds Authorization header with bearer token' do
|
||||
result = tool.perform(tool_context)
|
||||
|
||||
expect(result).to eq('{"authenticated": true}')
|
||||
expect(WebMock).to have_requested(:get, 'https://example.com/data')
|
||||
.with(headers: { 'Authorization' => 'Bearer secret_bearer_token' })
|
||||
end
|
||||
end
|
||||
|
||||
context 'with basic authentication' do
|
||||
before do
|
||||
custom_tool.update!(
|
||||
auth_type: 'basic',
|
||||
auth_config: { 'username' => 'user123', 'password' => 'pass456' },
|
||||
endpoint_url: 'https://example.com/data',
|
||||
response_template: nil
|
||||
)
|
||||
stub_request(:get, 'https://example.com/data')
|
||||
.with(basic_auth: %w[user123 pass456])
|
||||
.to_return(status: 200, body: '{"authenticated": true}')
|
||||
end
|
||||
|
||||
it 'adds basic auth credentials' do
|
||||
result = tool.perform(tool_context)
|
||||
|
||||
expect(result).to eq('{"authenticated": true}')
|
||||
expect(WebMock).to have_requested(:get, 'https://example.com/data')
|
||||
.with(basic_auth: %w[user123 pass456])
|
||||
end
|
||||
end
|
||||
|
||||
context 'with API key authentication' do
|
||||
before do
|
||||
custom_tool.update!(
|
||||
auth_type: 'api_key',
|
||||
auth_config: { 'key' => 'api_key_123', 'location' => 'header', 'name' => 'X-API-Key' },
|
||||
endpoint_url: 'https://example.com/data',
|
||||
response_template: nil
|
||||
)
|
||||
stub_request(:get, 'https://example.com/data')
|
||||
.with(headers: { 'X-API-Key' => 'api_key_123' })
|
||||
.to_return(status: 200, body: '{"authenticated": true}')
|
||||
end
|
||||
|
||||
it 'adds API key header' do
|
||||
result = tool.perform(tool_context)
|
||||
|
||||
expect(result).to eq('{"authenticated": true}')
|
||||
expect(WebMock).to have_requested(:get, 'https://example.com/data')
|
||||
.with(headers: { 'X-API-Key' => 'api_key_123' })
|
||||
end
|
||||
end
|
||||
|
||||
context 'with response template' do
|
||||
before do
|
||||
custom_tool.update!(
|
||||
endpoint_url: 'https://example.com/orders/123',
|
||||
response_template: 'Order status: {{ response.status }}, ID: {{ response.order_id }}'
|
||||
)
|
||||
stub_request(:get, 'https://example.com/orders/123')
|
||||
.to_return(status: 200, body: '{"status": "shipped", "order_id": "123"}')
|
||||
end
|
||||
|
||||
it 'formats response using template' do
|
||||
result = tool.perform(tool_context)
|
||||
|
||||
expect(result).to eq('Order status: shipped, ID: 123')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when handling errors' do
|
||||
it 'returns generic error message on network failure' do
|
||||
custom_tool.update!(endpoint_url: 'https://example.com/data')
|
||||
stub_request(:get, 'https://example.com/data').to_raise(SocketError.new('Failed to connect'))
|
||||
|
||||
result = tool.perform(tool_context)
|
||||
|
||||
expect(result).to eq('An error occurred while executing the request')
|
||||
end
|
||||
|
||||
it 'returns generic error message on timeout' do
|
||||
custom_tool.update!(endpoint_url: 'https://example.com/data')
|
||||
stub_request(:get, 'https://example.com/data').to_timeout
|
||||
|
||||
result = tool.perform(tool_context)
|
||||
|
||||
expect(result).to eq('An error occurred while executing the request')
|
||||
end
|
||||
|
||||
it 'returns generic error message on HTTP 404' do
|
||||
custom_tool.update!(endpoint_url: 'https://example.com/data')
|
||||
stub_request(:get, 'https://example.com/data').to_return(status: 404, body: 'Not found')
|
||||
|
||||
result = tool.perform(tool_context)
|
||||
|
||||
expect(result).to eq('An error occurred while executing the request')
|
||||
end
|
||||
|
||||
it 'returns generic error message on HTTP 500' do
|
||||
custom_tool.update!(endpoint_url: 'https://example.com/data')
|
||||
stub_request(:get, 'https://example.com/data').to_return(status: 500, body: 'Server error')
|
||||
|
||||
result = tool.perform(tool_context)
|
||||
|
||||
expect(result).to eq('An error occurred while executing the request')
|
||||
end
|
||||
|
||||
it 'logs error details' do
|
||||
custom_tool.update!(endpoint_url: 'https://example.com/data')
|
||||
stub_request(:get, 'https://example.com/data').to_raise(StandardError.new('Test error'))
|
||||
|
||||
expect(Rails.logger).to receive(:error).with(/HttpTool execution error.*Test error/)
|
||||
|
||||
tool.perform(tool_context)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when integrating with Toolable methods' do
|
||||
it 'correctly integrates URL rendering, body rendering, auth, and response formatting' do
|
||||
custom_tool.update!(
|
||||
http_method: 'POST',
|
||||
endpoint_url: 'https://example.com/users/{{ user_id }}/orders',
|
||||
request_template: '{"product": "{{ product }}", "quantity": {{ quantity }}}',
|
||||
auth_type: 'bearer',
|
||||
auth_config: { 'token' => 'integration_token' },
|
||||
response_template: 'Created order #{{ response.order_number }} for {{ response.product }}'
|
||||
)
|
||||
|
||||
stub_request(:post, 'https://example.com/users/42/orders')
|
||||
.with(
|
||||
body: '{"product": "Widget", "quantity": 5}',
|
||||
headers: {
|
||||
'Authorization' => 'Bearer integration_token',
|
||||
'Content-Type' => 'application/json'
|
||||
}
|
||||
)
|
||||
.to_return(status: 200, body: '{"order_number": "ORD-789", "product": "Widget"}')
|
||||
|
||||
result = tool.perform(tool_context, user_id: '42', product: 'Widget', quantity: 5)
|
||||
|
||||
expect(result).to eq('Created order #ORD-789 for Widget')
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,150 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe 'Devise::Mailer' do
|
||||
describe 'confirmation_instructions with Enterprise features' do
|
||||
let(:account) { create(:account) }
|
||||
let!(:confirmable_user) { create(:user, inviter: inviter_val, account: account) }
|
||||
let(:inviter_val) { nil }
|
||||
let(:mail) { Devise::Mailer.confirmation_instructions(confirmable_user.reload, nil, {}) }
|
||||
|
||||
before do
|
||||
confirmable_user.update!(confirmed_at: nil)
|
||||
confirmable_user.send(:generate_confirmation_token)
|
||||
end
|
||||
|
||||
context 'with SAML enabled account' do
|
||||
let(:saml_settings) { create(:account_saml_settings, account: account) }
|
||||
|
||||
before { saml_settings }
|
||||
|
||||
context 'when user has no inviter' do
|
||||
it 'shows standard welcome message without SSO references' do
|
||||
expect(mail.body).to match('We have a suite of powerful tools ready for you to explore.')
|
||||
expect(mail.body).not_to match('via Single Sign-On')
|
||||
end
|
||||
|
||||
it 'does not show activation instructions for SAML accounts' do
|
||||
expect(mail.body).not_to match('Please take a moment and click the link below and activate your account')
|
||||
end
|
||||
|
||||
it 'shows confirmation link' do
|
||||
expect(mail.body).to include("app/auth/confirmation?confirmation_token=#{confirmable_user.confirmation_token}")
|
||||
end
|
||||
end
|
||||
|
||||
context 'when user has inviter and SAML is enabled' do
|
||||
let(:inviter_val) { create(:user, :administrator, skip_confirmation: true, account: account) }
|
||||
|
||||
it 'mentions SSO invitation' do
|
||||
expect(mail.body).to match(
|
||||
"#{CGI.escapeHTML(inviter_val.name)}, with #{CGI.escapeHTML(account.name)}, has invited you to access.*via Single Sign-On \\(SSO\\)"
|
||||
)
|
||||
end
|
||||
|
||||
it 'explains SSO authentication' do
|
||||
expect(mail.body).to match('Your organization uses SSO for secure authentication')
|
||||
expect(mail.body).to match('You will not need a password to access your account')
|
||||
end
|
||||
|
||||
it 'does not show standard invitation message' do
|
||||
expect(mail.body).not_to match('has invited you to try out')
|
||||
end
|
||||
|
||||
it 'directs to SSO portal instead of password reset' do
|
||||
expect(mail.body).to match('You can access your account by logging in through your organization\'s SSO portal')
|
||||
expect(mail.body).not_to include('app/auth/password/edit')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when user is already confirmed and has inviter' do
|
||||
let(:inviter_val) { create(:user, :administrator, skip_confirmation: true, account: account) }
|
||||
|
||||
before do
|
||||
confirmable_user.confirm
|
||||
end
|
||||
|
||||
it 'shows SSO login instructions' do
|
||||
expect(mail.body).to match('You can now access your account by logging in through your organization\'s SSO portal')
|
||||
expect(mail.body).not_to include('/auth/sign_in')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when user updates email on SAML account' do
|
||||
let(:inviter_val) { create(:user, :administrator, skip_confirmation: true, account: account) }
|
||||
|
||||
before do
|
||||
confirmable_user.update!(email: 'updated@example.com')
|
||||
end
|
||||
|
||||
it 'still shows confirmation link for email verification' do
|
||||
expect(mail.body).to include('app/auth/confirmation?confirmation_token')
|
||||
expect(confirmable_user.unconfirmed_email.blank?).to be false
|
||||
end
|
||||
end
|
||||
|
||||
context 'when user is already confirmed with no inviter' do
|
||||
before do
|
||||
confirmable_user.confirm
|
||||
end
|
||||
|
||||
it 'shows SSO login instructions instead of regular login' do
|
||||
expect(mail.body).to match('You can now access your account by logging in through your organization\'s SSO portal')
|
||||
expect(mail.body).not_to include('/auth/sign_in')
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
context 'when account does not have SAML enabled' do
|
||||
context 'when user has inviter' do
|
||||
let(:inviter_val) { create(:user, :administrator, skip_confirmation: true, account: account) }
|
||||
|
||||
it 'shows standard invitation without SSO references' do
|
||||
expect(mail.body).to match('has invited you to try out Chatwoot')
|
||||
expect(mail.body).not_to match('via Single Sign-On')
|
||||
expect(mail.body).not_to match('SSO portal')
|
||||
end
|
||||
|
||||
it 'shows password reset link' do
|
||||
expect(mail.body).to include('app/auth/password/edit')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when user has no inviter' do
|
||||
it 'shows standard welcome message and activation instructions' do
|
||||
expect(mail.body).to match('We have a suite of powerful tools ready for you to explore')
|
||||
expect(mail.body).to match('Please take a moment and click the link below and activate your account')
|
||||
end
|
||||
|
||||
it 'shows confirmation link' do
|
||||
expect(mail.body).to include("app/auth/confirmation?confirmation_token=#{confirmable_user.confirmation_token}")
|
||||
end
|
||||
end
|
||||
|
||||
context 'when user is already confirmed' do
|
||||
let(:inviter_val) { create(:user, :administrator, skip_confirmation: true, account: account) }
|
||||
|
||||
before do
|
||||
confirmable_user.confirm
|
||||
end
|
||||
|
||||
it 'shows regular login link' do
|
||||
expect(mail.body).to include('/auth/sign_in')
|
||||
expect(mail.body).not_to match('SSO portal')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when user updates email' do
|
||||
before do
|
||||
confirmable_user.update!(email: 'updated@example.com')
|
||||
end
|
||||
|
||||
it 'shows confirmation link for email verification' do
|
||||
expect(mail.body).to include('app/auth/confirmation?confirmation_token')
|
||||
expect(confirmable_user.unconfirmed_email.blank?).to be false
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,134 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe AccountSamlSettings, type: :model do
|
||||
let(:account) { create(:account) }
|
||||
let(:saml_settings) { build(:account_saml_settings, account: account) }
|
||||
|
||||
describe 'associations' do
|
||||
it { is_expected.to belong_to(:account) }
|
||||
end
|
||||
|
||||
describe 'validations' do
|
||||
it 'requires sso_url' do
|
||||
settings = build(:account_saml_settings, account: account, sso_url: nil)
|
||||
expect(settings).not_to be_valid
|
||||
expect(settings.errors[:sso_url]).to include("can't be blank")
|
||||
end
|
||||
|
||||
it 'requires certificate' do
|
||||
settings = build(:account_saml_settings, account: account, certificate: nil)
|
||||
expect(settings).not_to be_valid
|
||||
expect(settings.errors[:certificate]).to include("can't be blank")
|
||||
end
|
||||
|
||||
it 'requires idp_entity_id' do
|
||||
settings = build(:account_saml_settings, account: account, idp_entity_id: nil)
|
||||
expect(settings).not_to be_valid
|
||||
expect(settings.errors[:idp_entity_id]).to include("can't be blank")
|
||||
end
|
||||
end
|
||||
|
||||
describe '#saml_enabled?' do
|
||||
it 'returns true when required fields are present' do
|
||||
settings = build(:account_saml_settings,
|
||||
account: account,
|
||||
sso_url: 'https://example.com/sso',
|
||||
certificate: 'valid-certificate')
|
||||
expect(settings.saml_enabled?).to be true
|
||||
end
|
||||
|
||||
it 'returns false when sso_url is missing' do
|
||||
settings = build(:account_saml_settings,
|
||||
account: account,
|
||||
sso_url: nil,
|
||||
certificate: 'valid-certificate')
|
||||
expect(settings.saml_enabled?).to be false
|
||||
end
|
||||
|
||||
it 'returns false when certificate is missing' do
|
||||
settings = build(:account_saml_settings,
|
||||
account: account,
|
||||
sso_url: 'https://example.com/sso',
|
||||
certificate: nil)
|
||||
expect(settings.saml_enabled?).to be false
|
||||
end
|
||||
end
|
||||
|
||||
describe 'sp_entity_id auto-generation' do
|
||||
it 'automatically generates sp_entity_id when creating' do
|
||||
settings = build(:account_saml_settings, account: account, sp_entity_id: nil)
|
||||
expect(settings).to be_valid
|
||||
settings.save!
|
||||
expect(settings.sp_entity_id).to eq("http://localhost:3000/saml/sp/#{account.id}")
|
||||
end
|
||||
|
||||
it 'does not override existing sp_entity_id' do
|
||||
custom_id = 'https://custom.example.com/saml/sp/123'
|
||||
settings = build(:account_saml_settings, account: account, sp_entity_id: custom_id)
|
||||
settings.save!
|
||||
expect(settings.sp_entity_id).to eq(custom_id)
|
||||
end
|
||||
end
|
||||
|
||||
describe '#certificate_fingerprint' do
|
||||
let(:valid_cert_pem) do
|
||||
key = OpenSSL::PKey::RSA.new(2048)
|
||||
cert = OpenSSL::X509::Certificate.new
|
||||
cert.version = 2
|
||||
cert.serial = 1
|
||||
cert.subject = OpenSSL::X509::Name.parse('/C=US/ST=Test/L=Test/O=Test/CN=test.example.com')
|
||||
cert.issuer = cert.subject
|
||||
cert.public_key = key.public_key
|
||||
cert.not_before = Time.zone.now
|
||||
cert.not_after = cert.not_before + (365 * 24 * 60 * 60)
|
||||
cert.sign(key, OpenSSL::Digest.new('SHA256'))
|
||||
cert.to_pem
|
||||
end
|
||||
|
||||
it 'returns fingerprint for valid certificate' do
|
||||
settings = build(:account_saml_settings, account: account, certificate: valid_cert_pem)
|
||||
fingerprint = settings.certificate_fingerprint
|
||||
|
||||
expect(fingerprint).to be_present
|
||||
expect(fingerprint).to match(/^[A-F0-9]{2}(:[A-F0-9]{2}){19}$/) # SHA1 fingerprint format
|
||||
end
|
||||
|
||||
it 'returns nil for blank certificate' do
|
||||
settings = build(:account_saml_settings, account: account, certificate: '')
|
||||
expect(settings.certificate_fingerprint).to be_nil
|
||||
end
|
||||
|
||||
it 'returns nil for invalid certificate' do
|
||||
settings = build(:account_saml_settings, account: account, certificate: 'invalid-cert-data')
|
||||
expect(settings.certificate_fingerprint).to be_nil
|
||||
end
|
||||
|
||||
it 'formats fingerprint correctly' do
|
||||
settings = build(:account_saml_settings, account: account, certificate: valid_cert_pem)
|
||||
fingerprint = settings.certificate_fingerprint
|
||||
|
||||
# Should be uppercase with colons separating each byte
|
||||
expect(fingerprint).to match(/^[A-F0-9:]+$/)
|
||||
expect(fingerprint.count(':')).to eq(19) # 20 bytes = 19 colons
|
||||
end
|
||||
end
|
||||
|
||||
describe 'callbacks' do
|
||||
describe 'after_create_commit' do
|
||||
it 'queues job to set account users to saml provider' do
|
||||
expect(Saml::UpdateAccountUsersProviderJob).to receive(:perform_later).with(account.id, 'saml')
|
||||
create(:account_saml_settings, account: account)
|
||||
end
|
||||
end
|
||||
|
||||
describe 'after_destroy_commit' do
|
||||
it 'queues job to reset account users provider' do
|
||||
settings = create(:account_saml_settings, account: account)
|
||||
expect(Saml::UpdateAccountUsersProviderJob).to receive(:perform_later).with(account.id, 'email')
|
||||
settings.destroy
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,388 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe Captain::CustomTool, type: :model do
|
||||
describe 'associations' do
|
||||
it { is_expected.to belong_to(:account) }
|
||||
end
|
||||
|
||||
describe 'validations' do
|
||||
it { is_expected.to validate_presence_of(:title) }
|
||||
it { is_expected.to validate_presence_of(:endpoint_url) }
|
||||
it { is_expected.to define_enum_for(:http_method).with_values('GET' => 'GET', 'POST' => 'POST').backed_by_column_of_type(:string) }
|
||||
|
||||
it {
|
||||
expect(subject).to define_enum_for(:auth_type).with_values('none' => 'none', 'bearer' => 'bearer', 'basic' => 'basic',
|
||||
'api_key' => 'api_key').backed_by_column_of_type(:string).with_prefix(:auth)
|
||||
}
|
||||
|
||||
describe 'slug uniqueness' do
|
||||
let(:account) { create(:account) }
|
||||
|
||||
it 'validates uniqueness of slug scoped to account' do
|
||||
create(:captain_custom_tool, account: account, slug: 'custom_test_tool')
|
||||
duplicate = build(:captain_custom_tool, account: account, slug: 'custom_test_tool')
|
||||
|
||||
expect(duplicate).not_to be_valid
|
||||
expect(duplicate.errors[:slug]).to include('has already been taken')
|
||||
end
|
||||
|
||||
it 'allows same slug across different accounts' do
|
||||
account2 = create(:account)
|
||||
create(:captain_custom_tool, account: account, slug: 'custom_test_tool')
|
||||
different_account_tool = build(:captain_custom_tool, account: account2, slug: 'custom_test_tool')
|
||||
|
||||
expect(different_account_tool).to be_valid
|
||||
end
|
||||
end
|
||||
|
||||
describe 'param_schema validation' do
|
||||
let(:account) { create(:account) }
|
||||
|
||||
it 'is valid with proper param_schema' do
|
||||
tool = build(:captain_custom_tool, account: account, param_schema: [
|
||||
{ 'name' => 'order_id', 'type' => 'string', 'description' => 'Order ID', 'required' => true }
|
||||
])
|
||||
|
||||
expect(tool).to be_valid
|
||||
end
|
||||
|
||||
it 'is valid with empty param_schema' do
|
||||
tool = build(:captain_custom_tool, account: account, param_schema: [])
|
||||
|
||||
expect(tool).to be_valid
|
||||
end
|
||||
|
||||
it 'is invalid when param_schema is missing name' do
|
||||
tool = build(:captain_custom_tool, account: account, param_schema: [
|
||||
{ 'type' => 'string', 'description' => 'Order ID' }
|
||||
])
|
||||
|
||||
expect(tool).not_to be_valid
|
||||
end
|
||||
|
||||
it 'is invalid when param_schema is missing type' do
|
||||
tool = build(:captain_custom_tool, account: account, param_schema: [
|
||||
{ 'name' => 'order_id', 'description' => 'Order ID' }
|
||||
])
|
||||
|
||||
expect(tool).not_to be_valid
|
||||
end
|
||||
|
||||
it 'is invalid when param_schema is missing description' do
|
||||
tool = build(:captain_custom_tool, account: account, param_schema: [
|
||||
{ 'name' => 'order_id', 'type' => 'string' }
|
||||
])
|
||||
|
||||
expect(tool).not_to be_valid
|
||||
end
|
||||
|
||||
it 'is invalid with additional properties in param_schema' do
|
||||
tool = build(:captain_custom_tool, account: account, param_schema: [
|
||||
{ 'name' => 'order_id', 'type' => 'string', 'description' => 'Order ID', 'extra_field' => 'value' }
|
||||
])
|
||||
|
||||
expect(tool).not_to be_valid
|
||||
end
|
||||
|
||||
it 'is valid when required field is omitted (defaults to optional param)' do
|
||||
tool = build(:captain_custom_tool, account: account, param_schema: [
|
||||
{ 'name' => 'order_id', 'type' => 'string', 'description' => 'Order ID' }
|
||||
])
|
||||
|
||||
expect(tool).to be_valid
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'scopes' do
|
||||
let(:account) { create(:account) }
|
||||
|
||||
describe '.enabled' do
|
||||
it 'returns only enabled custom tools' do
|
||||
enabled_tool = create(:captain_custom_tool, account: account, enabled: true)
|
||||
disabled_tool = create(:captain_custom_tool, account: account, enabled: false)
|
||||
|
||||
expect(described_class.enabled).to include(enabled_tool)
|
||||
expect(described_class.enabled).not_to include(disabled_tool)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'slug generation' do
|
||||
let(:account) { create(:account) }
|
||||
|
||||
it 'generates slug from title on creation' do
|
||||
tool = create(:captain_custom_tool, account: account, title: 'Fetch Order Status')
|
||||
|
||||
expect(tool.slug).to eq('custom_fetch_order_status')
|
||||
end
|
||||
|
||||
it 'adds custom_ prefix to generated slug' do
|
||||
tool = create(:captain_custom_tool, account: account, title: 'My Tool')
|
||||
|
||||
expect(tool.slug).to start_with('custom_')
|
||||
end
|
||||
|
||||
it 'does not override manually set slug' do
|
||||
tool = create(:captain_custom_tool, account: account, title: 'Test Tool', slug: 'custom_manual_slug')
|
||||
|
||||
expect(tool.slug).to eq('custom_manual_slug')
|
||||
end
|
||||
|
||||
it 'handles slug collisions by appending random suffix' do
|
||||
create(:captain_custom_tool, account: account, title: 'Test Tool', slug: 'custom_test_tool')
|
||||
tool2 = create(:captain_custom_tool, account: account, title: 'Test Tool')
|
||||
|
||||
expect(tool2.slug).to match(/^custom_test_tool_[a-z0-9]{6}$/)
|
||||
end
|
||||
|
||||
it 'handles multiple slug collisions' do
|
||||
create(:captain_custom_tool, account: account, title: 'Test Tool', slug: 'custom_test_tool')
|
||||
create(:captain_custom_tool, account: account, title: 'Test Tool', slug: 'custom_test_tool_abc123')
|
||||
tool3 = create(:captain_custom_tool, account: account, title: 'Test Tool')
|
||||
|
||||
expect(tool3.slug).to match(/^custom_test_tool_[a-z0-9]{6}$/)
|
||||
expect(tool3.slug).not_to eq('custom_test_tool')
|
||||
expect(tool3.slug).not_to eq('custom_test_tool_abc123')
|
||||
end
|
||||
|
||||
it 'does not generate slug when title is blank' do
|
||||
tool = build(:captain_custom_tool, account: account, title: nil)
|
||||
|
||||
expect(tool).not_to be_valid
|
||||
expect(tool.errors[:title]).to include("can't be blank")
|
||||
end
|
||||
|
||||
it 'parameterizes title correctly' do
|
||||
tool = create(:captain_custom_tool, account: account, title: 'Fetch Order Status & Details!')
|
||||
|
||||
expect(tool.slug).to eq('custom_fetch_order_status_details')
|
||||
end
|
||||
end
|
||||
|
||||
describe 'factory' do
|
||||
it 'creates a valid custom tool with default attributes' do
|
||||
tool = create(:captain_custom_tool)
|
||||
|
||||
expect(tool).to be_valid
|
||||
expect(tool.title).to be_present
|
||||
expect(tool.slug).to be_present
|
||||
expect(tool.endpoint_url).to be_present
|
||||
expect(tool.http_method).to eq('GET')
|
||||
expect(tool.auth_type).to eq('none')
|
||||
expect(tool.enabled).to be true
|
||||
end
|
||||
|
||||
it 'creates valid tool with POST trait' do
|
||||
tool = create(:captain_custom_tool, :with_post)
|
||||
|
||||
expect(tool.http_method).to eq('POST')
|
||||
expect(tool.request_template).to be_present
|
||||
end
|
||||
|
||||
it 'creates valid tool with bearer auth trait' do
|
||||
tool = create(:captain_custom_tool, :with_bearer_auth)
|
||||
|
||||
expect(tool.auth_type).to eq('bearer')
|
||||
expect(tool.auth_config['token']).to eq('test_bearer_token_123')
|
||||
end
|
||||
|
||||
it 'creates valid tool with basic auth trait' do
|
||||
tool = create(:captain_custom_tool, :with_basic_auth)
|
||||
|
||||
expect(tool.auth_type).to eq('basic')
|
||||
expect(tool.auth_config['username']).to eq('test_user')
|
||||
expect(tool.auth_config['password']).to eq('test_pass')
|
||||
end
|
||||
|
||||
it 'creates valid tool with api key trait' do
|
||||
tool = create(:captain_custom_tool, :with_api_key)
|
||||
|
||||
expect(tool.auth_type).to eq('api_key')
|
||||
expect(tool.auth_config['key']).to eq('test_api_key')
|
||||
expect(tool.auth_config['location']).to eq('header')
|
||||
end
|
||||
end
|
||||
|
||||
describe 'Toolable concern' do
|
||||
let(:account) { create(:account) }
|
||||
|
||||
describe '#build_request_url' do
|
||||
it 'returns static URL when no template variables present' do
|
||||
tool = create(:captain_custom_tool, account: account, endpoint_url: 'https://api.example.com/orders')
|
||||
|
||||
expect(tool.build_request_url({})).to eq('https://api.example.com/orders')
|
||||
end
|
||||
|
||||
it 'renders URL template with params' do
|
||||
tool = create(:captain_custom_tool, account: account, endpoint_url: 'https://api.example.com/orders/{{ order_id }}')
|
||||
|
||||
expect(tool.build_request_url({ order_id: '12345' })).to eq('https://api.example.com/orders/12345')
|
||||
end
|
||||
|
||||
it 'handles multiple template variables' do
|
||||
tool = create(:captain_custom_tool, account: account,
|
||||
endpoint_url: 'https://api.example.com/{{ resource }}/{{ id }}?details={{ show_details }}')
|
||||
|
||||
result = tool.build_request_url({ resource: 'orders', id: '123', show_details: 'true' })
|
||||
expect(result).to eq('https://api.example.com/orders/123?details=true')
|
||||
end
|
||||
end
|
||||
|
||||
describe '#build_request_body' do
|
||||
it 'returns nil when request_template is blank' do
|
||||
tool = create(:captain_custom_tool, account: account, request_template: nil)
|
||||
|
||||
expect(tool.build_request_body({})).to be_nil
|
||||
end
|
||||
|
||||
it 'renders request body template with params' do
|
||||
tool = create(:captain_custom_tool, account: account,
|
||||
request_template: '{ "order_id": "{{ order_id }}", "source": "chatwoot" }')
|
||||
|
||||
result = tool.build_request_body({ order_id: '12345' })
|
||||
expect(result).to eq('{ "order_id": "12345", "source": "chatwoot" }')
|
||||
end
|
||||
end
|
||||
|
||||
describe '#build_auth_headers' do
|
||||
it 'returns empty hash for none auth type' do
|
||||
tool = create(:captain_custom_tool, account: account, auth_type: 'none')
|
||||
|
||||
expect(tool.build_auth_headers).to eq({})
|
||||
end
|
||||
|
||||
it 'returns bearer token header' do
|
||||
tool = create(:captain_custom_tool, :with_bearer_auth, account: account)
|
||||
|
||||
expect(tool.build_auth_headers).to eq({ 'Authorization' => 'Bearer test_bearer_token_123' })
|
||||
end
|
||||
|
||||
it 'returns API key header when location is header' do
|
||||
tool = create(:captain_custom_tool, :with_api_key, account: account)
|
||||
|
||||
expect(tool.build_auth_headers).to eq({ 'X-API-Key' => 'test_api_key' })
|
||||
end
|
||||
|
||||
it 'returns empty hash for API key when location is not header' do
|
||||
tool = create(:captain_custom_tool, account: account, auth_type: 'api_key',
|
||||
auth_config: { key: 'test_key', location: 'query', name: 'api_key' })
|
||||
|
||||
expect(tool.build_auth_headers).to eq({})
|
||||
end
|
||||
|
||||
it 'returns empty hash for basic auth' do
|
||||
tool = create(:captain_custom_tool, :with_basic_auth, account: account)
|
||||
|
||||
expect(tool.build_auth_headers).to eq({})
|
||||
end
|
||||
end
|
||||
|
||||
describe '#build_basic_auth_credentials' do
|
||||
it 'returns nil for non-basic auth types' do
|
||||
tool = create(:captain_custom_tool, account: account, auth_type: 'none')
|
||||
|
||||
expect(tool.build_basic_auth_credentials).to be_nil
|
||||
end
|
||||
|
||||
it 'returns username and password array for basic auth' do
|
||||
tool = create(:captain_custom_tool, :with_basic_auth, account: account)
|
||||
|
||||
expect(tool.build_basic_auth_credentials).to eq(%w[test_user test_pass])
|
||||
end
|
||||
end
|
||||
|
||||
describe '#format_response' do
|
||||
it 'returns raw response when no response_template' do
|
||||
tool = create(:captain_custom_tool, account: account, response_template: nil)
|
||||
|
||||
expect(tool.format_response('raw response')).to eq('raw response')
|
||||
end
|
||||
|
||||
it 'renders response template with JSON response' do
|
||||
tool = create(:captain_custom_tool, account: account,
|
||||
response_template: 'Order status: {{ response.status }}')
|
||||
raw_response = '{"status": "shipped", "tracking": "123ABC"}'
|
||||
|
||||
result = tool.format_response(raw_response)
|
||||
expect(result).to eq('Order status: shipped')
|
||||
end
|
||||
|
||||
it 'handles response template with multiple fields' do
|
||||
tool = create(:captain_custom_tool, account: account,
|
||||
response_template: 'Order {{ response.id }} is {{ response.status }}. Tracking: {{ response.tracking }}')
|
||||
raw_response = '{"id": "12345", "status": "delivered", "tracking": "ABC123"}'
|
||||
|
||||
result = tool.format_response(raw_response)
|
||||
expect(result).to eq('Order 12345 is delivered. Tracking: ABC123')
|
||||
end
|
||||
|
||||
it 'handles non-JSON response' do
|
||||
tool = create(:captain_custom_tool, account: account,
|
||||
response_template: 'Response: {{ response }}')
|
||||
raw_response = 'plain text response'
|
||||
|
||||
result = tool.format_response(raw_response)
|
||||
expect(result).to eq('Response: plain text response')
|
||||
end
|
||||
end
|
||||
|
||||
describe '#to_tool_metadata' do
|
||||
it 'returns tool metadata hash with custom flag' do
|
||||
tool = create(:captain_custom_tool, account: account,
|
||||
slug: 'custom_test-tool',
|
||||
title: 'Test Tool',
|
||||
description: 'A test tool')
|
||||
|
||||
metadata = tool.to_tool_metadata
|
||||
expect(metadata).to eq({
|
||||
id: 'custom_test-tool',
|
||||
title: 'Test Tool',
|
||||
description: 'A test tool',
|
||||
custom: true
|
||||
})
|
||||
end
|
||||
end
|
||||
|
||||
describe '#tool' do
|
||||
let(:assistant) { create(:captain_assistant, account: account) }
|
||||
|
||||
it 'returns HttpTool instance' do
|
||||
tool = create(:captain_custom_tool, account: account)
|
||||
|
||||
tool_instance = tool.tool(assistant)
|
||||
expect(tool_instance).to be_a(Captain::Tools::HttpTool)
|
||||
end
|
||||
|
||||
it 'sets description on the tool class' do
|
||||
tool = create(:captain_custom_tool, account: account, description: 'Fetches order data')
|
||||
|
||||
tool_instance = tool.tool(assistant)
|
||||
expect(tool_instance.description).to eq('Fetches order data')
|
||||
end
|
||||
|
||||
it 'sets parameters on the tool class' do
|
||||
tool = create(:captain_custom_tool, :with_params, account: account)
|
||||
|
||||
tool_instance = tool.tool(assistant)
|
||||
params = tool_instance.parameters
|
||||
|
||||
expect(params.keys).to contain_exactly(:order_id, :include_details)
|
||||
expect(params[:order_id].name).to eq(:order_id)
|
||||
expect(params[:order_id].type).to eq('string')
|
||||
expect(params[:order_id].description).to eq('The order ID')
|
||||
expect(params[:order_id].required).to be true
|
||||
|
||||
expect(params[:include_details].name).to eq(:include_details)
|
||||
expect(params[:include_details].required).to be false
|
||||
end
|
||||
|
||||
it 'works with empty param_schema' do
|
||||
tool = create(:captain_custom_tool, account: account, param_schema: [])
|
||||
|
||||
tool_instance = tool.tool(assistant)
|
||||
expect(tool_instance.parameters).to be_empty
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -4,6 +4,17 @@ RSpec.describe Captain::Document, type: :model do
|
||||
let(:account) { create(:account) }
|
||||
let(:assistant) { create(:captain_assistant, account: account) }
|
||||
|
||||
describe 'URL normalization' do
|
||||
it 'removes a trailing slash before validation' do
|
||||
document = create(:captain_document,
|
||||
assistant: assistant,
|
||||
account: account,
|
||||
external_link: 'https://example.com/path/')
|
||||
|
||||
expect(document.external_link).to eq('https://example.com/path')
|
||||
end
|
||||
end
|
||||
|
||||
describe 'PDF support' do
|
||||
let(:pdf_document) do
|
||||
doc = build(:captain_document, assistant: assistant, account: account)
|
||||
@@ -82,4 +93,161 @@ RSpec.describe Captain::Document, type: :model do
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'response builder job callback' do
|
||||
before { clear_enqueued_jobs }
|
||||
|
||||
describe 'non-PDF documents' do
|
||||
it 'enqueues when created with available status and content' do
|
||||
expect do
|
||||
create(:captain_document, assistant: assistant, account: account, status: :available)
|
||||
end.to have_enqueued_job(Captain::Documents::ResponseBuilderJob)
|
||||
end
|
||||
|
||||
it 'does not enqueue when created available without content' do
|
||||
expect do
|
||||
create(:captain_document, assistant: assistant, account: account, status: :available, content: nil)
|
||||
end.not_to have_enqueued_job(Captain::Documents::ResponseBuilderJob)
|
||||
end
|
||||
|
||||
it 'enqueues when status transitions to available with existing content' do
|
||||
document = create(:captain_document, assistant: assistant, account: account, status: :in_progress)
|
||||
|
||||
expect do
|
||||
document.update!(status: :available)
|
||||
end.to have_enqueued_job(Captain::Documents::ResponseBuilderJob)
|
||||
end
|
||||
|
||||
it 'does not enqueue when status transitions to available without content' do
|
||||
document = create(
|
||||
:captain_document,
|
||||
assistant: assistant,
|
||||
account: account,
|
||||
status: :in_progress,
|
||||
content: nil
|
||||
)
|
||||
|
||||
expect do
|
||||
document.update!(status: :available)
|
||||
end.not_to have_enqueued_job(Captain::Documents::ResponseBuilderJob)
|
||||
end
|
||||
|
||||
it 'enqueues when content is populated on an available document' do
|
||||
document = create(
|
||||
:captain_document,
|
||||
assistant: assistant,
|
||||
account: account,
|
||||
status: :available,
|
||||
content: nil
|
||||
)
|
||||
clear_enqueued_jobs
|
||||
|
||||
expect do
|
||||
document.update!(content: 'Fresh content from crawl')
|
||||
end.to have_enqueued_job(Captain::Documents::ResponseBuilderJob)
|
||||
end
|
||||
|
||||
it 'enqueues when content changes on an available document' do
|
||||
document = create(
|
||||
:captain_document,
|
||||
assistant: assistant,
|
||||
account: account,
|
||||
status: :available,
|
||||
content: 'Initial content'
|
||||
)
|
||||
clear_enqueued_jobs
|
||||
|
||||
expect do
|
||||
document.update!(content: 'Updated crawl content')
|
||||
end.to have_enqueued_job(Captain::Documents::ResponseBuilderJob)
|
||||
end
|
||||
|
||||
it 'does not enqueue when content is cleared on an available document' do
|
||||
document = create(
|
||||
:captain_document,
|
||||
assistant: assistant,
|
||||
account: account,
|
||||
status: :available,
|
||||
content: 'Initial content'
|
||||
)
|
||||
clear_enqueued_jobs
|
||||
|
||||
expect do
|
||||
document.update!(content: nil)
|
||||
end.not_to have_enqueued_job(Captain::Documents::ResponseBuilderJob)
|
||||
end
|
||||
|
||||
it 'does not enqueue for metadata-only updates' do
|
||||
document = create(:captain_document, assistant: assistant, account: account, status: :available)
|
||||
clear_enqueued_jobs
|
||||
|
||||
expect do
|
||||
document.update!(metadata: { 'title' => 'Updated Again' })
|
||||
end.not_to have_enqueued_job(Captain::Documents::ResponseBuilderJob)
|
||||
end
|
||||
|
||||
it 'does not enqueue while document remains in progress' do
|
||||
document = create(:captain_document, assistant: assistant, account: account, status: :in_progress)
|
||||
|
||||
expect do
|
||||
document.update!(metadata: { 'title' => 'Updated' })
|
||||
end.not_to have_enqueued_job(Captain::Documents::ResponseBuilderJob)
|
||||
end
|
||||
end
|
||||
|
||||
describe 'PDF documents' do
|
||||
def build_pdf_document(status:, content:)
|
||||
build(
|
||||
:captain_document,
|
||||
assistant: assistant,
|
||||
account: account,
|
||||
status: status,
|
||||
content: content
|
||||
).tap do |doc|
|
||||
doc.pdf_file.attach(
|
||||
io: StringIO.new('PDF content'),
|
||||
filename: 'sample.pdf',
|
||||
content_type: 'application/pdf'
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
it 'enqueues when created available without content' do
|
||||
document = build_pdf_document(status: :available, content: nil)
|
||||
|
||||
expect do
|
||||
document.save!
|
||||
end.to have_enqueued_job(Captain::Documents::ResponseBuilderJob)
|
||||
end
|
||||
|
||||
it 'enqueues when status transitions to available' do
|
||||
document = build_pdf_document(status: :in_progress, content: nil)
|
||||
document.save!
|
||||
clear_enqueued_jobs
|
||||
|
||||
expect do
|
||||
document.update!(status: :available)
|
||||
end.to have_enqueued_job(Captain::Documents::ResponseBuilderJob)
|
||||
end
|
||||
|
||||
it 'does not enqueue when content updates without status change' do
|
||||
document = build_pdf_document(status: :available, content: nil)
|
||||
document.save!
|
||||
clear_enqueued_jobs
|
||||
|
||||
expect do
|
||||
document.update!(content: 'Extracted PDF text')
|
||||
end.not_to have_enqueued_job(Captain::Documents::ResponseBuilderJob)
|
||||
end
|
||||
end
|
||||
|
||||
it 'does not enqueue when the document is destroyed' do
|
||||
document = create(:captain_document, assistant: assistant, account: account, status: :available)
|
||||
clear_enqueued_jobs
|
||||
|
||||
expect do
|
||||
document.destroy!
|
||||
end.not_to have_enqueued_job(Captain::Documents::ResponseBuilderJob)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -48,9 +48,9 @@ RSpec.describe Captain::Scenario, type: :model do
|
||||
|
||||
before do
|
||||
# Mock available tools
|
||||
allow(described_class).to receive(:available_tool_ids).and_return(%w[
|
||||
add_contact_note add_private_note update_priority
|
||||
])
|
||||
allow(described_class).to receive(:built_in_tool_ids).and_return(%w[
|
||||
add_contact_note add_private_note update_priority
|
||||
])
|
||||
end
|
||||
|
||||
describe 'validate_instruction_tools' do
|
||||
@@ -102,6 +102,49 @@ RSpec.describe Captain::Scenario, type: :model do
|
||||
expect(scenario).not_to be_valid
|
||||
expect(scenario.errors[:instruction]).not_to include(/contains invalid tools/)
|
||||
end
|
||||
|
||||
it 'is valid with custom tool references' do
|
||||
create(:captain_custom_tool, account: account, slug: 'custom_fetch-order')
|
||||
scenario = build(:captain_scenario,
|
||||
assistant: assistant,
|
||||
account: account,
|
||||
instruction: 'Use [@Fetch Order](tool://custom_fetch-order) to get order details')
|
||||
|
||||
expect(scenario).to be_valid
|
||||
end
|
||||
|
||||
it 'is invalid with custom tool from different account' do
|
||||
other_account = create(:account)
|
||||
create(:captain_custom_tool, account: other_account, slug: 'custom_fetch-order')
|
||||
scenario = build(:captain_scenario,
|
||||
assistant: assistant,
|
||||
account: account,
|
||||
instruction: 'Use [@Fetch Order](tool://custom_fetch-order) to get order details')
|
||||
|
||||
expect(scenario).not_to be_valid
|
||||
expect(scenario.errors[:instruction]).to include('contains invalid tools: custom_fetch-order')
|
||||
end
|
||||
|
||||
it 'is invalid with disabled custom tool' do
|
||||
create(:captain_custom_tool, account: account, slug: 'custom_fetch-order', enabled: false)
|
||||
scenario = build(:captain_scenario,
|
||||
assistant: assistant,
|
||||
account: account,
|
||||
instruction: 'Use [@Fetch Order](tool://custom_fetch-order) to get order details')
|
||||
|
||||
expect(scenario).not_to be_valid
|
||||
expect(scenario.errors[:instruction]).to include('contains invalid tools: custom_fetch-order')
|
||||
end
|
||||
|
||||
it 'is valid with mixed static and custom tool references' do
|
||||
create(:captain_custom_tool, account: account, slug: 'custom_fetch-order')
|
||||
scenario = build(:captain_scenario,
|
||||
assistant: assistant,
|
||||
account: account,
|
||||
instruction: 'Use [@Add Note](tool://add_contact_note) and [@Fetch Order](tool://custom_fetch-order)')
|
||||
|
||||
expect(scenario).to be_valid
|
||||
end
|
||||
end
|
||||
|
||||
describe 'resolve_tool_references' do
|
||||
@@ -146,6 +189,140 @@ RSpec.describe Captain::Scenario, type: :model do
|
||||
end
|
||||
end
|
||||
|
||||
describe 'custom tool integration' do
|
||||
let(:account) { create(:account) }
|
||||
let(:assistant) { create(:captain_assistant, account: account) }
|
||||
|
||||
before do
|
||||
allow(described_class).to receive(:built_in_tool_ids).and_return(%w[add_contact_note])
|
||||
allow(described_class).to receive(:built_in_agent_tools).and_return([
|
||||
{ id: 'add_contact_note', title: 'Add Contact Note',
|
||||
description: 'Add a note' }
|
||||
])
|
||||
end
|
||||
|
||||
describe '#resolved_tools' do
|
||||
it 'includes custom tool metadata' do
|
||||
create(:captain_custom_tool, account: account, slug: 'custom_fetch-order',
|
||||
title: 'Fetch Order', description: 'Gets order details')
|
||||
scenario = create(:captain_scenario,
|
||||
assistant: assistant,
|
||||
account: account,
|
||||
instruction: 'Use [@Fetch Order](tool://custom_fetch-order)')
|
||||
|
||||
resolved = scenario.send(:resolved_tools)
|
||||
expect(resolved.length).to eq(1)
|
||||
expect(resolved.first[:id]).to eq('custom_fetch-order')
|
||||
expect(resolved.first[:title]).to eq('Fetch Order')
|
||||
expect(resolved.first[:description]).to eq('Gets order details')
|
||||
end
|
||||
|
||||
it 'includes both static and custom tools' do
|
||||
create(:captain_custom_tool, account: account, slug: 'custom_fetch-order')
|
||||
scenario = create(:captain_scenario,
|
||||
assistant: assistant,
|
||||
account: account,
|
||||
instruction: 'Use [@Add Note](tool://add_contact_note) and [@Fetch Order](tool://custom_fetch-order)')
|
||||
|
||||
resolved = scenario.send(:resolved_tools)
|
||||
expect(resolved.length).to eq(2)
|
||||
expect(resolved.map { |t| t[:id] }).to contain_exactly('add_contact_note', 'custom_fetch-order')
|
||||
end
|
||||
|
||||
it 'excludes disabled custom tools' do
|
||||
custom_tool = create(:captain_custom_tool, account: account, slug: 'custom_fetch-order', enabled: true)
|
||||
scenario = create(:captain_scenario,
|
||||
assistant: assistant,
|
||||
account: account,
|
||||
instruction: 'Use [@Fetch Order](tool://custom_fetch-order)')
|
||||
|
||||
custom_tool.update!(enabled: false)
|
||||
|
||||
resolved = scenario.send(:resolved_tools)
|
||||
expect(resolved).to be_empty
|
||||
end
|
||||
end
|
||||
|
||||
describe '#resolve_tool_instance' do
|
||||
it 'returns HttpTool instance for custom tools' do
|
||||
create(:captain_custom_tool, account: account, slug: 'custom_fetch-order')
|
||||
scenario = create(:captain_scenario, assistant: assistant, account: account)
|
||||
|
||||
tool_metadata = { id: 'custom_fetch-order', custom: true }
|
||||
tool_instance = scenario.send(:resolve_tool_instance, tool_metadata)
|
||||
expect(tool_instance).to be_a(Captain::Tools::HttpTool)
|
||||
end
|
||||
|
||||
it 'returns nil for disabled custom tools' do
|
||||
create(:captain_custom_tool, account: account, slug: 'custom_fetch-order', enabled: false)
|
||||
scenario = create(:captain_scenario, assistant: assistant, account: account)
|
||||
|
||||
tool_metadata = { id: 'custom_fetch-order', custom: true }
|
||||
tool_instance = scenario.send(:resolve_tool_instance, tool_metadata)
|
||||
expect(tool_instance).to be_nil
|
||||
end
|
||||
|
||||
it 'returns static tool instance for non-custom tools' do
|
||||
scenario = create(:captain_scenario, assistant: assistant, account: account)
|
||||
allow(described_class).to receive(:resolve_tool_class).with('add_contact_note').and_return(
|
||||
Class.new do
|
||||
def initialize(_assistant); end
|
||||
end
|
||||
)
|
||||
|
||||
tool_metadata = { id: 'add_contact_note' }
|
||||
tool_instance = scenario.send(:resolve_tool_instance, tool_metadata)
|
||||
expect(tool_instance).not_to be_nil
|
||||
expect(tool_instance).not_to be_a(Captain::Tools::HttpTool)
|
||||
end
|
||||
end
|
||||
|
||||
describe '#agent_tools' do
|
||||
it 'returns array of tool instances including custom tools' do
|
||||
create(:captain_custom_tool, account: account, slug: 'custom_fetch-order')
|
||||
scenario = create(:captain_scenario,
|
||||
assistant: assistant,
|
||||
account: account,
|
||||
instruction: 'Use [@Fetch Order](tool://custom_fetch-order)')
|
||||
|
||||
tools = scenario.send(:agent_tools)
|
||||
expect(tools.length).to eq(1)
|
||||
expect(tools.first).to be_a(Captain::Tools::HttpTool)
|
||||
end
|
||||
|
||||
it 'excludes disabled custom tools from execution' do
|
||||
custom_tool = create(:captain_custom_tool, account: account, slug: 'custom_fetch-order', enabled: true)
|
||||
scenario = create(:captain_scenario,
|
||||
assistant: assistant,
|
||||
account: account,
|
||||
instruction: 'Use [@Fetch Order](tool://custom_fetch-order)')
|
||||
|
||||
custom_tool.update!(enabled: false)
|
||||
|
||||
tools = scenario.send(:agent_tools)
|
||||
expect(tools).to be_empty
|
||||
end
|
||||
|
||||
it 'returns mixed static and custom tool instances' do
|
||||
create(:captain_custom_tool, account: account, slug: 'custom_fetch-order')
|
||||
scenario = create(:captain_scenario,
|
||||
assistant: assistant,
|
||||
account: account,
|
||||
instruction: 'Use [@Add Note](tool://add_contact_note) and [@Fetch Order](tool://custom_fetch-order)')
|
||||
|
||||
allow(described_class).to receive(:resolve_tool_class).with('add_contact_note').and_return(
|
||||
Class.new do
|
||||
def initialize(_assistant); end
|
||||
end
|
||||
)
|
||||
|
||||
tools = scenario.send(:agent_tools)
|
||||
expect(tools.length).to eq(2)
|
||||
expect(tools.last).to be_a(Captain::Tools::HttpTool)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'factory' do
|
||||
it 'creates a valid scenario with associations' do
|
||||
account = create(:account)
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe Company, type: :model do
|
||||
context 'with validations' do
|
||||
it { is_expected.to validate_presence_of(:account_id) }
|
||||
it { is_expected.to validate_presence_of(:name) }
|
||||
it { is_expected.to validate_length_of(:name).is_at_most(100) }
|
||||
it { is_expected.to validate_length_of(:description).is_at_most(1000) }
|
||||
|
||||
describe 'domain validation' do
|
||||
it { is_expected.to allow_value('example.com').for(:domain) }
|
||||
it { is_expected.to allow_value('sub.example.com').for(:domain) }
|
||||
it { is_expected.to allow_value('').for(:domain) }
|
||||
it { is_expected.to allow_value(nil).for(:domain) }
|
||||
it { is_expected.not_to allow_value('invalid-domain').for(:domain) }
|
||||
it { is_expected.not_to allow_value('.example.com').for(:domain) }
|
||||
end
|
||||
end
|
||||
|
||||
context 'with associations' do
|
||||
it { is_expected.to belong_to(:account) }
|
||||
it { is_expected.to have_many(:contacts).dependent(:nullify) }
|
||||
end
|
||||
|
||||
describe 'scopes' do
|
||||
let(:account) { create(:account) }
|
||||
let!(:company_b) { create(:company, name: 'B Company', account: account) }
|
||||
let!(:company_a) { create(:company, name: 'A Company', account: account) }
|
||||
let!(:company_c) { create(:company, name: 'C Company', account: account) }
|
||||
|
||||
describe '.ordered_by_name' do
|
||||
it 'orders companies by name alphabetically' do
|
||||
companies = described_class.where(account: account).ordered_by_name
|
||||
expect(companies.map(&:name)).to eq([company_a.name, company_b.name, company_c.name])
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -42,58 +42,6 @@ RSpec.describe Concerns::CaptainToolsHelpers, type: :concern do
|
||||
end
|
||||
end
|
||||
|
||||
describe '.available_agent_tools' do
|
||||
before do
|
||||
# Mock the YAML file loading
|
||||
allow(YAML).to receive(:load_file).and_return([
|
||||
{
|
||||
'id' => 'add_contact_note',
|
||||
'title' => 'Add Contact Note',
|
||||
'description' => 'Add a note to a contact',
|
||||
'icon' => 'note-add'
|
||||
},
|
||||
{
|
||||
'id' => 'invalid_tool',
|
||||
'title' => 'Invalid Tool',
|
||||
'description' => 'This tool does not exist',
|
||||
'icon' => 'invalid'
|
||||
}
|
||||
])
|
||||
|
||||
# Mock class resolution - only add_contact_note exists
|
||||
allow(test_class).to receive(:resolve_tool_class) do |tool_id|
|
||||
case tool_id
|
||||
when 'add_contact_note'
|
||||
Captain::Tools::AddContactNoteTool
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
it 'returns only resolvable tools' do
|
||||
tools = test_class.available_agent_tools
|
||||
|
||||
expect(tools.length).to eq(1)
|
||||
expect(tools.first).to eq({
|
||||
id: 'add_contact_note',
|
||||
title: 'Add Contact Note',
|
||||
description: 'Add a note to a contact',
|
||||
icon: 'note-add'
|
||||
})
|
||||
end
|
||||
|
||||
it 'logs warnings for unresolvable tools' do
|
||||
expect(Rails.logger).to receive(:warn).with('Tool class not found for ID: invalid_tool')
|
||||
|
||||
test_class.available_agent_tools
|
||||
end
|
||||
|
||||
it 'memoizes the result' do
|
||||
expect(YAML).to receive(:load_file).once.and_return([])
|
||||
|
||||
2.times { test_class.available_agent_tools }
|
||||
end
|
||||
end
|
||||
|
||||
describe '.resolve_tool_class' do
|
||||
it 'resolves valid tool classes' do
|
||||
# Mock the constantize to return a class
|
||||
@@ -116,28 +64,6 @@ RSpec.describe Concerns::CaptainToolsHelpers, type: :concern do
|
||||
end
|
||||
end
|
||||
|
||||
describe '.available_tool_ids' do
|
||||
before do
|
||||
allow(test_class).to receive(:available_agent_tools).and_return([
|
||||
{ id: 'add_contact_note', title: 'Add Contact Note', description: '...',
|
||||
icon: 'note' },
|
||||
{ id: 'update_priority', title: 'Update Priority', description: '...',
|
||||
icon: 'priority' }
|
||||
])
|
||||
end
|
||||
|
||||
it 'returns array of tool IDs' do
|
||||
ids = test_class.available_tool_ids
|
||||
expect(ids).to eq(%w[add_contact_note update_priority])
|
||||
end
|
||||
|
||||
it 'memoizes the result' do
|
||||
expect(test_class).to receive(:available_agent_tools).once.and_return([])
|
||||
|
||||
2.times { test_class.available_tool_ids }
|
||||
end
|
||||
end
|
||||
|
||||
describe '#extract_tool_ids_from_text' do
|
||||
it 'extracts tool IDs from text' do
|
||||
text = 'First [@Add Contact Note](tool://add_contact_note) then [@Update Priority](tool://update_priority)'
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe Contact, type: :model do
|
||||
describe 'company auto-association' do
|
||||
let(:account) { create(:account) }
|
||||
|
||||
context 'when creating a new contact with business email' do
|
||||
it 'automatically creates and associates a company' do
|
||||
expect do
|
||||
create(:contact, email: 'john@acme.com', account: account)
|
||||
end.to change(Company, :count).by(1)
|
||||
contact = described_class.last
|
||||
expect(contact.company).to be_present
|
||||
expect(contact.company.domain).to eq('acme.com')
|
||||
end
|
||||
|
||||
it 'does not create company for free email providers' do
|
||||
expect do
|
||||
create(:contact, email: 'john@gmail.com', account: account)
|
||||
end.not_to change(Company, :count)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when updating a contact to add email for first time' do
|
||||
it 'creates and associates company' do
|
||||
contact = create(:contact, email: nil, account: account)
|
||||
expect do
|
||||
contact.update(email: 'john@acme.com')
|
||||
end.to change(Company, :count).by(1)
|
||||
contact.reload
|
||||
expect(contact.company.domain).to eq('acme.com')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when updating a contact that already has a company' do
|
||||
it 'does not change company when email changes' do
|
||||
existing_company = create(:company, domain: 'oldcompany.com', account: account)
|
||||
contact = create(:contact, email: 'john@oldcompany.com', company: existing_company, account: account)
|
||||
|
||||
expect do
|
||||
contact.update(email: 'john@new_company.com')
|
||||
end.not_to change(Company, :count)
|
||||
contact.reload
|
||||
expect(contact.company).to eq(existing_company)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when multiple contacts share the same domain' do
|
||||
it 'associates all contacts with the same company' do
|
||||
contacts = ['john@acme.com', 'jane@acme.com', 'bob@acme.com']
|
||||
contacts.each do |contact|
|
||||
create(:contact, email: contact, account: account)
|
||||
end
|
||||
|
||||
expect(Company.where(domain: 'acme.com', account: account).count).to eq(1)
|
||||
company = Company.find_by(domain: 'acme.com', account: account)
|
||||
expect(company.contacts.count).to eq(contacts.length)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -15,8 +15,8 @@ RSpec.describe Inbox do
|
||||
create(:conversation, inbox: inbox, assignee: inbox_member_1.user)
|
||||
# to test conversations in other inboxes won't impact
|
||||
create_list(:conversation, 3, assignee: inbox_member_1.user)
|
||||
create_list(:conversation, 2, inbox: inbox, assignee: inbox_member_2.user)
|
||||
create_list(:conversation, 3, inbox: inbox, assignee: inbox_member_3.user)
|
||||
create_list(:conversation, 2, inbox: inbox, account: inbox.account, assignee: inbox_member_2.user)
|
||||
create_list(:conversation, 3, inbox: inbox, account: inbox.account, assignee: inbox_member_3.user)
|
||||
end
|
||||
|
||||
it 'validated max_assignment_limit' do
|
||||
@@ -33,7 +33,7 @@ RSpec.describe Inbox do
|
||||
end
|
||||
|
||||
it 'returns all member ids when inbox max_assignment_limit is not configured' do
|
||||
expect(inbox.member_ids_with_assignment_capacity).to eq(inbox.members.ids)
|
||||
expect(inbox.member_ids_with_assignment_capacity).to match_array(inbox.members.ids)
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe CompanyPolicy, type: :policy do
|
||||
subject(:company_policy) { described_class }
|
||||
|
||||
let(:account) { create(:account) }
|
||||
let(:administrator) { create(:user, :administrator, account: account) }
|
||||
let(:agent) { create(:user, account: account) }
|
||||
let(:company) { create(:company, account: account) }
|
||||
|
||||
let(:administrator_context) { { user: administrator, account: account, account_user: account.account_users.first } }
|
||||
let(:agent_context) { { user: agent, account: account, account_user: account.account_users.first } }
|
||||
|
||||
permissions :index?, :show?, :create?, :update? do
|
||||
context 'when administrator' do
|
||||
it { expect(company_policy).to permit(administrator_context, company) }
|
||||
end
|
||||
|
||||
context 'when agent' do
|
||||
it { expect(company_policy).to permit(agent_context, company) }
|
||||
end
|
||||
end
|
||||
|
||||
permissions :destroy? do
|
||||
context 'when administrator' do
|
||||
it { expect(company_policy).to permit(administrator_context, company) }
|
||||
end
|
||||
|
||||
context 'when agent' do
|
||||
it { expect(company_policy).not_to permit(agent_context, company) }
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,65 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe ConversationPolicy, type: :policy do
|
||||
subject { described_class }
|
||||
|
||||
let(:account) { create(:account) }
|
||||
let(:agent) { create(:user, account: account, role: :agent) }
|
||||
let(:inbox) { create(:inbox, account: account) }
|
||||
let(:agent_account_user) { agent.account_users.find_by(account: account) }
|
||||
let(:context) { { user: agent, account: account, account_user: agent_account_user } }
|
||||
|
||||
before do
|
||||
create(:inbox_member, user: agent, inbox: inbox)
|
||||
end
|
||||
|
||||
permissions :show? do
|
||||
context 'when role grants conversation_unassigned_manage' do
|
||||
let(:custom_role) { create(:custom_role, account: account, permissions: ['conversation_unassigned_manage']) }
|
||||
|
||||
before do
|
||||
agent_account_user.update!(role: :agent, custom_role: custom_role)
|
||||
end
|
||||
|
||||
it 'allows access to conversations assigned to the agent' do
|
||||
conversation = create(:conversation, account: account, inbox: inbox, assignee: agent)
|
||||
|
||||
expect(subject).to permit(context, conversation)
|
||||
end
|
||||
|
||||
it 'denies access to conversations assigned to someone else' do
|
||||
other_agent = create(:user, account: account, role: :agent)
|
||||
conversation = create(:conversation, account: account, inbox: inbox, assignee: other_agent)
|
||||
|
||||
expect(subject).not_to permit(context, conversation)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when role grants conversation_participating_manage' do
|
||||
let(:custom_role) { create(:custom_role, account: account, permissions: ['conversation_participating_manage']) }
|
||||
|
||||
before do
|
||||
agent_account_user.update!(role: :agent, custom_role: custom_role)
|
||||
end
|
||||
|
||||
it 'allows access to conversations assigned to the agent' do
|
||||
conversation = create(:conversation, account: account, inbox: inbox, assignee: agent)
|
||||
|
||||
expect(subject).to permit(context, conversation)
|
||||
end
|
||||
|
||||
it 'allows access to conversations where the agent is a participant' do
|
||||
conversation = create(:conversation, account: account, inbox: inbox, assignee: nil)
|
||||
create(:conversation_participant, conversation: conversation, account: account, user: agent)
|
||||
|
||||
expect(subject).to permit(context, conversation)
|
||||
end
|
||||
|
||||
it 'denies access to unrelated conversations' do
|
||||
conversation = create(:conversation, account: account, inbox: inbox, assignee: nil)
|
||||
|
||||
expect(subject).not_to permit(context, conversation)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -13,7 +13,7 @@ RSpec.describe Captain::Assistant::AgentRunnerService do
|
||||
let(:mock_runner) { instance_double(Agents::Runner) }
|
||||
let(:mock_agent) { instance_double(Agents::Agent) }
|
||||
let(:mock_scenario_agent) { instance_double(Agents::Agent) }
|
||||
let(:mock_result) { instance_double(Agents::RunResult, output: { 'response' => 'Test response' }) }
|
||||
let(:mock_result) { instance_double(Agents::RunResult, output: { 'response' => 'Test response' }, context: nil) }
|
||||
|
||||
let(:message_history) do
|
||||
[
|
||||
@@ -90,7 +90,8 @@ RSpec.describe Captain::Assistant::AgentRunnerService do
|
||||
|
||||
expect(mock_runner).to receive(:run).with(
|
||||
'I need help with my account',
|
||||
context: expected_context
|
||||
context: expected_context,
|
||||
max_turns: 100
|
||||
)
|
||||
|
||||
service.generate_response(message_history: message_history)
|
||||
@@ -99,7 +100,7 @@ RSpec.describe Captain::Assistant::AgentRunnerService do
|
||||
it 'processes and formats agent result' do
|
||||
result = service.generate_response(message_history: message_history)
|
||||
|
||||
expect(result).to eq({ 'response' => 'Test response' })
|
||||
expect(result).to eq({ 'response' => 'Test response', 'agent_name' => nil })
|
||||
end
|
||||
|
||||
context 'when no scenarios are enabled' do
|
||||
@@ -118,14 +119,15 @@ RSpec.describe Captain::Assistant::AgentRunnerService do
|
||||
end
|
||||
|
||||
context 'when agent result is a string' do
|
||||
let(:mock_result) { instance_double(Agents::RunResult, output: 'Simple string response') }
|
||||
let(:mock_result) { instance_double(Agents::RunResult, output: 'Simple string response', context: nil) }
|
||||
|
||||
it 'formats string response correctly' do
|
||||
result = service.generate_response(message_history: message_history)
|
||||
|
||||
expect(result).to eq({
|
||||
'response' => 'Simple string response',
|
||||
'reasoning' => 'Processed by agent'
|
||||
'reasoning' => 'Processed by agent',
|
||||
'agent_name' => nil
|
||||
})
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe Captain::Onboarding::WebsiteAnalyzerService do
|
||||
let(:website_url) { 'https://example.com' }
|
||||
let(:service) { described_class.new(website_url) }
|
||||
let(:mock_crawler) { instance_double(Captain::Tools::SimplePageCrawlService) }
|
||||
let(:mock_client) { instance_double(OpenAI::Client) }
|
||||
|
||||
before do
|
||||
create(:installation_config, name: 'CAPTAIN_OPEN_AI_API_KEY', value: 'test-key')
|
||||
allow(Captain::Tools::SimplePageCrawlService).to receive(:new).and_return(mock_crawler)
|
||||
allow(service).to receive(:client).and_return(mock_client)
|
||||
allow(service).to receive(:model).and_return('gpt-3.5-turbo')
|
||||
end
|
||||
|
||||
describe '#analyze' do
|
||||
context 'when website content is available and OpenAI call is successful' do
|
||||
let(:openai_response) do
|
||||
{
|
||||
'choices' => [{
|
||||
'message' => {
|
||||
'content' => {
|
||||
'business_name' => 'Example Corp',
|
||||
'suggested_assistant_name' => 'Alex from Example Corp',
|
||||
'description' => 'You specialize in helping customers with business solutions and support'
|
||||
}.to_json
|
||||
}
|
||||
}]
|
||||
}
|
||||
end
|
||||
|
||||
before do
|
||||
allow(mock_crawler).to receive(:body_text_content).and_return('Welcome to Example Corp')
|
||||
allow(mock_crawler).to receive(:page_title).and_return('Example Corp - Home')
|
||||
allow(mock_crawler).to receive(:meta_description).and_return('Leading provider of business solutions')
|
||||
allow(mock_crawler).to receive(:favicon_url).and_return('https://example.com/favicon.ico')
|
||||
allow(mock_client).to receive(:chat).and_return(openai_response)
|
||||
end
|
||||
|
||||
it 'returns success' do
|
||||
result = service.analyze
|
||||
|
||||
expect(result[:success]).to be true
|
||||
expect(result[:data]).to include(
|
||||
business_name: 'Example Corp',
|
||||
suggested_assistant_name: 'Alex from Example Corp',
|
||||
description: 'You specialize in helping customers with business solutions and support',
|
||||
website_url: website_url,
|
||||
favicon_url: 'https://example.com/favicon.ico'
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when website content is errored' do
|
||||
before do
|
||||
allow(mock_crawler).to receive(:body_text_content).and_raise(StandardError, 'Network error')
|
||||
end
|
||||
|
||||
it 'returns error' do
|
||||
result = service.analyze
|
||||
|
||||
expect(result[:success]).to be false
|
||||
expect(result[:error]).to eq('Failed to fetch website content')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when website content is unavailable' do
|
||||
before do
|
||||
allow(mock_crawler).to receive(:body_text_content).and_return('')
|
||||
allow(mock_crawler).to receive(:page_title).and_return('')
|
||||
allow(mock_crawler).to receive(:meta_description).and_return('')
|
||||
end
|
||||
|
||||
it 'returns error' do
|
||||
result = service.analyze
|
||||
|
||||
expect(result[:success]).to be false
|
||||
expect(result[:error]).to eq('Failed to fetch website content')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when OpenAI error' do
|
||||
before do
|
||||
allow(mock_crawler).to receive(:body_text_content).and_return('Welcome to Example Corp')
|
||||
allow(mock_crawler).to receive(:page_title).and_return('Example Corp - Home')
|
||||
allow(mock_crawler).to receive(:meta_description).and_return('Leading provider of business solutions')
|
||||
allow(mock_crawler).to receive(:favicon_url).and_return('https://example.com/favicon.ico')
|
||||
allow(mock_client).to receive(:chat).and_raise(StandardError, 'API error')
|
||||
end
|
||||
|
||||
it 'returns error' do
|
||||
result = service.analyze
|
||||
|
||||
expect(result[:success]).to be false
|
||||
expect(result[:error]).to eq('API error')
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -125,4 +125,63 @@ RSpec.describe Captain::Tools::SimplePageCrawlService do
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
describe '#meta_description' do
|
||||
context 'when meta description exists' do
|
||||
before do
|
||||
stub_request(:get, base_url)
|
||||
.to_return(body: '<html><head><meta name="description" content="This is a test page description"></head></html>')
|
||||
end
|
||||
|
||||
it 'returns the meta description content' do
|
||||
expect(service.meta_description).to eq('This is a test page description')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when meta description does not exist' do
|
||||
before do
|
||||
stub_request(:get, base_url)
|
||||
.to_return(body: '<html><head><title>Test</title></head></html>')
|
||||
end
|
||||
|
||||
it 'returns nil' do
|
||||
expect(service.meta_description).to be_nil
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe '#favicon_url' do
|
||||
context 'when favicon exists with relative URL' do
|
||||
before do
|
||||
stub_request(:get, base_url)
|
||||
.to_return(body: '<html><head><link rel="icon" href="/favicon.ico"></head></html>')
|
||||
end
|
||||
|
||||
it 'returns the resolved absolute favicon URL' do
|
||||
expect(service.favicon_url).to eq('https://example.com/favicon.ico')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when favicon exists with absolute URL' do
|
||||
before do
|
||||
stub_request(:get, base_url)
|
||||
.to_return(body: '<html><head><link rel="icon" href="https://cdn.example.com/favicon.ico"></head></html>')
|
||||
end
|
||||
|
||||
it 'returns the absolute favicon URL' do
|
||||
expect(service.favicon_url).to eq('https://cdn.example.com/favicon.ico')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when favicon does not exist' do
|
||||
before do
|
||||
stub_request(:get, base_url)
|
||||
.to_return(body: '<html><head><title>Test</title></head></html>')
|
||||
end
|
||||
|
||||
it 'returns nil' do
|
||||
expect(service.favicon_url).to be_nil
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe Companies::BusinessEmailDetectorService, type: :service do
|
||||
let(:service) { described_class.new(email) }
|
||||
|
||||
describe '#perform' do
|
||||
context 'when email is from a business domain' do
|
||||
let(:email) { 'user@acme.com' }
|
||||
let(:valid_email_address) { instance_double(ValidEmail2::Address, valid?: true, disposable_domain?: false) }
|
||||
|
||||
before do
|
||||
allow(ValidEmail2::Address).to receive(:new).with(email).and_return(valid_email_address)
|
||||
allow(EmailProviderInfo).to receive(:call).with(email).and_return(nil)
|
||||
end
|
||||
|
||||
it 'returns true' do
|
||||
expect(service.perform).to be(true)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when email is from gmail' do
|
||||
let(:email) { 'user@gmail.com' }
|
||||
let(:valid_email_address) { instance_double(ValidEmail2::Address, valid?: true, disposable_domain?: false) }
|
||||
|
||||
before do
|
||||
allow(ValidEmail2::Address).to receive(:new).with(email).and_return(valid_email_address)
|
||||
allow(EmailProviderInfo).to receive(:call).with(email).and_return('gmail')
|
||||
end
|
||||
|
||||
it 'returns false' do
|
||||
expect(service.perform).to be(false)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when email is from Brazilian free provider' do
|
||||
let(:email) { 'user@uol.com.br' }
|
||||
let(:valid_email_address) { instance_double(ValidEmail2::Address, valid?: true, disposable_domain?: false) }
|
||||
|
||||
before do
|
||||
allow(ValidEmail2::Address).to receive(:new).with(email).and_return(valid_email_address)
|
||||
allow(EmailProviderInfo).to receive(:call).with(email).and_return('uol')
|
||||
end
|
||||
|
||||
it 'returns false' do
|
||||
expect(service.perform).to be(false)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when email is disposable' do
|
||||
let(:email) { 'user@mailinator.com' }
|
||||
let(:disposable_email_address) { instance_double(ValidEmail2::Address, valid?: true, disposable_domain?: true) }
|
||||
|
||||
it 'returns false' do
|
||||
allow(ValidEmail2::Address).to receive(:new).with(email).and_return(disposable_email_address)
|
||||
expect(service.perform).to be(false)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when email is invalid format' do
|
||||
let(:email) { 'invalid-email' }
|
||||
let(:invalid_email_address) { instance_double(ValidEmail2::Address, valid?: false) }
|
||||
|
||||
it 'returns false' do
|
||||
allow(ValidEmail2::Address).to receive(:new).with(email).and_return(invalid_email_address)
|
||||
expect(service.perform).to be(false)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when email is nil' do
|
||||
let(:email) { nil }
|
||||
|
||||
it 'remains false' do
|
||||
expect(service.perform).to be(false)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when email is empty string' do
|
||||
let(:email) { '' }
|
||||
|
||||
it 'returns false' do
|
||||
expect(service.perform).to be(false)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when email domain is uppercase' do
|
||||
let(:email) { 'user@GMAIL.COM' }
|
||||
let(:valid_email_address) { instance_double(ValidEmail2::Address, valid?: true, disposable_domain?: false) }
|
||||
|
||||
before do
|
||||
allow(ValidEmail2::Address).to receive(:new).with(email).and_return(valid_email_address)
|
||||
allow(EmailProviderInfo).to receive(:call).with(email).and_return('gmail')
|
||||
end
|
||||
|
||||
it 'returns false (case insensitive)' do
|
||||
expect(service.perform).to be(false)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,83 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe Contacts::CompanyAssociationService, type: :service do
|
||||
let(:account) { create(:account) }
|
||||
let(:service) { described_class.new }
|
||||
|
||||
describe '#associate_company_from_email' do
|
||||
context 'when contact has business email and no company' do
|
||||
it 'creates a new company and associates it' do
|
||||
contact = create(:contact, email: 'john@acme.com', account: account, company_id: nil)
|
||||
Company.delete_all # Delete any companies created by the callback
|
||||
# rubocop:disable Rails/SkipsModelValidations
|
||||
contact.update_column(:company_id, nil) # Delete the company association created by the callback
|
||||
# rubocop:enable Rails/SkipsModelValidations
|
||||
|
||||
valid_email_address = instance_double(ValidEmail2::Address, valid?: true, disposable_domain?: false)
|
||||
allow(ValidEmail2::Address).to receive(:new).with('john@acme.com').and_return(valid_email_address)
|
||||
allow(EmailProviderInfo).to receive(:call).with('john@acme.com').and_return(nil)
|
||||
|
||||
expect do
|
||||
service.associate_company_from_email(contact)
|
||||
end.to change(Company, :count).by(1)
|
||||
|
||||
contact.reload
|
||||
expect(contact.company).to be_present
|
||||
expect(contact.company.domain).to eq('acme.com')
|
||||
expect(contact.company.name).to eq('Acme')
|
||||
end
|
||||
|
||||
it 'reuses existing company with same domain' do
|
||||
existing_company = create(:company, domain: 'acme.com', account: account)
|
||||
contact = create(:contact, email: 'john@acme.com', account: account, company_id: nil)
|
||||
# rubocop:disable Rails/SkipsModelValidations
|
||||
contact.update_column(:company_id, nil) # Delete the company association created by the callback
|
||||
# rubocop:enable Rails/SkipsModelValidations
|
||||
|
||||
valid_email_address = instance_double(ValidEmail2::Address, valid?: true, disposable_domain?: false)
|
||||
allow(ValidEmail2::Address).to receive(:new).with('john@acme.com').and_return(valid_email_address)
|
||||
allow(EmailProviderInfo).to receive(:call).with('john@acme.com').and_return(nil)
|
||||
|
||||
expect do
|
||||
service.associate_company_from_email(contact)
|
||||
end.not_to change(Company, :count)
|
||||
|
||||
contact.reload
|
||||
expect(contact.company).to eq(existing_company)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when contact already has a company' do
|
||||
it 'skips association and returns nil' do
|
||||
existing_company = create(:company, account: account)
|
||||
contact = create(:contact, email: 'john@acme.com', account: account, company_id: existing_company.id)
|
||||
result = service.associate_company_from_email(contact)
|
||||
|
||||
expect(result).to be_nil
|
||||
contact.reload
|
||||
expect(contact.company).to eq(existing_company)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when contact has free email provider' do
|
||||
it 'skips association for email' do
|
||||
contact = create(:contact, email: 'john@gmail.com', account: account, company_id: nil)
|
||||
expect do
|
||||
service.associate_company_from_email(contact)
|
||||
end.not_to change(Company, :count)
|
||||
contact.reload
|
||||
expect(contact.company).to be_nil
|
||||
end
|
||||
end
|
||||
|
||||
context 'when contact has no email' do
|
||||
it 'skips association' do
|
||||
contact = create(:contact, email: nil, account: account, company_id: nil)
|
||||
|
||||
result = service.associate_company_from_email(contact)
|
||||
expect(result).to be_nil
|
||||
expect(contact.reload.company).to be_nil
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,57 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe Voice::InboundCallBuilder do
|
||||
let(:account) { create(:account) }
|
||||
let(:channel) { create(:channel_voice, account: account, phone_number: '+15551230001') }
|
||||
let(:inbox) { channel.inbox }
|
||||
|
||||
let(:from_number) { '+15550001111' }
|
||||
let(:to_number) { channel.phone_number }
|
||||
let(:call_sid) { 'CA1234567890abcdef' }
|
||||
|
||||
before do
|
||||
allow(Twilio::VoiceWebhookSetupService).to receive(:new)
|
||||
.and_return(instance_double(Twilio::VoiceWebhookSetupService, perform: "AP#{SecureRandom.hex(16)}"))
|
||||
end
|
||||
|
||||
def build_and_perform
|
||||
described_class.new(
|
||||
account: account,
|
||||
inbox: inbox,
|
||||
from_number: from_number,
|
||||
to_number: to_number,
|
||||
call_sid: call_sid
|
||||
).perform
|
||||
end
|
||||
|
||||
it 'creates a new conversation with inbound ringing attributes' do
|
||||
builder = build_and_perform
|
||||
conversation = builder.conversation
|
||||
expect(conversation).to be_present
|
||||
expect(conversation.account_id).to eq(account.id)
|
||||
expect(conversation.inbox_id).to eq(inbox.id)
|
||||
expect(conversation.identifier).to eq(call_sid)
|
||||
expect(conversation.additional_attributes['call_direction']).to eq('inbound')
|
||||
expect(conversation.additional_attributes['call_status']).to eq('ringing')
|
||||
end
|
||||
|
||||
it 'creates a voice_call message with ringing status' do
|
||||
builder = build_and_perform
|
||||
conversation = builder.conversation
|
||||
msg = conversation.messages.voice_calls.last
|
||||
expect(msg).to be_present
|
||||
expect(msg.message_type).to eq('incoming')
|
||||
expect(msg.content_type).to eq('voice_call')
|
||||
expect(msg.content_attributes.dig('data', 'call_sid')).to eq(call_sid)
|
||||
expect(msg.content_attributes.dig('data', 'status')).to eq('ringing')
|
||||
end
|
||||
|
||||
it 'returns TwiML that informs the caller we are connecting' do
|
||||
builder = build_and_perform
|
||||
xml = builder.twiml_response
|
||||
expect(xml).to include('Please wait while we connect you to an agent')
|
||||
expect(xml).to include('<Say')
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,63 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe Voice::StatusUpdateService do
|
||||
let(:account) { create(:account) }
|
||||
let!(:contact) { create(:contact, account: account, phone_number: from_number) }
|
||||
let(:contact_inbox) { ContactInbox.create!(contact: contact, inbox: inbox, source_id: from_number) }
|
||||
let(:conversation) do
|
||||
Conversation.create!(
|
||||
account_id: account.id,
|
||||
inbox_id: inbox.id,
|
||||
contact_id: contact.id,
|
||||
contact_inbox_id: contact_inbox.id,
|
||||
identifier: call_sid,
|
||||
additional_attributes: { 'call_direction' => 'inbound', 'call_status' => 'ringing' }
|
||||
)
|
||||
end
|
||||
let(:message) do
|
||||
conversation.messages.create!(
|
||||
account_id: account.id,
|
||||
inbox_id: inbox.id,
|
||||
message_type: :incoming,
|
||||
sender: contact,
|
||||
content: 'Voice Call',
|
||||
content_type: 'voice_call',
|
||||
content_attributes: { data: { call_sid: call_sid, status: 'ringing' } }
|
||||
)
|
||||
end
|
||||
let(:channel) { create(:channel_voice, account: account, phone_number: '+15551230002') }
|
||||
let(:inbox) { channel.inbox }
|
||||
let(:from_number) { '+15550002222' }
|
||||
let(:call_sid) { 'CATESTSTATUS123' }
|
||||
|
||||
before do
|
||||
allow(Twilio::VoiceWebhookSetupService).to receive(:new)
|
||||
.and_return(instance_double(Twilio::VoiceWebhookSetupService, perform: "AP#{SecureRandom.hex(16)}"))
|
||||
end
|
||||
|
||||
it 'updates conversation and last voice message with call status' do
|
||||
# Ensure records are created after stub setup
|
||||
conversation
|
||||
message
|
||||
|
||||
described_class.new(
|
||||
account: account,
|
||||
call_sid: call_sid,
|
||||
call_status: 'completed'
|
||||
).perform
|
||||
|
||||
conversation.reload
|
||||
message.reload
|
||||
|
||||
expect(conversation.additional_attributes['call_status']).to eq('completed')
|
||||
expect(message.content_attributes.dig('data', 'status')).to eq('completed')
|
||||
end
|
||||
|
||||
it 'no-ops when conversation not found' do
|
||||
expect do
|
||||
described_class.new(account: account, call_sid: 'UNKNOWN', call_status: 'busy').perform
|
||||
end.not_to raise_error
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,31 @@
|
||||
FactoryBot.define do
|
||||
factory :account_saml_settings do
|
||||
account
|
||||
sso_url { 'https://idp.example.com/saml/sso' }
|
||||
certificate do
|
||||
key = OpenSSL::PKey::RSA.new(2048)
|
||||
cert = OpenSSL::X509::Certificate.new
|
||||
cert.version = 2
|
||||
cert.serial = 1
|
||||
cert.subject = OpenSSL::X509::Name.parse('/C=US/ST=Test/L=Test/O=Test/CN=test.example.com')
|
||||
cert.issuer = cert.subject
|
||||
cert.public_key = key.public_key
|
||||
cert.not_before = Time.zone.now
|
||||
cert.not_after = cert.not_before + (365 * 24 * 60 * 60)
|
||||
cert.sign(key, OpenSSL::Digest.new('SHA256'))
|
||||
cert.to_pem
|
||||
end
|
||||
idp_entity_id { 'https://idp.example.com/saml/metadata' }
|
||||
role_mappings { {} }
|
||||
|
||||
trait :with_role_mappings do
|
||||
role_mappings do
|
||||
{
|
||||
'Administrators' => { 'role' => 1 },
|
||||
'Agents' => { 'role' => 0 },
|
||||
'Custom-Team' => { 'custom_role_id' => 5 }
|
||||
}
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,51 @@
|
||||
FactoryBot.define do
|
||||
factory :captain_custom_tool, class: 'Captain::CustomTool' do
|
||||
sequence(:title) { |n| "Custom Tool #{n}" }
|
||||
description { 'A custom HTTP tool for external API integration' }
|
||||
endpoint_url { 'https://api.example.com/endpoint' }
|
||||
http_method { 'GET' }
|
||||
auth_type { 'none' }
|
||||
auth_config { {} }
|
||||
param_schema { [] }
|
||||
enabled { true }
|
||||
association :account
|
||||
|
||||
trait :with_post do
|
||||
http_method { 'POST' }
|
||||
request_template { '{ "key": "{{ value }}" }' }
|
||||
end
|
||||
|
||||
trait :with_bearer_auth do
|
||||
auth_type { 'bearer' }
|
||||
auth_config { { token: 'test_bearer_token_123' } }
|
||||
end
|
||||
|
||||
trait :with_basic_auth do
|
||||
auth_type { 'basic' }
|
||||
auth_config { { username: 'test_user', password: 'test_pass' } }
|
||||
end
|
||||
|
||||
trait :with_api_key do
|
||||
auth_type { 'api_key' }
|
||||
auth_config { { key: 'test_api_key', location: 'header', name: 'X-API-Key' } }
|
||||
end
|
||||
|
||||
trait :with_templates do
|
||||
request_template { '{ "order_id": "{{ order_id }}", "source": "chatwoot" }' }
|
||||
response_template { 'Order status: {{ response.status }}' }
|
||||
end
|
||||
|
||||
trait :with_params do
|
||||
param_schema do
|
||||
[
|
||||
{ 'name' => 'order_id', 'type' => 'string', 'description' => 'The order ID', 'required' => true },
|
||||
{ 'name' => 'include_details', 'type' => 'boolean', 'description' => 'Include order details', 'required' => false }
|
||||
]
|
||||
end
|
||||
end
|
||||
|
||||
trait :disabled do
|
||||
enabled { false }
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -13,5 +13,9 @@ FactoryBot.define do
|
||||
sequence(:phone_number) { |n| "+123456789#{n}1" }
|
||||
messaging_service_sid { nil }
|
||||
end
|
||||
|
||||
trait :whatsapp do
|
||||
medium { :whatsapp }
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
FactoryBot.define do
|
||||
factory :company do
|
||||
sequence(:name) { |n| "Company #{n}" }
|
||||
sequence(:domain) { |n| "company#{n}.com" }
|
||||
description { 'A sample company description' }
|
||||
account
|
||||
|
||||
trait :without_domain do
|
||||
domain { nil }
|
||||
end
|
||||
|
||||
trait :with_avatar do
|
||||
avatar { fixture_file_upload(Rails.root.join('spec/assets/avatar.png'), 'image/png') }
|
||||
end
|
||||
|
||||
trait :with_long_description do
|
||||
description { 'A' * 500 }
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -27,6 +27,13 @@ FactoryBot.define do
|
||||
end
|
||||
end
|
||||
|
||||
trait :bot_message do
|
||||
message_type { 'outgoing' }
|
||||
after(:build) do |message|
|
||||
message.sender = nil
|
||||
end
|
||||
end
|
||||
|
||||
after(:build) do |message|
|
||||
message.sender ||= message.outgoing? ? create(:user, account: message.account) : create(:contact, account: message.account)
|
||||
message.inbox ||= message.conversation&.inbox || create(:inbox, account: message.account)
|
||||
|
||||
@@ -2,6 +2,7 @@ require 'rails_helper'
|
||||
|
||||
describe EmailChannelFinder do
|
||||
include ActionMailbox::TestHelper
|
||||
|
||||
let!(:channel_email) { create(:channel_email) }
|
||||
|
||||
describe '#perform' do
|
||||
@@ -48,6 +49,75 @@ describe EmailChannelFinder do
|
||||
expect(channel).to eq(channel_email)
|
||||
end
|
||||
|
||||
it 'skip bcc email when account is configured to skip BCC processing' do
|
||||
channel_email.update(email: 'test@example.com')
|
||||
reply_mail.mail['to'] = nil
|
||||
reply_mail.mail['bcc'] = 'test@example.com'
|
||||
|
||||
allow(GlobalConfigService).to receive(:load)
|
||||
.with('SKIP_INCOMING_BCC_PROCESSING', '')
|
||||
.and_return(channel_email.account_id.to_s)
|
||||
|
||||
channel = described_class.new(reply_mail.mail).perform
|
||||
expect(channel).to be_nil
|
||||
end
|
||||
|
||||
it 'skip bcc email when account is in multiple account ids config' do
|
||||
channel_email.update(email: 'test@example.com')
|
||||
reply_mail.mail['to'] = nil
|
||||
reply_mail.mail['bcc'] = 'test@example.com'
|
||||
|
||||
# Include this account along with other account IDs
|
||||
other_account_ids = [123, 456, channel_email.account_id, 789]
|
||||
allow(GlobalConfigService).to receive(:load)
|
||||
.with('SKIP_INCOMING_BCC_PROCESSING', '')
|
||||
.and_return(other_account_ids.join(','))
|
||||
|
||||
channel = described_class.new(reply_mail.mail).perform
|
||||
expect(channel).to be_nil
|
||||
end
|
||||
|
||||
it 'process bcc email when account is not in skip config' do
|
||||
channel_email.update(email: 'test@example.com')
|
||||
reply_mail.mail['to'] = nil
|
||||
reply_mail.mail['bcc'] = 'test@example.com'
|
||||
|
||||
# Configure other account IDs but not this one
|
||||
other_account_ids = [123, 456, 789]
|
||||
allow(GlobalConfigService).to receive(:load)
|
||||
.with('SKIP_INCOMING_BCC_PROCESSING', '')
|
||||
.and_return(other_account_ids.join(','))
|
||||
|
||||
channel = described_class.new(reply_mail.mail).perform
|
||||
expect(channel).to eq(channel_email)
|
||||
end
|
||||
|
||||
it 'process bcc email when skip config is empty' do
|
||||
channel_email.update(email: 'test@example.com')
|
||||
reply_mail.mail['to'] = nil
|
||||
reply_mail.mail['bcc'] = 'test@example.com'
|
||||
|
||||
allow(GlobalConfigService).to receive(:load)
|
||||
.with('SKIP_INCOMING_BCC_PROCESSING', '')
|
||||
.and_return('')
|
||||
|
||||
channel = described_class.new(reply_mail.mail).perform
|
||||
expect(channel).to eq(channel_email)
|
||||
end
|
||||
|
||||
it 'process bcc email when skip config is nil' do
|
||||
channel_email.update(email: 'test@example.com')
|
||||
reply_mail.mail['to'] = nil
|
||||
reply_mail.mail['bcc'] = 'test@example.com'
|
||||
|
||||
allow(GlobalConfigService).to receive(:load)
|
||||
.with('SKIP_INCOMING_BCC_PROCESSING', '')
|
||||
.and_return(nil)
|
||||
|
||||
channel = described_class.new(reply_mail.mail).perform
|
||||
expect(channel).to eq(channel_email)
|
||||
end
|
||||
|
||||
it 'return channel with X-Original-To email' do
|
||||
channel_email.update(email: 'test@example.com')
|
||||
reply_mail.mail['to'] = nil
|
||||
@@ -55,6 +125,19 @@ describe EmailChannelFinder do
|
||||
channel = described_class.new(reply_mail.mail).perform
|
||||
expect(channel).to eq(channel_email)
|
||||
end
|
||||
|
||||
it 'process X-Original-To email even when account is configured to skip BCC processing' do
|
||||
channel_email.update(email: 'test@example.com')
|
||||
reply_mail.mail['to'] = nil
|
||||
reply_mail.mail['X-Original-To'] = 'test@example.com'
|
||||
|
||||
allow(GlobalConfigService).to receive(:load)
|
||||
.with('SKIP_INCOMING_BCC_PROCESSING', '')
|
||||
.and_return(channel_email.account_id.to_s)
|
||||
|
||||
channel = described_class.new(reply_mail.mail).perform
|
||||
expect(channel).to eq(channel_email)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -103,13 +103,11 @@ RSpec.describe Account::ContactsExportJob do
|
||||
expect(csv_data.length).to eq(1)
|
||||
end
|
||||
|
||||
# TODO: This returns unresolved contacts as well since filter service returns the same
|
||||
# Change this when we make changes to filter service and ensure only resolved contacts are returned
|
||||
it 'returns filtered data which inclues unresolved contacts when filter is provided' do
|
||||
it 'returns filtered data limited to resolved contacts when filter is provided' do
|
||||
create(:contact, account: account, email: nil, phone_number: nil, additional_attributes: { :country_code => 'India' })
|
||||
described_class.perform_now(account.id, user.id, [], { :payload => [city_filter.merge(:query_operator => nil)] }.with_indifferent_access)
|
||||
csv_data = CSV.parse(account.contacts_export.download, headers: true)
|
||||
expect(csv_data.length).to eq(5)
|
||||
expect(csv_data.length).to eq(4)
|
||||
end
|
||||
|
||||
it 'returns filtered data when multiple filters are provided' do
|
||||
|
||||
@@ -1,36 +1,119 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe Avatar::AvatarFromUrlJob do
|
||||
let(:avatarable) { create(:contact) }
|
||||
let(:avatar_url) { 'https://example.com/avatar.png' }
|
||||
let(:file) { fixture_file_upload(Rails.root.join('spec/assets/avatar.png'), 'image/png') }
|
||||
let(:valid_url) { 'https://example.com/avatar.png' }
|
||||
|
||||
it 'enqueues the job' do
|
||||
expect { described_class.perform_later(avatarable, avatar_url) }.to have_enqueued_job(described_class)
|
||||
.on_queue('purgable')
|
||||
contact = create(:contact)
|
||||
expect { described_class.perform_later(contact, 'https://example.com/avatar.png') }
|
||||
.to have_enqueued_job(described_class).on_queue('purgable')
|
||||
end
|
||||
|
||||
it 'will attach avatar from url' do
|
||||
expect(avatarable.avatar).not_to be_attached
|
||||
expect(Down).to receive(:download).with(avatar_url,
|
||||
max_size: 15 * 1024 * 1024).and_return(fixture_file_upload(Rails.root.join('spec/assets/avatar.png'),
|
||||
'image/png'))
|
||||
described_class.perform_now(avatarable, avatar_url)
|
||||
expect(avatarable.avatar).to be_attached
|
||||
context 'with rate-limited avatarable (Contact)' do
|
||||
let(:avatarable) { create(:contact) }
|
||||
|
||||
it 'attaches and updates sync attributes' do
|
||||
expect(Down).to receive(:download).with(valid_url, max_size: Avatar::AvatarFromUrlJob::MAX_DOWNLOAD_SIZE).and_return(file)
|
||||
described_class.perform_now(avatarable, valid_url)
|
||||
avatarable.reload
|
||||
expect(avatarable.avatar).to be_attached
|
||||
expect(avatarable.additional_attributes['avatar_url_hash']).to eq(Digest::SHA256.hexdigest(valid_url))
|
||||
expect(avatarable.additional_attributes['last_avatar_sync_at']).to be_present
|
||||
end
|
||||
|
||||
it 'returns early when rate limited' do
|
||||
ts = 30.seconds.ago.iso8601
|
||||
avatarable.update(additional_attributes: { 'last_avatar_sync_at' => ts })
|
||||
expect(Down).not_to receive(:download)
|
||||
described_class.perform_now(avatarable, valid_url)
|
||||
avatarable.reload
|
||||
expect(avatarable.avatar).not_to be_attached
|
||||
expect(avatarable.additional_attributes['last_avatar_sync_at']).to be_present
|
||||
expect(Time.zone.parse(avatarable.additional_attributes['last_avatar_sync_at']))
|
||||
.to be > Time.zone.parse(ts)
|
||||
expect(avatarable.additional_attributes['avatar_url_hash']).to eq(Digest::SHA256.hexdigest(valid_url))
|
||||
end
|
||||
|
||||
it 'returns early when hash unchanged' do
|
||||
avatarable.update(additional_attributes: { 'avatar_url_hash' => Digest::SHA256.hexdigest(valid_url) })
|
||||
expect(Down).not_to receive(:download)
|
||||
described_class.perform_now(avatarable, valid_url)
|
||||
expect(avatarable.avatar).not_to be_attached
|
||||
avatarable.reload
|
||||
expect(avatarable.additional_attributes['last_avatar_sync_at']).to be_present
|
||||
expect(avatarable.additional_attributes['avatar_url_hash']).to eq(Digest::SHA256.hexdigest(valid_url))
|
||||
end
|
||||
|
||||
it 'updates sync attributes even when URL is invalid' do
|
||||
invalid_url = 'invalid_url'
|
||||
expect(Down).not_to receive(:download)
|
||||
described_class.perform_now(avatarable, invalid_url)
|
||||
avatarable.reload
|
||||
expect(avatarable.avatar).not_to be_attached
|
||||
expect(avatarable.additional_attributes['last_avatar_sync_at']).to be_present
|
||||
expect(avatarable.additional_attributes['avatar_url_hash']).to eq(Digest::SHA256.hexdigest(invalid_url))
|
||||
end
|
||||
|
||||
it 'updates sync attributes when file download is valid but content type is unsupported' do
|
||||
temp_file = Tempfile.new(['invalid', '.xml'])
|
||||
temp_file.write('<invalid>content</invalid>')
|
||||
temp_file.rewind
|
||||
|
||||
uploaded = ActionDispatch::Http::UploadedFile.new(
|
||||
tempfile: temp_file,
|
||||
filename: 'invalid.xml',
|
||||
type: 'application/xml'
|
||||
)
|
||||
|
||||
expect(Down).to receive(:download).with(valid_url, max_size: Avatar::AvatarFromUrlJob::MAX_DOWNLOAD_SIZE).and_return(uploaded)
|
||||
|
||||
described_class.perform_now(avatarable, valid_url)
|
||||
avatarable.reload
|
||||
|
||||
expect(avatarable.avatar).not_to be_attached
|
||||
expect(avatarable.additional_attributes['last_avatar_sync_at']).to be_present
|
||||
expect(avatarable.additional_attributes['avatar_url_hash']).to eq(Digest::SHA256.hexdigest(valid_url))
|
||||
|
||||
temp_file.close
|
||||
temp_file.unlink
|
||||
end
|
||||
end
|
||||
|
||||
context 'with regular avatarable' do
|
||||
let(:avatarable) { create(:agent_bot) }
|
||||
|
||||
it 'downloads and attaches avatar' do
|
||||
expect(Down).to receive(:download).with(valid_url, max_size: Avatar::AvatarFromUrlJob::MAX_DOWNLOAD_SIZE).and_return(file)
|
||||
described_class.perform_now(avatarable, valid_url)
|
||||
expect(avatarable.avatar).to be_attached
|
||||
end
|
||||
end
|
||||
|
||||
# ref: https://github.com/chatwoot/chatwoot/issues/10449
|
||||
it 'will not throw error if the avatar url is not valid and the file does not have a filename' do
|
||||
# Create a temporary file with no filename and content type application/xml
|
||||
it 'does not raise error when downloaded file has no filename (invalid content)' do
|
||||
contact = create(:contact)
|
||||
temp_file = Tempfile.new(['invalid', '.xml'])
|
||||
temp_file.write('<invalid>content</invalid>')
|
||||
temp_file.rewind
|
||||
|
||||
expect(Down).to receive(:download).with(avatar_url, max_size: 15 * 1024 * 1024)
|
||||
expect(Down).to receive(:download).with(valid_url, max_size: Avatar::AvatarFromUrlJob::MAX_DOWNLOAD_SIZE)
|
||||
.and_return(ActionDispatch::Http::UploadedFile.new(tempfile: temp_file, type: 'application/xml'))
|
||||
|
||||
expect { described_class.perform_now(avatarable, avatar_url) }.not_to raise_error
|
||||
expect { described_class.perform_now(contact, valid_url) }.not_to raise_error
|
||||
|
||||
temp_file.close
|
||||
temp_file.unlink # deletes the temp file
|
||||
temp_file.unlink
|
||||
end
|
||||
|
||||
it 'skips sync attribute updates when URL is nil' do
|
||||
contact = create(:contact)
|
||||
expect(Down).not_to receive(:download)
|
||||
|
||||
expect { described_class.perform_now(contact, nil) }.not_to raise_error
|
||||
|
||||
contact.reload
|
||||
expect(contact.additional_attributes['last_avatar_sync_at']).to be_nil
|
||||
expect(contact.additional_attributes['avatar_url_hash']).to be_nil
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe Contacts::BulkActionJob, type: :job do
|
||||
let(:account) { create(:account) }
|
||||
let(:user) { create(:user, account: account) }
|
||||
let(:params) { { 'ids' => [1], 'labels' => { 'add' => ['vip'] } } }
|
||||
|
||||
it 'invokes the bulk action service with account and user' do
|
||||
service_instance = instance_double(Contacts::BulkActionService, perform: true)
|
||||
|
||||
allow(Contacts::BulkActionService).to receive(:new).and_return(service_instance)
|
||||
|
||||
described_class.perform_now(account.id, user.id, params)
|
||||
|
||||
expect(Contacts::BulkActionService).to have_received(:new).with(
|
||||
account: account,
|
||||
user: user,
|
||||
params: params
|
||||
)
|
||||
expect(service_instance).to have_received(:perform)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,33 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe ConversationReplyEmailJob, type: :job do
|
||||
let(:conversation) { create(:conversation) }
|
||||
let(:mailer) { double }
|
||||
let(:mailer_action) { double }
|
||||
|
||||
before do
|
||||
allow(Conversation).to receive(:find).and_return(conversation)
|
||||
allow(ConversationReplyMailer).to receive(:with).and_return(mailer)
|
||||
allow(mailer).to receive(:reply_with_summary).and_return(mailer_action)
|
||||
allow(mailer).to receive(:reply_without_summary).and_return(mailer_action)
|
||||
allow(mailer_action).to receive(:deliver_later).and_return(true)
|
||||
end
|
||||
|
||||
it 'enqueues on mailers queue' do
|
||||
ActiveJob::Base.queue_adapter = :test
|
||||
expect do
|
||||
described_class.perform_later(conversation.id, 123)
|
||||
end.to have_enqueued_job(described_class).on_queue('mailers')
|
||||
end
|
||||
|
||||
it 'calls reply_with_summary when last incoming message was not email' do
|
||||
described_class.perform_now(conversation.id, 123)
|
||||
expect(mailer).to have_received(:reply_with_summary)
|
||||
end
|
||||
|
||||
it 'calls reply_without_summary when last incoming message was email' do
|
||||
create(:message, conversation: conversation, message_type: :incoming, content_type: 'incoming_email')
|
||||
described_class.perform_now(conversation.id, 123)
|
||||
expect(mailer).to have_received(:reply_without_summary)
|
||||
end
|
||||
end
|
||||
@@ -1,20 +1,74 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe DeleteObjectJob do
|
||||
subject(:job) { described_class.perform_later(account) }
|
||||
RSpec.describe DeleteObjectJob, type: :job do
|
||||
describe '#perform' do
|
||||
context 'when object is heavy (Inbox)' do
|
||||
let!(:account) { create(:account) }
|
||||
let!(:inbox) { create(:inbox, account: account) }
|
||||
|
||||
let(:account) { create(:account) }
|
||||
before do
|
||||
create_list(:conversation, 3, account: account, inbox: inbox)
|
||||
ReportingEvent.create!(account: account, inbox: inbox, name: 'inbox_metric', value: 1.0)
|
||||
end
|
||||
|
||||
it 'enqueues the job' do
|
||||
expect { job }.to have_enqueued_job(described_class)
|
||||
.with(account)
|
||||
.on_queue('low')
|
||||
end
|
||||
it 'enqueues on the low queue' do
|
||||
expect { described_class.perform_later(inbox) }
|
||||
.to have_enqueued_job(described_class).with(inbox).on_queue('low')
|
||||
end
|
||||
|
||||
context 'when an object is passed to the job' do
|
||||
it 'is deleted' do
|
||||
described_class.perform_now(account)
|
||||
expect { account.reload }.to raise_error(ActiveRecord::RecordNotFound)
|
||||
it 'pre-deletes heavy associations and then destroys the object' do
|
||||
conv_ids = inbox.conversations.pluck(:id)
|
||||
ci_ids = inbox.contact_inboxes.pluck(:id)
|
||||
contact_ids = inbox.contacts.pluck(:id)
|
||||
re_ids = inbox.reporting_events.pluck(:id)
|
||||
|
||||
described_class.perform_now(inbox)
|
||||
|
||||
expect(Conversation.where(id: conv_ids)).to be_empty
|
||||
expect(ContactInbox.where(id: ci_ids)).to be_empty
|
||||
expect(ReportingEvent.where(id: re_ids)).to be_empty
|
||||
# Contacts should not be deleted for inbox destroy
|
||||
expect(Contact.where(id: contact_ids)).not_to be_empty
|
||||
expect { inbox.reload }.to raise_error(ActiveRecord::RecordNotFound)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when object is heavy (Account)' do
|
||||
let!(:account) { create(:account) }
|
||||
let!(:inbox1) { create(:inbox, account: account) }
|
||||
let!(:inbox2) { create(:inbox, account: account) }
|
||||
|
||||
before do
|
||||
create_list(:conversation, 2, account: account, inbox: inbox1)
|
||||
create_list(:conversation, 1, account: account, inbox: inbox2)
|
||||
ReportingEvent.create!(account: account, name: 'acct_metric', value: 2.5)
|
||||
ReportingEvent.create!(account: account, inbox: inbox1, name: 'acct_inbox_metric', value: 3.5)
|
||||
end
|
||||
|
||||
it 'pre-deletes conversations, contacts, inboxes and reporting events and then destroys the account' do
|
||||
conv_ids = account.conversations.pluck(:id)
|
||||
contact_ids = account.contacts.pluck(:id)
|
||||
inbox_ids = account.inboxes.pluck(:id)
|
||||
re_ids = account.reporting_events.pluck(:id)
|
||||
|
||||
described_class.perform_now(account)
|
||||
|
||||
expect(Conversation.where(id: conv_ids)).to be_empty
|
||||
expect(Contact.where(id: contact_ids)).to be_empty
|
||||
expect(Inbox.where(id: inbox_ids)).to be_empty
|
||||
expect(ReportingEvent.where(id: re_ids)).to be_empty
|
||||
expect { account.reload }.to raise_error(ActiveRecord::RecordNotFound)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when object is regular (Label)' do
|
||||
it 'just destroys the object' do
|
||||
label = create(:label)
|
||||
|
||||
described_class.perform_now(label)
|
||||
|
||||
expect { label.reload }.to raise_error(ActiveRecord::RecordNotFound)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -108,5 +108,32 @@ RSpec.describe SendReplyJob do
|
||||
expect(process_service).to receive(:perform)
|
||||
described_class.perform_now(message.id)
|
||||
end
|
||||
|
||||
it 'calls ::Email::SendOnEmailService when its email message' do
|
||||
email_channel = create(:channel_email)
|
||||
message = create(:message, conversation: create(:conversation, inbox: email_channel.inbox))
|
||||
allow(Email::SendOnEmailService).to receive(:new).with(message: message).and_return(process_service)
|
||||
expect(Email::SendOnEmailService).to receive(:new).with(message: message)
|
||||
expect(process_service).to receive(:perform)
|
||||
described_class.perform_now(message.id)
|
||||
end
|
||||
|
||||
it 'calls ::Messages::SendEmailNotificationService when its webwidget message' do
|
||||
webwidget_channel = create(:channel_widget)
|
||||
message = create(:message, conversation: create(:conversation, inbox: webwidget_channel.inbox))
|
||||
allow(Messages::SendEmailNotificationService).to receive(:new).with(message: message).and_return(process_service)
|
||||
expect(Messages::SendEmailNotificationService).to receive(:new).with(message: message)
|
||||
expect(process_service).to receive(:perform)
|
||||
described_class.perform_now(message.id)
|
||||
end
|
||||
|
||||
it 'calls ::Messages::SendEmailNotificationService when its api channel message' do
|
||||
api_channel = create(:channel_api)
|
||||
message = create(:message, conversation: create(:conversation, inbox: api_channel.inbox))
|
||||
allow(Messages::SendEmailNotificationService).to receive(:new).with(message: message).and_return(process_service)
|
||||
expect(Messages::SendEmailNotificationService).to receive(:new).with(message: message)
|
||||
expect(process_service).to receive(:perform)
|
||||
described_class.perform_now(message.id)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -157,6 +157,19 @@ describe Integrations::Slack::IncomingMessageBuilder do
|
||||
|
||||
expect(conversation.messages.count).to eql(messages_count)
|
||||
end
|
||||
|
||||
it 'handles different file types correctly' do
|
||||
expect(hook).not_to be_nil
|
||||
video_attachment_params = message_with_attachments.deep_dup
|
||||
video_attachment_params[:event][:files][0][:filetype] = 'mp4'
|
||||
video_attachment_params[:event][:files][0][:mimetype] = 'video/mp4'
|
||||
|
||||
builder = described_class.new(video_attachment_params)
|
||||
allow(builder).to receive(:sender).and_return(nil)
|
||||
|
||||
expect { builder.perform }.not_to raise_error
|
||||
expect(conversation.messages.last.attachments).to be_any
|
||||
end
|
||||
end
|
||||
|
||||
context 'when link shared' do
|
||||
|
||||
@@ -163,8 +163,11 @@ describe Integrations::Slack::SendOnSlackService do
|
||||
attachment.file.attach(io: Rails.root.join('spec/assets/avatar.png').open, filename: 'avatar.png', content_type: 'image/png')
|
||||
|
||||
expect(slack_client).to receive(:files_upload_v2).with(
|
||||
filename: attachment.file.filename.to_s,
|
||||
content: anything,
|
||||
files: [{
|
||||
filename: attachment.file.filename.to_s,
|
||||
content: anything,
|
||||
title: attachment.file.filename.to_s
|
||||
}],
|
||||
channel_id: hook.reference_id,
|
||||
thread_ts: conversation.identifier,
|
||||
initial_comment: 'Attached File!'
|
||||
@@ -179,27 +182,27 @@ describe Integrations::Slack::SendOnSlackService do
|
||||
end
|
||||
|
||||
it 'sent multiple attachments on slack' do
|
||||
expect(slack_client).to receive(:chat_postMessage).with(
|
||||
channel: hook.reference_id,
|
||||
text: message.content,
|
||||
username: "#{message.sender.name} (Contact)",
|
||||
thread_ts: conversation.identifier,
|
||||
icon_url: anything,
|
||||
unfurl_links: true
|
||||
).and_return(slack_message)
|
||||
expect(slack_client).to receive(:chat_postMessage).and_return(slack_message)
|
||||
|
||||
attachment1 = message.attachments.new(account_id: message.account_id, file_type: :image)
|
||||
attachment1.file.attach(io: Rails.root.join('spec/assets/avatar.png').open, filename: 'avatar.png', content_type: 'image/png')
|
||||
|
||||
attachment2 = message.attachments.new(account_id: message.account_id, file_type: :image)
|
||||
attachment2.file.attach(io: Rails.root.join('spec/assets/avatar.png').open, filename: 'logo.png', content_type: 'image/png')
|
||||
|
||||
expect(slack_client).to receive(:files_upload_v2).twice.and_return(file_attachment)
|
||||
expected_files = [
|
||||
{ filename: 'avatar.png', content: anything, title: 'avatar.png' },
|
||||
{ filename: 'logo.png', content: anything, title: 'logo.png' }
|
||||
]
|
||||
expect(slack_client).to receive(:files_upload_v2).with(
|
||||
files: expected_files,
|
||||
channel_id: hook.reference_id,
|
||||
thread_ts: conversation.identifier,
|
||||
initial_comment: 'Attached File!'
|
||||
).and_return(file_attachment)
|
||||
|
||||
message.save!
|
||||
builder.perform
|
||||
|
||||
expect(message.external_source_id_slack).to eq 'cw-origin-6789.12345'
|
||||
expect(message.attachments.count).to eq 2
|
||||
end
|
||||
|
||||
@@ -217,14 +220,17 @@ describe Integrations::Slack::SendOnSlackService do
|
||||
attachment.file.attach(io: Rails.root.join('spec/assets/avatar.png').open, filename: 'avatar.png', content_type: 'image/png')
|
||||
|
||||
expect(slack_client).to receive(:files_upload_v2).with(
|
||||
filename: attachment.file.filename.to_s,
|
||||
content: anything,
|
||||
files: [{
|
||||
filename: attachment.file.filename.to_s,
|
||||
content: anything,
|
||||
title: attachment.file.filename.to_s
|
||||
}],
|
||||
channel_id: hook.reference_id,
|
||||
thread_ts: conversation.identifier,
|
||||
initial_comment: 'Attached File!'
|
||||
).and_raise(Slack::Web::Api::Errors::SlackError.new('File upload failed'))
|
||||
|
||||
expect(Rails.logger).to receive(:error).with('Failed to upload file avatar.png: File upload failed')
|
||||
expect(Rails.logger).to receive(:error).with('Failed to upload files: File upload failed')
|
||||
|
||||
message.save!
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
require 'rails_helper'
|
||||
|
||||
describe Webhooks::Trigger do
|
||||
include ActiveJob::TestHelper
|
||||
|
||||
subject(:trigger) { described_class }
|
||||
|
||||
let!(:account) { create(:account) }
|
||||
@@ -8,8 +10,18 @@ describe Webhooks::Trigger do
|
||||
let!(:conversation) { create(:conversation, inbox: inbox) }
|
||||
let!(:message) { create(:message, account: account, inbox: inbox, conversation: conversation) }
|
||||
|
||||
let!(:webhook_type) { :api_inbox_webhook }
|
||||
let(:webhook_type) { :api_inbox_webhook }
|
||||
let!(:url) { 'https://test.com' }
|
||||
let(:agent_bot_error_content) { I18n.t('conversations.activity.agent_bot.error_moved_to_open') }
|
||||
|
||||
before do
|
||||
ActiveJob::Base.queue_adapter = :test
|
||||
end
|
||||
|
||||
after do
|
||||
clear_enqueued_jobs
|
||||
clear_performed_jobs
|
||||
end
|
||||
|
||||
describe '#execute' do
|
||||
it 'triggers webhook' do
|
||||
@@ -54,6 +66,57 @@ describe Webhooks::Trigger do
|
||||
).and_raise(RestClient::ExceptionWithResponse.new('error', 500)).once
|
||||
expect { trigger.execute(url, payload, webhook_type) }.to change { message.reload.status }.from('sent').to('failed')
|
||||
end
|
||||
|
||||
context 'when webhook type is agent bot' do
|
||||
let(:webhook_type) { :agent_bot_webhook }
|
||||
|
||||
it 'reopens conversation and enqueues activity message if pending' do
|
||||
conversation.update(status: :pending)
|
||||
payload = { event: 'message_created', conversation: { id: conversation.id }, id: message.id }
|
||||
|
||||
expect(RestClient::Request).to receive(:execute)
|
||||
.with(
|
||||
method: :post,
|
||||
url: url,
|
||||
payload: payload.to_json,
|
||||
headers: { content_type: :json, accept: :json },
|
||||
timeout: 5
|
||||
).and_raise(RestClient::ExceptionWithResponse.new('error', 500)).once
|
||||
|
||||
expect do
|
||||
perform_enqueued_jobs do
|
||||
trigger.execute(url, payload, webhook_type)
|
||||
end
|
||||
end.not_to(change { message.reload.status })
|
||||
|
||||
expect(conversation.reload.status).to eq('open')
|
||||
|
||||
activity_message = conversation.reload.messages.order(:created_at).last
|
||||
expect(activity_message.message_type).to eq('activity')
|
||||
expect(activity_message.content).to eq(agent_bot_error_content)
|
||||
end
|
||||
|
||||
it 'does not change message status or enqueue activity when conversation is not pending' do
|
||||
payload = { event: 'message_created', conversation: { id: conversation.id }, id: message.id }
|
||||
|
||||
expect(RestClient::Request).to receive(:execute)
|
||||
.with(
|
||||
method: :post,
|
||||
url: url,
|
||||
payload: payload.to_json,
|
||||
headers: { content_type: :json, accept: :json },
|
||||
timeout: 5
|
||||
).and_raise(RestClient::ExceptionWithResponse.new('error', 500)).once
|
||||
|
||||
expect do
|
||||
trigger.execute(url, payload, webhook_type)
|
||||
end.not_to(change { message.reload.status })
|
||||
|
||||
expect(Conversations::ActivityMessageJob).not_to have_been_enqueued
|
||||
|
||||
expect(conversation.reload.status).to eq('open')
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
it 'does not update message status if webhook fails for other events' do
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
require 'rails_helper'
|
||||
|
||||
describe AutomationRuleListener do
|
||||
let(:listener) { described_class.instance }
|
||||
let!(:account) { create(:account) }
|
||||
let!(:user) { create(:user, account: account) }
|
||||
let!(:inbox) { create(:inbox, account: account) }
|
||||
let!(:contact) { create(:contact, account: account) }
|
||||
let!(:conversation) { create(:conversation, account: account, inbox: inbox, contact: contact) }
|
||||
let(:label1) { create(:label, account: account, title: 'bug') }
|
||||
let(:label2) { create(:label, account: account, title: 'feature') }
|
||||
let(:label3) { create(:label, account: account, title: 'urgent') }
|
||||
|
||||
before do
|
||||
Current.user = user
|
||||
end
|
||||
|
||||
describe 'conversation_updated with label conditions and actions' do
|
||||
context 'when label is added and automation rule has label condition' do
|
||||
let(:automation_rule) do
|
||||
create(:automation_rule,
|
||||
event_name: 'conversation_updated',
|
||||
account: account,
|
||||
conditions: [
|
||||
{
|
||||
attribute_key: 'labels',
|
||||
filter_operator: 'equal_to',
|
||||
values: ['bug'],
|
||||
query_operator: nil
|
||||
}
|
||||
],
|
||||
actions: [
|
||||
{
|
||||
action_name: 'add_label',
|
||||
action_params: ['urgent']
|
||||
},
|
||||
{
|
||||
action_name: 'send_message',
|
||||
action_params: ['Bug report received. We will investigate this issue.']
|
||||
}
|
||||
])
|
||||
end
|
||||
|
||||
it 'triggers automation when the specified label is added' do
|
||||
automation_rule # Create the automation rule
|
||||
expect(Messages::MessageBuilder).to receive(:new).and_call_original
|
||||
|
||||
# Add the 'bug' label to trigger the automation
|
||||
conversation.add_labels(['bug'])
|
||||
|
||||
# Dispatch the event
|
||||
event = Events::Base.new('conversation_updated', Time.zone.now, {
|
||||
conversation: conversation,
|
||||
changed_attributes: { label_list: [[], ['bug']] }
|
||||
})
|
||||
|
||||
listener.conversation_updated(event)
|
||||
|
||||
# Verify the label was added by automation
|
||||
expect(conversation.reload.label_list).to include('urgent')
|
||||
|
||||
# Verify a message was sent
|
||||
expect(conversation.messages.last.content).to eq('Bug report received. We will investigate this issue.')
|
||||
end
|
||||
|
||||
it 'does not trigger automation when a different label is added' do
|
||||
automation_rule # Create the automation rule
|
||||
expect(Messages::MessageBuilder).not_to receive(:new)
|
||||
|
||||
# Add a different label
|
||||
conversation.add_labels(['feature'])
|
||||
|
||||
event = Events::Base.new('conversation_updated', Time.zone.now, {
|
||||
conversation: conversation,
|
||||
changed_attributes: { label_list: [[], ['feature']] }
|
||||
})
|
||||
|
||||
listener.conversation_updated(event)
|
||||
|
||||
# Verify the automation did not run
|
||||
expect(conversation.reload.label_list).not_to include('urgent')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when automation rule has is_present label condition' do
|
||||
let(:automation_rule) do
|
||||
create(:automation_rule,
|
||||
event_name: 'conversation_updated',
|
||||
account: account,
|
||||
conditions: [
|
||||
{
|
||||
attribute_key: 'labels',
|
||||
filter_operator: 'is_present',
|
||||
values: [],
|
||||
query_operator: nil
|
||||
}
|
||||
],
|
||||
actions: [
|
||||
{
|
||||
action_name: 'send_message',
|
||||
action_params: ['Thank you for adding a label to categorize this conversation.']
|
||||
}
|
||||
])
|
||||
end
|
||||
|
||||
it 'triggers automation when any label is added to an unlabeled conversation' do
|
||||
automation_rule # Create the automation rule
|
||||
expect(Messages::MessageBuilder).to receive(:new).and_call_original
|
||||
|
||||
# Add any label to trigger the automation
|
||||
conversation.add_labels(['feature'])
|
||||
|
||||
event = Events::Base.new('conversation_updated', Time.zone.now, {
|
||||
conversation: conversation,
|
||||
changed_attributes: { label_list: [[], ['feature']] }
|
||||
})
|
||||
|
||||
listener.conversation_updated(event)
|
||||
|
||||
# Verify a message was sent
|
||||
expect(conversation.messages.last.content).to eq('Thank you for adding a label to categorize this conversation.')
|
||||
end
|
||||
|
||||
it 'still triggers when labels are removed but conversation still has labels' do
|
||||
automation_rule # Create the automation rule
|
||||
# Start with multiple labels
|
||||
conversation.add_labels(%w[bug feature])
|
||||
conversation.reload
|
||||
|
||||
expect(Messages::MessageBuilder).to receive(:new).and_call_original
|
||||
|
||||
# Remove one label but conversation still has labels
|
||||
conversation.update_labels(['bug'])
|
||||
|
||||
event = Events::Base.new('conversation_updated', Time.zone.now, {
|
||||
conversation: conversation,
|
||||
changed_attributes: { label_list: [%w[bug feature], ['bug']] }
|
||||
})
|
||||
|
||||
listener.conversation_updated(event)
|
||||
|
||||
# Should still trigger because conversation has labels (is_present condition)
|
||||
expect(conversation.messages.last.content).to eq('Thank you for adding a label to categorize this conversation.')
|
||||
end
|
||||
|
||||
it 'does not trigger when all labels are removed' do
|
||||
automation_rule # Create the automation rule
|
||||
# Start with labels
|
||||
conversation.add_labels(['bug'])
|
||||
conversation.reload
|
||||
|
||||
expect(Messages::MessageBuilder).not_to receive(:new)
|
||||
|
||||
# Remove all labels
|
||||
conversation.update_labels([])
|
||||
|
||||
event = Events::Base.new('conversation_updated', Time.zone.now, {
|
||||
conversation: conversation,
|
||||
changed_attributes: { label_list: [['bug'], []] }
|
||||
})
|
||||
|
||||
listener.conversation_updated(event)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when automation rule has remove_label action' do
|
||||
let!(:automation_rule) do
|
||||
create(:automation_rule,
|
||||
event_name: 'conversation_updated',
|
||||
account: account,
|
||||
conditions: [
|
||||
{
|
||||
attribute_key: 'labels',
|
||||
filter_operator: 'equal_to',
|
||||
values: ['urgent'],
|
||||
query_operator: nil
|
||||
}
|
||||
],
|
||||
actions: [
|
||||
{
|
||||
action_name: 'remove_label',
|
||||
action_params: ['bug']
|
||||
}
|
||||
])
|
||||
end
|
||||
|
||||
it 'removes specified labels when condition is met' do
|
||||
automation_rule # Create the automation rule
|
||||
# Start with both labels
|
||||
conversation.add_labels(%w[bug urgent])
|
||||
|
||||
event = Events::Base.new('conversation_updated', Time.zone.now, {
|
||||
conversation: conversation,
|
||||
changed_attributes: { label_list: [['bug'], %w[bug urgent]] }
|
||||
})
|
||||
|
||||
listener.conversation_updated(event)
|
||||
|
||||
# Verify the bug label was removed but urgent remains
|
||||
expect(conversation.reload.label_list).to include('urgent')
|
||||
expect(conversation.reload.label_list).not_to include('bug')
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'preventing infinite loops' do
|
||||
let!(:automation_rule) do
|
||||
create(:automation_rule,
|
||||
event_name: 'conversation_updated',
|
||||
account: account,
|
||||
conditions: [
|
||||
{
|
||||
attribute_key: 'labels',
|
||||
filter_operator: 'equal_to',
|
||||
values: ['bug'],
|
||||
query_operator: nil
|
||||
}
|
||||
],
|
||||
actions: [
|
||||
{
|
||||
action_name: 'add_label',
|
||||
action_params: ['processed']
|
||||
}
|
||||
])
|
||||
end
|
||||
|
||||
it 'does not trigger automation when performed by automation rule' do
|
||||
automation_rule # Create the automation rule
|
||||
conversation.add_labels(['bug'])
|
||||
|
||||
# Simulate event performed by automation rule
|
||||
event = Events::Base.new('conversation_updated', Time.zone.now, {
|
||||
conversation: conversation,
|
||||
changed_attributes: { label_list: [[], ['bug']] },
|
||||
performed_by: automation_rule
|
||||
})
|
||||
|
||||
# Should not process the event since it was performed by automation
|
||||
expect(AutomationRules::ActionService).not_to receive(:new)
|
||||
|
||||
listener.conversation_updated(event)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -66,6 +66,20 @@ RSpec.describe ApplicationMailbox do
|
||||
expect(dbl).to receive(:perform_processing).and_return(true)
|
||||
described_class.route reply_cc_mail
|
||||
end
|
||||
|
||||
it 'skips routing when BCC processing is disabled for account' do
|
||||
allow(GlobalConfigService).to receive(:load).with('SKIP_INCOMING_BCC_PROCESSING', '').and_return(channel_email.account_id.to_s)
|
||||
|
||||
# Create a BCC-only email scenario
|
||||
bcc_mail = create_inbound_email_from_fixture('support.eml')
|
||||
bcc_mail.mail['to'] = nil
|
||||
bcc_mail.mail['bcc'] = 'care@example.com'
|
||||
|
||||
channel_email.update(email: 'care@example.com')
|
||||
|
||||
expect(DefaultMailbox).to receive(:new).and_return(double.tap { |d| expect(d).to receive(:perform_processing) })
|
||||
described_class.route bcc_mail
|
||||
end
|
||||
end
|
||||
|
||||
describe 'Invalid Mail To Address' do
|
||||
|
||||
@@ -334,5 +334,19 @@ RSpec.describe SupportMailbox do
|
||||
expect(conversation.messages.last.content_attributes['email']['subject']).to eq('attachment with html')
|
||||
end
|
||||
end
|
||||
|
||||
describe 'when BCC processing is disabled for account' do
|
||||
before do
|
||||
allow(GlobalConfigService).to receive(:load).with('SKIP_INCOMING_BCC_PROCESSING', '').and_return(account.id.to_s)
|
||||
end
|
||||
|
||||
it 'does not process BCC-only emails' do
|
||||
bcc_mail = create_inbound_email_from_fixture('support.eml')
|
||||
bcc_mail.mail['to'] = nil
|
||||
bcc_mail.mail['bcc'] = 'care@example.com'
|
||||
|
||||
expect { described_class.receive bcc_mail }.to raise_error('Email channel/inbox not found')
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -17,8 +17,7 @@ RSpec.describe AdministratorNotifications::BaseMailer do
|
||||
# Call the private method
|
||||
admin_emails = mailer.send(:admin_emails)
|
||||
|
||||
expect(admin_emails).to include(admin1.email)
|
||||
expect(admin_emails).to include(admin2.email)
|
||||
expect(admin_emails).to contain_exactly(admin1.email, admin2.email)
|
||||
expect(admin_emails).not_to include(agent.email)
|
||||
end
|
||||
end
|
||||
@@ -49,7 +48,7 @@ RSpec.describe AdministratorNotifications::BaseMailer do
|
||||
|
||||
# Mock the send_mail_with_liquid method
|
||||
expect(mailer).to receive(:send_mail_with_liquid).with(
|
||||
to: [admin1.email, admin2.email],
|
||||
to: contain_exactly(admin1.email, admin2.email),
|
||||
subject: subject
|
||||
).and_return(true)
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ RSpec.describe AdministratorNotifications::ChannelNotificationsMailer do
|
||||
let(:class_instance) { described_class.new }
|
||||
let!(:account) { create(:account) }
|
||||
let!(:administrator) { create(:user, :administrator, email: 'agent1@example.com', account: account) }
|
||||
let!(:another_administrator) { create(:user, :administrator, email: 'agent2@example.com', account: account) }
|
||||
|
||||
describe 'facebook_disconnect' do
|
||||
before do
|
||||
@@ -26,7 +27,7 @@ RSpec.describe AdministratorNotifications::ChannelNotificationsMailer do
|
||||
end
|
||||
|
||||
it 'renders the receiver email' do
|
||||
expect(mail.to).to eq([administrator.email])
|
||||
expect(mail.to).to contain_exactly(administrator.email, another_administrator.email)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -41,7 +42,7 @@ RSpec.describe AdministratorNotifications::ChannelNotificationsMailer do
|
||||
end
|
||||
|
||||
it 'renders the receiver email' do
|
||||
expect(mail.to).to eq([administrator.email])
|
||||
expect(mail.to).to contain_exactly(administrator.email, another_administrator.email)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -55,7 +56,7 @@ RSpec.describe AdministratorNotifications::ChannelNotificationsMailer do
|
||||
end
|
||||
|
||||
it 'renders the receiver email' do
|
||||
expect(mail.to).to eq([administrator.email])
|
||||
expect(mail.to).to contain_exactly(administrator.email, another_administrator.email)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -6,6 +6,7 @@ RSpec.describe AdministratorNotifications::IntegrationsNotificationMailer do
|
||||
|
||||
let!(:account) { create(:account) }
|
||||
let!(:administrator) { create(:user, :administrator, email: 'admin@example.com', account: account) }
|
||||
let!(:another_administrator) { create(:user, :administrator, email: 'owner@example.com', account: account) }
|
||||
|
||||
describe 'slack_disconnect' do
|
||||
let(:mail) { described_class.with(account: account).slack_disconnect.deliver_now }
|
||||
@@ -15,7 +16,7 @@ RSpec.describe AdministratorNotifications::IntegrationsNotificationMailer do
|
||||
end
|
||||
|
||||
it 'renders the receiver email' do
|
||||
expect(mail.to).to eq([administrator.email])
|
||||
expect(mail.to).to contain_exactly(administrator.email, another_administrator.email)
|
||||
end
|
||||
|
||||
it 'includes reconnect instructions in the body' do
|
||||
@@ -35,7 +36,7 @@ RSpec.describe AdministratorNotifications::IntegrationsNotificationMailer do
|
||||
end
|
||||
|
||||
it 'renders the receiver email' do
|
||||
expect(mail.to).to eq([administrator.email])
|
||||
expect(mail.to).to contain_exactly(administrator.email, another_administrator.email)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -243,8 +243,8 @@ RSpec.describe ConversationReplyMailer do
|
||||
expect(mail.decoded).to include message.content
|
||||
end
|
||||
|
||||
it 'updates the source_id' do
|
||||
expect(mail.message_id).to eq message.source_id
|
||||
it 'builds messageID properly' do
|
||||
expect(mail.message_id).to eq("conversation/#{conversation.uuid}/messages/#{message.id}@#{conversation.account.domain}")
|
||||
end
|
||||
|
||||
context 'when message is a CSAT survey' do
|
||||
@@ -335,6 +335,118 @@ RSpec.describe ConversationReplyMailer do
|
||||
expect(mail.body.encoded).not_to match(%r{<a [^>]*>avatar\.png</a>})
|
||||
end
|
||||
end
|
||||
|
||||
context 'with custom email content' do
|
||||
it 'uses custom HTML content when available and creates multipart email' do
|
||||
message_with_custom_content = create(:message,
|
||||
conversation: conversation,
|
||||
account: account,
|
||||
message_type: 'outgoing',
|
||||
content: 'Regular message content',
|
||||
content_attributes: {
|
||||
email: {
|
||||
html_content: {
|
||||
reply: '<p>Custom <strong>HTML</strong> content for email</p>'
|
||||
},
|
||||
text_content: {
|
||||
reply: 'Custom text content for email'
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
mail = described_class.email_reply(message_with_custom_content).deliver_now
|
||||
|
||||
# Check HTML part contains custom HTML content
|
||||
html_part = mail.html_part || mail
|
||||
expect(html_part.body.encoded).to include('<p>Custom <strong>HTML</strong> content for email</p>')
|
||||
expect(html_part.body.encoded).not_to include('Regular message content')
|
||||
|
||||
# Check text part contains custom text content
|
||||
text_part = mail.text_part
|
||||
if text_part
|
||||
expect(text_part.body.encoded).to include('Custom text content for email')
|
||||
expect(text_part.body.encoded).not_to include('Regular message content')
|
||||
end
|
||||
end
|
||||
|
||||
it 'falls back to markdown rendering when custom HTML content is not available' do
|
||||
message_without_custom_content = create(:message,
|
||||
conversation: conversation,
|
||||
account: account,
|
||||
message_type: 'outgoing',
|
||||
content: 'Regular **markdown** content')
|
||||
|
||||
mail = described_class.email_reply(message_without_custom_content).deliver_now
|
||||
|
||||
html_part = mail.html_part || mail
|
||||
expect(html_part.body.encoded).to include('<strong>markdown</strong>')
|
||||
expect(html_part.body.encoded).to include('Regular')
|
||||
end
|
||||
|
||||
it 'handles empty custom HTML content gracefully' do
|
||||
message_with_empty_content = create(:message,
|
||||
conversation: conversation,
|
||||
account: account,
|
||||
message_type: 'outgoing',
|
||||
content: 'Regular **markdown** content',
|
||||
content_attributes: {
|
||||
email: {
|
||||
html_content: {
|
||||
reply: ''
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
mail = described_class.email_reply(message_with_empty_content).deliver_now
|
||||
|
||||
html_part = mail.html_part || mail
|
||||
expect(html_part.body.encoded).to include('<strong>markdown</strong>')
|
||||
expect(html_part.body.encoded).to include('Regular')
|
||||
end
|
||||
|
||||
it 'handles nil custom HTML content gracefully' do
|
||||
message_with_nil_content = create(:message,
|
||||
conversation: conversation,
|
||||
account: account,
|
||||
message_type: 'outgoing',
|
||||
content: 'Regular **markdown** content',
|
||||
content_attributes: {
|
||||
email: {
|
||||
html_content: {
|
||||
reply: nil
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
mail = described_class.email_reply(message_with_nil_content).deliver_now
|
||||
|
||||
expect(mail.body.encoded).to include('<strong>markdown</strong>')
|
||||
expect(mail.body.encoded).to include('Regular')
|
||||
end
|
||||
|
||||
it 'uses custom text content in text part when only text is provided' do
|
||||
message_with_text_only = create(:message,
|
||||
conversation: conversation,
|
||||
account: account,
|
||||
message_type: 'outgoing',
|
||||
content: 'Regular message content',
|
||||
content_attributes: {
|
||||
email: {
|
||||
text_content: {
|
||||
reply: 'Custom text content only'
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
mail = described_class.email_reply(message_with_text_only).deliver_now
|
||||
|
||||
text_part = mail.text_part
|
||||
if text_part
|
||||
expect(text_part.body.encoded).to include('Custom text content only')
|
||||
expect(text_part.body.encoded).not_to include('Regular message content')
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
context 'when smtp enabled for email channel' do
|
||||
|
||||
@@ -8,7 +8,6 @@ RSpec.describe Account do
|
||||
it { is_expected.to have_many(:inboxes).dependent(:destroy_async) }
|
||||
it { is_expected.to have_many(:conversations).dependent(:destroy_async) }
|
||||
it { is_expected.to have_many(:contacts).dependent(:destroy_async) }
|
||||
it { is_expected.to have_many(:telegram_bots).dependent(:destroy_async) }
|
||||
it { is_expected.to have_many(:canned_responses).dependent(:destroy_async) }
|
||||
it { is_expected.to have_many(:facebook_pages).class_name('::Channel::FacebookPage').dependent(:destroy_async) }
|
||||
it { is_expected.to have_many(:web_widgets).class_name('::Channel::WebWidget').dependent(:destroy_async) }
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe ApplicationRecord do
|
||||
it_behaves_like 'encrypted external credential',
|
||||
factory: :channel_email,
|
||||
attribute: :smtp_password,
|
||||
value: 'smtp-secret'
|
||||
|
||||
it_behaves_like 'encrypted external credential',
|
||||
factory: :channel_email,
|
||||
attribute: :imap_password,
|
||||
value: 'imap-secret'
|
||||
|
||||
it_behaves_like 'encrypted external credential',
|
||||
factory: :channel_twilio_sms,
|
||||
attribute: :auth_token,
|
||||
value: 'twilio-secret'
|
||||
|
||||
it_behaves_like 'encrypted external credential',
|
||||
factory: :integrations_hook,
|
||||
attribute: :access_token,
|
||||
value: 'hook-secret'
|
||||
|
||||
it_behaves_like 'encrypted external credential',
|
||||
factory: :channel_facebook_page,
|
||||
attribute: :page_access_token,
|
||||
value: 'fb-page-secret'
|
||||
|
||||
it_behaves_like 'encrypted external credential',
|
||||
factory: :channel_facebook_page,
|
||||
attribute: :user_access_token,
|
||||
value: 'fb-user-secret'
|
||||
|
||||
it_behaves_like 'encrypted external credential',
|
||||
factory: :channel_instagram,
|
||||
attribute: :access_token,
|
||||
value: 'ig-secret'
|
||||
|
||||
it_behaves_like 'encrypted external credential',
|
||||
factory: :channel_line,
|
||||
attribute: :line_channel_secret,
|
||||
value: 'line-secret'
|
||||
|
||||
it_behaves_like 'encrypted external credential',
|
||||
factory: :channel_line,
|
||||
attribute: :line_channel_token,
|
||||
value: 'line-token-secret'
|
||||
|
||||
it_behaves_like 'encrypted external credential',
|
||||
factory: :channel_telegram,
|
||||
attribute: :bot_token,
|
||||
value: 'telegram-secret'
|
||||
|
||||
it_behaves_like 'encrypted external credential',
|
||||
factory: :channel_twitter_profile,
|
||||
attribute: :twitter_access_token,
|
||||
value: 'twitter-access-secret'
|
||||
|
||||
it_behaves_like 'encrypted external credential',
|
||||
factory: :channel_twitter_profile,
|
||||
attribute: :twitter_access_token_secret,
|
||||
value: 'twitter-secret-secret'
|
||||
|
||||
context 'when backfilling legacy plaintext' do
|
||||
before do
|
||||
skip('encryption keys missing; see run_mfa_spec workflow') unless Chatwoot.encryption_configured?
|
||||
end
|
||||
|
||||
it 'reads existing plaintext and encrypts on update' do
|
||||
account = create(:account)
|
||||
channel = create(:channel_email, account: account, smtp_password: nil)
|
||||
|
||||
# Simulate legacy plaintext by updating the DB directly
|
||||
sql = ActiveRecord::Base.send(
|
||||
:sanitize_sql_array,
|
||||
['UPDATE channel_email SET smtp_password = ? WHERE id = ?', 'legacy-plain', channel.id]
|
||||
)
|
||||
ActiveRecord::Base.connection.execute(sql)
|
||||
|
||||
legacy_record = Channel::Email.find(channel.id)
|
||||
expect(legacy_record.smtp_password).to eq('legacy-plain')
|
||||
|
||||
legacy_record.update!(smtp_password: 'encrypted-now')
|
||||
|
||||
stored_value = legacy_record.reload.read_attribute_before_type_cast(:smtp_password)
|
||||
expect(stored_value).to be_present
|
||||
expect(stored_value).not_to include('encrypted-now')
|
||||
expect(legacy_record.smtp_password).to eq('encrypted-now')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when looking up telegram legacy records' do
|
||||
before do
|
||||
skip('encryption keys missing; see run_mfa_spec workflow') unless Chatwoot.encryption_configured?
|
||||
end
|
||||
|
||||
it 'finds plaintext records via fallback lookup' do
|
||||
channel = create(:channel_telegram, bot_token: 'legacy-token')
|
||||
|
||||
# Simulate legacy plaintext by updating the DB directly
|
||||
sql = ActiveRecord::Base.send(
|
||||
:sanitize_sql_array,
|
||||
['UPDATE channel_telegram SET bot_token = ? WHERE id = ?', 'legacy-token', channel.id]
|
||||
)
|
||||
ActiveRecord::Base.connection.execute(sql)
|
||||
|
||||
found = Channel::Telegram.find_by(bot_token: 'legacy-token')
|
||||
expect(found).to eq(channel)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -60,6 +60,32 @@ RSpec.describe AutomationRule do
|
||||
expect(rule.valid?).to be false
|
||||
expect(rule.errors.messages[:conditions]).to eq(['Automation conditions should have query operator.'])
|
||||
end
|
||||
|
||||
it 'allows labels as a valid condition attribute' do
|
||||
params[:conditions] = [
|
||||
{
|
||||
attribute_key: 'labels',
|
||||
filter_operator: 'equal_to',
|
||||
values: ['bug'],
|
||||
query_operator: nil
|
||||
}
|
||||
]
|
||||
rule = FactoryBot.build(:automation_rule, params)
|
||||
expect(rule.valid?).to be true
|
||||
end
|
||||
|
||||
it 'validates label condition operators' do
|
||||
params[:conditions] = [
|
||||
{
|
||||
attribute_key: 'labels',
|
||||
filter_operator: 'is_present',
|
||||
values: [],
|
||||
query_operator: nil
|
||||
}
|
||||
]
|
||||
rule = FactoryBot.build(:automation_rule, params)
|
||||
expect(rule.valid?).to be true
|
||||
end
|
||||
end
|
||||
|
||||
describe 'reauthorizable' do
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe Featurable do
|
||||
let(:account) { create(:account) }
|
||||
|
||||
describe 'WhatsApp embedded signup feature' do
|
||||
it 'is disabled by default' do
|
||||
expect(account.feature_whatsapp_embedded_signup?).to be false
|
||||
expect(account.feature_enabled?('whatsapp_embedded_signup')).to be false
|
||||
end
|
||||
|
||||
describe '#enable_features!' do
|
||||
it 'enables the whatsapp embedded signup feature' do
|
||||
account.enable_features!(:whatsapp_embedded_signup)
|
||||
expect(account.feature_whatsapp_embedded_signup?).to be true
|
||||
expect(account.feature_enabled?('whatsapp_embedded_signup')).to be true
|
||||
end
|
||||
|
||||
it 'enables multiple features at once' do
|
||||
account.enable_features!(:whatsapp_embedded_signup, :help_center)
|
||||
expect(account.feature_whatsapp_embedded_signup?).to be true
|
||||
expect(account.feature_help_center?).to be true
|
||||
end
|
||||
end
|
||||
|
||||
describe '#disable_features!' do
|
||||
before do
|
||||
account.enable_features!(:whatsapp_embedded_signup)
|
||||
end
|
||||
|
||||
it 'disables the whatsapp embedded signup feature' do
|
||||
expect(account.feature_whatsapp_embedded_signup?).to be true
|
||||
|
||||
account.disable_features!(:whatsapp_embedded_signup)
|
||||
expect(account.feature_whatsapp_embedded_signup?).to be false
|
||||
end
|
||||
end
|
||||
|
||||
describe '#enabled_features' do
|
||||
it 'includes whatsapp_embedded_signup when enabled' do
|
||||
account.enable_features!(:whatsapp_embedded_signup)
|
||||
expect(account.enabled_features).to include('whatsapp_embedded_signup' => true)
|
||||
end
|
||||
|
||||
it 'does not include whatsapp_embedded_signup when disabled' do
|
||||
account.disable_features!(:whatsapp_embedded_signup)
|
||||
expect(account.enabled_features).not_to include('whatsapp_embedded_signup' => true)
|
||||
end
|
||||
end
|
||||
|
||||
describe '#all_features' do
|
||||
it 'includes whatsapp_embedded_signup in all features list' do
|
||||
expect(account.all_features).to have_key('whatsapp_embedded_signup')
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -29,6 +29,26 @@ RSpec.describe 'SwitchLocale Concern', type: :controller do
|
||||
end
|
||||
end
|
||||
|
||||
context 'when user has a locale set in ui_settings' do
|
||||
let(:user) { create(:user, ui_settings: { 'locale' => 'es' }) }
|
||||
|
||||
before { controller.instance_variable_set(:@user, user) }
|
||||
|
||||
it 'returns the user locale' do
|
||||
expect(controller.send(:locale_from_user)).to eq('es')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when user does not have a locale set' do
|
||||
let(:user) { create(:user, ui_settings: {}) }
|
||||
|
||||
before { controller.instance_variable_set(:@user, user) }
|
||||
|
||||
it 'returns nil' do
|
||||
expect(controller.send(:locale_from_user)).to be_nil
|
||||
end
|
||||
end
|
||||
|
||||
context 'when request is from custom domain' do
|
||||
before { request.host = portal.custom_domain }
|
||||
|
||||
|
||||
@@ -136,7 +136,7 @@ RSpec.describe Conversation do
|
||||
notifiable_assignee_change: false,
|
||||
changed_attributes: changed_attributes,
|
||||
performed_by: nil
|
||||
).exactly(2).times
|
||||
)
|
||||
end
|
||||
|
||||
it 'runs after_update callbacks' do
|
||||
@@ -215,7 +215,7 @@ RSpec.describe Conversation do
|
||||
it 'adds a message for system auto resolution if marked resolved by system' do
|
||||
account.update(auto_resolve_after: 40 * 24 * 60)
|
||||
conversation2 = create(:conversation, status: 'open', account: account, assignee: old_assignee)
|
||||
Current.user = nil
|
||||
Current.reset
|
||||
|
||||
message_data = if account.auto_resolve_after >= 1440 && account.auto_resolve_after % 1440 == 0
|
||||
{ key: 'auto_resolved_days', count: account.auto_resolve_after / 1440 }
|
||||
|
||||
+107
-30
@@ -4,6 +4,12 @@ require 'rails_helper'
|
||||
require Rails.root.join 'spec/models/concerns/liquidable_shared.rb'
|
||||
|
||||
RSpec.describe Message do
|
||||
before do
|
||||
# rubocop:disable RSpec/AnyInstance
|
||||
allow_any_instance_of(described_class).to receive(:reindex_for_search).and_return(true)
|
||||
# rubocop:enable RSpec/AnyInstance
|
||||
end
|
||||
|
||||
context 'with validations' do
|
||||
it { is_expected.to validate_presence_of(:inbox_id) }
|
||||
it { is_expected.to validate_presence_of(:conversation_id) }
|
||||
@@ -310,43 +316,52 @@ RSpec.describe Message do
|
||||
end
|
||||
|
||||
context 'with conversation continuity' do
|
||||
it 'calls notify email method on after save for outgoing messages in website channel' do
|
||||
allow(ConversationReplyEmailWorker).to receive(:perform_in).and_return(true)
|
||||
message.message_type = 'outgoing'
|
||||
message.save!
|
||||
expect(ConversationReplyEmailWorker).to have_received(:perform_in)
|
||||
let(:inbox_with_continuity) do
|
||||
create(:inbox, account: message.account,
|
||||
channel: build(:channel_widget, account: message.account, continuity_via_email: true))
|
||||
end
|
||||
|
||||
it 'does not call notify email for website channel if continuity is disabled' do
|
||||
message.inbox = create(:inbox, account: message.account,
|
||||
channel: build(:channel_widget, account: message.account, continuity_via_email: false))
|
||||
allow(ConversationReplyEmailWorker).to receive(:perform_in).and_return(true)
|
||||
it 'schedules email notification for outgoing messages in website channel' do
|
||||
message.inbox = inbox_with_continuity
|
||||
message.conversation.update!(inbox: inbox_with_continuity)
|
||||
message.conversation.contact.update!(email: 'test@example.com')
|
||||
message.message_type = 'outgoing'
|
||||
message.save!
|
||||
expect(ConversationReplyEmailWorker).not_to have_received(:perform_in)
|
||||
|
||||
ActiveJob::Base.queue_adapter = :test
|
||||
allow(Redis::Alfred).to receive(:set).and_return(true)
|
||||
perform_enqueued_jobs(only: SendReplyJob) do
|
||||
expect { message.save! }.to have_enqueued_job(ConversationReplyEmailJob).with(message.conversation.id, kind_of(Integer)).on_queue('mailers')
|
||||
end
|
||||
end
|
||||
|
||||
it 'wont call notify email method for private notes' do
|
||||
it 'does not schedule email for website channel if continuity is disabled' do
|
||||
inbox_without_continuity = create(:inbox, account: message.account,
|
||||
channel: build(:channel_widget, account: message.account, continuity_via_email: false))
|
||||
message.inbox = inbox_without_continuity
|
||||
message.conversation.update!(inbox: inbox_without_continuity)
|
||||
message.conversation.contact.update!(email: 'test@example.com')
|
||||
message.message_type = 'outgoing'
|
||||
|
||||
ActiveJob::Base.queue_adapter = :test
|
||||
expect { message.save! }.not_to have_enqueued_job(ConversationReplyEmailJob)
|
||||
end
|
||||
|
||||
it 'does not schedule email for private notes' do
|
||||
message.inbox = inbox_with_continuity
|
||||
message.conversation.update!(inbox: inbox_with_continuity)
|
||||
message.conversation.contact.update!(email: 'test@example.com')
|
||||
message.private = true
|
||||
allow(ConversationReplyEmailWorker).to receive(:perform_in).and_return(true)
|
||||
message.save!
|
||||
expect(ConversationReplyEmailWorker).not_to have_received(:perform_in)
|
||||
end
|
||||
|
||||
it 'calls EmailReply worker if the channel is email' do
|
||||
message.inbox = create(:inbox, account: message.account, channel: build(:channel_email, account: message.account))
|
||||
allow(EmailReplyWorker).to receive(:perform_in).and_return(true)
|
||||
message.message_type = 'outgoing'
|
||||
message.content_attributes = { email: { text_content: { quoted: 'quoted text' } } }
|
||||
message.save!
|
||||
expect(EmailReplyWorker).to have_received(:perform_in).with(1.second, message.id)
|
||||
|
||||
ActiveJob::Base.queue_adapter = :test
|
||||
expect { message.save! }.not_to have_enqueued_job(ConversationReplyEmailJob)
|
||||
end
|
||||
|
||||
it 'wont call notify email method unless its website or email channel' do
|
||||
message.inbox = create(:inbox, account: message.account, channel: build(:channel_api, account: message.account))
|
||||
allow(ConversationReplyEmailWorker).to receive(:perform_in).and_return(true)
|
||||
it 'calls SendReplyJob for all channels' do
|
||||
allow(SendReplyJob).to receive(:perform_later).and_return(true)
|
||||
message.message_type = 'outgoing'
|
||||
message.save!
|
||||
expect(ConversationReplyEmailWorker).not_to have_received(:perform_in)
|
||||
expect(SendReplyJob).to have_received(:perform_later).with(message.id)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -621,7 +636,7 @@ RSpec.describe Message do
|
||||
|
||||
before do
|
||||
allow(ChatwootApp).to receive(:advanced_search_allowed?).and_return(true)
|
||||
account.enable_features('advanced_search')
|
||||
account.enable_features('advanced_search_indexing')
|
||||
end
|
||||
|
||||
context 'when advanced search is not allowed globally' do
|
||||
@@ -634,9 +649,10 @@ RSpec.describe Message do
|
||||
end
|
||||
end
|
||||
|
||||
context 'when advanced search feature is not enabled for account' do
|
||||
context 'when advanced search feature is not enabled for account on chatwoot cloud' do
|
||||
before do
|
||||
account.disable_features('advanced_search')
|
||||
allow(ChatwootApp).to receive(:chatwoot_cloud?).and_return(true)
|
||||
account.disable_features('advanced_search_indexing')
|
||||
end
|
||||
|
||||
it 'returns false' do
|
||||
@@ -644,6 +660,17 @@ RSpec.describe Message do
|
||||
end
|
||||
end
|
||||
|
||||
context 'when advanced search feature is not enabled for account on self-hosted' do
|
||||
before do
|
||||
allow(ChatwootApp).to receive(:chatwoot_cloud?).and_return(false)
|
||||
account.disable_features('advanced_search_indexing')
|
||||
end
|
||||
|
||||
it 'returns true' do
|
||||
expect(message.should_index?).to be true
|
||||
end
|
||||
end
|
||||
|
||||
context 'when message type is not incoming or outgoing' do
|
||||
before do
|
||||
message.message_type = 'activity'
|
||||
@@ -666,4 +693,54 @@ RSpec.describe Message do
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe '#reindex_for_search callback' do
|
||||
let(:account) { create(:account) }
|
||||
let(:conversation) { create(:conversation, account: account) }
|
||||
|
||||
before do
|
||||
allow(ChatwootApp).to receive(:advanced_search_allowed?).and_return(true)
|
||||
account.enable_features('advanced_search_indexing')
|
||||
end
|
||||
|
||||
context 'when message should be indexed' do
|
||||
it 'calls reindex_for_search for incoming message on create' do
|
||||
message = build(:message, conversation: conversation, account: account, message_type: :incoming)
|
||||
expect(message).to receive(:reindex_for_search)
|
||||
message.save!
|
||||
end
|
||||
|
||||
it 'calls reindex_for_search for outgoing message on update' do
|
||||
# rubocop:disable RSpec/AnyInstance
|
||||
allow_any_instance_of(described_class).to receive(:reindex_for_search).and_return(true)
|
||||
# rubocop:enable RSpec/AnyInstance
|
||||
message = create(:message, conversation: conversation, account: account, message_type: :outgoing)
|
||||
expect(message).to receive(:reindex_for_search).and_return(true)
|
||||
message.update!(content: 'Updated content')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when message should not be indexed' do
|
||||
it 'does not call reindex_for_search for activity message' do
|
||||
message = build(:message, conversation: conversation, account: account, message_type: :activity)
|
||||
expect(message).not_to receive(:reindex_for_search)
|
||||
message.save!
|
||||
end
|
||||
|
||||
it 'does not call reindex_for_search for unpaid account on cloud' do
|
||||
allow(ChatwootApp).to receive(:chatwoot_cloud?).and_return(true)
|
||||
account.disable_features('advanced_search_indexing')
|
||||
message = build(:message, conversation: conversation, account: account, message_type: :incoming)
|
||||
expect(message).not_to receive(:reindex_for_search)
|
||||
message.save!
|
||||
end
|
||||
|
||||
it 'does not call reindex_for_search when advanced search is not allowed' do
|
||||
allow(ChatwootApp).to receive(:advanced_search_allowed?).and_return(false)
|
||||
message = build(:message, conversation: conversation, account: account, message_type: :incoming)
|
||||
expect(message).not_to receive(:reindex_for_search)
|
||||
message.save!
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -110,4 +110,148 @@ RSpec.describe User do
|
||||
expect(new_user.email).to eq('test123@test.com')
|
||||
end
|
||||
end
|
||||
|
||||
describe '2FA/MFA functionality' do
|
||||
before do
|
||||
skip('Skipping since MFA is not configured in this environment') unless Chatwoot.encryption_configured?
|
||||
end
|
||||
|
||||
let(:user) { create(:user, password: 'Test@123456') }
|
||||
|
||||
describe '#enable_two_factor!' do
|
||||
it 'generates OTP secret for 2FA setup' do
|
||||
expect(user.otp_secret).to be_nil
|
||||
expect(user.otp_required_for_login).to be_falsey
|
||||
|
||||
user.enable_two_factor!
|
||||
|
||||
expect(user.otp_secret).not_to be_nil
|
||||
# otp_required_for_login is false until verification is complete
|
||||
expect(user.otp_required_for_login).to be_falsey
|
||||
end
|
||||
end
|
||||
|
||||
describe '#disable_two_factor!' do
|
||||
before do
|
||||
user.enable_two_factor!
|
||||
user.update!(otp_required_for_login: true) # Simulate verified 2FA
|
||||
user.generate_backup_codes!
|
||||
end
|
||||
|
||||
it 'disables 2FA and clears OTP secret' do
|
||||
user.disable_two_factor!
|
||||
|
||||
expect(user.otp_secret).to be_nil
|
||||
expect(user.otp_required_for_login).to be_falsey
|
||||
expect(user.otp_backup_codes).to be_blank # Can be nil or empty array
|
||||
end
|
||||
end
|
||||
|
||||
describe '#generate_backup_codes!' do
|
||||
before do
|
||||
user.enable_two_factor!
|
||||
end
|
||||
|
||||
it 'generates 10 backup codes' do
|
||||
codes = user.generate_backup_codes!
|
||||
|
||||
expect(codes).to be_an(Array)
|
||||
expect(codes.length).to eq(10)
|
||||
expect(codes.first).to match(/\A[A-F0-9]{8}\z/) # 8-character hex codes
|
||||
expect(user.otp_backup_codes).not_to be_nil
|
||||
end
|
||||
end
|
||||
|
||||
describe '#two_factor_provisioning_uri' do
|
||||
before do
|
||||
user.enable_two_factor!
|
||||
end
|
||||
|
||||
it 'generates a valid provisioning URI for QR code' do
|
||||
uri = user.two_factor_provisioning_uri
|
||||
|
||||
expect(uri).to include('otpauth://totp/')
|
||||
expect(uri).to include(CGI.escape(user.email))
|
||||
expect(uri).to include('Chatwoot')
|
||||
end
|
||||
end
|
||||
|
||||
describe '#validate_backup_code!' do
|
||||
let(:backup_codes) { user.generate_backup_codes! }
|
||||
|
||||
before do
|
||||
user.enable_two_factor!
|
||||
backup_codes
|
||||
end
|
||||
|
||||
it 'validates and invalidates correct backup code' do
|
||||
code = backup_codes.first
|
||||
result = user.validate_backup_code!(code)
|
||||
expect(result).to be_truthy
|
||||
|
||||
# Verify it's marked as used
|
||||
user.reload
|
||||
expect(user.otp_backup_codes).to include('XXXXXXXX')
|
||||
end
|
||||
|
||||
it 'rejects invalid backup code' do
|
||||
result = user.validate_backup_code!('invalid')
|
||||
expect(result).to be_falsey
|
||||
end
|
||||
|
||||
it 'rejects already used backup code' do
|
||||
code = backup_codes.first
|
||||
user.validate_backup_code!(code)
|
||||
|
||||
# Try to use the same code again
|
||||
result = user.validate_backup_code!(code)
|
||||
expect(result).to be_falsey
|
||||
end
|
||||
|
||||
it 'handles blank code' do
|
||||
result = user.validate_backup_code!(nil)
|
||||
expect(result).to be_falsey
|
||||
|
||||
result = user.validate_backup_code!('')
|
||||
expect(result).to be_falsey
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe '#active_account_user' do
|
||||
let(:user) { create(:user) }
|
||||
let(:account1) { create(:account) }
|
||||
let(:account2) { create(:account) }
|
||||
let(:account3) { create(:account) }
|
||||
|
||||
before do
|
||||
# Create account_users with different active_at values
|
||||
create(:account_user, user: user, account: account1, active_at: 2.days.ago)
|
||||
create(:account_user, user: user, account: account2, active_at: 1.day.ago)
|
||||
create(:account_user, user: user, account: account3, active_at: nil) # New account with NULL active_at
|
||||
end
|
||||
|
||||
it 'returns the account_user with the most recent active_at, prioritizing timestamps over NULL values' do
|
||||
# Should return account2 (most recent timestamp) even though account3 was created last with NULL active_at
|
||||
expect(user.active_account_user.account_id).to eq(account2.id)
|
||||
end
|
||||
|
||||
it 'returns NULL active_at account only when no other accounts have active_at' do
|
||||
# Remove active_at from all accounts
|
||||
user.account_users.each { |au| au.update!(active_at: nil) }
|
||||
|
||||
# Should return one of the accounts (behavior is undefined but consistent)
|
||||
expect(user.active_account_user).to be_present
|
||||
end
|
||||
|
||||
context 'when multiple accounts have NULL active_at' do
|
||||
before do
|
||||
create(:account_user, user: user, account: create(:account), active_at: nil)
|
||||
end
|
||||
|
||||
it 'still prioritizes accounts with timestamps' do
|
||||
expect(user.active_account_user.account_id).to eq(account2.id)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -4,11 +4,12 @@ RSpec.describe ConversationPolicy, type: :policy do
|
||||
subject { described_class }
|
||||
|
||||
let(:account) { create(:account) }
|
||||
let(:conversation) { create(:conversation, account: account) }
|
||||
let(:administrator) { create(:user, account: account, role: :administrator) }
|
||||
let(:agent) { create(:user, account: account, role: :agent) }
|
||||
let(:administrator_context) { { user: administrator, account: account, account_user: administrator.account_users.first } }
|
||||
let(:agent_context) { { user: agent, account: account, account_user: agent.account_users.first } }
|
||||
let(:administrator_context) { { user: administrator, account: account, account_user: administrator.account_users.find_by(account: account) } }
|
||||
let(:agent_context) { { user: agent, account: account, account_user: agent.account_users.find_by(account: account) } }
|
||||
|
||||
let(:conversation) { create(:conversation, account: account) }
|
||||
|
||||
permissions :destroy? do
|
||||
context 'when user is an administrator' do
|
||||
@@ -31,4 +32,42 @@ RSpec.describe ConversationPolicy, type: :policy do
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
permissions :show? do
|
||||
context 'when user is an administrator' do
|
||||
it 'allows access' do
|
||||
expect(subject).to permit(administrator_context, conversation)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when agent has inbox access' do
|
||||
let(:inbox) { create(:inbox, account: account) }
|
||||
let(:conversation) { create(:conversation, account: account, inbox: inbox) }
|
||||
|
||||
before { create(:inbox_member, user: agent, inbox: inbox) }
|
||||
|
||||
it 'allows access' do
|
||||
expect(subject).to permit(agent_context, conversation)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when agent has team access' do
|
||||
let(:team) { create(:team, account: account) }
|
||||
let(:conversation) { create(:conversation, :with_team, account: account, team: team) }
|
||||
|
||||
before { create(:team_member, team: team, user: agent) }
|
||||
|
||||
it 'allows access' do
|
||||
expect(subject).to permit(agent_context, conversation)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when agent lacks inbox and team access' do
|
||||
let(:conversation) { create(:conversation, account: account) }
|
||||
|
||||
it 'denies access' do
|
||||
expect(subject).not_to permit(agent_context, conversation)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe Messages::SearchDataPresenter do
|
||||
let(:presenter) { described_class.new(message) }
|
||||
let(:account) { create(:account) }
|
||||
let(:inbox) { create(:inbox, account: account) }
|
||||
let(:contact) { create(:contact, account: account) }
|
||||
let(:conversation) { create(:conversation, account: account, inbox: inbox, contact: contact) }
|
||||
let(:message) { create(:message, account: account, inbox: inbox, conversation: conversation, sender: contact) }
|
||||
|
||||
describe '#search_data' do
|
||||
let(:expected_data) do
|
||||
{
|
||||
content: message.content,
|
||||
account_id: message.account_id,
|
||||
inbox_id: message.inbox_id,
|
||||
conversation_id: message.conversation_id,
|
||||
message_type: message.message_type,
|
||||
private: message.private,
|
||||
created_at: message.created_at,
|
||||
source_id: message.source_id,
|
||||
sender_id: message.sender_id,
|
||||
sender_type: message.sender_type,
|
||||
conversation: {
|
||||
id: conversation.display_id
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
it 'returns search index payload with core fields' do
|
||||
expect(presenter.search_data).to include(expected_data)
|
||||
end
|
||||
|
||||
context 'with attachments' do
|
||||
before do
|
||||
attachment = message.attachments.new(account_id: message.account_id, file_type: :image)
|
||||
attachment.file.attach(io: Rails.root.join('spec/assets/avatar.png').open, filename: 'avatar.png', content_type: 'image/png')
|
||||
attachment.meta = { 'transcribed_text' => 'Hello world' }
|
||||
end
|
||||
|
||||
it 'includes attachment transcriptions' do
|
||||
attachments_data = presenter.search_data[:attachments]
|
||||
expect(attachments_data).to be_an(Array)
|
||||
expect(attachments_data.first).to include(transcribed_text: 'Hello world')
|
||||
end
|
||||
end
|
||||
|
||||
context 'with email content attributes' do
|
||||
before do
|
||||
message.update(
|
||||
content_attributes: { email: { subject: 'Test Subject' } }
|
||||
)
|
||||
end
|
||||
|
||||
it 'includes email subject' do
|
||||
content_attrs = presenter.search_data[:content_attributes]
|
||||
expect(content_attrs[:email][:subject]).to eq('Test Subject')
|
||||
end
|
||||
end
|
||||
|
||||
context 'with campaign and automation data' do
|
||||
before do
|
||||
message.update(
|
||||
additional_attributes: { 'campaign_id' => '123' },
|
||||
content_attributes: { 'automation_rule_id' => '456' }
|
||||
)
|
||||
end
|
||||
|
||||
it 'includes campaign_id' do
|
||||
expect(presenter.search_data[:additional_attributes][:campaign_id]).to eq('123')
|
||||
end
|
||||
|
||||
it 'includes automation_rule_id' do
|
||||
expect(presenter.search_data[:additional_attributes][:automation_rule_id]).to eq('456')
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,274 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe 'MFA API', type: :request do
|
||||
before do
|
||||
skip('Skipping since MFA is not configured in this environment') unless Chatwoot.encryption_configured?
|
||||
allow(Chatwoot).to receive(:mfa_enabled?).and_return(true)
|
||||
end
|
||||
|
||||
let(:account) { create(:account) }
|
||||
let(:user) { create(:user, account: account, password: 'Test@123456') }
|
||||
|
||||
describe 'GET /api/v1/profile/mfa' do
|
||||
context 'when 2FA is disabled' do
|
||||
it 'returns MFA disabled status' do
|
||||
get '/api/v1/profile/mfa',
|
||||
headers: user.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
json_response = response.parsed_body
|
||||
expect(json_response['enabled']).to be_falsey
|
||||
expect(json_response['backup_codes_generated']).to be_falsey
|
||||
end
|
||||
end
|
||||
|
||||
context 'when 2FA is enabled' do
|
||||
before do
|
||||
user.enable_two_factor!
|
||||
user.update!(otp_required_for_login: true)
|
||||
end
|
||||
|
||||
it 'returns MFA enabled status' do
|
||||
get '/api/v1/profile/mfa',
|
||||
headers: user.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
json_response = response.parsed_body
|
||||
expect(json_response['enabled']).to be_truthy
|
||||
end
|
||||
|
||||
context 'with backup codes generated' do
|
||||
before do
|
||||
user.generate_backup_codes!
|
||||
end
|
||||
|
||||
it 'indicates backup codes are generated' do
|
||||
get '/api/v1/profile/mfa',
|
||||
headers: user.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
json_response = response.parsed_body
|
||||
expect(json_response['backup_codes_generated']).to be_truthy
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'POST /api/v1/profile/mfa' do
|
||||
context 'when 2FA is not enabled' do
|
||||
it 'enables 2FA and returns QR code URL' do
|
||||
post '/api/v1/profile/mfa',
|
||||
headers: user.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
json_response = response.parsed_body
|
||||
expect(json_response['provisioning_url']).not_to be_nil
|
||||
expect(json_response['provisioning_url']).to include('otpauth://totp')
|
||||
expect(json_response['secret']).not_to be_nil
|
||||
|
||||
user.reload
|
||||
expect(user.otp_secret).not_to be_nil
|
||||
end
|
||||
end
|
||||
|
||||
context 'when 2FA is already enabled' do
|
||||
before do
|
||||
user.enable_two_factor!
|
||||
user.update!(otp_required_for_login: true)
|
||||
end
|
||||
|
||||
it 'returns error message' do
|
||||
post '/api/v1/profile/mfa',
|
||||
headers: user.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
json_response = response.parsed_body
|
||||
expect(json_response['error']).to eq(I18n.t('errors.mfa.already_enabled'))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'POST /api/v1/profile/mfa/verify' do
|
||||
before do
|
||||
user.enable_two_factor!
|
||||
end
|
||||
|
||||
context 'with valid OTP code' do
|
||||
it 'verifies and confirms 2FA setup with backup codes' do
|
||||
otp_code = user.current_otp
|
||||
|
||||
post '/api/v1/profile/mfa/verify',
|
||||
params: { otp_code: otp_code },
|
||||
headers: user.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
json_response = response.parsed_body
|
||||
expect(json_response['enabled']).to be_truthy
|
||||
expect(json_response['backup_codes']).to be_an(Array)
|
||||
expect(json_response['backup_codes'].length).to eq(10)
|
||||
|
||||
user.reload
|
||||
expect(user.otp_required_for_login).to be_truthy
|
||||
expect(user.otp_backup_codes).not_to be_nil
|
||||
end
|
||||
end
|
||||
|
||||
context 'with invalid OTP code' do
|
||||
it 'returns error message' do
|
||||
post '/api/v1/profile/mfa/verify',
|
||||
params: { otp_code: '000000' },
|
||||
headers: user.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
json_response = response.parsed_body
|
||||
expect(json_response['error']).to eq(I18n.t('errors.mfa.invalid_code'))
|
||||
end
|
||||
end
|
||||
|
||||
context 'when 2FA is already verified' do
|
||||
before do
|
||||
user.update!(otp_required_for_login: true)
|
||||
end
|
||||
|
||||
it 'returns already enabled error' do
|
||||
post '/api/v1/profile/mfa/verify',
|
||||
params: { otp_code: user.current_otp },
|
||||
headers: user.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
json_response = response.parsed_body
|
||||
expect(json_response['error']).to eq(I18n.t('errors.mfa.already_enabled'))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'DELETE /api/v1/profile/mfa' do
|
||||
context 'when 2FA is enabled' do
|
||||
before do
|
||||
user.enable_two_factor!
|
||||
user.update!(otp_required_for_login: true)
|
||||
user.generate_backup_codes!
|
||||
end
|
||||
|
||||
context 'with valid password and OTP' do
|
||||
it 'disables 2FA successfully' do
|
||||
otp_code = user.current_otp
|
||||
|
||||
delete '/api/v1/profile/mfa',
|
||||
params: { password: 'Test@123456', otp_code: otp_code },
|
||||
headers: user.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
json_response = response.parsed_body
|
||||
expect(json_response['enabled']).to be_falsey
|
||||
|
||||
user.reload
|
||||
expect(user.otp_required_for_login).to be_falsey
|
||||
expect(user.otp_secret).to be_nil
|
||||
expect(user.otp_backup_codes).to be_blank
|
||||
end
|
||||
end
|
||||
|
||||
context 'with invalid password' do
|
||||
it 'returns error message' do
|
||||
otp_code = user.current_otp
|
||||
|
||||
delete '/api/v1/profile/mfa',
|
||||
params: { password: 'wrong_password', otp_code: otp_code },
|
||||
headers: user.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
json_response = response.parsed_body
|
||||
expect(json_response['error']).to include('Invalid')
|
||||
end
|
||||
end
|
||||
|
||||
context 'with invalid OTP' do
|
||||
it 'returns error message' do
|
||||
delete '/api/v1/profile/mfa',
|
||||
params: { password: 'Test@123456', otp_code: '000000' },
|
||||
headers: user.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
json_response = response.parsed_body
|
||||
expect(json_response['error']).to include('Invalid')
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
context 'when 2FA is not enabled' do
|
||||
it 'returns not enabled error' do
|
||||
delete '/api/v1/profile/mfa',
|
||||
params: { password: 'Test@123456', otp_code: '123456' },
|
||||
headers: user.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
json_response = response.parsed_body
|
||||
expect(json_response['error']).to eq(I18n.t('errors.mfa.not_enabled'))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'POST /api/v1/profile/mfa/backup_codes' do
|
||||
context 'when 2FA is enabled' do
|
||||
before do
|
||||
user.enable_two_factor!
|
||||
user.update!(otp_required_for_login: true)
|
||||
end
|
||||
|
||||
context 'with valid OTP' do
|
||||
it 'generates new backup codes' do
|
||||
otp_code = user.current_otp
|
||||
|
||||
post '/api/v1/profile/mfa/backup_codes',
|
||||
params: { otp_code: otp_code },
|
||||
headers: user.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
json_response = response.parsed_body
|
||||
expect(json_response['backup_codes']).to be_an(Array)
|
||||
expect(json_response['backup_codes'].length).to eq(10)
|
||||
end
|
||||
end
|
||||
|
||||
context 'with invalid OTP' do
|
||||
it 'returns error message' do
|
||||
post '/api/v1/profile/mfa/backup_codes',
|
||||
params: { otp_code: '000000' },
|
||||
headers: user.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
json_response = response.parsed_body
|
||||
expect(json_response['error']).to eq(I18n.t('errors.mfa.invalid_code'))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
context 'when 2FA is not enabled' do
|
||||
it 'returns not enabled error' do
|
||||
post '/api/v1/profile/mfa/backup_codes',
|
||||
params: { otp_code: '123456' },
|
||||
headers: user.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
json_response = response.parsed_body
|
||||
expect(json_response['error']).to eq(I18n.t('errors.mfa.not_enabled'))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -118,6 +118,45 @@ RSpec.describe AutomationRules::ActionService do
|
||||
end
|
||||
end
|
||||
|
||||
describe '#perform with add_label action' do
|
||||
before do
|
||||
rule.actions << { action_name: 'add_label', action_params: %w[bug feature] }
|
||||
rule.save
|
||||
end
|
||||
|
||||
it 'will add labels to conversation' do
|
||||
described_class.new(rule, account, conversation).perform
|
||||
expect(conversation.reload.label_list).to include('bug', 'feature')
|
||||
end
|
||||
|
||||
it 'will not duplicate existing labels' do
|
||||
conversation.add_labels(['bug'])
|
||||
described_class.new(rule, account, conversation).perform
|
||||
expect(conversation.reload.label_list.count('bug')).to eq(1)
|
||||
expect(conversation.reload.label_list).to include('feature')
|
||||
end
|
||||
end
|
||||
|
||||
describe '#perform with remove_label action' do
|
||||
before do
|
||||
conversation.add_labels(%w[bug feature support])
|
||||
rule.actions << { action_name: 'remove_label', action_params: %w[bug feature] }
|
||||
rule.save
|
||||
end
|
||||
|
||||
it 'will remove specified labels from conversation' do
|
||||
described_class.new(rule, account, conversation).perform
|
||||
expect(conversation.reload.label_list).not_to include('bug', 'feature')
|
||||
expect(conversation.reload.label_list).to include('support')
|
||||
end
|
||||
|
||||
it 'will not fail if labels do not exist on conversation' do
|
||||
conversation.update_labels(['support']) # Remove bug and feature first
|
||||
expect { described_class.new(rule, account, conversation).perform }.not_to raise_error
|
||||
expect(conversation.reload.label_list).to include('support')
|
||||
end
|
||||
end
|
||||
|
||||
describe '#perform with add_private_note action' do
|
||||
let(:message_builder) { double }
|
||||
|
||||
|
||||
@@ -134,5 +134,86 @@ RSpec.describe AutomationRules::ConditionsFilterService do
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
context 'when conditions based on labels' do
|
||||
before do
|
||||
conversation.add_labels(['bug'])
|
||||
end
|
||||
|
||||
context 'when filter_operator is equal_to' do
|
||||
before do
|
||||
rule.conditions = [
|
||||
{ 'values': ['bug'], 'attribute_key': 'labels', 'query_operator': nil, 'filter_operator': 'equal_to' }
|
||||
]
|
||||
rule.save
|
||||
end
|
||||
|
||||
it 'will return true when conversation has the label' do
|
||||
expect(described_class.new(rule, conversation, { changed_attributes: {} }).perform).to be(true)
|
||||
end
|
||||
|
||||
it 'will return false when conversation does not have the label' do
|
||||
rule.conditions = [
|
||||
{ 'values': ['feature'], 'attribute_key': 'labels', 'query_operator': nil, 'filter_operator': 'equal_to' }
|
||||
]
|
||||
rule.save
|
||||
expect(described_class.new(rule, conversation, { changed_attributes: {} }).perform).to be(false)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when filter_operator is not_equal_to' do
|
||||
before do
|
||||
rule.conditions = [
|
||||
{ 'values': ['feature'], 'attribute_key': 'labels', 'query_operator': nil, 'filter_operator': 'not_equal_to' }
|
||||
]
|
||||
rule.save
|
||||
end
|
||||
|
||||
it 'will return true when conversation does not have the label' do
|
||||
expect(described_class.new(rule, conversation, { changed_attributes: {} }).perform).to be(true)
|
||||
end
|
||||
|
||||
it 'will return false when conversation has the label' do
|
||||
conversation.add_labels(['feature'])
|
||||
expect(described_class.new(rule, conversation, { changed_attributes: {} }).perform).to be(false)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when filter_operator is is_present' do
|
||||
before do
|
||||
rule.conditions = [
|
||||
{ 'values': [], 'attribute_key': 'labels', 'query_operator': nil, 'filter_operator': 'is_present' }
|
||||
]
|
||||
rule.save
|
||||
end
|
||||
|
||||
it 'will return true when conversation has any labels' do
|
||||
expect(described_class.new(rule, conversation, { changed_attributes: {} }).perform).to be(true)
|
||||
end
|
||||
|
||||
it 'will return false when conversation has no labels' do
|
||||
conversation.update_labels([])
|
||||
expect(described_class.new(rule, conversation, { changed_attributes: {} }).perform).to be(false)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when filter_operator is is_not_present' do
|
||||
before do
|
||||
rule.conditions = [
|
||||
{ 'values': [], 'attribute_key': 'labels', 'query_operator': nil, 'filter_operator': 'is_not_present' }
|
||||
]
|
||||
rule.save
|
||||
end
|
||||
|
||||
it 'will return false when conversation has any labels' do
|
||||
expect(described_class.new(rule, conversation, { changed_attributes: {} }).perform).to be(false)
|
||||
end
|
||||
|
||||
it 'will return true when conversation has no labels' do
|
||||
conversation.update_labels([])
|
||||
expect(described_class.new(rule, conversation, { changed_attributes: {} }).perform).to be(true)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
require 'rails_helper'
|
||||
|
||||
describe BaseTokenService do
|
||||
let(:payload) { { user_id: 1, exp: 5.minutes.from_now.to_i } }
|
||||
let(:token_service) { described_class.new(payload: payload) }
|
||||
|
||||
describe '#generate_token' do
|
||||
it 'generates a JWT token with the provided payload' do
|
||||
token = token_service.generate_token
|
||||
expect(token).to be_present
|
||||
expect(token).to be_a(String)
|
||||
end
|
||||
|
||||
it 'encodes the payload correctly' do
|
||||
token = token_service.generate_token
|
||||
decoded = JWT.decode(token, Rails.application.secret_key_base, true, algorithm: 'HS256').first
|
||||
expect(decoded['user_id']).to eq(1)
|
||||
end
|
||||
end
|
||||
|
||||
describe '#decode_token' do
|
||||
let(:token) { token_service.generate_token }
|
||||
let(:decoder_service) { described_class.new(token: token) }
|
||||
|
||||
it 'decodes a valid JWT token' do
|
||||
decoded = decoder_service.decode_token
|
||||
expect(decoded[:user_id]).to eq(1)
|
||||
end
|
||||
|
||||
it 'returns empty hash for invalid token' do
|
||||
invalid_service = described_class.new(token: 'invalid_token')
|
||||
expect(invalid_service.decode_token).to eq({})
|
||||
end
|
||||
|
||||
it 'returns empty hash for expired token' do
|
||||
expired_payload = { user_id: 1, exp: 1.minute.ago.to_i }
|
||||
expired_token = JWT.encode(expired_payload, Rails.application.secret_key_base, 'HS256')
|
||||
expired_service = described_class.new(token: expired_token)
|
||||
expect(expired_service.decode_token).to eq({})
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,38 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe Contacts::BulkActionService do
|
||||
subject(:service) { described_class.new(account: account, user: user, params: params) }
|
||||
|
||||
let(:account) { create(:account) }
|
||||
let(:user) { create(:user, account: account) }
|
||||
|
||||
describe '#perform' do
|
||||
context 'when delete action is requested via action_name' do
|
||||
let(:params) { { ids: [1, 2], action_name: 'delete' } }
|
||||
|
||||
it 'delegates to the bulk delete service' do
|
||||
bulk_delete_service = instance_double(Contacts::BulkDeleteService, perform: true)
|
||||
|
||||
expect(Contacts::BulkDeleteService).to receive(:new)
|
||||
.with(account: account, contact_ids: [1, 2])
|
||||
.and_return(bulk_delete_service)
|
||||
|
||||
service.perform
|
||||
end
|
||||
end
|
||||
|
||||
context 'when labels are provided' do
|
||||
let(:params) { { ids: [10, 20], labels: { add: %w[vip support] }, extra: 'ignored' } }
|
||||
|
||||
it 'delegates to the bulk assign labels service with permitted params' do
|
||||
bulk_assign_service = instance_double(Contacts::BulkAssignLabelsService, perform: true)
|
||||
|
||||
expect(Contacts::BulkAssignLabelsService).to receive(:new)
|
||||
.with(account: account, contact_ids: [10, 20], labels: %w[vip support])
|
||||
.and_return(bulk_assign_service)
|
||||
|
||||
service.perform
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,48 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe Contacts::BulkAssignLabelsService do
|
||||
subject(:service) do
|
||||
described_class.new(
|
||||
account: account,
|
||||
contact_ids: [contact_one.id, contact_two.id, other_contact.id],
|
||||
labels: labels
|
||||
)
|
||||
end
|
||||
|
||||
let(:account) { create(:account) }
|
||||
let!(:contact_one) { create(:contact, account: account) }
|
||||
let!(:contact_two) { create(:contact, account: account) }
|
||||
let!(:other_contact) { create(:contact) }
|
||||
let(:labels) { %w[vip support] }
|
||||
|
||||
it 'assigns labels to the contacts that belong to the account' do
|
||||
service.perform
|
||||
|
||||
expect(contact_one.reload.label_list).to include(*labels)
|
||||
expect(contact_two.reload.label_list).to include(*labels)
|
||||
end
|
||||
|
||||
it 'does not assign labels to contacts outside the account' do
|
||||
service.perform
|
||||
|
||||
expect(other_contact.reload.label_list).to be_empty
|
||||
end
|
||||
|
||||
it 'returns ids of contacts that were updated' do
|
||||
result = service.perform
|
||||
|
||||
expect(result[:success]).to be(true)
|
||||
expect(result[:updated_contact_ids]).to contain_exactly(contact_one.id, contact_two.id)
|
||||
end
|
||||
|
||||
it 'returns success with no updates when labels are blank' do
|
||||
result = described_class.new(
|
||||
account: account,
|
||||
contact_ids: [contact_one.id],
|
||||
labels: []
|
||||
).perform
|
||||
|
||||
expect(result).to eq(success: true, updated_contact_ids: [])
|
||||
expect(contact_one.reload.label_list).to be_empty
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,24 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe Contacts::BulkDeleteService do
|
||||
subject(:service) { described_class.new(account: account, contact_ids: contact_ids) }
|
||||
|
||||
let(:account) { create(:account) }
|
||||
let!(:contact_one) { create(:contact, account: account) }
|
||||
let!(:contact_two) { create(:contact, account: account) }
|
||||
let(:contact_ids) { [contact_one.id, contact_two.id] }
|
||||
|
||||
describe '#perform' do
|
||||
it 'deletes the provided contacts' do
|
||||
expect { service.perform }
|
||||
.to change { account.contacts.exists?(contact_one.id) }.from(true).to(false)
|
||||
.and change { account.contacts.exists?(contact_two.id) }.from(true).to(false)
|
||||
end
|
||||
|
||||
it 'returns when no contact ids are provided' do
|
||||
empty_service = described_class.new(account: account, contact_ids: [])
|
||||
|
||||
expect { empty_service.perform }.not_to change(Contact, :count)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -7,9 +7,25 @@ describe Contacts::FilterService do
|
||||
let!(:first_user) { create(:user, account: account) }
|
||||
let!(:second_user) { create(:user, account: account) }
|
||||
let!(:inbox) { create(:inbox, account: account, enable_auto_assignment: false) }
|
||||
let!(:en_contact) { create(:contact, account: account, additional_attributes: { 'country_code': 'uk' }) }
|
||||
let!(:el_contact) { create(:contact, account: account, additional_attributes: { 'country_code': 'gr' }) }
|
||||
let!(:cs_contact) { create(:contact, account: account, additional_attributes: { 'country_code': 'cz' }) }
|
||||
let!(:en_contact) do
|
||||
create(:contact,
|
||||
account: account,
|
||||
email: Faker::Internet.unique.email,
|
||||
additional_attributes: { 'country_code': 'uk' })
|
||||
end
|
||||
let!(:el_contact) do
|
||||
create(:contact,
|
||||
account: account,
|
||||
email: Faker::Internet.unique.email,
|
||||
additional_attributes: { 'country_code': 'gr' })
|
||||
end
|
||||
let!(:cs_contact) do
|
||||
create(:contact,
|
||||
:with_phone_number,
|
||||
account: account,
|
||||
email: Faker::Internet.unique.email,
|
||||
additional_attributes: { 'country_code': 'cz' })
|
||||
end
|
||||
|
||||
before do
|
||||
create(:inbox_member, user: first_user, inbox: inbox)
|
||||
@@ -65,9 +81,50 @@ describe Contacts::FilterService do
|
||||
end
|
||||
end
|
||||
|
||||
context 'with standard attributes - phone' do
|
||||
it 'filter contacts by name' do
|
||||
params[:payload] = [
|
||||
{
|
||||
attribute_key: 'phone_number',
|
||||
filter_operator: 'equal_to',
|
||||
values: [cs_contact.phone_number],
|
||||
query_operator: nil
|
||||
}.with_indifferent_access
|
||||
]
|
||||
|
||||
result = filter_service.new(account, first_user, params).perform
|
||||
expect(result[:count]).to be 1
|
||||
expect(result[:contacts].length).to be 1
|
||||
expect(result[:contacts].first.name).to eq(cs_contact.name)
|
||||
end
|
||||
end
|
||||
|
||||
context 'with standard attributes - phone (without +)' do
|
||||
it 'filter contacts by name' do
|
||||
params[:payload] = [
|
||||
{
|
||||
attribute_key: 'phone_number',
|
||||
filter_operator: 'equal_to',
|
||||
values: [cs_contact.phone_number[1..]],
|
||||
query_operator: nil
|
||||
}.with_indifferent_access
|
||||
]
|
||||
|
||||
result = filter_service.new(account, first_user, params).perform
|
||||
expect(result[:count]).to be 1
|
||||
expect(result[:contacts].length).to be 1
|
||||
expect(result[:contacts].first.name).to eq(cs_contact.name)
|
||||
end
|
||||
end
|
||||
|
||||
context 'with standard attributes - blocked' do
|
||||
it 'filter contacts by blocked' do
|
||||
blocked_contact = create(:contact, account: account, blocked: true)
|
||||
blocked_contact = create(
|
||||
:contact,
|
||||
account: account,
|
||||
blocked: true,
|
||||
email: Faker::Internet.unique.email
|
||||
)
|
||||
params = { payload: [{ attribute_key: 'blocked', filter_operator: 'equal_to', values: ['true'],
|
||||
query_operator: nil }.with_indifferent_access] }
|
||||
result = filter_service.new(account, first_user, params).perform
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
require 'rails_helper'
|
||||
|
||||
describe Email::SendOnEmailService do
|
||||
let(:account) { create(:account) }
|
||||
let(:email_channel) { create(:channel_email, account: account) }
|
||||
let(:inbox) { create(:inbox, account: account, channel: email_channel) }
|
||||
let(:conversation) { create(:conversation, account: account, inbox: inbox) }
|
||||
let(:message) { create(:message, conversation: conversation, message_type: 'outgoing') }
|
||||
let(:service) { described_class.new(message: message) }
|
||||
|
||||
describe '#perform' do
|
||||
let(:mailer_context) { instance_double(ConversationReplyMailer) }
|
||||
let(:delivery) { instance_double(ActionMailer::MessageDelivery) }
|
||||
let(:email_message) { instance_double(Mail::Message) }
|
||||
|
||||
before do
|
||||
allow(ConversationReplyMailer).to receive(:with).with(account: message.account).and_return(mailer_context)
|
||||
end
|
||||
|
||||
context 'when message is email notifiable' do
|
||||
before do
|
||||
allow(mailer_context).to receive(:email_reply).with(message).and_return(delivery)
|
||||
allow(delivery).to receive(:deliver_now).and_return(email_message)
|
||||
allow(email_message).to receive(:message_id).and_return(
|
||||
"conversation/#{conversation.uuid}/messages/" \
|
||||
"#{message.id}@#{conversation.account.domain}"
|
||||
)
|
||||
end
|
||||
|
||||
it 'sends email via ConversationReplyMailer' do
|
||||
service.perform
|
||||
|
||||
expect(ConversationReplyMailer).to have_received(:with).with(account: message.account)
|
||||
expect(mailer_context).to have_received(:email_reply).with(message)
|
||||
expect(delivery).to have_received(:deliver_now)
|
||||
end
|
||||
|
||||
it 'updates message source id on success' do
|
||||
service.perform
|
||||
|
||||
expect(message.reload.source_id).to eq("conversation/#{conversation.uuid}/messages/#{message.id}@#{conversation.account.domain}")
|
||||
end
|
||||
end
|
||||
|
||||
context 'when message is not email notifiable' do
|
||||
let(:message) { create(:message, conversation: conversation, message_type: 'incoming') }
|
||||
|
||||
before do
|
||||
allow(mailer_context).to receive(:email_reply)
|
||||
end
|
||||
|
||||
it 'does not send email' do
|
||||
service.perform
|
||||
|
||||
expect(ConversationReplyMailer).not_to have_received(:with)
|
||||
expect(mailer_context).not_to have_received(:email_reply)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when an error occurs' do
|
||||
let(:error_message) { 'SMTP connection failed' }
|
||||
let(:error) { StandardError.new(error_message) }
|
||||
let(:exception_tracker) { instance_double(ChatwootExceptionTracker, capture_exception: true) }
|
||||
let(:status_service) { instance_double(Messages::StatusUpdateService, perform: true) }
|
||||
|
||||
before do
|
||||
allow(mailer_context).to receive(:email_reply).with(message).and_return(delivery)
|
||||
allow(delivery).to receive(:deliver_now).and_raise(error)
|
||||
allow(ChatwootExceptionTracker).to receive(:new).and_return(exception_tracker)
|
||||
end
|
||||
|
||||
it 'captures the exception' do
|
||||
expect(ChatwootExceptionTracker).to receive(:new).with(error, account: message.account)
|
||||
|
||||
service.perform
|
||||
end
|
||||
|
||||
it 'updates message status to failed' do
|
||||
service.perform
|
||||
|
||||
expect(message.reload.status).to eq('failed')
|
||||
expect(message.reload.external_error).to eq(error_message)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -35,6 +35,62 @@ describe Line::IncomingMessageService do
|
||||
}.with_indifferent_access
|
||||
end
|
||||
|
||||
let(:follow_params) do
|
||||
{
|
||||
'destination': '2342234234',
|
||||
'events': [
|
||||
{
|
||||
'replyToken': '8cf9239d56244f4197887e939187e19e',
|
||||
'type': 'follow',
|
||||
'mode': 'active',
|
||||
'timestamp': 1_462_629_479_859,
|
||||
'source': {
|
||||
'type': 'user',
|
||||
'userId': 'U4af4980629'
|
||||
}
|
||||
}
|
||||
]
|
||||
}.with_indifferent_access
|
||||
end
|
||||
|
||||
let(:multi_user_params) do
|
||||
{
|
||||
'destination': '2342234234',
|
||||
'events': [
|
||||
{
|
||||
'replyToken': '0f3779fba3b349968c5d07db31eab56f1',
|
||||
'type': 'message',
|
||||
'mode': 'active',
|
||||
'timestamp': 1_462_629_479_859,
|
||||
'source': {
|
||||
'type': 'user',
|
||||
'userId': 'U4af4980629'
|
||||
},
|
||||
'message': {
|
||||
'id': '3257081',
|
||||
'type': 'text',
|
||||
'text': 'Hello, world 1'
|
||||
}
|
||||
},
|
||||
{
|
||||
'replyToken': '0f3779fba3b349968c5d07db31eab56f2',
|
||||
'type': 'message',
|
||||
'mode': 'active',
|
||||
'timestamp': 1_462_629_479_859,
|
||||
'source': {
|
||||
'type': 'user',
|
||||
'userId': 'U4af49806292'
|
||||
},
|
||||
'message': {
|
||||
'id': '3257082',
|
||||
'type': 'text',
|
||||
'text': 'Hello, world 2'
|
||||
}
|
||||
}
|
||||
]
|
||||
}.with_indifferent_access
|
||||
end
|
||||
|
||||
let(:image_params) do
|
||||
{
|
||||
'destination': '2342234234',
|
||||
@@ -105,6 +161,40 @@ describe Line::IncomingMessageService do
|
||||
}.with_indifferent_access
|
||||
end
|
||||
|
||||
let(:file_params) do
|
||||
{
|
||||
'destination': '2342234234',
|
||||
'events': [
|
||||
{
|
||||
'replyToken': '0f3779fba3b349968c5d07db31eab56f',
|
||||
'type': 'message',
|
||||
'mode': 'active',
|
||||
'timestamp': 1_462_629_479_859,
|
||||
'source': {
|
||||
'type': 'user',
|
||||
'userId': 'U4af4980629'
|
||||
},
|
||||
'message': {
|
||||
'type': 'file',
|
||||
'id': '354718',
|
||||
'fileName': 'contacts.csv',
|
||||
'fileSize': 2978
|
||||
}
|
||||
},
|
||||
{
|
||||
'replyToken': '8cf9239d56244f4197887e939187e19e',
|
||||
'type': 'follow',
|
||||
'mode': 'active',
|
||||
'timestamp': 1_462_629_479_859,
|
||||
'source': {
|
||||
'type': 'user',
|
||||
'userId': 'U4af4980629'
|
||||
}
|
||||
}
|
||||
]
|
||||
}.with_indifferent_access
|
||||
end
|
||||
|
||||
let(:sticker_params) do
|
||||
{
|
||||
'destination': '2342234234',
|
||||
@@ -141,8 +231,8 @@ describe Line::IncomingMessageService do
|
||||
end
|
||||
|
||||
describe '#perform' do
|
||||
context 'when valid text message params' do
|
||||
it 'creates appropriate conversations, message and contacts' do
|
||||
context 'when non-text message params' do
|
||||
it 'does not create conversations, messages and contacts' do
|
||||
line_bot = double
|
||||
line_user_profile = double
|
||||
allow(Line::Bot::Client).to receive(:new).and_return(line_bot)
|
||||
@@ -154,12 +244,56 @@ describe Line::IncomingMessageService do
|
||||
'pictureUrl': 'https://test.com'
|
||||
}.to_json
|
||||
)
|
||||
described_class.new(inbox: line_channel.inbox, params: follow_params).perform
|
||||
expect(line_channel.inbox.conversations.size).to eq(0)
|
||||
expect(Contact.all.size).to eq(0)
|
||||
expect(line_channel.inbox.messages.size).to eq(0)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when valid text message params' do
|
||||
let(:line_bot) { double }
|
||||
let(:line_user_profile) { double }
|
||||
|
||||
before do
|
||||
allow(Line::Bot::Client).to receive(:new).and_return(line_bot)
|
||||
allow(line_bot).to receive(:get_profile).with('U4af4980629').and_return(line_user_profile)
|
||||
allow(line_user_profile).to receive(:body).and_return(
|
||||
{
|
||||
'displayName': 'LINE Test',
|
||||
'userId': 'U4af4980629',
|
||||
'pictureUrl': 'https://test.com'
|
||||
}.to_json
|
||||
)
|
||||
end
|
||||
|
||||
it 'creates appropriate conversations, message and contacts' do
|
||||
described_class.new(inbox: line_channel.inbox, params: params).perform
|
||||
expect(line_channel.inbox.conversations).not_to eq(0)
|
||||
expect(Contact.all.first.name).to eq('LINE Test')
|
||||
expect(Contact.all.first.additional_attributes['social_line_user_id']).to eq('U4af4980629')
|
||||
expect(line_channel.inbox.messages.first.content).to eq('Hello, world')
|
||||
end
|
||||
|
||||
it 'creates appropriate conversations, message and contacts for multi user' do
|
||||
line_user_profile2 = double
|
||||
allow(line_bot).to receive(:get_profile).with('U4af49806292').and_return(line_user_profile2)
|
||||
allow(line_user_profile2).to receive(:body).and_return(
|
||||
{
|
||||
'displayName': 'LINE Test 2',
|
||||
'userId': 'U4af49806292',
|
||||
'pictureUrl': 'https://test.com'
|
||||
}.to_json
|
||||
)
|
||||
described_class.new(inbox: line_channel.inbox, params: multi_user_params).perform
|
||||
expect(line_channel.inbox.conversations.size).to eq(2)
|
||||
expect(Contact.all.first.name).to eq('LINE Test')
|
||||
expect(Contact.all.first.additional_attributes['social_line_user_id']).to eq('U4af4980629')
|
||||
expect(Contact.all.last.name).to eq('LINE Test 2')
|
||||
expect(Contact.all.last.additional_attributes['social_line_user_id']).to eq('U4af49806292')
|
||||
expect(line_channel.inbox.messages.first.content).to eq('Hello, world 1')
|
||||
expect(line_channel.inbox.messages.last.content).to eq('Hello, world 2')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when valid sticker message params' do
|
||||
@@ -241,5 +375,35 @@ describe Line::IncomingMessageService do
|
||||
expect(line_channel.inbox.messages.first.attachments.first.file.blob.filename.to_s).to eq('media-354718.mp4')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when valid file message params' do
|
||||
it 'creates appropriate conversations, message and contacts' do
|
||||
line_bot = double
|
||||
line_user_profile = double
|
||||
allow(Line::Bot::Client).to receive(:new).and_return(line_bot)
|
||||
allow(line_bot).to receive(:get_profile).and_return(line_user_profile)
|
||||
file = fixture_file_upload(Rails.root.join('spec/assets/contacts.csv'), 'text/csv')
|
||||
allow(line_bot).to receive(:get_message_content).and_return(
|
||||
OpenStruct.new({
|
||||
body: Base64.encode64(file.read),
|
||||
content_type: 'text/csv'
|
||||
})
|
||||
)
|
||||
allow(line_user_profile).to receive(:body).and_return(
|
||||
{
|
||||
'displayName': 'LINE Test',
|
||||
'userId': 'U4af4980629',
|
||||
'pictureUrl': 'https://test.com'
|
||||
}.to_json
|
||||
)
|
||||
described_class.new(inbox: line_channel.inbox, params: file_params).perform
|
||||
expect(line_channel.inbox.conversations).not_to eq(0)
|
||||
expect(Contact.all.first.name).to eq('LINE Test')
|
||||
expect(Contact.all.first.additional_attributes['social_line_user_id']).to eq('U4af4980629')
|
||||
expect(line_channel.inbox.messages.first.content).to be_nil
|
||||
expect(line_channel.inbox.messages.first.attachments.first.file_type).to eq('file')
|
||||
expect(line_channel.inbox.messages.first.attachments.first.file.blob.filename.to_s).to eq('contacts.csv')
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -28,6 +28,14 @@ RSpec.describe LlmFormatter::ConversationLlmFormatter do
|
||||
content: 'Hello, I need help'
|
||||
)
|
||||
|
||||
create(
|
||||
:message,
|
||||
:bot_message,
|
||||
conversation: conversation,
|
||||
message_type: 'outgoing',
|
||||
content: 'Thanks for reaching out, an agent will reach out to you soon'
|
||||
)
|
||||
|
||||
create(
|
||||
:message,
|
||||
conversation: conversation,
|
||||
@@ -40,7 +48,8 @@ RSpec.describe LlmFormatter::ConversationLlmFormatter do
|
||||
"Channel: #{conversation.inbox.channel.name}",
|
||||
'Message History:',
|
||||
'User: Hello, I need help',
|
||||
'Support agent: How can I assist you today?',
|
||||
'Bot: Thanks for reaching out, an agent will reach out to you soon',
|
||||
'Support Agent: How can I assist you today?',
|
||||
''
|
||||
].join("\n")
|
||||
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
require 'rails_helper'
|
||||
|
||||
describe Messages::SendEmailNotificationService do
|
||||
let(:account) { create(:account) }
|
||||
let(:conversation) { create(:conversation, account: account) }
|
||||
let(:message) { create(:message, conversation: conversation, message_type: 'outgoing') }
|
||||
let(:service) { described_class.new(message: message) }
|
||||
|
||||
describe '#perform' do
|
||||
context 'when email notification should be sent' do
|
||||
let(:inbox) { create(:inbox, account: account, channel: create(:channel_widget, account: account, continuity_via_email: true)) }
|
||||
let(:conversation) { create(:conversation, account: account, inbox: inbox) }
|
||||
|
||||
before do
|
||||
conversation.contact.update!(email: 'test@example.com')
|
||||
allow(Redis::Alfred).to receive(:set).and_return(true)
|
||||
ActiveJob::Base.queue_adapter = :test
|
||||
end
|
||||
|
||||
it 'enqueues ConversationReplyEmailJob' do
|
||||
expect { service.perform }.to have_enqueued_job(ConversationReplyEmailJob).with(conversation.id, message.id).on_queue('mailers')
|
||||
end
|
||||
|
||||
it 'atomically sets redis key to prevent duplicate emails' do
|
||||
expected_key = format(Redis::Alfred::CONVERSATION_MAILER_KEY, conversation_id: conversation.id)
|
||||
|
||||
service.perform
|
||||
|
||||
expect(Redis::Alfred).to have_received(:set).with(expected_key, message.id, nx: true, ex: 1.hour.to_i)
|
||||
end
|
||||
|
||||
context 'when redis key already exists' do
|
||||
before do
|
||||
allow(Redis::Alfred).to receive(:set).and_return(false)
|
||||
end
|
||||
|
||||
it 'does not enqueue job' do
|
||||
expect { service.perform }.not_to have_enqueued_job(ConversationReplyEmailJob)
|
||||
end
|
||||
|
||||
it 'attempts atomic set once' do
|
||||
service.perform
|
||||
|
||||
expect(Redis::Alfred).to have_received(:set).once
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
context 'when handling concurrent requests' do
|
||||
let(:inbox) { create(:inbox, account: account, channel: create(:channel_widget, account: account, continuity_via_email: true)) }
|
||||
let(:conversation) { create(:conversation, account: account, inbox: inbox) }
|
||||
|
||||
before do
|
||||
conversation.contact.update!(email: 'test@example.com')
|
||||
end
|
||||
|
||||
it 'prevents duplicate jobs under race conditions' do
|
||||
# Create 5 threads that simultaneously try to enqueue workers for the same conversation
|
||||
threads = Array.new(5) do
|
||||
Thread.new do
|
||||
msg = create(:message, conversation: conversation, message_type: 'outgoing')
|
||||
described_class.new(message: msg).perform
|
||||
end
|
||||
end
|
||||
|
||||
threads.each(&:join)
|
||||
|
||||
# Only ONE job should be scheduled despite 5 concurrent attempts
|
||||
jobs_for_conversation = ActiveJob::Base.queue_adapter.enqueued_jobs.select do |job|
|
||||
job[:job] == ConversationReplyEmailJob && job[:args].first == conversation.id
|
||||
end
|
||||
expect(jobs_for_conversation.size).to eq(1)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when email notification should not be sent' do
|
||||
before do
|
||||
ActiveJob::Base.queue_adapter = :test
|
||||
end
|
||||
|
||||
context 'when message is not email notifiable' do
|
||||
let(:message) { create(:message, conversation: conversation, message_type: 'incoming') }
|
||||
|
||||
it 'does not enqueue job' do
|
||||
expect { service.perform }.not_to have_enqueued_job(ConversationReplyEmailJob)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when contact has no email' do
|
||||
let(:inbox) { create(:inbox, account: account, channel: create(:channel_widget, account: account, continuity_via_email: true)) }
|
||||
let(:conversation) { create(:conversation, account: account, inbox: inbox) }
|
||||
|
||||
before do
|
||||
conversation.contact.update!(email: nil)
|
||||
end
|
||||
|
||||
it 'does not enqueue job' do
|
||||
expect { service.perform }.not_to have_enqueued_job(ConversationReplyEmailJob)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when channel does not support email notifications' do
|
||||
let(:inbox) { create(:inbox, account: account, channel: create(:channel_sms, account: account)) }
|
||||
let(:conversation) { create(:conversation, account: account, inbox: inbox) }
|
||||
|
||||
before do
|
||||
conversation.contact.update!(email: 'test@example.com')
|
||||
end
|
||||
|
||||
it 'does not enqueue job' do
|
||||
expect { service.perform }.not_to have_enqueued_job(ConversationReplyEmailJob)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe '#should_send_email_notification?' do
|
||||
context 'with WebWidget channel' do
|
||||
let(:inbox) { create(:inbox, account: account, channel: create(:channel_widget, account: account, continuity_via_email: true)) }
|
||||
let(:conversation) { create(:conversation, account: account, inbox: inbox) }
|
||||
|
||||
before do
|
||||
conversation.contact.update!(email: 'test@example.com')
|
||||
end
|
||||
|
||||
it 'returns true when continuity_via_email is enabled' do
|
||||
expect(service.send(:should_send_email_notification?)).to be true
|
||||
end
|
||||
|
||||
context 'when continuity_via_email is disabled' do
|
||||
let(:inbox) { create(:inbox, account: account, channel: create(:channel_widget, account: account, continuity_via_email: false)) }
|
||||
|
||||
it 'returns false' do
|
||||
expect(service.send(:should_send_email_notification?)).to be false
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
context 'with API channel' do
|
||||
let(:inbox) { create(:inbox, account: account, channel: create(:channel_api, account: account)) }
|
||||
let(:conversation) { create(:conversation, account: account, inbox: inbox) }
|
||||
|
||||
before do
|
||||
conversation.contact.update!(email: 'test@example.com')
|
||||
allow(account).to receive(:feature_enabled?).and_return(false)
|
||||
allow(account).to receive(:feature_enabled?).with('email_continuity_on_api_channel').and_return(true)
|
||||
end
|
||||
|
||||
it 'returns true when email_continuity_on_api_channel feature is enabled' do
|
||||
expect(service.send(:should_send_email_notification?)).to be true
|
||||
end
|
||||
|
||||
context 'when email_continuity_on_api_channel feature is disabled' do
|
||||
before do
|
||||
allow(account).to receive(:feature_enabled?).and_return(false)
|
||||
allow(account).to receive(:feature_enabled?).with('email_continuity_on_api_channel').and_return(false)
|
||||
end
|
||||
|
||||
it 'returns false' do
|
||||
expect(service.send(:should_send_email_notification?)).to be false
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
context 'with other channels' do
|
||||
let(:inbox) { create(:inbox, account: account, channel: create(:channel_email, account: account)) }
|
||||
let(:conversation) { create(:conversation, account: account, inbox: inbox) }
|
||||
|
||||
before do
|
||||
conversation.contact.update!(email: 'test@example.com')
|
||||
end
|
||||
|
||||
it 'returns false' do
|
||||
expect(service.send(:should_send_email_notification?)).to be false
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,106 @@
|
||||
require 'rails_helper'
|
||||
|
||||
describe Mfa::AuthenticationService do
|
||||
before do
|
||||
skip('Skipping since MFA is not configured in this environment') unless Chatwoot.encryption_configured?
|
||||
user.enable_two_factor!
|
||||
user.update!(otp_required_for_login: true)
|
||||
end
|
||||
|
||||
let(:user) { create(:user) }
|
||||
|
||||
describe '#authenticate' do
|
||||
context 'with OTP code' do
|
||||
context 'when OTP is valid' do
|
||||
it 'returns true' do
|
||||
valid_otp = user.current_otp
|
||||
service = described_class.new(user: user, otp_code: valid_otp)
|
||||
expect(service.authenticate).to be_truthy
|
||||
end
|
||||
end
|
||||
|
||||
context 'when OTP is invalid' do
|
||||
it 'returns false' do
|
||||
service = described_class.new(user: user, otp_code: '000000')
|
||||
expect(service.authenticate).to be_falsey
|
||||
end
|
||||
end
|
||||
|
||||
context 'when OTP is nil' do
|
||||
it 'returns false' do
|
||||
service = described_class.new(user: user, otp_code: nil)
|
||||
expect(service.authenticate).to be_falsey
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
context 'with backup code' do
|
||||
let(:backup_codes) { user.generate_backup_codes! }
|
||||
|
||||
context 'when backup code is valid' do
|
||||
it 'returns true and invalidates the code' do
|
||||
valid_code = backup_codes.first
|
||||
service = described_class.new(user: user, backup_code: valid_code)
|
||||
|
||||
expect(service.authenticate).to be_truthy
|
||||
|
||||
# Code should be invalidated after use
|
||||
user.reload
|
||||
expect(user.otp_backup_codes).to include('XXXXXXXX')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when backup code is invalid' do
|
||||
it 'returns false' do
|
||||
service = described_class.new(user: user, backup_code: 'invalid')
|
||||
expect(service.authenticate).to be_falsey
|
||||
end
|
||||
end
|
||||
|
||||
context 'when backup code has already been used' do
|
||||
it 'returns false' do
|
||||
valid_code = backup_codes.first
|
||||
# Use the code once
|
||||
service = described_class.new(user: user, backup_code: valid_code)
|
||||
service.authenticate
|
||||
|
||||
# Try to use it again
|
||||
service2 = described_class.new(user: user.reload, backup_code: valid_code)
|
||||
expect(service2.authenticate).to be_falsey
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
context 'with neither OTP nor backup code' do
|
||||
it 'returns false' do
|
||||
service = described_class.new(user: user)
|
||||
expect(service.authenticate).to be_falsey
|
||||
end
|
||||
end
|
||||
|
||||
context 'when user is nil' do
|
||||
it 'returns false' do
|
||||
service = described_class.new(user: nil, otp_code: '123456')
|
||||
expect(service.authenticate).to be_falsey
|
||||
end
|
||||
end
|
||||
|
||||
context 'when both OTP and backup code are provided' do
|
||||
it 'uses OTP authentication first' do
|
||||
valid_otp = user.current_otp
|
||||
backup_codes = user.generate_backup_codes!
|
||||
|
||||
service = described_class.new(
|
||||
user: user,
|
||||
otp_code: valid_otp,
|
||||
backup_code: backup_codes.first
|
||||
)
|
||||
|
||||
expect(service.authenticate).to be_truthy
|
||||
# Backup code should not be consumed
|
||||
user.reload
|
||||
expect(user.otp_backup_codes).not_to include('XXXXXXXX')
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,72 @@
|
||||
require 'rails_helper'
|
||||
|
||||
describe Mfa::TokenService do
|
||||
before do
|
||||
skip('Skipping since MFA is not configured in this environment') unless Chatwoot.encryption_configured?
|
||||
end
|
||||
|
||||
let(:user) { create(:user) }
|
||||
let(:token_service) { described_class.new(user: user) }
|
||||
|
||||
describe '#generate_token' do
|
||||
it 'generates a JWT token with user_id' do
|
||||
token = token_service.generate_token
|
||||
expect(token).to be_present
|
||||
expect(token).to be_a(String)
|
||||
end
|
||||
|
||||
it 'includes user_id in the payload' do
|
||||
token = token_service.generate_token
|
||||
decoded = JWT.decode(token, Rails.application.secret_key_base, true, algorithm: 'HS256').first
|
||||
expect(decoded['user_id']).to eq(user.id)
|
||||
end
|
||||
|
||||
it 'sets expiration to 5 minutes from now' do
|
||||
allow(Time).to receive(:now).and_return(Time.zone.parse('2024-01-01 12:00:00'))
|
||||
token = token_service.generate_token
|
||||
decoded = JWT.decode(token, Rails.application.secret_key_base, true, algorithm: 'HS256').first
|
||||
expected_exp = Time.zone.parse('2024-01-01 12:05:00').to_i
|
||||
expect(decoded['exp']).to eq(expected_exp)
|
||||
end
|
||||
end
|
||||
|
||||
describe '#verify_token' do
|
||||
let(:valid_token) { token_service.generate_token }
|
||||
|
||||
context 'with valid token' do
|
||||
it 'returns the user' do
|
||||
verifier = described_class.new(token: valid_token)
|
||||
verified_user = verifier.verify_token
|
||||
expect(verified_user).to eq(user)
|
||||
end
|
||||
end
|
||||
|
||||
context 'with invalid token' do
|
||||
it 'returns nil for malformed token' do
|
||||
verifier = described_class.new(token: 'invalid_token')
|
||||
expect(verifier.verify_token).to be_nil
|
||||
end
|
||||
|
||||
it 'returns nil for expired token' do
|
||||
expired_payload = { user_id: user.id, exp: 1.minute.ago.to_i }
|
||||
expired_token = JWT.encode(expired_payload, Rails.application.secret_key_base, 'HS256')
|
||||
verifier = described_class.new(token: expired_token)
|
||||
expect(verifier.verify_token).to be_nil
|
||||
end
|
||||
|
||||
it 'returns nil for non-existent user' do
|
||||
payload = { user_id: 999_999, exp: 5.minutes.from_now.to_i }
|
||||
token = JWT.encode(payload, Rails.application.secret_key_base, 'HS256')
|
||||
verifier = described_class.new(token: token)
|
||||
expect(verifier.verify_token).to be_nil
|
||||
end
|
||||
end
|
||||
|
||||
context 'with blank token' do
|
||||
it 'returns nil' do
|
||||
verifier = described_class.new(token: nil)
|
||||
expect(verifier.verify_token).to be_nil
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user