Merge branch 'develop' into feat/github-integration

This commit is contained in:
Muhsin Keloth
2025-08-27 11:44:46 +05:30
committed by GitHub
77 changed files with 2764 additions and 1782 deletions
@@ -0,0 +1,80 @@
require 'rails_helper'
RSpec.describe 'Agent Capacity Policy Inbox Limits API', type: :request do
let(:account) { create(:account) }
let!(:agent_capacity_policy) { create(:agent_capacity_policy, account: account) }
let!(:inbox) { create(:inbox, account: account) }
let(:administrator) { create(:user, account: account, role: :administrator) }
let(:agent) { create(:user, account: account, role: :agent) }
describe 'POST /api/v1/accounts/{account.id}/agent_capacity_policies/{policy_id}/inbox_limits' do
context 'when not admin' do
it 'requires admin role' do
post "/api/v1/accounts/#{account.id}/agent_capacity_policies/#{agent_capacity_policy.id}/inbox_limits",
params: { inbox_id: inbox.id, conversation_limit: 10 },
headers: agent.create_new_auth_token,
as: :json
expect(response).to have_http_status(:unauthorized)
end
end
context 'when admin' do
it 'creates an inbox limit' do
post "/api/v1/accounts/#{account.id}/agent_capacity_policies/#{agent_capacity_policy.id}/inbox_limits",
params: { inbox_id: inbox.id, conversation_limit: 10 },
headers: administrator.create_new_auth_token,
as: :json
expect(response).to have_http_status(:success)
json_response = response.parsed_body
expect(json_response['conversation_limit']).to eq(10)
expect(json_response['inbox_id']).to eq(inbox.id)
end
it 'prevents duplicate inbox assignments' do
create(:inbox_capacity_limit, agent_capacity_policy: agent_capacity_policy, inbox: inbox)
post "/api/v1/accounts/#{account.id}/agent_capacity_policies/#{agent_capacity_policy.id}/inbox_limits",
params: { inbox_id: inbox.id, conversation_limit: 10 },
headers: administrator.create_new_auth_token,
as: :json
expect(response).to have_http_status(:unprocessable_entity)
expect(response.parsed_body['error']).to eq(I18n.t('agent_capacity_policy.inbox_already_assigned'))
end
end
end
describe 'PUT /api/v1/accounts/{account.id}/agent_capacity_policies/{policy_id}/inbox_limits/{id}' do
let!(:inbox_limit) { create(:inbox_capacity_limit, agent_capacity_policy: agent_capacity_policy, inbox: inbox, conversation_limit: 5) }
context 'when admin' do
it 'updates the inbox limit' do
put "/api/v1/accounts/#{account.id}/agent_capacity_policies/#{agent_capacity_policy.id}/inbox_limits/#{inbox_limit.id}",
params: { conversation_limit: 15 },
headers: administrator.create_new_auth_token,
as: :json
expect(response).to have_http_status(:success)
expect(response.parsed_body['conversation_limit']).to eq(15)
expect(inbox_limit.reload.conversation_limit).to eq(15)
end
end
end
describe 'DELETE /api/v1/accounts/{account.id}/agent_capacity_policies/{policy_id}/inbox_limits/{id}' do
let!(:inbox_limit) { create(:inbox_capacity_limit, agent_capacity_policy: agent_capacity_policy, inbox: inbox) }
context 'when admin' do
it 'removes the inbox limit' do
delete "/api/v1/accounts/#{account.id}/agent_capacity_policies/#{agent_capacity_policy.id}/inbox_limits/#{inbox_limit.id}",
headers: administrator.create_new_auth_token,
as: :json
expect(response).to have_http_status(:no_content)
expect(agent_capacity_policy.inbox_capacity_limits.find_by(id: inbox_limit.id)).to be_nil
end
end
end
end
@@ -0,0 +1,66 @@
require 'rails_helper'
RSpec.describe 'Agent Capacity Policy Users API', type: :request do
let(:account) { create(:account) }
let!(:agent_capacity_policy) { create(:agent_capacity_policy, account: account) }
let!(:user) { create(:user, account: account, role: :agent) }
let(:administrator) { create(:user, account: account, role: :administrator) }
let(:agent) { create(:user, account: account, role: :agent) }
describe 'GET /api/v1/accounts/{account.id}/agent_capacity_policies/{policy_id}/users' do
context 'when admin' do
it 'returns assigned users' do
user.account_users.first.update!(agent_capacity_policy: agent_capacity_policy)
get "/api/v1/accounts/#{account.id}/agent_capacity_policies/#{agent_capacity_policy.id}/users",
headers: administrator.create_new_auth_token,
as: :json
expect(response).to have_http_status(:success)
expect(response.parsed_body.first['id']).to eq(user.id)
end
end
end
describe 'POST /api/v1/accounts/{account.id}/agent_capacity_policies/{policy_id}/users' do
context 'when not admin' do
it 'requires admin role' do
post "/api/v1/accounts/#{account.id}/agent_capacity_policies/#{agent_capacity_policy.id}/users",
params: { user_id: user.id },
headers: agent.create_new_auth_token,
as: :json
expect(response).to have_http_status(:unauthorized)
end
end
context 'when admin' do
it 'assigns user to the policy' do
post "/api/v1/accounts/#{account.id}/agent_capacity_policies/#{agent_capacity_policy.id}/users",
params: { user_id: user.id },
headers: administrator.create_new_auth_token,
as: :json
expect(response).to have_http_status(:success)
expect(user.account_users.first.reload.agent_capacity_policy).to eq(agent_capacity_policy)
end
end
end
describe 'DELETE /api/v1/accounts/{account.id}/agent_capacity_policies/{policy_id}/users/{id}' do
context 'when admin' do
before do
user.account_users.first.update!(agent_capacity_policy: agent_capacity_policy)
end
it 'removes user from the policy' do
delete "/api/v1/accounts/#{account.id}/agent_capacity_policies/#{agent_capacity_policy.id}/users/#{user.id}",
headers: administrator.create_new_auth_token,
as: :json
expect(response).to have_http_status(:ok)
expect(user.account_users.first.reload.agent_capacity_policy).to be_nil
end
end
end
end
@@ -0,0 +1,202 @@
require 'rails_helper'
RSpec.describe 'Agent Capacity Policies API', type: :request do
let(:account) { create(:account) }
let!(:agent_capacity_policy) { create(:agent_capacity_policy, account: account) }
describe 'GET /api/v1/accounts/{account.id}/agent_capacity_policies' do
context 'when it is an unauthenticated user' do
it 'returns unauthorized' do
get "/api/v1/accounts/#{account.id}/agent_capacity_policies"
expect(response).to have_http_status(:unauthorized)
end
end
context 'when it is an authenticated agent' do
let(:agent) { create(:user, account: account, role: :agent) }
it 'returns unauthorized for agent' do
get "/api/v1/accounts/#{account.id}/agent_capacity_policies",
headers: agent.create_new_auth_token,
as: :json
expect(response).to have_http_status(:unauthorized)
end
end
context 'when it is an administrator' do
let(:administrator) { create(:user, account: account, role: :administrator) }
it 'returns all agent capacity policies' do
get "/api/v1/accounts/#{account.id}/agent_capacity_policies",
headers: administrator.create_new_auth_token,
as: :json
expect(response).to have_http_status(:success)
expect(response.parsed_body.first['id']).to eq(agent_capacity_policy.id)
end
end
end
describe 'GET /api/v1/accounts/{account.id}/agent_capacity_policies/{id}' do
context 'when it is an unauthenticated user' do
it 'returns unauthorized' do
get "/api/v1/accounts/#{account.id}/agent_capacity_policies/#{agent_capacity_policy.id}"
expect(response).to have_http_status(:unauthorized)
end
end
context 'when it is an authenticated agent' do
let(:agent) { create(:user, account: account, role: :agent) }
it 'returns unauthorized for agent' do
get "/api/v1/accounts/#{account.id}/agent_capacity_policies/#{agent_capacity_policy.id}",
headers: agent.create_new_auth_token,
as: :json
expect(response).to have_http_status(:unauthorized)
end
end
context 'when it is an administrator' do
let(:administrator) { create(:user, account: account, role: :administrator) }
it 'returns the agent capacity policy' do
get "/api/v1/accounts/#{account.id}/agent_capacity_policies/#{agent_capacity_policy.id}",
headers: administrator.create_new_auth_token,
as: :json
expect(response).to have_http_status(:success)
expect(response.parsed_body['id']).to eq(agent_capacity_policy.id)
end
end
end
describe 'POST /api/v1/accounts/{account.id}/agent_capacity_policies' do
context 'when it is an unauthenticated user' do
it 'returns unauthorized' do
post "/api/v1/accounts/#{account.id}/agent_capacity_policies"
expect(response).to have_http_status(:unauthorized)
end
end
context 'when it is an authenticated user' do
let(:agent) { create(:user, account: account, role: :agent) }
let(:administrator) { create(:user, account: account, role: :administrator) }
it 'returns unauthorized for agent' do
params = { agent_capacity_policy: { name: 'Test Policy' } }
post "/api/v1/accounts/#{account.id}/agent_capacity_policies",
params: params,
headers: agent.create_new_auth_token,
as: :json
expect(response).to have_http_status(:unauthorized)
end
it 'creates a new agent capacity policy when administrator' do
params = {
agent_capacity_policy: {
name: 'Test Policy',
description: 'Test Description',
exclusion_rules: { overall_capacity: 10 }
}
}
post "/api/v1/accounts/#{account.id}/agent_capacity_policies",
params: params,
headers: administrator.create_new_auth_token,
as: :json
expect(response).to have_http_status(:success)
expect(response.parsed_body['name']).to eq('Test Policy')
expect(response.parsed_body['description']).to eq('Test Description')
end
it 'returns validation errors for invalid data' do
params = { agent_capacity_policy: { name: '' } }
post "/api/v1/accounts/#{account.id}/agent_capacity_policies",
params: params,
headers: administrator.create_new_auth_token,
as: :json
expect(response).to have_http_status(:unprocessable_entity)
end
end
end
describe 'PUT /api/v1/accounts/{account.id}/agent_capacity_policies/{id}' do
context 'when it is an unauthenticated user' do
it 'returns unauthorized' do
put "/api/v1/accounts/#{account.id}/agent_capacity_policies/#{agent_capacity_policy.id}"
expect(response).to have_http_status(:unauthorized)
end
end
context 'when it is an authenticated user' do
let(:agent) { create(:user, account: account, role: :agent) }
let(:administrator) { create(:user, account: account, role: :administrator) }
it 'returns unauthorized for agent' do
params = { agent_capacity_policy: { name: 'Updated Policy' } }
put "/api/v1/accounts/#{account.id}/agent_capacity_policies/#{agent_capacity_policy.id}",
params: params,
headers: agent.create_new_auth_token,
as: :json
expect(response).to have_http_status(:unauthorized)
end
it 'updates the agent capacity policy when administrator' do
params = { agent_capacity_policy: { name: 'Updated Policy' } }
put "/api/v1/accounts/#{account.id}/agent_capacity_policies/#{agent_capacity_policy.id}",
params: params,
headers: administrator.create_new_auth_token,
as: :json
expect(response).to have_http_status(:success)
expect(response.parsed_body['name']).to eq('Updated Policy')
end
end
end
describe 'DELETE /api/v1/accounts/{account.id}/agent_capacity_policies/{id}' do
context 'when it is an unauthenticated user' do
it 'returns unauthorized' do
delete "/api/v1/accounts/#{account.id}/agent_capacity_policies/#{agent_capacity_policy.id}"
expect(response).to have_http_status(:unauthorized)
end
end
context 'when it is an authenticated user' do
let(:agent) { create(:user, account: account, role: :agent) }
let(:administrator) { create(:user, account: account, role: :administrator) }
it 'returns unauthorized for agent' do
delete "/api/v1/accounts/#{account.id}/agent_capacity_policies/#{agent_capacity_policy.id}",
headers: agent.create_new_auth_token,
as: :json
expect(response).to have_http_status(:unauthorized)
end
it 'deletes the agent capacity policy when administrator' do
delete "/api/v1/accounts/#{account.id}/agent_capacity_policies/#{agent_capacity_policy.id}",
headers: administrator.create_new_auth_token,
as: :json
expect(response).to have_http_status(:ok)
expect { agent_capacity_policy.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
end
end
@@ -24,6 +24,9 @@ RSpec.describe 'Enterprise Inboxes API', type: :request do
end
it 'creates a voice inbox when administrator' do
allow(Twilio::VoiceWebhookSetupService).to receive(:new).and_return(instance_double(Twilio::VoiceWebhookSetupService,
perform: "AP#{SecureRandom.hex(16)}"))
post "/api/v1/accounts/#{account.id}/inboxes",
headers: admin.create_new_auth_token,
params: { name: 'Voice Inbox',
@@ -31,7 +34,8 @@ RSpec.describe 'Enterprise Inboxes API', type: :request do
provider_config: { account_sid: "AC#{SecureRandom.hex(16)}",
auth_token: SecureRandom.hex(16),
api_key_sid: SecureRandom.hex(8),
api_key_secret: SecureRandom.hex(16) } } },
api_key_secret: SecureRandom.hex(16),
twiml_app_sid: "AP#{SecureRandom.hex(16)}" } } },
as: :json
expect(response).to have_http_status(:success)
@@ -13,7 +13,7 @@ RSpec.describe Captain::Documents::ResponseBuilderJob, type: :job do
before do
allow(Captain::Llm::FaqGeneratorService).to receive(:new)
.with(document.content)
.with(document.content, document.account.locale_english_name)
.and_return(faq_generator)
allow(faq_generator).to receive(:generate).and_return(faqs)
end
@@ -43,5 +43,26 @@ RSpec.describe Captain::Documents::ResponseBuilderJob, type: :job do
expect(first_response.documentable).to eq(document)
end
end
context 'with different locales' do
let(:spanish_account) { create(:account, locale: 'pt') }
let(:spanish_assistant) { create(:captain_assistant, account: spanish_account) }
let(:spanish_document) { create(:captain_document, assistant: spanish_assistant, account: spanish_account) }
let(:spanish_faq_generator) { instance_double(Captain::Llm::FaqGeneratorService) }
before do
allow(Captain::Llm::FaqGeneratorService).to receive(:new)
.with(spanish_document.content, 'portuguese')
.and_return(spanish_faq_generator)
allow(spanish_faq_generator).to receive(:generate).and_return(faqs)
end
it 'passes the correct locale to FAQ generator' do
described_class.new.perform(spanish_document)
expect(Captain::Llm::FaqGeneratorService).to have_received(:new)
.with(spanish_document.content, 'portuguese')
end
end
end
end
@@ -0,0 +1,29 @@
require 'rails_helper'
RSpec.describe AgentCapacityPolicy, type: :model do
let(:account) { create(:account) }
describe 'validations' do
it { is_expected.to validate_presence_of(:name) }
it { is_expected.to validate_length_of(:name).is_at_most(255) }
end
describe 'destruction' do
let(:policy) { create(:agent_capacity_policy, account: account) }
let(:user) { create(:user, account: account) }
let(:inbox) { create(:inbox, account: account) }
it 'destroys associated inbox capacity limits' do
create(:inbox_capacity_limit, agent_capacity_policy: policy, inbox: inbox)
expect { policy.destroy }.to change(InboxCapacityLimit, :count).by(-1)
end
it 'nullifies associated account users' do
account_user = user.account_users.first
account_user.update!(agent_capacity_policy: policy)
policy.destroy
expect(account_user.reload.agent_capacity_policy).to be_nil
end
end
end
+20 -1
View File
@@ -3,8 +3,13 @@
require 'rails_helper'
RSpec.describe Channel::Voice do
let(:twiml_app_sid) { 'AP1234567890abcdef' }
let(:channel) { create(:channel_voice) }
before do
allow(Twilio::VoiceWebhookSetupService).to receive(:new).and_return(instance_double(Twilio::VoiceWebhookSetupService, perform: twiml_app_sid))
end
it 'has a valid factory' do
expect(channel).to be_valid
end
@@ -40,12 +45,19 @@ RSpec.describe Channel::Voice do
expect(channel.errors[:provider_config]).to include('api_key_secret is required for Twilio provider')
end
it 'validates presence of twiml_app_sid in provider_config' do
channel.provider_config = { account_sid: 'sid', auth_token: 'token', api_key_sid: 'key', api_key_secret: 'secret' }
expect(channel).not_to be_valid
expect(channel.errors[:provider_config]).to include('twiml_app_sid is required for Twilio provider')
end
it 'is valid with all required provider_config fields' do
channel.provider_config = {
account_sid: 'test_sid',
auth_token: 'test_token',
api_key_sid: 'test_key',
api_key_secret: 'test_secret'
api_key_secret: 'test_secret',
twiml_app_sid: 'test_app_sid'
}
expect(channel).to be_valid
end
@@ -57,4 +69,11 @@ RSpec.describe Channel::Voice do
expect(channel.name).to include(channel.phone_number)
end
end
describe 'provisioning on create' do
it 'stores twiml_app_sid in provider_config' do
ch = create(:channel_voice)
expect(ch.provider_config.with_indifferent_access[:twiml_app_sid]).to eq(twiml_app_sid)
end
end
end
@@ -0,0 +1,33 @@
require 'rails_helper'
RSpec.describe InboxCapacityLimit, type: :model do
let(:account) { create(:account) }
let(:policy) { create(:agent_capacity_policy, account: account) }
let(:inbox) { create(:inbox, account: account) }
describe 'validations' do
subject { create(:inbox_capacity_limit, agent_capacity_policy: policy, inbox: inbox) }
it { is_expected.to validate_presence_of(:conversation_limit) }
it { is_expected.to validate_numericality_of(:conversation_limit).is_greater_than(0).only_integer }
it { is_expected.to validate_uniqueness_of(:inbox_id).scoped_to(:agent_capacity_policy_id) }
end
describe 'uniqueness constraint' do
it 'prevents duplicate inbox limits for the same policy' do
create(:inbox_capacity_limit, agent_capacity_policy: policy, inbox: inbox)
duplicate = build(:inbox_capacity_limit, agent_capacity_policy: policy, inbox: inbox)
expect(duplicate).not_to be_valid
expect(duplicate.errors[:inbox_id]).to include('has already been taken')
end
it 'allows the same inbox in different policies' do
other_policy = create(:agent_capacity_policy, account: account)
create(:inbox_capacity_limit, agent_capacity_policy: policy, inbox: inbox)
different_policy_limit = build(:inbox_capacity_limit, agent_capacity_policy: other_policy, inbox: inbox)
expect(different_policy_limit).to be_valid
end
end
end
@@ -0,0 +1,87 @@
require 'rails_helper'
RSpec.describe Captain::Llm::FaqGeneratorService do
let(:content) { 'Sample content for FAQ generation' }
let(:language) { 'english' }
let(:service) { described_class.new(content, language) }
let(:client) { instance_double(OpenAI::Client) }
before do
create(:installation_config, name: 'CAPTAIN_OPEN_AI_API_KEY', value: 'test-key')
allow(OpenAI::Client).to receive(:new).and_return(client)
end
describe '#generate' do
let(:sample_faqs) do
[
{ 'question' => 'What is this service?', 'answer' => 'It generates FAQs.' },
{ 'question' => 'How does it work?', 'answer' => 'Using AI technology.' }
]
end
let(:openai_response) do
{
'choices' => [
{
'message' => {
'content' => { faqs: sample_faqs }.to_json
}
}
]
}
end
context 'when successful' do
before do
allow(client).to receive(:chat).and_return(openai_response)
allow(Captain::Llm::SystemPromptsService).to receive(:faq_generator).and_return('system prompt')
end
it 'returns parsed FAQs' do
result = service.generate
expect(result).to eq(sample_faqs)
end
it 'calls OpenAI client with chat parameters' do
expect(client).to receive(:chat).with(parameters: hash_including(
model: 'gpt-4o-mini',
response_format: { type: 'json_object' },
messages: array_including(
hash_including(role: 'system'),
hash_including(role: 'user', content: content)
)
))
service.generate
end
it 'calls SystemPromptsService with correct language' do
expect(Captain::Llm::SystemPromptsService).to receive(:faq_generator).with(language)
service.generate
end
end
context 'with different language' do
let(:language) { 'spanish' }
before do
allow(client).to receive(:chat).and_return(openai_response)
end
it 'passes the correct language to SystemPromptsService' do
expect(Captain::Llm::SystemPromptsService).to receive(:faq_generator).with('spanish')
service.generate
end
end
context 'when OpenAI API fails' do
before do
allow(client).to receive(:chat).and_raise(OpenAI::Error.new('API Error'))
end
it 'handles the error and returns empty array' do
expect(Rails.logger).to receive(:error).with('OpenAI API Error: API Error')
expect(service.generate).to eq([])
end
end
end
end
@@ -0,0 +1,88 @@
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Twilio::VoiceWebhookSetupService do
let(:account_sid) { 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }
let(:auth_token) { 'auth_token_123' }
let(:api_key_sid) { 'SKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }
let(:api_key_secret) { 'api_key_secret_123' }
let(:phone_number) { '+15551230001' }
let(:frontend_url) { 'https://app.chatwoot.test' }
let(:channel) do
build(:channel_voice, phone_number: phone_number, provider_config: {
account_sid: account_sid,
auth_token: auth_token,
api_key_sid: api_key_sid,
api_key_secret: api_key_secret
})
end
let(:twilio_base_url) { "https://api.twilio.com/2010-04-01/Accounts/#{account_sid}" }
let(:incoming_numbers_url) { "#{twilio_base_url}/IncomingPhoneNumbers.json" }
let(:applications_url) { "#{twilio_base_url}/Applications.json" }
let(:phone_number_sid) { 'PN123' }
let(:phone_number_url) { "#{twilio_base_url}/IncomingPhoneNumbers/#{phone_number_sid}.json" }
before do
# Token validation using Account SID + Auth Token
stub_request(:get, /#{Regexp.escape(incoming_numbers_url)}.*/)
.with(basic_auth: [account_sid, auth_token])
.to_return(status: 200,
body: { incoming_phone_numbers: [], meta: { key: 'incoming_phone_numbers' } }.to_json,
headers: { 'Content-Type' => 'application/json' })
# Number lookup using API Key SID/Secret
stub_request(:get, /#{Regexp.escape(incoming_numbers_url)}.*/)
.with(basic_auth: [api_key_sid, api_key_secret])
.to_return(status: 200,
body: { incoming_phone_numbers: [{ sid: phone_number_sid }], meta: { key: 'incoming_phone_numbers' } }.to_json,
headers: { 'Content-Type' => 'application/json' })
# TwiML App create (voice only)
stub_request(:post, applications_url)
.with(basic_auth: [api_key_sid, api_key_secret])
.to_return(status: 201,
body: { sid: 'AP123' }.to_json,
headers: { 'Content-Type' => 'application/json' })
# Incoming Phone Number webhook update
stub_request(:post, phone_number_url)
.with(basic_auth: [api_key_sid, api_key_secret])
.to_return(status: 200,
body: { sid: phone_number_sid }.to_json,
headers: { 'Content-Type' => 'application/json' })
end
it 'creates a TwiML App and configures number webhooks with correct URLs' do
with_modified_env FRONTEND_URL: frontend_url do
service = described_class.new(channel: channel)
sid = service.perform
expect(sid).to eq('AP123')
expected_voice_url = channel.voice_call_webhook_url
expected_status_url = channel.voice_status_webhook_url
# Assert TwiML App creation body includes voice URL and POST method
expect(
a_request(:post, applications_url)
.with(body: hash_including('VoiceUrl' => expected_voice_url, 'VoiceMethod' => 'POST'))
).to have_been_made
# Assert number webhook update body includes both URLs and POST methods
expect(
a_request(:post, phone_number_url)
.with(
body: hash_including(
'VoiceUrl' => expected_voice_url,
'VoiceMethod' => 'POST',
'StatusCallback' => expected_status_url,
'StatusCallbackMethod' => 'POST'
)
)
).to have_been_made
end
end
end
+21
View File
@@ -0,0 +1,21 @@
FactoryBot.define do
factory :agent_capacity_policy do
account
sequence(:name) { |n| "Agent Capacity Policy #{n}" }
description { 'Test agent capacity policy' }
exclusion_rules { {} }
trait :with_overall_capacity do
exclusion_rules { { 'overall_capacity' => 10 } }
end
trait :with_time_exclusions do
exclusion_rules do
{
'hours' => [0, 1, 2, 3, 4, 5],
'days' => %w[saturday sunday]
}
end
end
end
end
+2 -1
View File
@@ -8,7 +8,8 @@ FactoryBot.define do
account_sid: "AC#{SecureRandom.hex(16)}",
auth_token: SecureRandom.hex(16),
api_key_sid: SecureRandom.hex(8),
api_key_secret: SecureRandom.hex(16)
api_key_secret: SecureRandom.hex(16),
twiml_app_sid: "AP#{SecureRandom.hex(16)}"
}
end
account
+7
View File
@@ -0,0 +1,7 @@
FactoryBot.define do
factory :inbox_capacity_limit do
association :agent_capacity_policy, factory: :agent_capacity_policy
inbox
conversation_limit { 5 }
end
end
@@ -0,0 +1,50 @@
require 'rails_helper'
RSpec.describe Channels::Twilio::TemplatesSyncJob do
let!(:account) { create(:account) }
let!(:twilio_channel) { create(:channel_twilio_sms, medium: :whatsapp, account: account) }
it 'enqueues the job' do
expect { described_class.perform_later(twilio_channel) }.to have_enqueued_job(described_class)
.on_queue('low')
.with(twilio_channel)
end
describe '#perform' do
let(:template_sync_service) { instance_double(Twilio::TemplateSyncService) }
context 'with successful template sync' do
it 'creates and calls the template sync service' do
expect(Twilio::TemplateSyncService).to receive(:new).with(channel: twilio_channel).and_return(template_sync_service)
expect(template_sync_service).to receive(:call).and_return(true)
described_class.perform_now(twilio_channel)
end
end
context 'with template sync exception' do
let(:error_message) { 'Twilio API error' }
before do
allow(Twilio::TemplateSyncService).to receive(:new).with(channel: twilio_channel).and_return(template_sync_service)
allow(template_sync_service).to receive(:call).and_raise(StandardError, error_message)
end
it 'does not suppress the exception' do
expect { described_class.perform_now(twilio_channel) }.to raise_error(StandardError, error_message)
end
end
context 'with nil channel' do
it 'handles nil channel gracefully' do
expect { described_class.perform_now(nil) }.to raise_error(NoMethodError)
end
end
end
describe 'job configuration' do
it 'is configured to run on low priority queue' do
expect(described_class.queue_name).to eq('low')
end
end
end
@@ -0,0 +1,598 @@
require 'rails_helper'
RSpec.describe Twilio::TemplateProcessorService do
subject(:processor_service) { described_class.new(channel: twilio_channel, template_params: template_params, message: message) }
let!(:account) { create(:account) }
let!(:twilio_channel) { create(:channel_twilio_sms, medium: :whatsapp, account: account) }
let!(:contact) { create(:contact, account: account) }
let!(:inbox) { create(:inbox, channel: twilio_channel, account: account) }
let!(:contact_inbox) { create(:contact_inbox, contact: contact, inbox: inbox) }
let!(:conversation) { create(:conversation, contact: contact, inbox: inbox, contact_inbox: contact_inbox) }
let!(:message) { create(:message, conversation: conversation, account: account) }
let(:content_templates) do
{
'templates' => [
{
'content_sid' => 'HX123456789',
'friendly_name' => 'hello_world',
'language' => 'en',
'status' => 'approved',
'template_type' => 'text',
'media_type' => nil,
'variables' => {},
'category' => 'utility',
'body' => 'Hello World!'
},
{
'content_sid' => 'HX987654321',
'friendly_name' => 'greet',
'language' => 'en',
'status' => 'approved',
'template_type' => 'text',
'media_type' => nil,
'variables' => { '1' => 'John' },
'category' => 'utility',
'body' => 'Hello {{1}}!'
},
{
'content_sid' => 'HX555666777',
'friendly_name' => 'product_showcase',
'language' => 'en',
'status' => 'approved',
'template_type' => 'media',
'media_type' => 'image',
'variables' => { '1' => 'https://example.com/image.jpg', '2' => 'iPhone', '3' => '$999' },
'category' => 'marketing',
'body' => 'Check out {{2}} for {{3}}'
},
{
'content_sid' => 'HX111222333',
'friendly_name' => 'welcome_message',
'language' => 'en_US',
'status' => 'approved',
'template_type' => 'quick_reply',
'media_type' => nil,
'variables' => {},
'category' => 'utility',
'body' => 'Welcome! How can we help?'
},
{
'content_sid' => 'HX444555666',
'friendly_name' => 'order_status',
'language' => 'es',
'status' => 'approved',
'template_type' => 'text',
'media_type' => nil,
'variables' => { '1' => 'Juan', '2' => 'ORD123' },
'category' => 'utility',
'body' => 'Hola {{1}}, tu pedido {{2}} está confirmado'
}
]
}
end
before do
twilio_channel.update!(content_templates: content_templates)
end
describe '#call' do
context 'with blank template_params' do
let(:template_params) { nil }
it 'returns nil values' do
result = processor_service.call
expect(result).to eq([nil, nil])
end
end
context 'with empty template_params' do
let(:template_params) { {} }
it 'returns nil values' do
result = processor_service.call
expect(result).to eq([nil, nil])
end
end
context 'with template not found' do
let(:template_params) do
{
'name' => 'nonexistent_template',
'language' => 'en'
}
end
it 'returns nil values' do
result = processor_service.call
expect(result).to eq([nil, nil])
end
end
context 'with text templates' do
context 'with simple text template (no variables)' do
let(:template_params) do
{
'name' => 'hello_world',
'language' => 'en'
}
end
it 'returns content_sid and empty variables' do
content_sid, content_variables = processor_service.call
expect(content_sid).to eq('HX123456789')
expect(content_variables).to eq({})
end
end
context 'with text template using processed_params format' do
let(:template_params) do
{
'name' => 'greet',
'language' => 'en',
'processed_params' => {
'1' => 'Alice',
'2' => 'Premium User'
}
}
end
it 'processes key-value parameters correctly' do
content_sid, content_variables = processor_service.call
expect(content_sid).to eq('HX987654321')
expect(content_variables).to eq({
'1' => 'Alice',
'2' => 'Premium User'
})
end
end
context 'with text template using WhatsApp Cloud API format' do
let(:template_params) do
{
'name' => 'greet',
'language' => 'en',
'parameters' => [
{
'type' => 'body',
'parameters' => [
{ 'type' => 'text', 'text' => 'Bob' }
]
}
]
}
end
it 'processes WhatsApp format parameters correctly' do
content_sid, content_variables = processor_service.call
expect(content_sid).to eq('HX987654321')
expect(content_variables).to eq({ '1' => 'Bob' })
end
end
context 'with multiple body parameters' do
let(:template_params) do
{
'name' => 'greet',
'language' => 'en',
'parameters' => [
{
'type' => 'body',
'parameters' => [
{ 'type' => 'text', 'text' => 'Charlie' },
{ 'type' => 'text', 'text' => 'VIP Member' }
]
}
]
}
end
it 'processes multiple parameters with sequential indexing' do
content_sid, content_variables = processor_service.call
expect(content_sid).to eq('HX987654321')
expect(content_variables).to eq({
'1' => 'Charlie',
'2' => 'VIP Member'
})
end
end
end
context 'with quick reply templates' do
let(:template_params) do
{
'name' => 'welcome_message',
'language' => 'en_US'
}
end
it 'processes quick reply templates like text templates' do
content_sid, content_variables = processor_service.call
expect(content_sid).to eq('HX111222333')
expect(content_variables).to eq({})
end
context 'with quick reply template having body parameters' do
let(:template_params) do
{
'name' => 'welcome_message',
'language' => 'en_US',
'parameters' => [
{
'type' => 'body',
'parameters' => [
{ 'type' => 'text', 'text' => 'Diana' }
]
}
]
}
end
it 'processes body parameters for quick reply templates' do
content_sid, content_variables = processor_service.call
expect(content_sid).to eq('HX111222333')
expect(content_variables).to eq({ '1' => 'Diana' })
end
end
end
context 'with media templates' do
context 'with media template using processed_params format' do
let(:template_params) do
{
'name' => 'product_showcase',
'language' => 'en',
'processed_params' => {
'1' => 'https://cdn.example.com/product.jpg',
'2' => 'MacBook Pro',
'3' => '$2499'
}
}
end
it 'processes key-value parameters for media templates' do
content_sid, content_variables = processor_service.call
expect(content_sid).to eq('HX555666777')
expect(content_variables).to eq({
'1' => 'https://cdn.example.com/product.jpg',
'2' => 'MacBook Pro',
'3' => '$2499'
})
end
end
context 'with media template using WhatsApp Cloud API format' do
let(:template_params) do
{
'name' => 'product_showcase',
'language' => 'en',
'parameters' => [
{
'type' => 'header',
'parameters' => [
{
'type' => 'image',
'image' => { 'link' => 'https://example.com/product-image.jpg' }
}
]
},
{
'type' => 'body',
'parameters' => [
{ 'type' => 'text', 'text' => 'Samsung Galaxy' },
{ 'type' => 'text', 'text' => '$899' }
]
}
]
}
end
it 'processes media header and body parameters correctly' do
content_sid, content_variables = processor_service.call
expect(content_sid).to eq('HX555666777')
expect(content_variables).to eq({
'1' => 'https://example.com/product-image.jpg',
'2' => 'Samsung Galaxy',
'3' => '$899'
})
end
end
context 'with video media template' do
let(:template_params) do
{
'name' => 'product_showcase',
'language' => 'en',
'parameters' => [
{
'type' => 'header',
'parameters' => [
{
'type' => 'video',
'video' => { 'link' => 'https://example.com/demo.mp4' }
}
]
},
{
'type' => 'body',
'parameters' => [
{ 'type' => 'text', 'text' => 'Product Demo' }
]
}
]
}
end
it 'processes video media parameters correctly' do
content_sid, content_variables = processor_service.call
expect(content_sid).to eq('HX555666777')
expect(content_variables).to eq({
'1' => 'https://example.com/demo.mp4',
'2' => 'Product Demo'
})
end
end
context 'with document media template' do
let(:template_params) do
{
'name' => 'product_showcase',
'language' => 'en',
'parameters' => [
{
'type' => 'header',
'parameters' => [
{
'type' => 'document',
'document' => { 'link' => 'https://example.com/brochure.pdf' }
}
]
},
{
'type' => 'body',
'parameters' => [
{ 'type' => 'text', 'text' => 'Product Brochure' }
]
}
]
}
end
it 'processes document media parameters correctly' do
content_sid, content_variables = processor_service.call
expect(content_sid).to eq('HX555666777')
expect(content_variables).to eq({
'1' => 'https://example.com/brochure.pdf',
'2' => 'Product Brochure'
})
end
end
context 'with header parameter without media link' do
let(:template_params) do
{
'name' => 'product_showcase',
'language' => 'en',
'parameters' => [
{
'type' => 'header',
'parameters' => [
{ 'type' => 'text', 'text' => 'Header Text' }
]
},
{
'type' => 'body',
'parameters' => [
{ 'type' => 'text', 'text' => 'Body Text' }
]
}
]
}
end
it 'skips header without media and processes body parameters' do
content_sid, content_variables = processor_service.call
expect(content_sid).to eq('HX555666777')
expect(content_variables).to eq({ '1' => 'Body Text' })
end
end
context 'with mixed component types' do
let(:template_params) do
{
'name' => 'product_showcase',
'language' => 'en',
'parameters' => [
{
'type' => 'header',
'parameters' => [
{
'type' => 'image',
'image' => { 'link' => 'https://example.com/header.jpg' }
}
]
},
{
'type' => 'body',
'parameters' => [
{ 'type' => 'text', 'text' => 'First param' },
{ 'type' => 'text', 'text' => 'Second param' }
]
},
{
'type' => 'footer',
'parameters' => []
}
]
}
end
it 'processes supported components and ignores unsupported ones' do
content_sid, content_variables = processor_service.call
expect(content_sid).to eq('HX555666777')
expect(content_variables).to eq({
'1' => 'https://example.com/header.jpg',
'2' => 'First param',
'3' => 'Second param'
})
end
end
end
context 'with language matching' do
context 'with exact language match' do
let(:template_params) do
{
'name' => 'order_status',
'language' => 'es'
}
end
it 'finds template with exact language match' do
content_sid, content_variables = processor_service.call
expect(content_sid).to eq('HX444555666')
expect(content_variables).to eq({})
end
end
context 'with default language fallback' do
let(:template_params) do
{
'name' => 'hello_world'
# No language specified, should default to 'en'
}
end
it 'defaults to English when no language specified' do
content_sid, content_variables = processor_service.call
expect(content_sid).to eq('HX123456789')
expect(content_variables).to eq({})
end
end
end
context 'with unapproved template status' do
let(:template_params) do
{
'name' => 'unapproved_template',
'language' => 'en'
}
end
before do
unapproved_template = {
'content_sid' => 'HX_UNAPPROVED',
'friendly_name' => 'unapproved_template',
'language' => 'en',
'status' => 'pending',
'template_type' => 'text',
'variables' => {},
'body' => 'This is unapproved'
}
updated_templates = content_templates['templates'] + [unapproved_template]
twilio_channel.update!(
content_templates: { 'templates' => updated_templates }
)
end
it 'ignores templates that are not approved' do
content_sid, content_variables = processor_service.call
expect(content_sid).to be_nil
expect(content_variables).to be_nil
end
end
context 'with unknown template type' do
let(:template_params) do
{
'name' => 'unknown_type',
'language' => 'en'
}
end
before do
unknown_template = {
'content_sid' => 'HX_UNKNOWN',
'friendly_name' => 'unknown_type',
'language' => 'en',
'status' => 'approved',
'template_type' => 'catalog',
'variables' => {},
'body' => 'Catalog template'
}
updated_templates = content_templates['templates'] + [unknown_template]
twilio_channel.update!(
content_templates: { 'templates' => updated_templates }
)
end
it 'returns empty content variables for unknown template types' do
content_sid, content_variables = processor_service.call
expect(content_sid).to eq('HX_UNKNOWN')
expect(content_variables).to eq({})
end
end
end
describe 'template finding behavior' do
context 'with no content_templates' do
let(:template_params) do
{
'name' => 'hello_world',
'language' => 'en'
}
end
before do
twilio_channel.update!(content_templates: {})
end
it 'returns nil values when content_templates is empty' do
result = processor_service.call
expect(result).to eq([nil, nil])
end
end
context 'with nil content_templates' do
let(:template_params) do
{
'name' => 'hello_world',
'language' => 'en'
}
end
before do
twilio_channel.update!(content_templates: nil)
end
it 'returns nil values when content_templates is nil' do
result = processor_service.call
expect(result).to eq([nil, nil])
end
end
end
end
@@ -0,0 +1,319 @@
require 'rails_helper'
RSpec.describe Twilio::TemplateSyncService do
subject(:sync_service) { described_class.new(channel: twilio_channel) }
let!(:account) { create(:account) }
let!(:twilio_channel) { create(:channel_twilio_sms, medium: :whatsapp, account: account) }
let(:twilio_client) { instance_double(Twilio::REST::Client) }
let(:content_api) { double }
let(:contents_list) { double }
# Mock Twilio template objects
let(:text_template) do
instance_double(
Twilio::REST::Content::V1::ContentInstance,
sid: 'HX123456789',
friendly_name: 'hello_world',
language: 'en',
date_created: Time.current,
date_updated: Time.current,
variables: {},
types: { 'twilio/text' => { 'body' => 'Hello World!' } }
)
end
let(:media_template) do
instance_double(
Twilio::REST::Content::V1::ContentInstance,
sid: 'HX987654321',
friendly_name: 'product_showcase',
language: 'en',
date_created: Time.current,
date_updated: Time.current,
variables: { '1' => 'iPhone', '2' => '$999' },
types: {
'twilio/media' => {
'body' => 'Check out {{1}} for {{2}}',
'media' => ['https://example.com/image.jpg']
}
}
)
end
let(:quick_reply_template) do
instance_double(
Twilio::REST::Content::V1::ContentInstance,
sid: 'HX555666777',
friendly_name: 'welcome_message',
language: 'en_US',
date_created: Time.current,
date_updated: Time.current,
variables: {},
types: {
'twilio/quick-reply' => {
'body' => 'Welcome! How can we help?',
'actions' => [
{ 'id' => 'support', 'title' => 'Support' },
{ 'id' => 'sales', 'title' => 'Sales' }
]
}
}
)
end
let(:catalog_template) do
instance_double(
Twilio::REST::Content::V1::ContentInstance,
sid: 'HX111222333',
friendly_name: 'product_catalog',
language: 'en',
date_created: Time.current,
date_updated: Time.current,
variables: {},
types: {
'twilio/catalog' => {
'body' => 'Check our catalog',
'catalog_id' => 'catalog123'
}
}
)
end
let(:templates) { [text_template, media_template, quick_reply_template, catalog_template] }
before do
allow(twilio_channel).to receive(:send).and_call_original
allow(twilio_channel).to receive(:send).with(:client).and_return(twilio_client)
allow(twilio_client).to receive(:content).and_return(content_api)
allow(content_api).to receive(:v1).and_return(content_api)
allow(content_api).to receive(:contents).and_return(contents_list)
allow(contents_list).to receive(:list).with(limit: 1000).and_return(templates)
end
describe '#call' do
context 'with successful sync' do
it 'fetches templates from Twilio and updates the channel' do
freeze_time do
result = sync_service.call
expect(result).to be_truthy
expect(contents_list).to have_received(:list).with(limit: 1000)
twilio_channel.reload
expect(twilio_channel.content_templates).to be_present
expect(twilio_channel.content_templates['templates']).to be_an(Array)
expect(twilio_channel.content_templates['templates'].size).to eq(4)
expect(twilio_channel.content_templates_last_updated).to be_within(1.second).of(Time.current)
end
end
it 'correctly formats text templates' do
sync_service.call
twilio_channel.reload
text_template_data = twilio_channel.content_templates['templates'].find do |t|
t['friendly_name'] == 'hello_world'
end
expect(text_template_data).to include(
'content_sid' => 'HX123456789',
'friendly_name' => 'hello_world',
'language' => 'en',
'status' => 'approved',
'template_type' => 'text',
'media_type' => nil,
'variables' => {},
'category' => 'utility',
'body' => 'Hello World!'
)
end
it 'correctly formats media templates' do
sync_service.call
twilio_channel.reload
media_template_data = twilio_channel.content_templates['templates'].find do |t|
t['friendly_name'] == 'product_showcase'
end
expect(media_template_data).to include(
'content_sid' => 'HX987654321',
'friendly_name' => 'product_showcase',
'language' => 'en',
'status' => 'approved',
'template_type' => 'media',
'media_type' => nil, # Would be derived from media content if present
'variables' => { '1' => 'iPhone', '2' => '$999' },
'category' => 'utility',
'body' => 'Check out {{1}} for {{2}}'
)
end
it 'correctly formats quick reply templates' do
sync_service.call
twilio_channel.reload
quick_reply_template_data = twilio_channel.content_templates['templates'].find do |t|
t['friendly_name'] == 'welcome_message'
end
expect(quick_reply_template_data).to include(
'content_sid' => 'HX555666777',
'friendly_name' => 'welcome_message',
'language' => 'en_US',
'status' => 'approved',
'template_type' => 'quick_reply',
'media_type' => nil,
'variables' => {},
'category' => 'utility',
'body' => 'Welcome! How can we help?'
)
end
it 'categorizes marketing templates correctly' do
marketing_template = instance_double(
Twilio::REST::Content::V1::ContentInstance,
sid: 'HX_MARKETING',
friendly_name: 'promo_offer_50_off',
language: 'en',
date_created: Time.current,
date_updated: Time.current,
variables: {},
types: { 'twilio/text' => { 'body' => '50% off sale!' } }
)
allow(contents_list).to receive(:list).with(limit: 1000).and_return([marketing_template])
sync_service.call
twilio_channel.reload
marketing_data = twilio_channel.content_templates['templates'].first
expect(marketing_data['category']).to eq('marketing')
end
it 'categorizes authentication templates correctly' do
auth_template = instance_double(
Twilio::REST::Content::V1::ContentInstance,
sid: 'HX_AUTH',
friendly_name: 'otp_verification',
language: 'en',
date_created: Time.current,
date_updated: Time.current,
variables: {},
types: { 'twilio/text' => { 'body' => 'Your OTP is {{1}}' } }
)
allow(contents_list).to receive(:list).with(limit: 1000).and_return([auth_template])
sync_service.call
twilio_channel.reload
auth_data = twilio_channel.content_templates['templates'].first
expect(auth_data['category']).to eq('authentication')
end
end
context 'with API error' do
before do
allow(contents_list).to receive(:list).and_raise(Twilio::REST::TwilioError.new('API Error'))
allow(Rails.logger).to receive(:error)
end
it 'handles Twilio::REST::TwilioError gracefully' do
result = sync_service.call
expect(result).to be_falsey
expect(Rails.logger).to have_received(:error).with('Twilio template sync failed: API Error')
end
end
context 'with generic error' do
before do
allow(contents_list).to receive(:list).and_raise(StandardError, 'Connection failed')
allow(Rails.logger).to receive(:error)
end
it 'propagates non-Twilio errors' do
expect { sync_service.call }.to raise_error(StandardError, 'Connection failed')
end
end
context 'with empty templates list' do
before do
allow(contents_list).to receive(:list).with(limit: 1000).and_return([])
end
it 'updates channel with empty templates array' do
sync_service.call
twilio_channel.reload
expect(twilio_channel.content_templates['templates']).to eq([])
expect(twilio_channel.content_templates_last_updated).to be_present
end
end
end
describe 'template categorization behavior' do
it 'defaults to utility category for unrecognized patterns' do
generic_template = instance_double(
Twilio::REST::Content::V1::ContentInstance,
sid: 'HX_GENERIC',
friendly_name: 'order_status',
language: 'en',
date_created: Time.current,
date_updated: Time.current,
variables: {},
types: { 'twilio/text' => { 'body' => 'Order updated' } }
)
allow(contents_list).to receive(:list).with(limit: 1000).and_return([generic_template])
sync_service.call
twilio_channel.reload
template_data = twilio_channel.content_templates['templates'].first
expect(template_data['category']).to eq('utility')
end
end
describe 'template type detection' do
context 'with multiple type definitions' do
let(:mixed_template) do
instance_double(
Twilio::REST::Content::V1::ContentInstance,
sid: 'HX_MIXED',
friendly_name: 'mixed_type',
language: 'en',
date_created: Time.current,
date_updated: Time.current,
variables: {},
types: {
'twilio/media' => { 'body' => 'Media content' },
'twilio/text' => { 'body' => 'Text content' }
}
)
end
before do
allow(contents_list).to receive(:list).with(limit: 1000).and_return([mixed_template])
end
it 'prioritizes media type for type detection but text for body extraction' do
sync_service.call
twilio_channel.reload
template_data = twilio_channel.content_templates['templates'].first
# derive_template_type prioritizes media
expect(template_data['template_type']).to eq('media')
# but extract_body_content prioritizes text
expect(template_data['body']).to eq('Text content')
end
end
end
end