Merge remote-tracking branch 'origin/develop' into captain/pdf_support_be

This commit is contained in:
Tanmay Deep Sharma
2025-08-19 11:52:57 +05:30
341 changed files with 8639 additions and 2394 deletions
@@ -0,0 +1,63 @@
require 'rails_helper'
RSpec.describe 'Assignment Policy Inboxes API', type: :request do
let(:account) { create(:account) }
let(:assignment_policy) { create(:assignment_policy, account: account) }
describe 'GET /api/v1/accounts/{account_id}/assignment_policies/{assignment_policy_id}/inboxes' do
context 'when it is an unauthenticated user' do
it 'returns unauthorized' do
get "/api/v1/accounts/#{account.id}/assignment_policies/#{assignment_policy.id}/inboxes"
expect(response).to have_http_status(:unauthorized)
end
end
context 'when it is an authenticated admin' do
let(:admin) { create(:user, account: account, role: :administrator) }
context 'when assignment policy has associated inboxes' do
before do
inbox1 = create(:inbox, account: account)
inbox2 = create(:inbox, account: account)
create(:inbox_assignment_policy, inbox: inbox1, assignment_policy: assignment_policy)
create(:inbox_assignment_policy, inbox: inbox2, assignment_policy: assignment_policy)
end
it 'returns all inboxes associated with the assignment policy' do
get "/api/v1/accounts/#{account.id}/assignment_policies/#{assignment_policy.id}/inboxes",
headers: admin.create_new_auth_token,
as: :json
expect(response).to have_http_status(:success)
json_response = response.parsed_body
expect(json_response['inboxes']).to be_an(Array)
expect(json_response['inboxes'].length).to eq(2)
end
end
context 'when assignment policy has no associated inboxes' do
it 'returns empty array' do
get "/api/v1/accounts/#{account.id}/assignment_policies/#{assignment_policy.id}/inboxes",
headers: admin.create_new_auth_token,
as: :json
expect(response).to have_http_status(:success)
json_response = response.parsed_body
expect(json_response['inboxes']).to eq([])
end
end
end
context 'when it is an agent' do
let(:agent) { create(:user, account: account, role: :agent) }
it 'returns unauthorized' do
get "/api/v1/accounts/#{account.id}/assignment_policies/#{assignment_policy.id}/inboxes",
headers: agent.create_new_auth_token,
as: :json
expect(response).to have_http_status(:unauthorized)
end
end
end
end
@@ -0,0 +1,326 @@
require 'rails_helper'
RSpec.describe 'Assignment Policies API', type: :request do
let(:account) { create(:account) }
describe 'GET /api/v1/accounts/{account.id}/assignment_policies' do
context 'when it is an unauthenticated user' do
it 'returns unauthorized' do
get "/api/v1/accounts/#{account.id}/assignment_policies"
expect(response).to have_http_status(:unauthorized)
end
end
context 'when it is an authenticated admin' do
let(:admin) { create(:user, account: account, role: :administrator) }
before do
create_list(:assignment_policy, 3, account: account)
end
it 'returns all assignment policies for the account' do
get "/api/v1/accounts/#{account.id}/assignment_policies",
headers: admin.create_new_auth_token,
as: :json
expect(response).to have_http_status(:success)
json_response = response.parsed_body
expect(json_response.length).to eq(3)
expect(json_response.first.keys).to include('id', 'name', 'description')
end
end
context 'when it is an agent' do
let(:agent) { create(:user, account: account, role: :agent) }
it 'returns unauthorized' do
get "/api/v1/accounts/#{account.id}/assignment_policies",
headers: agent.create_new_auth_token,
as: :json
expect(response).to have_http_status(:unauthorized)
end
end
end
describe 'GET /api/v1/accounts/{account.id}/assignment_policies/:id' do
let(:assignment_policy) { create(:assignment_policy, account: account) }
context 'when it is an unauthenticated user' do
it 'returns unauthorized' do
get "/api/v1/accounts/#{account.id}/assignment_policies/#{assignment_policy.id}"
expect(response).to have_http_status(:unauthorized)
end
end
context 'when it is an authenticated admin' do
let(:admin) { create(:user, account: account, role: :administrator) }
it 'returns the assignment policy' do
get "/api/v1/accounts/#{account.id}/assignment_policies/#{assignment_policy.id}",
headers: admin.create_new_auth_token,
as: :json
expect(response).to have_http_status(:success)
json_response = response.parsed_body
expect(json_response['id']).to eq(assignment_policy.id)
expect(json_response['name']).to eq(assignment_policy.name)
end
it 'returns not found for non-existent policy' do
get "/api/v1/accounts/#{account.id}/assignment_policies/999999",
headers: admin.create_new_auth_token,
as: :json
expect(response).to have_http_status(:not_found)
end
end
context 'when it is an agent' do
let(:agent) { create(:user, account: account, role: :agent) }
it 'returns unauthorized' do
get "/api/v1/accounts/#{account.id}/assignment_policies/#{assignment_policy.id}",
headers: agent.create_new_auth_token,
as: :json
expect(response).to have_http_status(:unauthorized)
end
end
end
describe 'POST /api/v1/accounts/{account.id}/assignment_policies' do
let(:valid_params) do
{
assignment_policy: {
name: 'New Assignment Policy',
description: 'Policy for new team',
conversation_priority: 'longest_waiting',
fair_distribution_limit: 15,
enabled: true
}
}
end
context 'when it is an unauthenticated user' do
it 'returns unauthorized' do
post "/api/v1/accounts/#{account.id}/assignment_policies", params: valid_params
expect(response).to have_http_status(:unauthorized)
end
end
context 'when it is an authenticated admin' do
let(:admin) { create(:user, account: account, role: :administrator) }
it 'creates a new assignment policy' do
expect do
post "/api/v1/accounts/#{account.id}/assignment_policies",
headers: admin.create_new_auth_token,
params: valid_params,
as: :json
end.to change(AssignmentPolicy, :count).by(1)
expect(response).to have_http_status(:success)
json_response = response.parsed_body
expect(json_response['name']).to eq('New Assignment Policy')
expect(json_response['conversation_priority']).to eq('longest_waiting')
end
it 'creates policy with minimal required params' do
minimal_params = { assignment_policy: { name: 'Minimal Policy' } }
expect do
post "/api/v1/accounts/#{account.id}/assignment_policies",
headers: admin.create_new_auth_token,
params: minimal_params,
as: :json
end.to change(AssignmentPolicy, :count).by(1)
expect(response).to have_http_status(:success)
end
it 'prevents duplicate policy names within account' do
create(:assignment_policy, account: account, name: 'Duplicate Policy')
duplicate_params = { assignment_policy: { name: 'Duplicate Policy' } }
expect do
post "/api/v1/accounts/#{account.id}/assignment_policies",
headers: admin.create_new_auth_token,
params: duplicate_params,
as: :json
end.not_to change(AssignmentPolicy, :count)
expect(response).to have_http_status(:unprocessable_entity)
end
it 'validates required fields' do
invalid_params = { assignment_policy: { name: '' } }
post "/api/v1/accounts/#{account.id}/assignment_policies",
headers: admin.create_new_auth_token,
params: invalid_params,
as: :json
expect(response).to have_http_status(:unprocessable_entity)
end
end
context 'when it is an agent' do
let(:agent) { create(:user, account: account, role: :agent) }
it 'returns unauthorized' do
post "/api/v1/accounts/#{account.id}/assignment_policies",
headers: agent.create_new_auth_token,
params: valid_params,
as: :json
expect(response).to have_http_status(:unauthorized)
end
end
end
describe 'PUT /api/v1/accounts/{account.id}/assignment_policies/:id' do
let(:assignment_policy) { create(:assignment_policy, account: account, name: 'Original Policy') }
let(:update_params) do
{
assignment_policy: {
name: 'Updated Policy',
description: 'Updated description',
fair_distribution_limit: 20
}
}
end
context 'when it is an unauthenticated user' do
it 'returns unauthorized' do
put "/api/v1/accounts/#{account.id}/assignment_policies/#{assignment_policy.id}",
params: update_params
expect(response).to have_http_status(:unauthorized)
end
end
context 'when it is an authenticated admin' do
let(:admin) { create(:user, account: account, role: :administrator) }
it 'updates the assignment policy' do
put "/api/v1/accounts/#{account.id}/assignment_policies/#{assignment_policy.id}",
headers: admin.create_new_auth_token,
params: update_params,
as: :json
expect(response).to have_http_status(:success)
assignment_policy.reload
expect(assignment_policy.name).to eq('Updated Policy')
expect(assignment_policy.fair_distribution_limit).to eq(20)
end
it 'allows partial updates' do
partial_params = { assignment_policy: { enabled: false } }
put "/api/v1/accounts/#{account.id}/assignment_policies/#{assignment_policy.id}",
headers: admin.create_new_auth_token,
params: partial_params,
as: :json
expect(response).to have_http_status(:success)
expect(assignment_policy.reload.enabled).to be(false)
expect(assignment_policy.name).to eq('Original Policy') # unchanged
end
it 'prevents duplicate names during update' do
create(:assignment_policy, account: account, name: 'Existing Policy')
duplicate_params = { assignment_policy: { name: 'Existing Policy' } }
put "/api/v1/accounts/#{account.id}/assignment_policies/#{assignment_policy.id}",
headers: admin.create_new_auth_token,
params: duplicate_params,
as: :json
expect(response).to have_http_status(:unprocessable_entity)
end
it 'returns not found for non-existent policy' do
put "/api/v1/accounts/#{account.id}/assignment_policies/999999",
headers: admin.create_new_auth_token,
params: update_params,
as: :json
expect(response).to have_http_status(:not_found)
end
end
context 'when it is an agent' do
let(:agent) { create(:user, account: account, role: :agent) }
it 'returns unauthorized' do
put "/api/v1/accounts/#{account.id}/assignment_policies/#{assignment_policy.id}",
headers: agent.create_new_auth_token,
params: update_params,
as: :json
expect(response).to have_http_status(:unauthorized)
end
end
end
describe 'DELETE /api/v1/accounts/{account.id}/assignment_policies/:id' do
let(:assignment_policy) { create(:assignment_policy, account: account) }
context 'when it is an unauthenticated user' do
it 'returns unauthorized' do
delete "/api/v1/accounts/#{account.id}/assignment_policies/#{assignment_policy.id}"
expect(response).to have_http_status(:unauthorized)
end
end
context 'when it is an authenticated admin' do
let(:admin) { create(:user, account: account, role: :administrator) }
it 'deletes the assignment policy' do
assignment_policy # create it first
expect do
delete "/api/v1/accounts/#{account.id}/assignment_policies/#{assignment_policy.id}",
headers: admin.create_new_auth_token,
as: :json
end.to change(AssignmentPolicy, :count).by(-1)
expect(response).to have_http_status(:ok)
end
it 'cascades deletion to associated inbox assignment policies' do
inbox = create(:inbox, account: account)
create(:inbox_assignment_policy, inbox: inbox, assignment_policy: assignment_policy)
expect do
delete "/api/v1/accounts/#{account.id}/assignment_policies/#{assignment_policy.id}",
headers: admin.create_new_auth_token,
as: :json
end.to change(InboxAssignmentPolicy, :count).by(-1)
expect(response).to have_http_status(:ok)
end
it 'returns not found for non-existent policy' do
delete "/api/v1/accounts/#{account.id}/assignment_policies/999999",
headers: admin.create_new_auth_token,
as: :json
expect(response).to have_http_status(:not_found)
end
end
context 'when it is an agent' do
let(:agent) { create(:user, account: account, role: :agent) }
it 'returns unauthorized' do
delete "/api/v1/accounts/#{account.id}/assignment_policies/#{assignment_policy.id}",
headers: agent.create_new_auth_token,
as: :json
expect(response).to have_http_status(:unauthorized)
end
end
end
end
@@ -0,0 +1,195 @@
require 'rails_helper'
RSpec.describe 'Inbox Assignment Policies API', type: :request do
let(:account) { create(:account) }
let(:inbox) { create(:inbox, account: account) }
let(:assignment_policy) { create(:assignment_policy, account: account) }
describe 'GET /api/v1/accounts/{account_id}/inboxes/{inbox_id}/assignment_policy' do
context 'when it is an unauthenticated user' do
it 'returns unauthorized' do
get "/api/v1/accounts/#{account.id}/inboxes/#{inbox.id}/assignment_policy"
expect(response).to have_http_status(:unauthorized)
end
end
context 'when it is an authenticated admin' do
let(:admin) { create(:user, account: account, role: :administrator) }
context 'when inbox has an assignment policy' do
before do
create(:inbox_assignment_policy, inbox: inbox, assignment_policy: assignment_policy)
end
it 'returns the assignment policy for the inbox' do
get "/api/v1/accounts/#{account.id}/inboxes/#{inbox.id}/assignment_policy",
headers: admin.create_new_auth_token,
as: :json
expect(response).to have_http_status(:success)
json_response = response.parsed_body
expect(json_response['id']).to eq(assignment_policy.id)
expect(json_response['name']).to eq(assignment_policy.name)
end
end
context 'when inbox has no assignment policy' do
it 'returns not found' do
get "/api/v1/accounts/#{account.id}/inboxes/#{inbox.id}/assignment_policy",
headers: admin.create_new_auth_token,
as: :json
expect(response).to have_http_status(:not_found)
end
end
end
context 'when it is an agent' do
let(:agent) { create(:user, account: account, role: :agent) }
it 'returns unauthorized' do
get "/api/v1/accounts/#{account.id}/inboxes/#{inbox.id}/assignment_policy",
headers: agent.create_new_auth_token,
as: :json
expect(response).to have_http_status(:unauthorized)
end
end
end
describe 'POST /api/v1/accounts/{account_id}/inboxes/{inbox_id}/assignment_policy' do
context 'when it is an unauthenticated user' do
it 'returns unauthorized' do
post "/api/v1/accounts/#{account.id}/inboxes/#{inbox.id}/assignment_policy",
params: { assignment_policy_id: assignment_policy.id }
expect(response).to have_http_status(:unauthorized)
end
end
context 'when it is an authenticated admin' do
let(:admin) { create(:user, account: account, role: :administrator) }
it 'assigns a policy to the inbox' do
expect do
post "/api/v1/accounts/#{account.id}/inboxes/#{inbox.id}/assignment_policy",
params: { assignment_policy_id: assignment_policy.id },
headers: admin.create_new_auth_token,
as: :json
end.to change(InboxAssignmentPolicy, :count).by(1)
expect(response).to have_http_status(:success)
json_response = response.parsed_body
expect(json_response['id']).to eq(assignment_policy.id)
end
it 'replaces existing assignment policy for inbox' do
other_policy = create(:assignment_policy, account: account)
create(:inbox_assignment_policy, inbox: inbox, assignment_policy: other_policy)
expect do
post "/api/v1/accounts/#{account.id}/inboxes/#{inbox.id}/assignment_policy",
params: { assignment_policy_id: assignment_policy.id },
headers: admin.create_new_auth_token,
as: :json
end.not_to change(InboxAssignmentPolicy, :count)
expect(response).to have_http_status(:success)
expect(inbox.reload.inbox_assignment_policy.assignment_policy).to eq(assignment_policy)
end
it 'returns not found for invalid assignment policy' do
post "/api/v1/accounts/#{account.id}/inboxes/#{inbox.id}/assignment_policy",
params: { assignment_policy_id: 999_999 },
headers: admin.create_new_auth_token,
as: :json
expect(response).to have_http_status(:not_found)
end
it 'returns not found for invalid inbox' do
post "/api/v1/accounts/#{account.id}/inboxes/999999/assignment_policy",
params: { assignment_policy_id: assignment_policy.id },
headers: admin.create_new_auth_token,
as: :json
expect(response).to have_http_status(:not_found)
end
end
context 'when it is an agent' do
let(:agent) { create(:user, account: account, role: :agent) }
it 'returns unauthorized' do
post "/api/v1/accounts/#{account.id}/inboxes/#{inbox.id}/assignment_policy",
params: { assignment_policy_id: assignment_policy.id },
headers: agent.create_new_auth_token,
as: :json
expect(response).to have_http_status(:unauthorized)
end
end
end
describe 'DELETE /api/v1/accounts/{account_id}/inboxes/{inbox_id}/assignment_policy' do
context 'when it is an unauthenticated user' do
it 'returns unauthorized' do
delete "/api/v1/accounts/#{account.id}/inboxes/#{inbox.id}/assignment_policy"
expect(response).to have_http_status(:unauthorized)
end
end
context 'when it is an authenticated admin' do
let(:admin) { create(:user, account: account, role: :administrator) }
context 'when inbox has an assignment policy' do
before do
create(:inbox_assignment_policy, inbox: inbox, assignment_policy: assignment_policy)
end
it 'removes the assignment policy from inbox' do
expect do
delete "/api/v1/accounts/#{account.id}/inboxes/#{inbox.id}/assignment_policy",
headers: admin.create_new_auth_token,
as: :json
end.to change(InboxAssignmentPolicy, :count).by(-1)
expect(response).to have_http_status(:success)
expect(inbox.reload.inbox_assignment_policy).to be_nil
end
end
context 'when inbox has no assignment policy' do
it 'returns error' do
expect do
delete "/api/v1/accounts/#{account.id}/inboxes/#{inbox.id}/assignment_policy",
headers: admin.create_new_auth_token,
as: :json
end.not_to change(InboxAssignmentPolicy, :count)
expect(response).to have_http_status(:not_found)
end
end
it 'returns not found for invalid inbox' do
delete "/api/v1/accounts/#{account.id}/inboxes/999999/assignment_policy",
headers: admin.create_new_auth_token,
as: :json
expect(response).to have_http_status(:not_found)
end
end
context 'when it is an agent' do
let(:agent) { create(:user, account: account, role: :agent) }
it 'returns unauthorized' do
delete "/api/v1/accounts/#{account.id}/inboxes/#{inbox.id}/assignment_policy",
headers: agent.create_new_auth_token,
as: :json
expect(response).to have_http_status(:unauthorized)
end
end
end
end
@@ -9,6 +9,7 @@ RSpec.describe Captain::Conversation::ResponseBuilderJob, type: :job do
describe '#perform' do
let(:conversation) { create(:conversation, inbox: inbox, account: account) }
let(:mock_llm_chat_service) { instance_double(Captain::Llm::AssistantChatService) }
let(:mock_agent_runner_service) { instance_double(Captain::Assistant::AgentRunnerService) }
before do
create(:message, conversation: conversation, content: 'Hello', message_type: :incoming)
@@ -16,19 +17,79 @@ RSpec.describe Captain::Conversation::ResponseBuilderJob, type: :job do
allow(inbox).to receive(:captain_active?).and_return(true)
allow(Captain::Llm::AssistantChatService).to receive(:new).and_return(mock_llm_chat_service)
allow(mock_llm_chat_service).to receive(:generate_response).and_return({ 'response' => 'Hey, welcome to Captain Specs' })
allow(Captain::Assistant::AgentRunnerService).to receive(:new).and_return(mock_agent_runner_service)
allow(mock_agent_runner_service).to receive(:generate_response).and_return({ 'response' => 'Hey, welcome to Captain V2' })
end
it 'generates and processes response' do
described_class.perform_now(conversation, assistant)
expect(conversation.messages.count).to eq(2)
expect(conversation.messages.outgoing.count).to eq(1)
expect(conversation.messages.last.content).to eq('Hey, welcome to Captain Specs')
context 'when captain_v2 is disabled' do
before do
allow(account).to receive(:feature_enabled?).and_return(false)
allow(account).to receive(:feature_enabled?).with('captain_integration_v2').and_return(false)
end
it 'uses Captain::Llm::AssistantChatService' do
expect(Captain::Llm::AssistantChatService).to receive(:new).with(assistant: assistant)
expect(Captain::Assistant::AgentRunnerService).not_to receive(:new)
described_class.perform_now(conversation, assistant)
expect(conversation.messages.last.content).to eq('Hey, welcome to Captain Specs')
end
it 'generates and processes response' do
described_class.perform_now(conversation, assistant)
expect(conversation.messages.count).to eq(2)
expect(conversation.messages.outgoing.count).to eq(1)
expect(conversation.messages.last.content).to eq('Hey, welcome to Captain Specs')
end
it 'increments usage response' do
described_class.perform_now(conversation, assistant)
account.reload
expect(account.usage_limits[:captain][:responses][:consumed]).to eq(1)
end
end
it 'increments usage response' do
described_class.perform_now(conversation, assistant)
account.reload
expect(account.usage_limits[:captain][:responses][:consumed]).to eq(1)
context 'when captain_v2 is enabled' do
before do
allow(account).to receive(:feature_enabled?).and_return(false)
allow(account).to receive(:feature_enabled?).with('captain_integration_v2').and_return(true)
end
it 'uses Captain::Assistant::AgentRunnerService' do
expect(Captain::Assistant::AgentRunnerService).to receive(:new).with(
assistant: assistant,
conversation: conversation
)
expect(Captain::Llm::AssistantChatService).not_to receive(:new)
described_class.perform_now(conversation, assistant)
expect(conversation.messages.last.content).to eq('Hey, welcome to Captain V2')
end
it 'passes message history to agent runner service' do
expected_messages = [
{ content: 'Hello', role: 'user' }
]
expect(mock_agent_runner_service).to receive(:generate_response).with(
message_history: expected_messages
)
described_class.perform_now(conversation, assistant)
end
it 'generates and processes response' do
described_class.perform_now(conversation, assistant)
expect(conversation.messages.count).to eq(2)
expect(conversation.messages.outgoing.count).to eq(1)
expect(conversation.messages.last.content).to eq('Hey, welcome to Captain V2')
end
it 'increments usage response' do
described_class.perform_now(conversation, assistant)
account.reload
expect(account.usage_limits[:captain][:responses][:consumed]).to eq(1)
end
end
context 'when message contains an image' do
@@ -0,0 +1,123 @@
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Captain::PromptRenderer do
let(:template_name) { 'test_template' }
let(:template_content) { 'Hello {{name}}, your balance is {{balance}}' }
let(:template_path) { Rails.root.join('enterprise', 'lib', 'captain', 'prompts', "#{template_name}.liquid") }
let(:context) { { name: 'John', balance: 100 } }
before do
allow(File).to receive(:exist?).and_return(false)
allow(File).to receive(:exist?).with(template_path).and_return(true)
allow(File).to receive(:read).with(template_path).and_return(template_content)
end
describe '.render' do
it 'renders template with context' do
result = described_class.render(template_name, context)
expect(result).to eq('Hello John, your balance is 100')
end
it 'handles string keys in context' do
string_context = { 'name' => 'Jane', 'balance' => 200 }
result = described_class.render(template_name, string_context)
expect(result).to eq('Hello Jane, your balance is 200')
end
it 'handles mixed symbol and string keys' do
mixed_context = { :name => 'Bob', 'balance' => 300 }
result = described_class.render(template_name, mixed_context)
expect(result).to eq('Hello Bob, your balance is 300')
end
it 'handles nested hash context' do
nested_template = 'User: {{user.name}}, Account: {{user.account.type}}'
nested_context = { user: { name: 'Alice', account: { type: 'premium' } } }
allow(File).to receive(:read).with(template_path).and_return(nested_template)
result = described_class.render(template_name, nested_context)
expect(result).to eq('User: Alice, Account: premium')
end
it 'handles empty context' do
simple_template = 'Hello World'
allow(File).to receive(:read).with(template_path).and_return(simple_template)
result = described_class.render(template_name, {})
expect(result).to eq('Hello World')
end
it 'loads and parses liquid template' do
liquid_template_double = instance_double(Liquid::Template)
allow(Liquid::Template).to receive(:parse).with(template_content).and_return(liquid_template_double)
allow(liquid_template_double).to receive(:render).with(hash_including('name', 'balance')).and_return('rendered')
result = described_class.render(template_name, context)
expect(result).to eq('rendered')
expect(Liquid::Template).to have_received(:parse).with(template_content)
end
end
describe '.load_template' do
it 'reads template file from correct path' do
described_class.send(:load_template, template_name)
expect(File).to have_received(:read).with(template_path)
end
it 'raises error when template does not exist' do
allow(File).to receive(:exist?).with(template_path).and_return(false)
expect { described_class.send(:load_template, template_name) }
.to raise_error("Template not found: #{template_name}")
end
it 'constructs correct template path' do
expected_path = Rails.root.join('enterprise/lib/captain/prompts/my_template.liquid')
allow(File).to receive(:exist?).with(expected_path).and_return(true)
allow(File).to receive(:read).with(expected_path).and_return('test content')
described_class.send(:load_template, 'my_template')
expect(File).to have_received(:exist?).with(expected_path)
end
end
describe '.stringify_keys' do
it 'converts symbol keys to strings' do
hash = { name: 'John', age: 30 }
result = described_class.send(:stringify_keys, hash)
expect(result).to eq({ 'name' => 'John', 'age' => 30 })
end
it 'handles nested hashes' do
hash = { user: { name: 'John', profile: { age: 30 } } }
result = described_class.send(:stringify_keys, hash)
expect(result).to eq({ 'user' => { 'name' => 'John', 'profile' => { 'age' => 30 } } })
end
it 'handles arrays with hashes' do
hash = { users: [{ name: 'John' }, { name: 'Jane' }] }
result = described_class.send(:stringify_keys, hash)
expect(result).to eq({ 'users' => [{ 'name' => 'John' }, { 'name' => 'Jane' }] })
end
it 'handles empty hash' do
result = described_class.send(:stringify_keys, {})
expect(result).to eq({})
end
end
end
@@ -0,0 +1,18 @@
require 'rails_helper'
RSpec.describe AssignmentPolicy do
let(:account) { create(:account) }
describe 'enum values' do
let(:assignment_policy) { create(:assignment_policy, account: account) }
describe 'assignment_order' do
it 'can be set to balanced' do
assignment_policy.update!(assignment_order: :balanced)
expect(assignment_policy.assignment_order).to eq('balanced')
expect(assignment_policy.round_robin?).to be false
expect(assignment_policy.balanced?).to be true
end
end
end
end
@@ -0,0 +1,186 @@
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Concerns::Agentable do
let(:dummy_class) do
Class.new do
include Concerns::Agentable
attr_accessor :temperature
def initialize(name: 'Test Agent', temperature: 0.8)
@name = name
@temperature = temperature
end
def self.name
'DummyClass'
end
private
def agent_name
@name
end
def prompt_context
{ base_key: 'base_value' }
end
end
end
let(:dummy_instance) { dummy_class.new }
let(:mock_agents_agent) { instance_double(Agents::Agent) }
let(:mock_installation_config) { instance_double(InstallationConfig, value: 'gpt-4-turbo') }
before do
allow(Agents::Agent).to receive(:new).and_return(mock_agents_agent)
allow(InstallationConfig).to receive(:find_by).with(name: 'CAPTAIN_OPEN_AI_MODEL').and_return(mock_installation_config)
allow(Captain::PromptRenderer).to receive(:render).and_return('rendered_template')
end
describe '#agent' do
it 'creates an Agents::Agent with correct parameters' do
expect(Agents::Agent).to receive(:new).with(
name: 'Test Agent',
instructions: instance_of(Proc),
tools: [],
model: 'gpt-4-turbo',
temperature: 0.8,
response_schema: Captain::ResponseSchema
)
dummy_instance.agent
end
it 'converts nil temperature to 0.0' do
dummy_instance.temperature = nil
expect(Agents::Agent).to receive(:new).with(
hash_including(temperature: 0.0)
)
dummy_instance.agent
end
it 'converts temperature to float' do
dummy_instance.temperature = '0.5'
expect(Agents::Agent).to receive(:new).with(
hash_including(temperature: 0.5)
)
dummy_instance.agent
end
end
describe '#agent_instructions' do
it 'calls Captain::PromptRenderer with base context' do
expect(Captain::PromptRenderer).to receive(:render).with(
'dummy_class',
hash_including(base_key: 'base_value')
)
dummy_instance.agent_instructions
end
it 'merges context state when provided' do
context_double = instance_double(Agents::RunContext,
context: {
state: {
conversation: { id: 123 },
contact: { name: 'John' }
}
})
expected_context = {
base_key: 'base_value',
conversation: { id: 123 },
contact: { name: 'John' }
}
expect(Captain::PromptRenderer).to receive(:render).with(
'dummy_class',
hash_including(expected_context)
)
dummy_instance.agent_instructions(context_double)
end
it 'handles context without state' do
context_double = instance_double(Agents::RunContext, context: {})
expect(Captain::PromptRenderer).to receive(:render).with(
'dummy_class',
hash_including(
base_key: 'base_value',
conversation: {},
contact: {}
)
)
dummy_instance.agent_instructions(context_double)
end
end
describe '#template_name' do
it 'returns underscored class name' do
expect(dummy_instance.send(:template_name)).to eq('dummy_class')
end
end
describe '#agent_tools' do
it 'returns empty array by default' do
expect(dummy_instance.send(:agent_tools)).to eq([])
end
end
describe '#agent_model' do
it 'returns value from InstallationConfig when present' do
expect(dummy_instance.send(:agent_model)).to eq('gpt-4-turbo')
end
it 'returns default model when config not found' do
allow(InstallationConfig).to receive(:find_by).and_return(nil)
expect(dummy_instance.send(:agent_model)).to eq('gpt-4.1-mini')
end
it 'returns default model when config value is nil' do
allow(mock_installation_config).to receive(:value).and_return(nil)
expect(dummy_instance.send(:agent_model)).to eq('gpt-4.1-mini')
end
end
describe '#agent_response_schema' do
it 'returns Captain::ResponseSchema' do
expect(dummy_instance.send(:agent_response_schema)).to eq(Captain::ResponseSchema)
end
end
describe 'required methods' do
let(:incomplete_class) do
Class.new do
include Concerns::Agentable
end
end
let(:incomplete_instance) { incomplete_class.new }
describe '#agent_name' do
it 'raises NotImplementedError when not implemented' do
expect { incomplete_instance.send(:agent_name) }
.to raise_error(NotImplementedError, /must implement agent_name/)
end
end
describe '#prompt_context' do
it 'raises NotImplementedError when not implemented' do
expect { incomplete_instance.send(:prompt_context) }
.to raise_error(NotImplementedError, /must implement prompt_context/)
end
end
end
end
@@ -0,0 +1,320 @@
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Captain::Assistant::AgentRunnerService do
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(:assistant) { create(:captain_assistant, account: account) }
let(:scenario) { create(:captain_scenario, assistant: assistant, enabled: true) }
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(:message_history) do
[
{ role: 'user', content: 'Hello there' },
{ role: 'assistant', content: 'Hi! How can I help you?', agent_name: 'Assistant' },
{ role: 'user', content: 'I need help with my account' }
]
end
before do
allow(assistant).to receive(:agent).and_return(mock_agent)
scenarios_relation = instance_double(Captain::Scenario)
allow(scenarios_relation).to receive(:enabled).and_return([scenario])
allow(assistant).to receive(:scenarios).and_return(scenarios_relation)
allow(scenario).to receive(:agent).and_return(mock_scenario_agent)
allow(Agents::Runner).to receive(:with_agents).and_return(mock_runner)
allow(mock_runner).to receive(:run).and_return(mock_result)
allow(mock_agent).to receive(:register_handoffs)
allow(mock_scenario_agent).to receive(:register_handoffs)
end
describe '#initialize' do
it 'sets instance variables correctly' do
service = described_class.new(assistant: assistant, conversation: conversation)
expect(service.instance_variable_get(:@assistant)).to eq(assistant)
expect(service.instance_variable_get(:@conversation)).to eq(conversation)
expect(service.instance_variable_get(:@callbacks)).to eq({})
end
it 'accepts callbacks parameter' do
callbacks = { on_agent_thinking: proc { |x| x } }
service = described_class.new(assistant: assistant, callbacks: callbacks)
expect(service.instance_variable_get(:@callbacks)).to eq(callbacks)
end
end
describe '#generate_response' do
subject(:service) { described_class.new(assistant: assistant, conversation: conversation) }
it 'builds agents and wires them together' do
expect(assistant).to receive(:agent).and_return(mock_agent)
scenarios_relation = instance_double(Captain::Scenario)
allow(scenarios_relation).to receive(:enabled).and_return([scenario])
expect(assistant).to receive(:scenarios).and_return(scenarios_relation)
expect(scenario).to receive(:agent).and_return(mock_scenario_agent)
expect(mock_agent).to receive(:register_handoffs).with(mock_scenario_agent)
expect(mock_scenario_agent).to receive(:register_handoffs).with(mock_agent)
service.generate_response(message_history: message_history)
end
it 'creates runner with agents' do
expect(Agents::Runner).to receive(:with_agents).with(mock_agent, mock_scenario_agent)
service.generate_response(message_history: message_history)
end
it 'runs agent with extracted user message and context' do
expected_context = {
conversation_history: [
{ role: :user, content: 'Hello there', agent_name: nil },
{ role: :assistant, content: 'Hi! How can I help you?', agent_name: 'Assistant' },
{ role: :user, content: 'I need help with my account', agent_name: nil }
],
state: hash_including(
account_id: account.id,
assistant_id: assistant.id,
conversation: hash_including(id: conversation.id),
contact: hash_including(id: contact.id)
)
}
expect(mock_runner).to receive(:run).with(
'I need help with my account',
context: expected_context
)
service.generate_response(message_history: message_history)
end
it 'processes and formats agent result' do
result = service.generate_response(message_history: message_history)
expect(result).to eq({ 'response' => 'Test response' })
end
context 'when no scenarios are enabled' do
before do
scenarios_relation = instance_double(Captain::Scenario)
allow(scenarios_relation).to receive(:enabled).and_return([])
allow(assistant).to receive(:scenarios).and_return(scenarios_relation)
end
it 'only uses assistant agent' do
expect(Agents::Runner).to receive(:with_agents).with(mock_agent)
expect(mock_agent).not_to receive(:register_handoffs)
service.generate_response(message_history: message_history)
end
end
context 'when agent result is a string' do
let(:mock_result) { instance_double(Agents::RunResult, output: 'Simple string response') }
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'
})
end
end
context 'when an error occurs' do
let(:error) { StandardError.new('Test error') }
before do
allow(mock_runner).to receive(:run).and_raise(error)
allow(ChatwootExceptionTracker).to receive(:new).and_return(
instance_double(ChatwootExceptionTracker, capture_exception: true)
)
end
it 'captures exception and returns error response' do
expect(ChatwootExceptionTracker).to receive(:new).with(error, account: conversation.account)
result = service.generate_response(message_history: message_history)
expect(result).to eq({
'response' => 'conversation_handoff',
'reasoning' => 'Error occurred: Test error'
})
end
it 'logs error details' do
expect(Rails.logger).to receive(:error).with('[Captain V2] AgentRunnerService error: Test error')
expect(Rails.logger).to receive(:error).with(kind_of(String))
service.generate_response(message_history: message_history)
end
context 'when conversation is nil' do
subject(:service) { described_class.new(assistant: assistant, conversation: nil) }
it 'handles missing conversation gracefully' do
expect(ChatwootExceptionTracker).to receive(:new).with(error, account: nil)
result = service.generate_response(message_history: message_history)
expect(result).to eq({
'response' => 'conversation_handoff',
'reasoning' => 'Error occurred: Test error'
})
end
end
end
end
describe '#build_context' do
subject(:service) { described_class.new(assistant: assistant, conversation: conversation) }
it 'builds context with conversation history and state' do
context = service.send(:build_context, message_history)
expect(context).to include(
conversation_history: array_including(
{ role: :user, content: 'Hello there', agent_name: nil },
{ role: :assistant, content: 'Hi! How can I help you?', agent_name: 'Assistant' }
),
state: hash_including(
account_id: account.id,
assistant_id: assistant.id
)
)
end
context 'with multimodal content' do
let(:multimodal_message_history) do
[
{
role: 'user',
content: [
{ type: 'text', text: 'Can you help with this image?' },
{ type: 'image_url', image_url: { url: 'https://example.com/image.jpg' } }
]
}
]
end
it 'extracts text content from multimodal messages' do
context = service.send(:build_context, multimodal_message_history)
expect(context[:conversation_history].first[:content]).to eq('Can you help with this image?')
end
end
end
describe '#extract_last_user_message' do
subject(:service) { described_class.new(assistant: assistant, conversation: conversation) }
it 'extracts the last user message' do
result = service.send(:extract_last_user_message, message_history)
expect(result).to eq('I need help with my account')
end
end
describe '#extract_text_from_content' do
subject(:service) { described_class.new(assistant: assistant, conversation: conversation) }
it 'extracts text from string content' do
result = service.send(:extract_text_from_content, 'Simple text')
expect(result).to eq('Simple text')
end
it 'extracts response from hash content' do
content = { 'response' => 'Hash response' }
result = service.send(:extract_text_from_content, content)
expect(result).to eq('Hash response')
end
it 'extracts text from multimodal array content' do
content = [
{ type: 'text', text: 'First part' },
{ type: 'image_url', image_url: { url: 'image.jpg' } },
{ type: 'text', text: 'Second part' }
]
result = service.send(:extract_text_from_content, content)
expect(result).to eq('First part Second part')
end
end
describe '#build_state' do
subject(:service) { described_class.new(assistant: assistant, conversation: conversation) }
it 'builds state with assistant and account information' do
state = service.send(:build_state)
expect(state).to include(
account_id: account.id,
assistant_id: assistant.id,
assistant_config: assistant.config
)
end
it 'includes conversation attributes when conversation is present' do
state = service.send(:build_state)
expect(state[:conversation]).to include(
id: conversation.id,
inbox_id: inbox.id,
contact_id: contact.id,
status: conversation.status
)
end
it 'includes contact attributes when contact is present' do
state = service.send(:build_state)
expect(state[:contact]).to include(
id: contact.id,
name: contact.name,
email: contact.email
)
end
context 'when conversation is nil' do
subject(:service) { described_class.new(assistant: assistant, conversation: nil) }
it 'builds state without conversation and contact' do
state = service.send(:build_state)
expect(state).to include(
account_id: account.id,
assistant_id: assistant.id,
assistant_config: assistant.config
)
expect(state).not_to have_key(:conversation)
expect(state).not_to have_key(:contact)
end
end
end
describe 'constants' do
it 'defines conversation state attributes' do
expect(described_class::CONVERSATION_STATE_ATTRIBUTES).to include(
:id, :display_id, :inbox_id, :contact_id, :status, :priority
)
end
it 'defines contact state attributes' do
expect(described_class::CONTACT_STATE_ATTRIBUTES).to include(
:id, :name, :email, :phone_number, :identifier, :contact_type
)
end
end
end
+12
View File
@@ -0,0 +1,12 @@
FactoryBot.define do
factory :assignment_policy do
account
sequence(:name) { |n| "Assignment Policy #{n}" }
description { 'Test assignment policy description' }
assignment_order { 0 }
conversation_priority { 0 }
fair_distribution_limit { 10 }
fair_distribution_window { 3600 }
enabled { true }
end
end
@@ -63,6 +63,25 @@ FactoryBot.define do
],
'sub_category' => 'CUSTOM',
'parameter_format' => 'NAMED'
},
{
'name' => 'test_no_params_template',
'status' => 'APPROVED',
'category' => 'UTILITY',
'language' => 'en',
'namespace' => 'ed41a221_133a_4558_a1d6_192960e3aee9',
'id' => '9876543210987654',
'length' => 1,
'parameter_format' => 'POSITIONAL',
'previous_category' => 'MARKETING',
'sub_category' => 'CUSTOM',
'components' => [
{
'text' => 'Thank you for contacting us! Your request has been processed successfully. Have a great day! 🙂',
'type' => 'BODY'
}
],
'rejected_reason' => 'NONE'
}]
end
message_templates_last_updated { Time.now.utc }
@@ -0,0 +1,6 @@
FactoryBot.define do
factory :inbox_assignment_policy do
inbox
assignment_policy
end
end
+177
View File
@@ -0,0 +1,177 @@
require 'rails_helper'
RSpec.describe ReportingEventHelper, type: :helper do
describe '#last_non_human_activity' do
let(:account) { create(:account) }
let(:inbox) { create(:inbox, account: account) }
let(:user) { create(:user, account: account) }
let(:conversation) { create(:conversation, account: account, inbox: inbox, assignee: user) }
context 'when conversation has no events' do
it 'returns conversation created_at' do
expect(helper.last_non_human_activity(conversation)).to eq(conversation.created_at)
end
end
context 'when conversation has bot handoff event' do
let!(:handoff_event) do
create(:reporting_event,
name: 'conversation_bot_handoff',
conversation_id: conversation.id,
account_id: account.id,
inbox_id: inbox.id,
event_end_time: 2.hours.ago)
end
it 'returns handoff event end time' do
expect(helper.last_non_human_activity(conversation).to_i).to eq(handoff_event.event_end_time.to_i)
end
end
context 'when conversation has bot resolved event' do
let!(:bot_resolved_event) do
create(:reporting_event,
name: 'conversation_bot_resolved',
conversation_id: conversation.id,
account_id: account.id,
inbox_id: inbox.id,
event_end_time: 3.hours.ago)
end
it 'returns bot resolved event end time' do
expect(helper.last_non_human_activity(conversation).to_i).to eq(bot_resolved_event.event_end_time.to_i)
end
end
context 'when conversation is reopened after bot resolution' do
let(:creation_time) { 5.days.ago }
let(:bot_resolution_time) { 5.days.ago + 5.minutes }
let(:reopening_time) { 1.hour.ago }
let!(:conversation) do
create(:conversation,
account: account,
inbox: inbox,
assignee: user,
created_at: creation_time)
end
before do
# First opened event
create(:reporting_event,
name: 'conversation_opened',
conversation_id: conversation.id,
account_id: account.id,
inbox_id: inbox.id,
value: 0,
event_start_time: creation_time,
event_end_time: creation_time)
# Bot resolved event
create(:reporting_event,
name: 'conversation_bot_resolved',
conversation_id: conversation.id,
account_id: account.id,
inbox_id: inbox.id,
event_start_time: creation_time,
event_end_time: bot_resolution_time)
# Resolved event
create(:reporting_event,
name: 'conversation_resolved',
conversation_id: conversation.id,
account_id: account.id,
inbox_id: inbox.id,
event_start_time: creation_time,
event_end_time: bot_resolution_time)
# Reopened event
create(:reporting_event,
name: 'conversation_opened',
conversation_id: conversation.id,
account_id: account.id,
inbox_id: inbox.id,
value: (reopening_time - bot_resolution_time).to_i,
event_start_time: bot_resolution_time,
event_end_time: reopening_time)
end
it 'returns the reopening event time, not the creation time' do
# This is the key test: last_non_human_activity should return the reopening time
# so that first response time is calculated from when the conversation was reopened,
# not from when it was originally created
expect(helper.last_non_human_activity(conversation).to_i).to eq(reopening_time.to_i)
# Verify it's not returning the creation time or bot resolution time
expect(helper.last_non_human_activity(conversation).to_i).not_to eq(creation_time.to_i)
expect(helper.last_non_human_activity(conversation).to_i).not_to eq(bot_resolution_time.to_i)
end
end
context 'when conversation has multiple types of events' do
let(:opened_event_time) { 1.hour.ago }
before do
create(:reporting_event,
name: 'conversation_bot_resolved',
conversation_id: conversation.id,
account_id: account.id,
inbox_id: inbox.id,
event_end_time: 4.hours.ago)
create(:reporting_event,
name: 'conversation_bot_handoff',
conversation_id: conversation.id,
account_id: account.id,
inbox_id: inbox.id,
event_end_time: 3.hours.ago)
create(:reporting_event,
name: 'conversation_opened',
conversation_id: conversation.id,
account_id: account.id,
inbox_id: inbox.id,
event_end_time: opened_event_time)
end
it 'returns the most recent handoff or opened event' do
# opened_event is more recent than handoff_event
expect(helper.last_non_human_activity(conversation).to_i).to eq(opened_event_time.to_i)
end
end
context 'when conversation has multiple reopenings' do
let(:third_opened_time) { 30.minutes.ago }
before do
create(:reporting_event,
name: 'conversation_opened',
conversation_id: conversation.id,
account_id: account.id,
inbox_id: inbox.id,
value: 0,
event_end_time: 5.days.ago)
create(:reporting_event,
name: 'conversation_opened',
conversation_id: conversation.id,
account_id: account.id,
inbox_id: inbox.id,
value: 3600,
event_end_time: 2.days.ago)
create(:reporting_event,
name: 'conversation_opened',
conversation_id: conversation.id,
account_id: account.id,
inbox_id: inbox.id,
value: 7200,
event_end_time: third_opened_time)
end
it 'returns the most recent opened event' do
expect(helper.last_non_human_activity(conversation).to_i).to eq(third_opened_time.to_i)
end
end
end
end
+57 -68
View File
@@ -10,23 +10,6 @@ describe Webhooks::InstagramEventsJob do
end
let!(:account) { create(:account) }
let!(:instagram_messenger_channel) { create(:channel_instagram_fb_page, account: account, instagram_id: 'chatwoot-app-user-id-1') }
let!(:instagram_messenger_inbox) { create(:inbox, channel: instagram_messenger_channel, account: account, greeting_enabled: false) }
let!(:instagram_channel) { create(:channel_instagram, account: account, instagram_id: 'chatwoot-app-user-id-1') }
let!(:instagram_inbox) { create(:inbox, channel: instagram_channel, account: account, greeting_enabled: false) }
# Combined message events into one helper
let(:message_events) do
{
dm: build(:instagram_message_create_event).with_indifferent_access,
standby: build(:instagram_message_standby_event).with_indifferent_access,
unsend: build(:instagram_message_unsend_event).with_indifferent_access,
attachment: build(:instagram_message_attachment_event).with_indifferent_access,
story_mention: build(:instagram_story_mention_event).with_indifferent_access,
story_mention_echo: build(:instagram_story_mention_event_with_echo).with_indifferent_access,
messaging_seen: build(:messaging_seen_event).with_indifferent_access,
unsupported: build(:instagram_message_unsupported_event).with_indifferent_access
}
end
def return_object_for(sender_id)
{ name: 'Jane',
@@ -38,21 +21,19 @@ describe Webhooks::InstagramEventsJob do
describe '#perform' do
context 'when handling messaging events for Instagram via Facebook page' do
let!(:instagram_messenger_channel) { create(:channel_instagram_fb_page, account: account, instagram_id: 'chatwoot-app-user-id-1') }
let!(:instagram_messenger_inbox) { create(:inbox, channel: instagram_messenger_channel, account: account, greeting_enabled: false) }
let(:fb_object) { double }
before do
instagram_inbox.destroy
end
it 'creates incoming message in the instagram inbox' do
dm_event = build(:instagram_message_create_event).with_indifferent_access
sender_id = dm_event[:entry][0][:messaging][0][:sender][:id]
allow(Koala::Facebook::API).to receive(:new).and_return(fb_object)
sender_id = message_events[:dm][:entry][0][:messaging][0][:sender][:id]
allow(fb_object).to receive(:get_object).and_return(
return_object_for(sender_id).with_indifferent_access
)
instagram_webhook.perform_now(message_events[:dm][:entry])
instagram_messenger_inbox.reload
instagram_webhook.perform_now(dm_event[:entry])
expect(instagram_messenger_inbox.contacts.count).to be 1
expect(instagram_messenger_inbox.contacts.last.additional_attributes['social_instagram_user_name']).to eq 'some_user_name'
@@ -62,14 +43,14 @@ describe Webhooks::InstagramEventsJob do
end
it 'creates standby message in the instagram inbox' do
standby_event = build(:instagram_message_standby_event).with_indifferent_access
sender_id = standby_event[:entry][0][:standby][0][:sender][:id]
allow(Koala::Facebook::API).to receive(:new).and_return(fb_object)
sender_id = message_events[:standby][:entry][0][:standby][0][:sender][:id]
allow(fb_object).to receive(:get_object).and_return(
return_object_for(sender_id).with_indifferent_access
)
instagram_webhook.perform_now(message_events[:standby][:entry])
instagram_messenger_inbox.reload
instagram_webhook.perform_now(standby_event[:entry])
expect(instagram_messenger_inbox.contacts.count).to be 1
expect(instagram_messenger_inbox.contacts.last.additional_attributes['social_instagram_user_name']).to eq 'some_user_name'
@@ -81,9 +62,11 @@ describe Webhooks::InstagramEventsJob do
end
it 'handle instagram unsend message event' do
unsend_event = build(:instagram_message_unsend_event).with_indifferent_access
sender_id = unsend_event[:entry][0][:messaging][0][:sender][:id]
message = create(:message, inbox_id: instagram_messenger_inbox.id, source_id: 'message-id-to-delete')
allow(Koala::Facebook::API).to receive(:new).and_return(fb_object)
sender_id = message_events[:unsend][:entry][0][:messaging][0][:sender][:id]
allow(fb_object).to receive(:get_object).and_return(
{
name: 'Jane',
@@ -96,7 +79,7 @@ describe Webhooks::InstagramEventsJob do
expect(instagram_messenger_inbox.messages.count).to be 1
instagram_webhook.perform_now(message_events[:unsend][:entry])
instagram_webhook.perform_now(unsend_event[:entry])
expect(instagram_messenger_inbox.messages.last.content).to eq 'This message was deleted'
expect(instagram_messenger_inbox.messages.last.deleted).to be true
@@ -105,14 +88,14 @@ describe Webhooks::InstagramEventsJob do
end
it 'creates incoming message with attachments in the instagram inbox' do
attachment_event = build(:instagram_message_attachment_event).with_indifferent_access
sender_id = attachment_event[:entry][0][:messaging][0][:sender][:id]
allow(Koala::Facebook::API).to receive(:new).and_return(fb_object)
sender_id = message_events[:attachment][:entry][0][:messaging][0][:sender][:id]
allow(fb_object).to receive(:get_object).and_return(
return_object_for(sender_id).with_indifferent_access
)
instagram_webhook.perform_now(message_events[:attachment][:entry])
instagram_messenger_inbox.reload
instagram_webhook.perform_now(attachment_event[:entry])
expect(instagram_messenger_inbox.contacts.count).to be 1
expect(instagram_messenger_inbox.messages.count).to be 1
@@ -120,8 +103,10 @@ describe Webhooks::InstagramEventsJob do
end
it 'creates incoming message with attachments in the instagram inbox for story mention' do
story_mention_event = build(:instagram_story_mention_event).with_indifferent_access
sender_id = story_mention_event[:entry][0][:messaging][0][:sender][:id]
allow(Koala::Facebook::API).to receive(:new).and_return(fb_object)
sender_id = message_events[:story_mention][:entry][0][:messaging][0][:sender][:id]
allow(fb_object).to receive(:get_object).and_return(
return_object_for(sender_id).with_indifferent_access,
{ story:
@@ -137,9 +122,7 @@ describe Webhooks::InstagramEventsJob do
id: 'instagram-message-id-1234' }.with_indifferent_access
)
instagram_webhook.perform_now(message_events[:story_mention][:entry])
instagram_messenger_inbox.reload
instagram_webhook.perform_now(story_mention_event[:entry])
expect(instagram_messenger_inbox.messages.count).to be 1
expect(instagram_messenger_inbox.messages.last.attachments.count).to be 1
@@ -149,12 +132,12 @@ describe Webhooks::InstagramEventsJob do
end
it 'does not create contact or messages when Facebook API call fails' do
story_mention_echo_event = build(:instagram_story_mention_event_with_echo).with_indifferent_access
allow(Koala::Facebook::API).to receive(:new).and_return(fb_object)
allow(fb_object).to receive(:get_object).and_raise(Koala::Facebook::ClientError)
instagram_webhook.perform_now(message_events[:story_mention_echo][:entry])
instagram_messenger_inbox.reload
instagram_webhook.perform_now(story_mention_echo_event[:entry])
expect(instagram_messenger_inbox.contacts.count).to be 0
expect(instagram_messenger_inbox.contact_inboxes.count).to be 0
@@ -162,21 +145,23 @@ describe Webhooks::InstagramEventsJob do
end
it 'handle messaging_seen callback' do
expect(Instagram::ReadStatusService).to receive(:new).with(params: message_events[:messaging_seen][:entry][0][:messaging][0],
messaging_seen_event = build(:messaging_seen_event).with_indifferent_access
expect(Instagram::ReadStatusService).to receive(:new).with(params: messaging_seen_event[:entry][0][:messaging][0],
channel: instagram_messenger_inbox.channel).and_call_original
instagram_webhook.perform_now(message_events[:messaging_seen][:entry])
instagram_webhook.perform_now(messaging_seen_event[:entry])
end
it 'handles unsupported message' do
unsupported_event = build(:instagram_message_unsupported_event).with_indifferent_access
sender_id = unsupported_event[:entry][0][:messaging][0][:sender][:id]
allow(Koala::Facebook::API).to receive(:new).and_return(fb_object)
sender_id = message_events[:unsupported][:entry][0][:messaging][0][:sender][:id]
allow(fb_object).to receive(:get_object).and_return(
return_object_for(sender_id).with_indifferent_access
)
instagram_webhook.perform_now(message_events[:unsupported][:entry])
instagram_messenger_inbox.reload
instagram_webhook.perform_now(unsupported_event[:entry])
expect(instagram_messenger_inbox.contacts.count).to be 1
expect(instagram_messenger_inbox.contacts.last.additional_attributes['social_instagram_user_name']).to eq 'some_user_name'
expect(instagram_messenger_inbox.conversations.count).to be 1
@@ -186,6 +171,9 @@ describe Webhooks::InstagramEventsJob do
end
context 'when handling messaging events for Instagram via Instagram login' do
let!(:instagram_channel) { create(:channel_instagram, account: account, instagram_id: 'chatwoot-app-user-id-1') }
let!(:instagram_inbox) { instagram_channel.inbox }
before do
instagram_channel.update(access_token: 'valid_instagram_token')
@@ -210,9 +198,8 @@ describe Webhooks::InstagramEventsJob do
end
it 'creates incoming message with correct contact info in the instagram direct inbox' do
instagram_webhook.perform_now(message_events[:dm][:entry])
instagram_inbox.reload
dm_event = build(:instagram_message_create_event).with_indifferent_access
instagram_webhook.perform_now(dm_event[:entry])
expect(instagram_inbox.contacts.count).to eq 1
expect(instagram_inbox.contacts.last.additional_attributes['social_instagram_user_name']).to eq 'some_user_name'
expect(instagram_inbox.conversations.count).to eq 1
@@ -221,7 +208,8 @@ describe Webhooks::InstagramEventsJob do
end
it 'sets correct instagram attributes on contact' do
instagram_webhook.perform_now(message_events[:dm][:entry])
dm_event = build(:instagram_message_create_event).with_indifferent_access
instagram_webhook.perform_now(dm_event[:entry])
instagram_inbox.reload
contact = instagram_inbox.contacts.last
@@ -233,6 +221,8 @@ describe Webhooks::InstagramEventsJob do
end
it 'handle instagram unsend message event' do
unsend_event = build(:instagram_message_unsend_event).with_indifferent_access
message = create(:message, inbox_id: instagram_inbox.id, source_id: 'message-id-to-delete', content: 'random_text')
# Create attachment correctly with account association
@@ -244,7 +234,7 @@ describe Webhooks::InstagramEventsJob do
expect(instagram_inbox.messages.count).to be 1
instagram_webhook.perform_now(message_events[:unsend][:entry])
instagram_webhook.perform_now(unsend_event[:entry])
message.reload
@@ -254,9 +244,8 @@ describe Webhooks::InstagramEventsJob do
end
it 'creates incoming message with attachments in the instagram direct inbox' do
instagram_webhook.perform_now(message_events[:attachment][:entry])
instagram_inbox.reload
attachment_event = build(:instagram_message_attachment_event).with_indifferent_access
instagram_webhook.perform_now(attachment_event[:entry])
expect(instagram_inbox.contacts.count).to be 1
expect(instagram_inbox.messages.count).to be 1
@@ -264,9 +253,8 @@ describe Webhooks::InstagramEventsJob do
end
it 'handles unsupported message' do
instagram_webhook.perform_now(message_events[:unsupported][:entry])
instagram_inbox.reload
unsupported_event = build(:instagram_message_unsupported_event).with_indifferent_access
instagram_webhook.perform_now(unsupported_event[:entry])
expect(instagram_inbox.contacts.count).to be 1
expect(instagram_inbox.contacts.last.additional_attributes['social_instagram_user_name']).to eq 'some_user_name'
expect(instagram_inbox.conversations.count).to be 1
@@ -275,12 +263,12 @@ describe Webhooks::InstagramEventsJob do
end
it 'does not create contact or messages when Instagram API call fails' do
story_mention_echo_event = build(:instagram_story_mention_event_with_echo).with_indifferent_access
stub_request(:get, %r{https://graph\.instagram\.com/v22\.0/.*\?.*})
.to_return(status: 401, body: { error: { message: 'Invalid OAuth access token' } }.to_json)
instagram_webhook.perform_now(message_events[:story_mention_echo][:entry])
instagram_inbox.reload
instagram_webhook.perform_now(story_mention_echo_event[:entry])
expect(instagram_inbox.contacts.count).to be 0
expect(instagram_inbox.contact_inboxes.count).to be 0
@@ -288,19 +276,20 @@ describe Webhooks::InstagramEventsJob do
end
it 'handles messaging_seen callback' do
expect(Instagram::ReadStatusService).to receive(:new).with(params: message_events[:messaging_seen][:entry][0][:messaging][0],
messaging_seen_event = build(:messaging_seen_event).with_indifferent_access
expect(Instagram::ReadStatusService).to receive(:new).with(params: messaging_seen_event[:entry][0][:messaging][0],
channel: instagram_inbox.channel).and_call_original
instagram_webhook.perform_now(message_events[:messaging_seen][:entry])
instagram_webhook.perform_now(messaging_seen_event[:entry])
end
it 'creates contact when Instagram API call returns `No matching Instagram user` (9010 error code)' do
stub_request(:get, %r{https://graph\.instagram\.com/v22\.0/.*\?.*})
.to_return(status: 401, body: { error: { message: 'No matching Instagram user', code: 9010 } }.to_json)
sender_id = message_events[:dm][:entry][0][:messaging][0][:sender][:id]
instagram_webhook.perform_now(message_events[:dm][:entry])
instagram_inbox.reload
dm_event = build(:instagram_message_create_event).with_indifferent_access
sender_id = dm_event[:entry][0][:messaging][0][:sender][:id]
instagram_webhook.perform_now(dm_event[:entry])
expect(instagram_inbox.contacts.count).to be 1
expect(instagram_inbox.contacts.last.name).to eq "Unknown (IG: #{sender_id})"
@@ -130,6 +130,42 @@ describe AutomationRuleListener do
end
end
describe 'conversation_resolved' do
let!(:automation_rule) { create(:automation_rule, event_name: 'conversation_resolved', account: account) }
let(:event) do
Events::Base.new('conversation_resolved', Time.zone.now, { conversation: conversation,
changed_attributes: { status: %w[Snoozed Open] } })
end
context 'when matching rules are present' do
it 'calls AutomationRules::ActionService if conditions match' do
allow(condition_match).to receive(:present?).and_return(true)
listener.conversation_resolved(event)
expect(AutomationRules::ActionService).to have_received(:new).with(automation_rule, account, conversation)
end
it 'does not call AutomationRules::ActionService if conditions do not match' do
allow(condition_match).to receive(:present?).and_return(false)
listener.conversation_resolved(event)
expect(AutomationRules::ActionService).not_to have_received(:new).with(automation_rule, account, conversation)
end
it 'calls AutomationRules::ActionService for each rule when multiple rules are present' do
create(:automation_rule, event_name: 'conversation_resolved', account: account)
allow(condition_match).to receive(:present?).and_return(true)
listener.conversation_resolved(event)
expect(AutomationRules::ActionService).to have_received(:new).twice
end
it 'does not call AutomationRules::ActionService if performed by automation' do
event.data[:performed_by] = automation_rule
allow(condition_match).to receive(:present?).and_return(true)
listener.conversation_resolved(event)
expect(AutomationRules::ActionService).not_to have_received(:new).with(automation_rule, account, conversation)
end
end
end
describe 'message_created' do
let!(:automation_rule) { create(:automation_rule, event_name: 'message_created', account: account) }
let!(:message) { create(:message, account: account, conversation: conversation) }
@@ -267,4 +267,177 @@ describe ReportingEventListener do
end
end
end
describe '#conversation_opened' do
context 'when conversation is opened for the first time' do
let(:new_conversation) { create(:conversation, account: account, inbox: inbox, assignee: user) }
it 'creates conversation_opened event with value 0' do
expect(account.reporting_events.where(name: 'conversation_opened').count).to be 0
event = Events::Base.new('conversation.opened', Time.zone.now, conversation: new_conversation)
listener.conversation_opened(event)
expect(account.reporting_events.where(name: 'conversation_opened').count).to be 1
opened_event = account.reporting_events.where(name: 'conversation_opened').first
expect(opened_event.value).to eq 0
expect(opened_event.value_in_business_hours).to eq 0
expect(opened_event.event_start_time).to be_within(1.second).of(new_conversation.created_at)
expect(opened_event.event_end_time).to be_within(1.second).of(new_conversation.updated_at)
end
end
context 'when conversation is reopened after being resolved' do
let(:resolved_time) { 2.hours.ago }
let(:reopened_time) { 1.hour.ago }
let(:reopened_conversation) do
create(:conversation, account: account, inbox: inbox, assignee: user, updated_at: reopened_time)
end
before do
# Create a resolved event first
create(:reporting_event,
name: 'conversation_resolved',
account_id: account.id,
inbox_id: inbox.id,
conversation_id: reopened_conversation.id,
user_id: user.id,
value: 3600,
event_start_time: reopened_conversation.created_at,
event_end_time: resolved_time)
end
it 'creates conversation_opened event' do
expect(account.reporting_events.where(name: 'conversation_opened').count).to be 0
event = Events::Base.new('conversation.opened', reopened_time, conversation: reopened_conversation)
listener.conversation_opened(event)
expect(account.reporting_events.where(name: 'conversation_opened').count).to be 1
end
it 'calculates correct time since resolution' do
event = Events::Base.new('conversation.opened', reopened_time, conversation: reopened_conversation)
listener.conversation_opened(event)
reopened_event = account.reporting_events.where(name: 'conversation_opened').first
expect(reopened_event.value).to be_within(1).of(3600) # 1 hour = 3600 seconds
expect(reopened_event.event_start_time).to be_within(1.second).of(resolved_time)
expect(reopened_event.event_end_time).to be_within(1.second).of(reopened_time)
end
it 'sets correct attributes for conversation_opened event' do
event = Events::Base.new('conversation.opened', reopened_time, conversation: reopened_conversation)
listener.conversation_opened(event)
reopened_event = account.reporting_events.where(name: 'conversation_opened').first
expect(reopened_event.account_id).to eq(account.id)
expect(reopened_event.inbox_id).to eq(inbox.id)
expect(reopened_event.conversation_id).to eq(reopened_conversation.id)
expect(reopened_event.user_id).to eq(user.id)
end
context 'when business hours enabled for inbox' do
let(:resolved_time) { Time.zone.parse('March 20, 2022 12:00') }
let(:reopened_time) { Time.zone.parse('March 21, 2022 14:00') }
let!(:business_hours_inbox) { create(:inbox, working_hours_enabled: true, account: account) }
let!(:business_hours_conversation) do
create(:conversation, account: account, inbox: business_hours_inbox, assignee: user, updated_at: reopened_time)
end
before do
create(:reporting_event,
name: 'conversation_resolved',
account_id: account.id,
inbox_id: business_hours_inbox.id,
conversation_id: business_hours_conversation.id,
user_id: user.id,
value: 3600,
event_start_time: business_hours_conversation.created_at,
event_end_time: resolved_time)
end
it 'creates conversation_opened event with business hour value' do
event = Events::Base.new('conversation.opened', reopened_time, conversation: business_hours_conversation)
listener.conversation_opened(event)
reopened_event = account.reporting_events.where(name: 'conversation_opened').first
expect(reopened_event.value_in_business_hours).to be 18_000.0 # 5 business hours (26 hours total - 21 non-business hours)
end
end
end
context 'when conversation has multiple resolutions' do
let(:first_resolved_time) { 3.hours.ago }
let(:second_resolved_time) { 1.hour.ago }
let(:reopened_time) { 30.minutes.ago }
let(:multiple_resolution_conversation) do
create(:conversation, account: account, inbox: inbox, assignee: user, updated_at: reopened_time)
end
before do
# Create first resolved event
create(:reporting_event,
name: 'conversation_resolved',
account_id: account.id,
inbox_id: inbox.id,
conversation_id: multiple_resolution_conversation.id,
user_id: user.id,
value: 3600,
event_start_time: multiple_resolution_conversation.created_at,
event_end_time: first_resolved_time)
# Create second resolved event (more recent)
create(:reporting_event,
name: 'conversation_resolved',
account_id: account.id,
inbox_id: inbox.id,
conversation_id: multiple_resolution_conversation.id,
user_id: user.id,
value: 1800,
event_start_time: first_resolved_time,
event_end_time: second_resolved_time)
end
it 'uses the most recent resolved event for calculation' do
event = Events::Base.new('conversation.opened', reopened_time, conversation: multiple_resolution_conversation)
listener.conversation_opened(event)
reopened_event = account.reporting_events.where(name: 'conversation_opened').first
expect(reopened_event.value).to be_within(1).of(1800) # 30 minutes from second resolution
expect(reopened_event.event_start_time).to be_within(1.second).of(second_resolved_time)
end
end
context 'when agent bot resolves and conversation is reopened' do
# This implicitly tests that the first_response time is correctly calculated
# By checking that a conversation reopened event is created with the correct values
let(:agent_bot) { create(:agent_bot, account: account) }
let(:agent_bot_inbox) { create(:inbox, account: account) }
let(:bot_resolved_time) { 2.hours.ago }
let(:reopened_time) { 1.hour.ago }
let(:bot_conversation) do
create(:conversation, account: account, inbox: agent_bot_inbox, assignee: user, updated_at: reopened_time)
end
before do
create(:agent_bot_inbox, agent_bot: agent_bot, inbox: agent_bot_inbox)
create(:reporting_event,
name: 'conversation_resolved',
account_id: account.id,
inbox_id: agent_bot_inbox.id,
conversation_id: bot_conversation.id,
user_id: user.id,
event_end_time: bot_resolved_time)
end
it 'creates conversation_opened event for agent bot reopening' do
event = Events::Base.new('conversation.opened', reopened_time, conversation: bot_conversation)
listener.conversation_opened(event)
reopened_event = account.reporting_events.where(name: 'conversation_opened').first
expect(reopened_event.value).to be_within(1).of(3600) # 1 hour since resolution
expect(reopened_event.event_start_time).to be_within(1.second).of(bot_resolved_time)
expect(reopened_event.event_end_time).to be_within(1.second).of(reopened_time)
end
end
end
end
+56
View File
@@ -0,0 +1,56 @@
require 'rails_helper'
RSpec.describe AssignmentPolicy do
describe 'associations' do
it { is_expected.to belong_to(:account) }
it { is_expected.to have_many(:inbox_assignment_policies).dependent(:destroy) }
it { is_expected.to have_many(:inboxes).through(:inbox_assignment_policies) }
end
describe 'validations' do
subject { build(:assignment_policy) }
it { is_expected.to validate_presence_of(:name) }
it { is_expected.to validate_uniqueness_of(:name).scoped_to(:account_id) }
end
describe 'fair distribution validations' do
it 'requires fair_distribution_limit to be greater than 0' do
policy = build(:assignment_policy, fair_distribution_limit: 0)
expect(policy).not_to be_valid
expect(policy.errors[:fair_distribution_limit]).to include('must be greater than 0')
end
it 'requires fair_distribution_window to be greater than 0' do
policy = build(:assignment_policy, fair_distribution_window: -1)
expect(policy).not_to be_valid
expect(policy.errors[:fair_distribution_window]).to include('must be greater than 0')
end
end
describe 'enum values' do
let(:assignment_policy) { create(:assignment_policy) }
describe 'conversation_priority' do
it 'can be set to earliest_created' do
assignment_policy.update!(conversation_priority: :earliest_created)
expect(assignment_policy.conversation_priority).to eq('earliest_created')
expect(assignment_policy.earliest_created?).to be true
end
it 'can be set to longest_waiting' do
assignment_policy.update!(conversation_priority: :longest_waiting)
expect(assignment_policy.conversation_priority).to eq('longest_waiting')
expect(assignment_policy.longest_waiting?).to be true
end
end
describe 'assignment_order' do
it 'can be set to round_robin' do
assignment_policy.update!(assignment_order: :round_robin)
expect(assignment_policy.assignment_order).to eq('round_robin')
expect(assignment_policy.round_robin?).to be true
end
end
end
end
+10
View File
@@ -82,6 +82,16 @@ RSpec.describe Attachment do
expect(attachment.thumb_url).to be_present
end
it 'handles unrepresentable images gracefully' do
attachment = message.attachments.create!(account_id: message.account_id, file_type: :image)
attachment.file.attach(io: StringIO.new('fake image'), filename: 'test.jpg', content_type: 'image/jpeg')
allow(attachment.file).to receive(:representation).and_raise(ActiveStorage::UnrepresentableError.new('Cannot represent'))
expect(Rails.logger).to receive(:warn).with(/Unrepresentable image attachment: #{attachment.id}/)
expect(attachment.thumb_url).to eq('')
end
end
describe 'meta data handling' do
@@ -16,6 +16,11 @@ describe Whatsapp::ChannelCreationService do
describe '#perform' do
before do
# Stub the webhook teardown service to prevent HTTP calls during cleanup
teardown_service = instance_double(Whatsapp::WebhookTeardownService)
allow(Whatsapp::WebhookTeardownService).to receive(:new).and_return(teardown_service)
allow(teardown_service).to receive(:perform)
# Clean up any existing channels to avoid phone number conflicts
Channel::Whatsapp.destroy_all
@@ -10,121 +10,100 @@ describe Whatsapp::EmbeddedSignupService do
phone_number_id: 'test_phone_number_id'
}
end
let(:service) do
described_class.new(
account: account,
params: params
)
let(:service) { described_class.new(account: account, params: params) }
let(:access_token) { 'test_access_token' }
let(:phone_info) do
{
phone_number_id: params[:phone_number_id],
phone_number: '+1234567890',
verified: true,
business_name: 'Test Business'
}
end
let(:channel) { instance_double(Channel::Whatsapp) }
describe '#perform' do
let(:access_token) { 'test_access_token' }
let(:phone_info) do
{
phone_number_id: params[:phone_number_id],
phone_number: '+1234567890',
verified: true,
business_name: 'Test Business'
}
end
let(:channel) { instance_double(Channel::Whatsapp) }
let(:service_doubles) do
{
token_exchange: instance_double(Whatsapp::TokenExchangeService),
phone_info: instance_double(Whatsapp::PhoneInfoService),
token_validation: instance_double(Whatsapp::TokenValidationService),
channel_creation: instance_double(Whatsapp::ChannelCreationService)
}
end
before do
allow(GlobalConfig).to receive(:clear_cache)
allow(Whatsapp::TokenExchangeService).to receive(:new).with(params[:code]).and_return(service_doubles[:token_exchange])
allow(service_doubles[:token_exchange]).to receive(:perform).and_return(access_token)
# Mock service dependencies
token_exchange = instance_double(Whatsapp::TokenExchangeService)
allow(Whatsapp::TokenExchangeService).to receive(:new).with(params[:code]).and_return(token_exchange)
allow(token_exchange).to receive(:perform).and_return(access_token)
phone_service = instance_double(Whatsapp::PhoneInfoService)
allow(Whatsapp::PhoneInfoService).to receive(:new)
.with(params[:waba_id], params[:phone_number_id], access_token).and_return(service_doubles[:phone_info])
allow(service_doubles[:phone_info]).to receive(:perform).and_return(phone_info)
.with(params[:waba_id], params[:phone_number_id], access_token).and_return(phone_service)
allow(phone_service).to receive(:perform).and_return(phone_info)
validation_service = instance_double(Whatsapp::TokenValidationService)
allow(Whatsapp::TokenValidationService).to receive(:new)
.with(access_token, params[:waba_id]).and_return(service_doubles[:token_validation])
allow(service_doubles[:token_validation]).to receive(:perform)
.with(access_token, params[:waba_id]).and_return(validation_service)
allow(validation_service).to receive(:perform)
channel_creation = instance_double(Whatsapp::ChannelCreationService)
allow(Whatsapp::ChannelCreationService).to receive(:new)
.with(account, { waba_id: params[:waba_id], business_name: 'Test Business' }, phone_info, access_token)
.and_return(service_doubles[:channel_creation])
allow(service_doubles[:channel_creation]).to receive(:perform).and_return(channel)
.and_return(channel_creation)
allow(channel_creation).to receive(:perform).and_return(channel)
# Webhook setup is now handled in the channel after_create callback
# So we stub it at the model level
webhook_service = instance_double(Whatsapp::WebhookSetupService)
allow(Whatsapp::WebhookSetupService).to receive(:new).and_return(webhook_service)
allow(webhook_service).to receive(:perform)
allow(channel).to receive(:setup_webhooks)
end
it 'orchestrates all services in the correct order' do
expect(service_doubles[:token_exchange]).to receive(:perform).ordered
expect(service_doubles[:phone_info]).to receive(:perform).ordered
expect(service_doubles[:token_validation]).to receive(:perform).ordered
expect(service_doubles[:channel_creation]).to receive(:perform).ordered
it 'creates channel and sets up webhooks' do
expect(channel).to receive(:setup_webhooks)
result = service.perform
expect(result).to eq(channel)
end
context 'when required parameters are missing' do
it 'raises error when code is blank' do
service = described_class.new(
account: account,
params: params.merge(code: '')
)
expect { service.perform }.to raise_error(ArgumentError, /Required parameters are missing: code/)
end
it 'raises error when business_id is blank' do
service = described_class.new(
account: account,
params: params.merge(business_id: '')
)
expect { service.perform }.to raise_error(ArgumentError, /Required parameters are missing: business_id/)
end
it 'raises error when waba_id is blank' do
service = described_class.new(
account: account,
params: params.merge(waba_id: '')
)
expect { service.perform }.to raise_error(ArgumentError, /Required parameters are missing: waba_id/)
end
it 'raises error when multiple parameters are blank' do
service = described_class.new(
account: account,
params: params.merge(code: '', business_id: '')
)
expect { service.perform }.to raise_error(ArgumentError, /Required parameters are missing: code, business_id/)
context 'when parameters are invalid' do
it 'raises ArgumentError for missing parameters' do
invalid_service = described_class.new(account: account, params: { code: '', business_id: '', waba_id: '' })
expect { invalid_service.perform }.to raise_error(ArgumentError, /Required parameters are missing/)
end
end
context 'when any service fails' do
it 'logs and re-raises the error' do
allow(service_doubles[:token_exchange]).to receive(:perform).and_raise('Token error')
context 'when service fails' do
it 'logs and re-raises errors' do
token_exchange = instance_double(Whatsapp::TokenExchangeService)
allow(Whatsapp::TokenExchangeService).to receive(:new).and_return(token_exchange)
allow(token_exchange).to receive(:perform).and_raise('Token error')
expect(Rails.logger).to receive(:error).with('[WHATSAPP] Embedded signup failed: Token error')
expect { service.perform }.to raise_error('Token error')
end
it 'prompts reauthorization when webhook setup fails' do
# Create a real channel to test the actual webhook failure behavior
real_channel = create(:channel_whatsapp, account: account, phone_number: '+1234567890',
validate_provider_config: false, sync_templates: false)
# Mock the channel creation to return our real channel
channel_creation = instance_double(Whatsapp::ChannelCreationService)
allow(Whatsapp::ChannelCreationService).to receive(:new).and_return(channel_creation)
allow(channel_creation).to receive(:perform).and_return(real_channel)
# Mock webhook setup to fail
allow(real_channel).to receive(:perform_webhook_setup).and_raise('Webhook setup error')
# Verify channel is not marked for reauthorization initially
expect(real_channel.reauthorization_required?).to be false
# The service completes successfully even if webhook fails (webhook error is rescued in setup_webhooks)
result = service.perform
expect(result).to eq(real_channel)
# Verify the channel is now marked for reauthorization
expect(real_channel.reauthorization_required?).to be true
end
end
context 'when inbox_id is provided (reauthorization flow)' do
context 'with reauthorization flow' do
let(:inbox_id) { 123 }
let(:reauth_service) { instance_double(Whatsapp::ReauthorizationService) }
let(:service_with_inbox) do
described_class.new(
account: account,
params: params,
inbox_id: inbox_id
)
described_class.new(account: account, params: params, inbox_id: inbox_id)
end
before do
@@ -137,16 +116,45 @@ describe Whatsapp::EmbeddedSignupService do
allow(reauth_service).to receive(:perform).with(access_token, phone_info).and_return(channel)
end
it 'uses ReauthorizationService instead of ChannelCreationService' do
expect(service_doubles[:token_exchange]).to receive(:perform).ordered
expect(service_doubles[:phone_info]).to receive(:perform).ordered
expect(service_doubles[:token_validation]).to receive(:perform).ordered
expect(reauth_service).to receive(:perform).with(access_token, phone_info).ordered
expect(service_doubles[:channel_creation]).not_to receive(:perform)
it 'uses ReauthorizationService and sets up webhooks' do
expect(reauth_service).to receive(:perform)
expect(channel).to receive(:setup_webhooks)
result = service_with_inbox.perform
expect(result).to eq(channel)
end
it 'clears reauthorization flag' do
inbox = create(:inbox, account: account)
whatsapp_channel = create(:channel_whatsapp, account: account, phone_number: '+1234567890',
validate_provider_config: false, sync_templates: false)
inbox.update!(channel: whatsapp_channel)
whatsapp_channel.prompt_reauthorization!
service_with_real_inbox = described_class.new(account: account, params: params, inbox_id: inbox.id)
# Mock the ReauthorizationService to return our test channel
reauth_service = instance_double(Whatsapp::ReauthorizationService)
allow(Whatsapp::ReauthorizationService).to receive(:new).with(
account: account,
inbox_id: inbox.id,
phone_number_id: params[:phone_number_id],
business_id: params[:business_id]
).and_return(reauth_service)
# Perform the reauthorization and clear the flag
allow(reauth_service).to receive(:perform) do
whatsapp_channel.reauthorized!
whatsapp_channel
end
allow(whatsapp_channel).to receive(:setup_webhooks).and_return(true)
expect(whatsapp_channel.reauthorization_required?).to be true
result = service_with_real_inbox.perform
expect(result).to eq(whatsapp_channel)
expect(whatsapp_channel.reauthorization_required?).to be false
end
end
end
end
@@ -371,5 +371,100 @@ describe Whatsapp::IncomingMessageService do
Redis::Alfred.delete(key)
end
end
context 'when profile name is available for contact updates' do
let(:wa_id) { '1234567890' }
let(:phone_number) { "+#{wa_id}" }
it 'updates existing contact name when current name matches phone number' do
# Create contact with phone number as name
existing_contact = create(:contact,
account: whatsapp_channel.inbox.account,
name: phone_number,
phone_number: phone_number)
create(:contact_inbox,
contact: existing_contact,
inbox: whatsapp_channel.inbox,
source_id: wa_id)
params = {
'contacts' => [{ 'profile' => { 'name' => 'Jane Smith' }, 'wa_id' => wa_id }],
'messages' => [{ 'from' => wa_id, 'id' => 'message123', 'text' => { 'body' => 'Hello' },
'timestamp' => '1633034394', 'type' => 'text' }]
}.with_indifferent_access
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
existing_contact.reload
expect(existing_contact.name).to eq('Jane Smith')
end
it 'does not update contact name when current name is different from phone number' do
# Create contact with human name
existing_contact = create(:contact,
account: whatsapp_channel.inbox.account,
name: 'John Doe',
phone_number: phone_number)
create(:contact_inbox,
contact: existing_contact,
inbox: whatsapp_channel.inbox,
source_id: wa_id)
params = {
'contacts' => [{ 'profile' => { 'name' => 'Jane Smith' }, 'wa_id' => wa_id }],
'messages' => [{ 'from' => wa_id, 'id' => 'message123', 'text' => { 'body' => 'Hello' },
'timestamp' => '1633034394', 'type' => 'text' }]
}.with_indifferent_access
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
existing_contact.reload
expect(existing_contact.name).to eq('John Doe') # Should not change
end
it 'updates contact name when current name matches formatted phone number' do
formatted_number = TelephoneNumber.parse(phone_number).international_number
# Create contact with formatted phone number as name
existing_contact = create(:contact,
account: whatsapp_channel.inbox.account,
name: formatted_number,
phone_number: phone_number)
create(:contact_inbox,
contact: existing_contact,
inbox: whatsapp_channel.inbox,
source_id: wa_id)
params = {
'contacts' => [{ 'profile' => { 'name' => 'Alice Johnson' }, 'wa_id' => wa_id }],
'messages' => [{ 'from' => wa_id, 'id' => 'message123', 'text' => { 'body' => 'Hello' },
'timestamp' => '1633034394', 'type' => 'text' }]
}.with_indifferent_access
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
existing_contact.reload
expect(existing_contact.name).to eq('Alice Johnson')
end
it 'does not update when profile name is blank' do
# Create contact with phone number as name
existing_contact = create(:contact,
account: whatsapp_channel.inbox.account,
name: phone_number,
phone_number: phone_number)
create(:contact_inbox,
contact: existing_contact,
inbox: whatsapp_channel.inbox,
source_id: wa_id)
params = {
'contacts' => [{ 'profile' => { 'name' => '' }, 'wa_id' => wa_id }],
'messages' => [{ 'from' => wa_id, 'id' => 'message123', 'text' => { 'body' => 'Hello' },
'timestamp' => '1633034394', 'type' => 'text' }]
}.with_indifferent_access
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
existing_contact.reload
expect(existing_contact.name).to eq(phone_number) # Should not change
end
end
end
end
@@ -133,7 +133,8 @@ describe Whatsapp::OneoffCampaignService do
)
)
)
)
),
nil
)
described_class.new(campaign: campaign).perform
@@ -164,8 +165,8 @@ describe Whatsapp::OneoffCampaignService do
allow(whatsapp_channel).to receive(:send_template).and_return(nil)
expect(whatsapp_channel).to receive(:send_template).with(contact_error.phone_number, anything).and_raise(StandardError, error_message)
expect(whatsapp_channel).to receive(:send_template).with(contact_success.phone_number, anything).once
expect(whatsapp_channel).to receive(:send_template).with(contact_error.phone_number, anything, nil).and_raise(StandardError, error_message)
expect(whatsapp_channel).to receive(:send_template).with(contact_success.phone_number, anything, nil).once
expect(Rails.logger).to receive(:error)
.with("Failed to send WhatsApp template message to #{contact_error.phone_number}: #{error_message}")
@@ -187,7 +187,7 @@ describe Whatsapp::Providers::WhatsappCloudService do
)
.to_return(status: 200, body: whatsapp_response.to_json, headers: response_headers)
expect(service.send_template('+123456789', template_info)).to eq('message_id')
expect(service.send_template('+123456789', template_info, message)).to eq('message_id')
end
end
end
@@ -287,7 +287,7 @@ describe Whatsapp::Providers::WhatsappCloudService do
context 'when there is a message' do
it 'logs error and updates message status' do
service.instance_variable_set(:@message, message)
service.send(:handle_error, error_response_object)
service.send(:handle_error, error_response_object, message)
expect(message.reload.status).to eq('failed')
expect(message.reload.external_error).to eq(error_message)
@@ -305,7 +305,7 @@ describe Whatsapp::Providers::WhatsappCloudService do
it 'logs error but does not update message' do
service.instance_variable_set(:@message, message)
service.send(:handle_error, error_response_object)
service.send(:handle_error, error_response_object, message)
expect(message.reload.status).not_to eq('failed')
expect(message.reload.external_error).to be_nil
@@ -133,6 +133,48 @@ describe Whatsapp::TemplateParameterConverterService do
end
end
context 'when processed_params is nil (parameter-less templates)' do
let(:nil_params) do
{
'processed_params' => nil
}
end
let(:parameterless_template) do
{
'name' => 'test_no_params_template',
'language' => 'en',
'parameter_format' => 'POSITIONAL',
'id' => '9876543210987654',
'status' => 'APPROVED',
'category' => 'UTILITY',
'previous_category' => 'MARKETING',
'sub_category' => 'CUSTOM',
'components' => [
{
'type' => 'BODY',
'text' => 'Thank you for contacting us! Your request has been processed successfully. Have a great day! 🙂'
}
]
}
end
it 'converts nil to empty enhanced format' do
converter = described_class.new(nil_params, parameterless_template)
result = converter.normalize_to_enhanced
expect(result['processed_params']).to eq({})
expect(result['format_version']).to eq('legacy')
end
it 'does not raise ArgumentError for nil processed_params' do
expect do
converter = described_class.new(nil_params, parameterless_template)
converter.normalize_to_enhanced
end.not_to raise_error
end
end
context 'when invalid format' do
let(:invalid_params) do
{
@@ -174,6 +216,26 @@ describe Whatsapp::TemplateParameterConverterService do
end
describe 'simplified conversion methods' do
describe '#convert_legacy_to_enhanced' do
it 'handles nil processed_params without raising error' do
converter = described_class.new({}, template)
result = converter.send(:convert_legacy_to_enhanced, nil, template)
expect(result).to eq({})
end
it 'returns empty hash for parameter-less templates' do
parameterless_template = {
'name' => 'no_params_template',
'language' => 'en',
'components' => [{ 'type' => 'BODY', 'text' => 'Hello World!' }]
}
converter = described_class.new({}, parameterless_template)
result = converter.send(:convert_legacy_to_enhanced, nil, parameterless_template)
expect(result).to eq({})
end
end
describe '#convert_array_to_body_params' do
it 'converts empty array' do
converter = described_class.new({}, template)
@@ -5,7 +5,7 @@ describe Whatsapp::WebhookSetupService do
create(:channel_whatsapp,
phone_number: '+1234567890',
provider_config: {
'phone_number_id' => 'test_phone_id',
'phone_number_id' => '123456789',
'webhook_verify_token' => 'test_verify_token'
},
provider: 'whatsapp_cloud',
@@ -18,9 +18,14 @@ describe Whatsapp::WebhookSetupService do
let(:api_client) { instance_double(Whatsapp::FacebookApiClient) }
before do
# Stub webhook teardown to prevent HTTP calls during cleanup
stub_request(:delete, /graph.facebook.com/).to_return(status: 200, body: '{}', headers: {})
# Clean up any existing channels to avoid phone number conflicts
Channel::Whatsapp.destroy_all
allow(Whatsapp::FacebookApiClient).to receive(:new).and_return(api_client)
# Default stub for phone_number_verified? with any argument
allow(api_client).to receive(:phone_number_verified?).and_return(false)
end
describe '#perform' do
@@ -148,5 +153,87 @@ describe Whatsapp::WebhookSetupService do
end
end
end
context 'when webhook setup fails and should trigger reauthorization' do
before do
allow(api_client).to receive(:phone_number_verified?).with('123456789').and_return(true)
allow(api_client).to receive(:subscribe_waba_webhook).and_raise('Invalid access token')
end
it 'raises error with webhook setup failure message' do
with_modified_env FRONTEND_URL: 'https://app.chatwoot.com' do
expect { service.perform }.to raise_error(/Webhook setup failed: Invalid access token/)
end
end
it 'logs the webhook setup failure' do
with_modified_env FRONTEND_URL: 'https://app.chatwoot.com' do
expect(Rails.logger).to receive(:error).with('[WHATSAPP] Webhook setup failed: Invalid access token')
expect { service.perform }.to raise_error(/Webhook setup failed/)
end
end
end
context 'when used during reauthorization flow' do
let(:existing_channel) do
create(:channel_whatsapp,
phone_number: '+1234567890',
provider_config: {
'phone_number_id' => '123456789',
'webhook_verify_token' => 'existing_verify_token',
'business_id' => 'existing_business_id',
'waba_id' => 'existing_waba_id'
},
provider: 'whatsapp_cloud',
sync_templates: false,
validate_provider_config: false)
end
let(:new_access_token) { 'new_access_token' }
let(:service_reauth) { described_class.new(existing_channel, waba_id, new_access_token) }
before do
allow(api_client).to receive(:phone_number_verified?).with('123456789').and_return(true)
allow(api_client).to receive(:subscribe_waba_webhook)
.with(waba_id, anything, 'existing_verify_token').and_return({ 'success' => true })
end
it 'successfully reauthorizes with new access token' do
with_modified_env FRONTEND_URL: 'https://app.chatwoot.com' do
expect(api_client).not_to receive(:register_phone_number)
expect(api_client).to receive(:subscribe_waba_webhook)
.with(waba_id, 'https://app.chatwoot.com/webhooks/whatsapp/+1234567890', 'existing_verify_token')
service_reauth.perform
end
end
it 'uses the existing webhook verify token during reauthorization' do
with_modified_env FRONTEND_URL: 'https://app.chatwoot.com' do
expect(api_client).to receive(:subscribe_waba_webhook)
.with(waba_id, anything, 'existing_verify_token')
service_reauth.perform
end
end
end
context 'when webhook setup is successful in creation flow' do
before do
allow(api_client).to receive(:phone_number_verified?).with('123456789').and_return(true)
allow(api_client).to receive(:subscribe_waba_webhook)
.with(waba_id, anything, 'test_verify_token').and_return({ 'success' => true })
end
it 'completes successfully without errors' do
with_modified_env FRONTEND_URL: 'https://app.chatwoot.com' do
expect { service.perform }.not_to raise_error
end
end
it 'does not log any errors' do
with_modified_env FRONTEND_URL: 'https://app.chatwoot.com' do
expect(Rails.logger).not_to receive(:error)
service.perform
end
end
end
end
end