Skip to content

Open-source live-chat, email support, omni-channel desk. An alternative to Intercom, Zendesk, Salesforce Service Cloud etc. 🔥💬

feat(voice): apply business hours to incoming calls (#16329)

Muhsin Keloth50ff77d41fdd
diff --git a/app/controllers/api/v1/accounts/inboxes_controller.rb b/app/controllers/api/v1/accounts/inboxes_controller.rb
index 0ff50bbd029..29d5f3a8bd3 100644
--- a/app/controllers/api/v1/accounts/inboxes_controller.rb
+++ b/app/controllers/api/v1/accounts/inboxes_controller.rb
@@ -9,7 +9,7 @@ class Api::V1::Accounts::InboxesController < Api::V1::Accounts::BaseController
include Api::V1::Accounts::Concerns::InboxSecretManagement
def index
- @inboxes = policy_scope(Current.account.inboxes)
+ @inboxes = inbox_scope
.includes(:channel, :portal, :working_hours, { avatar_attachment: :blob })
.order_by_name
end
@@ -84,6 +84,10 @@ class Api::V1::Accounts::InboxesController < Api::V1::Accounts::BaseController
private
+ def inbox_scope
+ policy_scope(Current.account.inboxes)
+ end
+
def fetch_inbox
@inbox = Current.account.inboxes.find(params[:id])
authorize @inbox, :show?
diff --git a/app/javascript/dashboard/api/inboxes.js b/app/javascript/dashboard/api/inboxes.js
index a31e099cf7c..f0615b8b7cf 100644
--- a/app/javascript/dashboard/api/inboxes.js
+++ b/app/javascript/dashboard/api/inboxes.js
@@ -93,6 +93,13 @@ class Inboxes extends CacheEnabledApiClient {
transcription_enabled: transcriptionEnabled,
});
}
+
+ setCallBusinessHours(inboxId, { enabled, message }) {
+ return axios.patch(`${this.url}/${inboxId}/call_business_hours`, {
+ business_hours_calls_enabled: enabled,
+ out_of_hours_call_message: message,
+ });
+ }
}
export default new Inboxes();
diff --git a/app/javascript/dashboard/components-next/message/bubbles/VoiceCall.vue b/app/javascript/dashboard/components-next/message/bubbles/VoiceCall.vue
index b1c00c4a336..5307e6e6f4c 100644
--- a/app/javascript/dashboard/components-next/message/bubbles/VoiceCall.vue
+++ b/app/javascript/dashboard/components-next/message/bubbles/VoiceCall.vue
@@ -170,6 +170,9 @@ const subtext = computed(() => {
if (isOutbound.value) {
return t('CONVERSATION.VOICE_CALL.NO_ANSWER_OUTBOUND_SUBTEXT');
}
+ if (endReason.value === VOICE_CALL_END_REASON.OUTSIDE_WORKING_HOURS) {
+ return t('CONVERSATION.VOICE_CALL.MISSED_CALL_OUTSIDE_HOURS');
+ }
if (wasDeclinedByAgent.value && displayAgentName.value) {
return t('CONVERSATION.VOICE_CALL.MISSED_CALL_DECLINED_BY', {
agentName: displayAgentName.value,
diff --git a/app/javascript/dashboard/components-next/message/constants.js b/app/javascript/dashboard/components-next/message/constants.js
index 72a2c503a2b..c957ee981f2 100644
--- a/app/javascript/dashboard/components-next/message/constants.js
+++ b/app/javascript/dashboard/components-next/message/constants.js
@@ -109,4 +109,5 @@ export const VOICE_CALL_OUTBOUND_INIT_STATUS = {
export const VOICE_CALL_END_REASON = {
AGENT_REJECTED: 'agent_rejected',
+ OUTSIDE_WORKING_HOURS: 'outside_working_hours',
};
diff --git a/app/javascript/dashboard/i18n/locale/en/conversation.json b/app/javascript/dashboard/i18n/locale/en/conversation.json
index 3e2c3abc234..8ca91495d8d 100644
--- a/app/javascript/dashboard/i18n/locale/en/conversation.json
+++ b/app/javascript/dashboard/i18n/locale/en/conversation.json
@@ -141,6 +141,7 @@
"MISSED_CALL": "Missed call",
"MISSED_CALL_INBOUND_SUBTEXT": "No agent picked up",
"MISSED_CALL_DECLINED_BY": "Declined by {agentName}",
+ "MISSED_CALL_OUTSIDE_HOURS": "Outside business hours",
"CALL_ENDED": "Call ended",
"HANDLED_BY": "Handled by {agentName}",
"NOT_ANSWERED_YET": "Not answered yet",
diff --git a/app/javascript/dashboard/i18n/locale/en/inboxMgmt.json b/app/javascript/dashboard/i18n/locale/en/inboxMgmt.json
index d30ceb2c349..801336a12ab 100644
--- a/app/javascript/dashboard/i18n/locale/en/inboxMgmt.json
+++ b/app/javascript/dashboard/i18n/locale/en/inboxMgmt.json
@@ -788,6 +788,19 @@
"TRANSCRIPTION": {
"LABEL": "Transcribe recordings",
"DESCRIPTION": "Turn each recording into a text transcript. Uses Captain and requires audio transcription to be enabled for the account."
+ },
+ "BUSINESS_HOURS": {
+ "LABEL": "Apply business hours to calls",
+ "DESCRIPTION": "Outside this inbox's business hours, incoming calls don't ring agents. The caller gets your out-of-hours message, and the call is logged as missed.",
+ "HOURS_NOT_ENABLED": "Business hours are turned off for this inbox, so calls keep ringing. Turn them on in the Business Hours tab.",
+ "MESSAGE": {
+ "LABEL": "Out-of-hours message",
+ "PLACEHOLDER": "Our support team is available Monday through Friday, from 9 AM to 6 PM. Please call again during business hours.",
+ "TWILIO_HELP": "Saving generates the spoken announcement using one Captain response credit. You can listen to the saved audio below."
+ },
+ "READ_BY_TWILIO": "Captain isn't available. You can save the text for Twilio to read.",
+ "ACTIVE": "Current announcement",
+ "SAVE": "Save announcement"
}
},
"WHATSAPP_CALLING": {
diff --git a/app/javascript/dashboard/routes/dashboard/settings/inbox/settingsPage/CallBusinessHoursSettings.vue b/app/javascript/dashboard/routes/dashboard/settings/inbox/settingsPage/CallBusinessHoursSettings.vue
new file mode 100644
index 00000000000..3145d468ebf
--- /dev/null
+++ b/app/javascript/dashboard/routes/dashboard/settings/inbox/settingsPage/CallBusinessHoursSettings.vue
@@ -0,0 +1,155 @@
+<script setup>
+import { ref, computed, watch } from 'vue';
+import { useStore } from 'vuex';
+import { useI18n } from 'vue-i18n';
+import { useAlert } from 'dashboard/composables';
+import SettingsToggleSection from 'dashboard/components-next/Settings/SettingsToggleSection.vue';
+import TextArea from 'dashboard/components-next/textarea/TextArea.vue';
+import NextButton from 'dashboard/components-next/button/Button.vue';
+
+const props = defineProps({
+ inbox: {
+ type: Object,
+ required: true,
+ },
+});
+
+const MESSAGE_MAX_LENGTH = 1000;
+const store = useStore();
+const { t } = useI18n();
+const enabled = ref(!!props.inbox.business_hours_calls_enabled);
+const message = ref(props.inbox.out_of_hours_call_message || '');
+const isSaving = ref(false);
+const isDirty = computed(
+ () => message.value.trim() !== (props.inbox.out_of_hours_call_message || '')
+);
+const audioUrl = computed(() => props.inbox.out_of_hours_call_audio_url);
+const canSave = computed(
+ () =>
+ !isSaving.value &&
+ !!message.value.trim() &&
+ (isDirty.value || !audioUrl.value)
+);
+
+watch(
+ [
+ () => props.inbox.id,
+ () => !!props.inbox.business_hours_calls_enabled,
+ () => props.inbox.out_of_hours_call_message || '',
+ ],
+ ([, savedEnabled, savedMessage]) => {
+ enabled.value = !!savedEnabled;
+ message.value = savedMessage || '';
+ }
+);
+
+const showError = error =>
+ useAlert(
+ error?.response?.data?.error || t('INBOX_MGMT.EDIT.API.ERROR_MESSAGE')
+ );
+const save = async (nextEnabled = enabled.value, useDraft = true) => {
+ if (isSaving.value) return;
+ isSaving.value = true;
+ try {
+ await store.dispatch('inboxes/updateCallBusinessHours', {
+ id: props.inbox.id,
+ enabled: nextEnabled,
+ message: useDraft
+ ? message.value.trim()
+ : props.inbox.out_of_hours_call_message || '',
+ });
+ useAlert(t('INBOX_MGMT.EDIT.API.SUCCESS_MESSAGE'));
+ } catch (error) {
+ enabled.value = !!props.inbox.business_hours_calls_enabled;
+ showError(error);
+ } finally {
+ isSaving.value = false;
+ }
+};
+const toggle = value => {
+ enabled.value = value;
+ if (value && !props.inbox.out_of_hours_call_message) return;
+ save(value, false);
+};
+</script>
+
+<template>
+ <div :class="{ 'pointer-events-none opacity-60': isSaving }">
+ <SettingsToggleSection
+ :model-value="enabled"
+ :header="$t('INBOX_MGMT.VOICE_CONFIGURATION.BUSINESS_HOURS.LABEL')"
+ :description="
+ $t('INBOX_MGMT.VOICE_CONFIGURATION.BUSINESS_HOURS.DESCRIPTION')
+ "
+ @update:model-value="toggle"
+ >
+ <template v-if="enabled" #editor>
+ <div class="flex flex-col gap-3">
+ <p
+ v-if="!inbox.working_hours_enabled"
+ class="text-body-main text-n-amber-11"
+ >
+ {{
+ $t(
+ 'INBOX_MGMT.VOICE_CONFIGURATION.BUSINESS_HOURS.HOURS_NOT_ENABLED'
+ )
+ }}
+ </p>
+ <TextArea
+ :id="`out-of-hours-call-message-${inbox.id}`"
+ v-model="message"
+ :label="
+ $t('INBOX_MGMT.VOICE_CONFIGURATION.BUSINESS_HOURS.MESSAGE.LABEL')
+ "
+ :placeholder="
+ $t(
+ 'INBOX_MGMT.VOICE_CONFIGURATION.BUSINESS_HOURS.MESSAGE.PLACEHOLDER'
+ )
+ "
+ :max-length="MESSAGE_MAX_LENGTH"
+ :disabled="isSaving"
+ show-character-count
+ auto-height
+ />
+ <p class="text-body-main text-n-slate-11">
+ {{
+ $t(
+ 'INBOX_MGMT.VOICE_CONFIGURATION.BUSINESS_HOURS.MESSAGE.TWILIO_HELP'
+ )
+ }}
+ </p>
+ <p
+ v-if="inbox.out_of_hours_call_message && !audioUrl"
+ class="text-body-main text-n-slate-11"
+ >
+ {{
+ $t('INBOX_MGMT.VOICE_CONFIGURATION.BUSINESS_HOURS.READ_BY_TWILIO')
+ }}
+ </p>
+ <template v-if="audioUrl">
+ <span class="text-body-main text-n-slate-12">{{
+ $t('INBOX_MGMT.VOICE_CONFIGURATION.BUSINESS_HOURS.ACTIVE')
+ }}</span>
+ <audio
+ :key="audioUrl"
+ :src="audioUrl"
+ controls
+ class="w-full"
+ :aria-label="
+ $t('INBOX_MGMT.VOICE_CONFIGURATION.BUSINESS_HOURS.ACTIVE')
+ "
+ />
+ </template>
+ <div>
+ <NextButton
+ :label="$t('INBOX_MGMT.VOICE_CONFIGURATION.BUSINESS_HOURS.SAVE')"
+ :is-loading="isSaving"
+ :disabled="!canSave"
+ @click="save()"
+ />
+ </div>
+ </div>
+ </template>
+ </SettingsToggleSection>
+ </div>
+</template>
diff --git a/app/javascript/dashboard/routes/dashboard/settings/inbox/settingsPage/VoiceConfigurationPage.vue b/app/javascript/dashboard/routes/dashboard/settings/inbox/settingsPage/VoiceConfigurationPage.vue
index 818c6416a7a..4afde752906 100644
--- a/app/javascript/dashboard/routes/dashboard/settings/inbox/settingsPage/VoiceConfigurationPage.vue
+++ b/app/javascript/dashboard/routes/dashboard/settings/inbox/settingsPage/VoiceConfigurationPage.vue
@@ -7,6 +7,7 @@ import NextInput from 'dashboard/components-next/input/Input.vue';
import NextButton from 'dashboard/components-next/button/Button.vue';
import Spinner from 'dashboard/components-next/spinner/Spinner.vue';
import CallRecordingSettings from './CallRecordingSettings.vue';
+import CallBusinessHoursSettings from './CallBusinessHoursSettings.vue';
export default {
components: {
@@ -16,6 +17,7 @@ export default {
NextButton,
Spinner,
CallRecordingSettings,
+ CallBusinessHoursSettings,
},
props: {
inbox: {
@@ -219,6 +221,8 @@ export default {
<CallRecordingSettings v-if="inbox.voice_enabled" :inbox="inbox" />
+ <CallBusinessHoursSettings v-if="inbox.voice_enabled" :inbox="inbox" />
+
<div v-if="inbox.voice_enabled && inbox.voice_call_webhook_url">
<SettingsFieldSection
:label="$t('INBOX_MGMT.ADD.VOICE.CONFIGURATION.TWILIO_VOICE_URL_TITLE')"
diff --git a/app/javascript/dashboard/routes/dashboard/settings/inbox/settingsPage/specs/CallBusinessHoursSettings.spec.js b/app/javascript/dashboard/routes/dashboard/settings/inbox/settingsPage/specs/CallBusinessHoursSettings.spec.js
new file mode 100644
index 00000000000..cbcadafd576
--- /dev/null
+++ b/app/javascript/dashboard/routes/dashboard/settings/inbox/settingsPage/specs/CallBusinessHoursSettings.spec.js
@@ -0,0 +1,142 @@
+import { mount, flushPromises } from '@vue/test-utils';
+import CallBusinessHoursSettings from '../CallBusinessHoursSettings.vue';
+import TextArea from 'dashboard/components-next/textarea/TextArea.vue';
+import NextButton from 'dashboard/components-next/button/Button.vue';
+import SettingsToggleSection from 'dashboard/components-next/Settings/SettingsToggleSection.vue';
+
+const { dispatch, alert } = vi.hoisted(() => ({
+ dispatch: vi.fn(),
+ alert: vi.fn(),
+}));
+
+vi.mock('vuex', async importOriginal => ({
+ ...(await importOriginal()),
+ useStore: () => ({ dispatch }),
+}));
+vi.mock('dashboard/composables', () => ({ useAlert: alert }));
+const inbox = {
+ id: 387,
+ working_hours_enabled: true,
+ business_hours_calls_enabled: true,
+ out_of_hours_call_message: 'Call again tomorrow.',
+ out_of_hours_call_audio_url: '/announcement.mp3',
+};
+
+const mountComponent = (overrides, stubs = {}) =>
+ mount(CallBusinessHoursSettings, {
+ props: { inbox: { ...inbox, ...overrides } },
+ global: {
+ stubs: {
+ TextArea: true,
+ Spinner: true,
+ Icon: true,
+ ...stubs,
+ SettingsToggleSection: {
+ props: ['modelValue', 'header', 'description'],
+ template: '<section><slot name="editor" /></section>',
+ },
+ },
+ },
+ });
+
+describe('CallBusinessHoursSettings', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('associates the announcement label with an inbox-specific textarea', () => {
+ const wrapper = mountComponent({}, { TextArea: false });
+ const textarea = wrapper.find('textarea');
+
+ expect(textarea.attributes('id')).toBe('out-of-hours-call-message-387');
+ expect(wrapper.find('label').attributes('for')).toBe(
+ textarea.attributes('id')
+ );
+ });
+
+ it('keeps playback of the saved announcement while editing', async () => {
+ const wrapper = mountComponent();
+ expect(wrapper.find('audio').attributes('src')).toBe('/announcement.mp3');
+
+ wrapper
+ .findComponent(TextArea)
+ .vm.$emit('update:modelValue', 'New announcement');
+ await wrapper.vm.$nextTick();
+
+ expect(wrapper.find('audio').attributes('src')).toBe('/announcement.mp3');
+ });
+
+ it('saves edited text with one button and disables editing until saving completes', async () => {
+ let finish;
+ dispatch.mockReturnValue(
+ new Promise(resolve => {
+ finish = resolve;
+ })
+ );
+ const wrapper = mountComponent();
+ wrapper
+ .findComponent(TextArea)
+ .vm.$emit('update:modelValue', ' Updated announcement ');
+ await wrapper.vm.$nextTick();
+ wrapper.findComponent(NextButton).vm.$emit('click');
+ await wrapper.vm.$nextTick();
+
+ expect(dispatch).toHaveBeenCalledWith('inboxes/updateCallBusinessHours', {
+ id: 387,
+ enabled: true,
+ message: 'Updated announcement',
+ });
+ expect(wrapper.findComponent(TextArea).props('disabled')).toBe(true);
+ expect(
+ wrapper.findComponent(NextButton).find('button').element.disabled
+ ).toBe(true);
+ finish();
+ await flushPromises();
+ });
+
+ it('preserves unsaved text when an unrelated inbox refresh arrives', async () => {
+ const wrapper = mountComponent();
+ wrapper
+ .findComponent(TextArea)
+ .vm.$emit('update:modelValue', 'Unsaved announcement');
+ await wrapper.vm.$nextTick();
+ await wrapper.setProps({ inbox: { ...inbox } });
+
+ expect(wrapper.findComponent(TextArea).props('modelValue')).toBe(
+ 'Unsaved announcement'
+ );
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it('allows saving unchanged text when audio is missing and disables saving once audio exists', async () => {
+ dispatch.mockResolvedValue();
+ const wrapper = mountComponent({ out_of_hours_call_audio_url: null });
+ const button = wrapper.findComponent(NextButton).find('button');
+
+ expect(button.element.disabled).toBe(false);
+ await button.trigger('click');
+ await flushPromises();
+
+ expect(dispatch).toHaveBeenCalledWith('inboxes/updateCallBusinessHours', {
+ id: 387,
+ enabled: true,
+ message: inbox.out_of_hours_call_message,
+ });
+
+ await wrapper.setProps({ inbox: { ...inbox } });
+
+ expect(button.element.disabled).toBe(true);
+ });
+
+ it('restores the saved toggle after a failed update', async () => {
+ dispatch.mockRejectedValue(new Error('Update failed'));
+ const wrapper = mountComponent();
+ wrapper
+ .findComponent(SettingsToggleSection)
+ .vm.$emit('update:modelValue', false);
+ await flushPromises();
+
+ expect(
+ wrapper.findComponent(SettingsToggleSection).props('modelValue')
+ ).toBe(true);
+ expect(alert).toHaveBeenCalled();
+ });
+});
diff --git a/app/javascript/dashboard/store/modules/inboxes.js b/app/javascript/dashboard/store/modules/inboxes.js
index f4c8a807874..e4f155a2943 100644
--- a/app/javascript/dashboard/store/modules/inboxes.js
+++ b/app/javascript/dashboard/store/modules/inboxes.js
@@ -262,6 +262,13 @@ export const actions = {
throwErrorMessage(error);
}
},
+ updateCallBusinessHours: async ({ commit }, { id, enabled, message }) => {
+ const response = await InboxesAPI.setCallBusinessHours(id, {
+ enabled,
+ message,
+ });
+ commit(types.default.EDIT_INBOXES, response.data);
+ },
updateInboxIMAP: async ({ commit }, { id, ...inboxParams }) => {
commit(types.default.SET_INBOXES_UI_FLAG, { isUpdatingIMAP: true });
try {
diff --git a/app/views/api/v1/models/_inbox.json.jbuilder b/app/views/api/v1/models/_inbox.json.jbuilder
index f7db925f1f6..a4732a13d7e 100644
--- a/app/views/api/v1/models/_inbox.json.jbuilder
+++ b/app/views/api/v1/models/_inbox.json.jbuilder
@@ -163,6 +163,11 @@ if resource.twilio? && resource.channel.respond_to?(:voice_enabled?)
json.inbound_calls_enabled resource.channel.inbound_calls_enabled?
json.recording_enabled resource.channel.try(:recording_enabled?)
json.transcription_enabled resource.channel.try(:transcription_enabled?)
+ json.business_hours_calls_enabled resource.channel.try(:business_hours_calls_enabled?)
+ json.out_of_hours_call_message resource.channel.try(:out_of_hours_call_message)
+ if resource.respond_to?(:out_of_hours_call_audio) && resource.out_of_hours_call_audio.attached?
+ json.out_of_hours_call_audio_url rails_blob_path(resource.out_of_hours_call_audio, only_path: true)
+ end
json.account_auth_token_configured resource.channel.try(:account_auth_token_configured?) == true
json.voice_configured resource.channel.try(:twiml_app_sid).present?
json.has_api_key_secret resource.channel.try(:api_key_secret).present?
diff --git a/config/llm.yml b/config/llm.yml
index 544048d40ac..805b686572b 100644
--- a/config/llm.yml
+++ b/config/llm.yml
@@ -71,6 +71,10 @@ models:
provider: openai
display_name: 'GPT-4o Mini Transcribe'
credit_multiplier: 1
+ gpt-4o-mini-tts-2025-12-15:
+ provider: openai
+ display_name: 'GPT-4o Mini TTS'
+ credit_multiplier: 1
text-embedding-3-small:
provider: openai
display_name: 'Text Embedding 3 Small'
@@ -207,6 +211,9 @@ features:
audio_transcription:
models: [gpt-4o-mini-transcribe, whisper-1]
default: gpt-4o-mini-transcribe
+ call_announcement:
+ models: [gpt-4o-mini-tts-2025-12-15]
+ default: gpt-4o-mini-tts-2025-12-15
help_center_search:
models: [text-embedding-3-small]
default: text-embedding-3-small
diff --git a/config/locales/en.yml b/config/locales/en.yml
index 2236fd8d86b..7dba1941e79 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -44,6 +44,11 @@ en:
success: 'Channel reauthorized successfully'
not_required: 'Reauthorization is not required for this inbox'
invalid_channel: 'Invalid channel type for reauthorization'
+ call_business_hours:
+ unsupported_inbox: 'Business hours for calls require a Twilio voice inbox'
+ invalid_settings: 'Provide a boolean for business hours and text for the announcement'
+ message_required: 'Add the message callers hear outside business hours'
+ message_too_long: 'The out-of-hours message must be 1000 characters or fewer'
auth:
saml:
invalid_email: 'Please enter a valid email address'
diff --git a/config/routes.rb b/config/routes.rb
index 4ea579a599b..443523b566b 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -349,6 +349,7 @@ Rails.application.routes.draw do
post :disable_whatsapp_calling, on: :member
post :set_inbound_calls, on: :member
post :set_call_recording, on: :member
+ resource :call_business_hours, only: [:update], controller: 'inboxes/call_business_hours'
end
resource :csat_template, only: [:show, :create], controller: 'inbox_csat_templates' do
diff --git a/enterprise/app/controllers/api/v1/accounts/inboxes/call_business_hours_controller.rb b/enterprise/app/controllers/api/v1/accounts/inboxes/call_business_hours_controller.rb
new file mode 100644
index 00000000000..7b3faae028a
--- /dev/null
+++ b/enterprise/app/controllers/api/v1/accounts/inboxes/call_business_hours_controller.rb
@@ -0,0 +1,36 @@
+class Api::V1::Accounts::Inboxes::CallBusinessHoursController < Api::V1::Accounts::BaseController
+ before_action :fetch_inbox
+ before_action :validate_settings
+
+ def update
+ Voice::BusinessHoursSettingsService.new(
+ inbox: @inbox, enabled: params[:business_hours_calls_enabled], message: @message
+ ).perform
+ @inbox.update_account_cache
+ render 'api/v1/accounts/inboxes/show'
+ end
+
+ private
+
+ def fetch_inbox
+ @inbox = Current.account.inboxes.find(params[:inbox_id])
+ authorize @inbox, :update?
+ return if @inbox.twilio? && @inbox.channel.voice_enabled?
+
+ render_could_not_create_error(I18n.t('inbox.call_business_hours.unsupported_inbox'))
+ end
+
+ def validate_settings
+ enabled = params[:business_hours_calls_enabled]
+ message = params[:out_of_hours_call_message]
+ unless [true, false].include?(enabled) && message.is_a?(String)
+ return render_could_not_create_error(I18n.t('inbox.call_business_hours.invalid_settings'))
+ end
+
+ @message = message.strip
+ return render_could_not_create_error(I18n.t('inbox.call_business_hours.message_required')) if enabled && @message.empty?
+ return unless @message.length > Voice::BusinessHoursSettingsService::MESSAGE_MAX_LENGTH
+
+ render_could_not_create_error(I18n.t('inbox.call_business_hours.message_too_long'))
+ end
+end
diff --git a/enterprise/app/controllers/enterprise/api/v1/accounts/inboxes_controller.rb b/enterprise/app/controllers/enterprise/api/v1/accounts/inboxes_controller.rb
index 4a769fbd419..d3785a0e748 100644
--- a/enterprise/app/controllers/enterprise/api/v1/accounts/inboxes_controller.rb
+++ b/enterprise/app/controllers/enterprise/api/v1/accounts/inboxes_controller.rb
@@ -64,6 +64,8 @@ module Enterprise::Api::V1::Accounts::InboxesController
private
+ def inbox_scope = super.with_attached_out_of_hours_call_audio
+
def ensure_whatsapp_calling_supported
channel = @inbox.channel
return true if channel.is_a?(Channel::Whatsapp) && channel.voice_calling_supported?
diff --git a/enterprise/app/controllers/twilio/voice_controller.rb b/enterprise/app/controllers/twilio/voice_controller.rb
index bf5f3e78766..a4ae7b81cbc 100644
--- a/enterprise/app/controllers/twilio/voice_controller.rb
+++ b/enterprise/app/controllers/twilio/voice_controller.rb
@@ -27,6 +27,8 @@ class Twilio::VoiceController < ApplicationController
return render xml: reject_twiml if reject_inbound?
call = resolve_call
+ return render 'twilio/voice/out_of_hours', formats: [:xml] if call.outside_working_hours? && !agent_leg?(twilio_from)
+
# The leg was answered after the call ended (e.g. hangup raced the cancel); don't strand it in an empty conference.
return render xml: hangup_twiml unless open_leg?(call)
@@ -131,22 +133,18 @@ class Twilio::VoiceController < ApplicationController
sid = params[:call_sid].presence
raise ArgumentError, 'call_sid is required for agent leg' if sid.blank?
- inbox_calls.find_by!(provider_call_id: sid)
+ inbox.calls.twilio.find_by!(provider_call_id: sid)
end
def sync_outbound_leg(call_sid:, direction:)
parent_sid = params['ParentCallSid'].presence
lookup_sid = direction == 'outbound-dial' ? parent_sid || call_sid : call_sid
- call = inbox_calls.find_by!(provider_call_id: lookup_sid)
+ call = inbox.calls.twilio.find_by!(provider_call_id: lookup_sid)
call.merge_meta!('parent_call_sid' => parent_sid) if parent_sid.present? && call.parent_call_sid != parent_sid
call
end
- def inbox_calls
- Call.where(inbox_id: inbox.id, provider: :twilio)
- end
-
def conference_twiml(call)
conference_sid = ensure_conference_sid!(call)
@@ -194,8 +192,8 @@ class Twilio::VoiceController < ApplicationController
def find_call_for_conference!(friendly_name, call_sid)
name = friendly_name.to_s
- call = inbox_calls.by_conference_sid(name).first if name.present?
- call || inbox_calls.find_by!(provider_call_id: call_sid)
+ call = inbox.calls.twilio.by_conference_sid(name).first if name.present?
+ call || inbox.calls.twilio.find_by!(provider_call_id: call_sid)
end
# Twilio's recording webhook only sends its internal ConferenceSid (CF...),
diff --git a/enterprise/app/helpers/twilio/voice_helper.rb b/enterprise/app/helpers/twilio/voice_helper.rb
new file mode 100644
index 00000000000..0149ed107d1
--- /dev/null
+++ b/enterprise/app/helpers/twilio/voice_helper.rb
@@ -0,0 +1,12 @@
+module Twilio::VoiceHelper
+ # Languages supported by Twilio's basic voices. Other account languages retain the English default.
+ ANNOUNCEMENT_LANGUAGES = {
+ 'en' => 'en-US', 'en-GB' => 'en-GB', 'de' => 'de-DE',
+ 'es' => 'es-ES', 'fr' => 'fr-FR', 'it' => 'it-IT'
+ }.freeze
+
+ def out_of_hours_call_language(inbox)
+ locale = inbox.account.locale.tr('_', '-')
+ ANNOUNCEMENT_LANGUAGES.fetch(locale) { ANNOUNCEMENT_LANGUAGES.fetch(locale.split('-').first, 'en-US') }
+ end
+end
diff --git a/enterprise/app/models/call.rb b/enterprise/app/models/call.rb
index 09e6807a035..9fbcfc6a9ba 100644
--- a/enterprise/app/models/call.rb
+++ b/enterprise/app/models/call.rb
@@ -34,6 +34,7 @@
class Call < ApplicationRecord
STATUSES = %w[ringing in_progress completed no_answer failed rejected].freeze
TERMINAL_STATUSES = %w[completed no_answer failed rejected].freeze
+ OUTSIDE_WORKING_HOURS = 'outside_working_hours'.freeze
store_accessor :meta, :conference_sid, :twilio_conference_sid, :recording_sid, :parent_call_sid, :initiated_at, :ended_at,
:accepted_broadcast_at, :recording_enabled, :provider_status
@@ -76,6 +77,10 @@ class Call < ApplicationRecord
find_by(provider: provider, provider_call_id: sid)
end
+ def outside_working_hours?
+ end_reason == OUTSIDE_WORKING_HOURS
+ end
+
# An inbound call nobody answered, however it ended: unanswered, or completed or failed
# with no agent on it, as when the caller hangs up during the ring and the provider
# reports that leg completed
diff --git a/enterprise/app/models/enterprise/channel/twilio_sms.rb b/enterprise/app/models/enterprise/channel/twilio_sms.rb
index 2e440200f17..c08340441fe 100644
--- a/enterprise/app/models/enterprise/channel/twilio_sms.rb
+++ b/enterprise/app/models/enterprise/channel/twilio_sms.rb
@@ -13,6 +13,14 @@ module Enterprise::Channel::TwilioSms
end
end
+ def business_hours_calls_enabled?
+ provider_config['business_hours_calls_enabled'] == true
+ end
+
+ def out_of_hours_call_message
+ provider_config['out_of_hours_call_message']
+ end
+
def account_auth_token_configured?
provider_config['account_auth_token_configured'] == true
end
diff --git a/enterprise/app/models/enterprise/concerns/inbox.rb b/enterprise/app/models/enterprise/concerns/inbox.rb
index 4c021f79b8b..e3643f227a4 100644
--- a/enterprise/app/models/enterprise/concerns/inbox.rb
+++ b/enterprise/app/models/enterprise/concerns/inbox.rb
@@ -9,10 +9,15 @@ module Enterprise::Concerns::Inbox
has_many :inbox_capacity_limits, dependent: :destroy
has_many :calls, dependent: :destroy_async
has_many :conversation_outcomes, dependent: :destroy_async
+ has_one_attached :out_of_hours_call_audio
before_create :ensure_create_permitted
end
+ def closed_for_calls?
+ twilio? && channel.business_hours_calls_enabled? && out_of_office?
+ end
+
def ensure_create_permitted
raise CustomExceptions::Inbox::LimitExceeded.new({}) if account.inboxes.count >= account.usage_limits[:inboxes]
end
diff --git a/enterprise/app/services/llm/legacy_base_open_ai_service.rb b/enterprise/app/services/llm/legacy_base_open_ai_service.rb
index 09d67e1b716..db441a77914 100644
--- a/enterprise/app/services/llm/legacy_base_open_ai_service.rb
+++ b/enterprise/app/services/llm/legacy_base_open_ai_service.rb
@@ -5,6 +5,7 @@
# - Captain::Llm::PdfProcessingService (files.upload for assistants)
# - Captain::Llm::PaginatedFaqGeneratorService (uses file_id from uploaded files)
# - Llm::SpeechToTextService (audio.transcribe)
+# - Llm::TextToSpeechService (audio.speech)
#
# For all other LLM operations, use Llm::BaseAiService with RubyLLM instead.
class Llm::LegacyBaseOpenAiService
diff --git a/enterprise/app/services/llm/text_to_speech_service.rb b/enterprise/app/services/llm/text_to_speech_service.rb
new file mode 100644
index 00000000000..77ca234060f
--- /dev/null
+++ b/enterprise/app/services/llm/text_to_speech_service.rb
@@ -0,0 +1,24 @@
+class Llm::TextToSpeechService < Llm::LegacyBaseOpenAiService
+ VOICE = 'alloy'.freeze
+
+ attr_reader :text, :account
+
+ def self.available_for?(account)
+ account.feature_enabled?('captain_integration') &&
+ account.usage_limits[:captain][:responses][:current_available].positive? &&
+ InstallationConfig.find_by(name: 'CAPTAIN_OPEN_AI_API_KEY')&.value.present?
+ end
+
+ def initialize(text:, account:)
+ super()
+ @text = text
+ @account = account
+ end
+
+ def perform
+ model = Llm::FeatureRouter.resolve(feature: 'call_announcement', account: account)[:model]
+ audio = client.audio.speech(parameters: { model: model, input: text, voice: VOICE, response_format: 'mp3' })
+ account.increment_response_usage
+ audio
+ end
+end
diff --git a/enterprise/app/services/voice/business_hours_settings_service.rb b/enterprise/app/services/voice/business_hours_settings_service.rb
new file mode 100644
index 00000000000..9593c72201d
--- /dev/null
+++ b/enterprise/app/services/voice/business_hours_settings_service.rb
@@ -0,0 +1,35 @@
+class Voice::BusinessHoursSettingsService
+ MESSAGE_MAX_LENGTH = 1000
+
+ pattr_initialize [:inbox!, :enabled!, :message!]
+
+ def perform
+ channel = inbox.channel
+ changed = message != channel.out_of_hours_call_message
+ audio = recorded_audio(changed)
+
+ channel.with_lock do
+ changed = message != channel.out_of_hours_call_message
+ inbox.reload
+ # Register the attachment change before the channel touches a second Inbox instance.
+ if audio
+ inbox.out_of_hours_call_audio.attach(io: StringIO.new(audio), filename: "out-of-hours-#{inbox.id}.mp3", content_type: 'audio/mpeg')
+ elsif changed
+ inbox.out_of_hours_call_audio.purge_later
+ end
+ channel.update!(provider_config: channel.provider_config.merge(
+ 'business_hours_calls_enabled' => enabled,
+ 'out_of_hours_call_message' => message
+ ))
+ end
+ end
+
+ private
+
+ def recorded_audio(changed)
+ return unless enabled && Llm::TextToSpeechService.available_for?(inbox.account)
+ return unless changed || !inbox.out_of_hours_call_audio.attached?
+
+ Llm::TextToSpeechService.new(text: message, account: inbox.account).perform
+ end
+end
diff --git a/enterprise/app/services/voice/inbound_call_builder.rb b/enterprise/app/services/voice/inbound_call_builder.rb
index a129257da21..fefada83920 100644
--- a/enterprise/app/services/voice/inbound_call_builder.rb
+++ b/enterprise/app/services/voice/inbound_call_builder.rb
@@ -39,8 +39,10 @@ class Voice::InboundCallBuilder
created = create_call!(contact, conversation)
message = Voice::CallMessageBuilder.new(created).perform!
created.update!(message_id: message.id)
- record_ring_audience(created)
- ring_phones(created)
+ unless created.outside_working_hours?
+ record_ring_audience(created)
+ ring_phones(created)
+ end
created
end
rescue ActiveRecord::RecordNotUnique
@@ -125,12 +127,19 @@ class Voice::InboundCallBuilder
contact: contact,
provider: provider,
direction: :incoming,
- status: 'ringing',
provider_call_id: call_sid,
- meta: { 'initiated_at' => Time.zone.now.to_i }.merge(extra_meta.stringify_keys)
+ **initial_state
)
# `conference_sid` is a Twilio bridging concept; WhatsApp goes browser↔Meta.
call.update!(conference_sid: call.default_conference_sid) if call.twilio?
call
end
+
+ def initial_state
+ now = Time.zone.now.to_i
+ meta = { 'initiated_at' => now }.merge(extra_meta.stringify_keys)
+ return { status: 'ringing', meta: meta } unless provider == :twilio && inbox.closed_for_calls?
+
+ { status: 'no_answer', end_reason: Call::OUTSIDE_WORKING_HOURS, meta: meta.merge('ended_at' => now) }
+ end
end
diff --git a/enterprise/app/views/twilio/voice/out_of_hours.xml.builder b/enterprise/app/views/twilio/voice/out_of_hours.xml.builder
new file mode 100644
index 00000000000..6f186746bb9
--- /dev/null
+++ b/enterprise/app/views/twilio/voice/out_of_hours.xml.builder
@@ -0,0 +1,8 @@
+xml.Response do
+ if @inbox.out_of_hours_call_audio.attached?
+ xml.Play url_for(@inbox.out_of_hours_call_audio)
+ else
+ xml.Say @inbox.channel.out_of_hours_call_message, language: out_of_hours_call_language(@inbox)
+ end
+ xml.Hangup
+end
diff --git a/spec/enterprise/controllers/api/v1/accounts/inboxes/call_business_hours_controller_spec.rb b/spec/enterprise/controllers/api/v1/accounts/inboxes/call_business_hours_controller_spec.rb
new file mode 100644
index 00000000000..a7e4ab781d1
--- /dev/null
+++ b/spec/enterprise/controllers/api/v1/accounts/inboxes/call_business_hours_controller_spec.rb
@@ -0,0 +1,91 @@
+require 'rails_helper'
+
+RSpec.describe 'Call business hours API', type: :request do
+ let(:account) { create(:account) }
+ let(:admin) { create(:user, account: account, role: :administrator) }
+ let(:channel) { create(:channel_twilio_sms, :with_voice, account: account) }
+ let(:inbox) { channel.inbox }
+ let(:url) { "/api/v1/accounts/#{account.id}/inboxes/#{inbox.id}/call_business_hours" }
+ let(:params) { { business_hours_calls_enabled: true, out_of_hours_call_message: ' Call again tomorrow. ' } }
+
+ before do
+ allow(Twilio::VoiceWebhookSetupService).to receive(:new)
+ .and_return(instance_double(Twilio::VoiceWebhookSetupService, perform: "AP#{SecureRandom.hex(16)}"))
+ allow(Llm::TextToSpeechService).to receive(:available_for?).and_return(false)
+ end
+
+ it 'allows administrators to save settings and returns the trimmed announcement' do
+ patch url, headers: admin.create_new_auth_token, params: params, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body).to include('business_hours_calls_enabled' => true, 'out_of_hours_call_message' => 'Call again tomorrow.')
+ end
+
+ it 'generates and saves audio with the edited text in one request' do
+ allow(Llm::TextToSpeechService).to receive(:available_for?).and_return(true)
+ generator = instance_double(Llm::TextToSpeechService, perform: 'new audio')
+ expect(Llm::TextToSpeechService).to receive(:new).with(text: 'Call again tomorrow.', account: account).and_return(generator)
+
+ patch url, headers: admin.create_new_auth_token, params: params, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(inbox.reload.out_of_hours_call_audio.download).to eq('new audio')
+ expect(response.parsed_body.fetch('out_of_hours_call_audio_url')).to include('.mp3')
+ expect(channel.reload.out_of_hours_call_message).to eq('Call again tomorrow.')
+ end
+
+ it 'preserves active audio when generation fails' do
+ allow(Llm::TextToSpeechService).to receive(:available_for?).and_return(true)
+ generator = instance_double(Llm::TextToSpeechService)
+ allow(Llm::TextToSpeechService).to receive(:new).and_return(generator)
+ allow(generator).to receive(:perform).and_raise(Faraday::ServerError, 'Generation failed')
+ inbox.out_of_hours_call_audio.attach(io: StringIO.new('active'), filename: 'active.mp3', content_type: 'audio/mpeg')
+ active = inbox.out_of_hours_call_audio.blob
+
+ patch url, headers: admin.create_new_auth_token, params: params, as: :json
+
+ expect(response).to have_http_status(:internal_server_error)
+ expect(inbox.reload.out_of_hours_call_audio.blob).to eq(active)
+ end
+
+ it 'does not allow agents to change the settings' do
+ agent = create(:user, account: account, role: :agent)
+ create(:inbox_member, inbox: inbox, user: agent)
+
+ patch url, headers: agent.create_new_auth_token, params: params, as: :json
+
+ expect(response).to have_http_status(:unauthorized)
+ expect(channel.reload).not_to be_business_hours_calls_enabled
+ end
+
+ it 'does not expose another account inbox' do
+ other_admin = create(:user, account: create(:account), role: :administrator)
+ patch url, headers: other_admin.create_new_auth_token, params: params, as: :json
+
+ expect(response).to have_http_status(:unauthorized)
+ end
+
+ [
+ { business_hours_calls_enabled: 'true' },
+ { out_of_hours_call_message: ['message'] },
+ { out_of_hours_call_message: ' ' },
+ { out_of_hours_call_message: 'a' * 1001 }
+ ].each do |invalid|
+ it "rejects invalid settings #{invalid.keys.join(', ')} with #{invalid.values.first.class}" do
+ patch url, headers: admin.create_new_auth_token, params: params.merge(invalid), as: :json
+
+ expect(response).to have_http_status(:unprocessable_entity)
+ expect(channel.reload).not_to be_business_hours_calls_enabled
+ end
+ end
+
+ it 'rejects inboxes without Twilio voice' do
+ allow(Twilio::VoiceTeardownService).to receive(:new)
+ .and_return(instance_double(Twilio::VoiceTeardownService, perform: nil))
+ channel.update!(voice_enabled: false)
+
+ patch url, headers: admin.create_new_auth_token, params: params, as: :json
+
+ expect(response).to have_http_status(:unprocessable_entity)
+ end
+end
diff --git a/spec/enterprise/controllers/enterprise/api/v1/accounts/inboxes_controller_spec.rb b/spec/enterprise/controllers/enterprise/api/v1/accounts/inboxes_controller_spec.rb
index b506e9e344e..23fe34783f3 100644
--- a/spec/enterprise/controllers/enterprise/api/v1/accounts/inboxes_controller_spec.rb
+++ b/spec/enterprise/controllers/enterprise/api/v1/accounts/inboxes_controller_spec.rb
@@ -4,6 +4,37 @@ RSpec.describe 'Enterprise Inboxes API', type: :request do
let(:account) { create(:account) }
let(:admin) { create(:user, account: account, role: :administrator) }
+ describe 'GET /api/v1/accounts/:account_id/inboxes' do
+ it 'preloads announcement attachments and blobs for the inbox list' do
+ channels = create_list(:channel_twilio_sms, 2, account: account)
+ channels.each do |channel|
+ channel.inbox.out_of_hours_call_audio.attach(io: StringIO.new('audio'), filename: 'announcement.mp3', content_type: 'audio/mpeg')
+ end
+ create(:channel_twilio_sms, account: account)
+ headers = admin.create_new_auth_token
+ attachment_queries = []
+ blob_queries = []
+ subscriber = lambda do |*args|
+ payload = args.last
+ blob_queries << payload if payload[:name] == 'ActiveStorage::Blob Load'
+ next unless payload[:name] == 'ActiveStorage::Attachment Load'
+ next unless payload[:binds].any? { |bind| bind.value_for_database == 'out_of_hours_call_audio' }
+
+ attachment_queries << payload
+ end
+
+ ActiveSupport::Notifications.subscribed(subscriber, 'sql.active_record') do
+ get "/api/v1/accounts/#{account.id}/inboxes", headers: headers, as: :json
+ end
+
+ expect(response).to have_http_status(:ok)
+ expect(attachment_queries.size).to eq(1)
+ expect(blob_queries.size).to eq(1)
+ announcements = response.parsed_body.fetch('payload').filter_map { |inbox| inbox['out_of_hours_call_audio_url'] }
+ expect(announcements.size).to eq(2)
+ end
+ end
+
describe 'POST /api/v1/accounts/{account.id}/inboxes' do
let(:inbox) { create(:inbox, account: account) }
diff --git a/spec/enterprise/controllers/twilio/voice_controller_spec.rb b/spec/enterprise/controllers/twilio/voice_controller_spec.rb
index 2c6e88515a7..dd70dfadf9f 100644
--- a/spec/enterprise/controllers/twilio/voice_controller_spec.rb
+++ b/spec/enterprise/controllers/twilio/voice_controller_spec.rb
@@ -19,6 +19,84 @@ RSpec.describe 'Twilio::VoiceController', type: :request do
let(:to_number) { channel.phone_number }
let(:inbound_call_params) { { 'CallSid' => call_sid, 'From' => from_number, 'To' => to_number, 'Direction' => 'inbound' } }
+ context 'when outside business hours' do
+ before do
+ inbox.update!(working_hours_enabled: true, timezone: 'America/Los_Angeles')
+ inbox.working_hours.each { |hours| hours.update!(closed_all_day: true, open_all_day: false) }
+ channel.update!(provider_config: channel.provider_config.merge(
+ 'business_hours_calls_enabled' => true,
+ 'out_of_hours_call_message' => 'Please call during business hours.'
+ ))
+ end
+
+ it 'announces closure and hangs up without ringing agents, including on retries' do
+ account.enable_features!('channel_voice', 'mobile_voice_push')
+ expect(Voice::VoipPushService).not_to receive(:recipients_for)
+
+ 2.times { post "/twilio/voice/call/#{digits}", params: inbound_call_params }
+
+ xml = Nokogiri::XML(response.body)
+ expect(xml.at_xpath('//Say').text).to eq('Please call during business hours.')
+ expect(xml.at_xpath('//Hangup')).to be_present
+ expect(xml.at_xpath('//Dial')).to be_nil
+ call = inbox.calls.sole
+ expect(call).to have_attributes(status: 'no_answer', end_reason: 'outside_working_hours', ring_state: {})
+ expect(Voice::VoipPushJob).not_to have_been_enqueued
+ expect(Voice::MissedCallNotificationJob).not_to have_been_enqueued
+ end
+
+ it 'plays the saved generated audio before hanging up' do
+ inbox.out_of_hours_call_audio.attach(io: StringIO.new('audio'), filename: 'announcement.mp3', content_type: 'audio/mpeg')
+
+ post "/twilio/voice/call/#{digits}", params: inbound_call_params
+
+ xml = Nokogiri::XML(response.body)
+ expect(xml.at_xpath('//Play').text).to include('announcement.mp3')
+ expect(xml.at_xpath('//Hangup')).to be_present
+ expect(xml.at_xpath('//Say')).to be_nil
+ end
+
+ it 'reads the text fallback using the account language' do
+ account.update!(locale: 'de')
+ channel.update!(provider_config: channel.provider_config.merge('out_of_hours_call_message' => 'Bitte rufen Sie morgen an.'))
+
+ post "/twilio/voice/call/#{digits}", params: inbound_call_params
+
+ announcement = Nokogiri::XML(response.body).at_xpath('//Say')
+ expect(announcement.text).to eq('Bitte rufen Sie morgen an.')
+ expect(announcement['language']).to eq('de-DE')
+ end
+
+ it 'uses a supported default for account languages unavailable in the basic Twilio voice' do
+ account.update!(locale: 'ml')
+
+ post "/twilio/voice/call/#{digits}", params: inbound_call_params
+
+ expect(Nokogiri::XML(response.body).at_xpath('//Say')['language']).to eq('en-US')
+ end
+
+ it 'rings normally when applying business hours to calls is disabled' do
+ channel.update!(provider_config: channel.provider_config.merge('business_hours_calls_enabled' => false))
+
+ post "/twilio/voice/call/#{digits}", params: inbound_call_params
+
+ expect(Nokogiri::XML(response.body).at_xpath('//Conference')).to be_present
+ expect(inbox.calls.sole).to have_attributes(status: 'ringing', end_reason: nil)
+ end
+
+ it 'rings normally during business hours in the inbox timezone' do
+ travel_to Time.utc(2026, 10, 19, 19) do
+ inbox.working_hours.find_by!(day_of_week: 1).update!(closed_all_day: false, open_hour: 9, open_minutes: 0,
+ close_hour: 17, close_minutes: 0)
+
+ post "/twilio/voice/call/#{digits}", params: inbound_call_params
+
+ expect(Nokogiri::XML(response.body).at_xpath('//Conference')).to be_present
+ expect(inbox.calls.sole).to be_ringing
+ end
+ end
+ end
+
it 'invokes Voice::InboundCallBuilder for inbound calls and renders conference TwiML' do
conversation = create(:conversation, account: account, inbox: inbox)
contact = conversation.contact
diff --git a/spec/enterprise/services/llm/text_to_speech_service_spec.rb b/spec/enterprise/services/llm/text_to_speech_service_spec.rb
new file mode 100644
index 00000000000..c2052542e6b
--- /dev/null
+++ b/spec/enterprise/services/llm/text_to_speech_service_spec.rb
@@ -0,0 +1,40 @@
+require 'rails_helper'
+
+RSpec.describe Llm::TextToSpeechService do
+ let(:account) { create(:account) }
+ let(:text) { 'Please call during business hours.' }
+ let(:service) { described_class.new(text: text, account: account) }
+
+ before do
+ InstallationConfig.find_or_create_by!(name: 'CAPTAIN_OPEN_AI_API_KEY') { |config| config.value = 'test-api-key' }
+ end
+
+ it 'uses the announcement model and consumes one response after successful generation' do
+ request = stub_request(:post, 'https://api.openai.com/v1/audio/speech')
+ .with(body: { model: 'gpt-4o-mini-tts-2025-12-15', input: text, voice: 'alloy', response_format: 'mp3' }.to_json)
+ .to_return(status: 200, body: 'generated audio', headers: { 'Content-Type' => 'audio/mpeg' })
+ expect(account).to receive(:increment_response_usage).once
+
+ expect(service.perform).to eq('generated audio')
+ expect(request).to have_been_requested.once
+ end
+
+ it 'does not consume a response when audio generation fails' do
+ stub_request(:post, 'https://api.openai.com/v1/audio/speech').to_return(status: 500)
+ expect(account).not_to receive(:increment_response_usage)
+
+ expect { service.perform }.to(raise_error { |error| expect(error.class.name).to eq('Faraday::ServerError') })
+ end
+
+ it 'requires Captain and available response credits' do
+ account.disable_features!('captain_integration')
+ expect(described_class.available_for?(account)).to be(false)
+
+ account.enable_features!('captain_integration')
+ allow(account).to receive(:usage_limits).and_return(captain: { responses: { current_available: 0 } })
+ expect(described_class.available_for?(account)).to be(false)
+
+ allow(account).to receive(:usage_limits).and_return(captain: { responses: { current_available: 1 } })
+ expect(described_class.available_for?(account)).to be(true)
+ end
+end
diff --git a/spec/enterprise/services/voice/business_hours_settings_service_spec.rb b/spec/enterprise/services/voice/business_hours_settings_service_spec.rb
new file mode 100644
index 00000000000..a4462f97b76
--- /dev/null
+++ b/spec/enterprise/services/voice/business_hours_settings_service_spec.rb
@@ -0,0 +1,84 @@
+require 'rails_helper'
+
+RSpec.describe Voice::BusinessHoursSettingsService do
+ let(:channel) { create(:channel_twilio_sms) }
+ let(:inbox) { channel.inbox }
+ let(:message) { 'Please call again tomorrow.' }
+
+ before do
+ allow(Llm::TextToSpeechService).to receive(:available_for?).and_return(false)
+ end
+
+ it 'generates audio before saving and retains the upload on the original inbox instance' do
+ allow(Llm::TextToSpeechService).to receive(:available_for?).and_return(true)
+ generator = instance_double(Llm::TextToSpeechService, perform: 'generated audio')
+ allow(Llm::TextToSpeechService).to receive(:new).with(text: message, account: inbox.account).and_return(generator)
+
+ described_class.new(inbox: inbox, enabled: true, message: message).perform
+
+ expect(channel.reload.out_of_hours_call_message).to eq(message)
+ expect(channel).to be_business_hours_calls_enabled
+ expect(inbox.out_of_hours_call_audio.download).to eq('generated audio')
+ end
+
+ it 'preserves settings changed by another request during audio generation' do
+ allow(Llm::TextToSpeechService).to receive(:available_for?).and_return(true)
+ generator = instance_double(Llm::TextToSpeechService)
+ allow(Llm::TextToSpeechService).to receive(:new).with(text: message, account: inbox.account).and_return(generator)
+ allow(generator).to receive(:perform) do
+ other_channel = Channel::TwilioSms.find(channel.id)
+ other_channel.update!(provider_config: other_channel.provider_config.merge(
+ 'recording_enabled' => false, 'inbound_calls_enabled' => false
+ ))
+ 'generated audio'
+ end
+
+ described_class.new(inbox: inbox, enabled: true, message: message).perform
+
+ expect(channel.reload.provider_config).to include(
+ 'recording_enabled' => false, 'inbound_calls_enabled' => false,
+ 'business_hours_calls_enabled' => true, 'out_of_hours_call_message' => message
+ )
+ expect(inbox.reload.out_of_hours_call_audio.download).to eq('generated audio')
+ end
+
+ it 'removes stale audio when the text changes without Captain available' do
+ inbox.out_of_hours_call_audio.attach(io: StringIO.new('old audio'), filename: 'old.mp3', content_type: 'audio/mpeg')
+
+ described_class.new(inbox: inbox, enabled: true, message: message).perform
+
+ expect(channel.reload.out_of_hours_call_message).to eq(message)
+ expect(inbox.reload.out_of_hours_call_audio).not_to be_attached
+ end
+
+ it 'removes audio saved by another request when restoring older text while disabling calls' do
+ channel.update!(provider_config: { 'out_of_hours_call_message' => message })
+ inbox.out_of_hours_call_audio.attach(io: StringIO.new('old audio'), filename: 'old.mp3', content_type: 'audio/mpeg')
+ inbox.out_of_hours_call_audio.blob
+ allow(channel).to receive(:with_lock).and_wrap_original do |method, &block|
+ other_channel = Channel::TwilioSms.find(channel.id)
+ other_channel.inbox.out_of_hours_call_audio.attach(io: StringIO.new('new audio'), filename: 'new.mp3', content_type: 'audio/mpeg')
+ other_channel.update!(provider_config: { 'out_of_hours_call_message' => 'New announcement.' })
+ method.call(&block)
+ end
+
+ described_class.new(inbox: inbox, enabled: false, message: message).perform
+
+ expect(channel.reload.out_of_hours_call_message).to eq(message)
+ expect(channel).not_to be_business_hours_calls_enabled
+ expect(inbox.reload.out_of_hours_call_audio).not_to be_attached
+ end
+
+ it 'keeps existing audio without generating again when only the toggle changes' do
+ channel.update!(provider_config: { 'out_of_hours_call_message' => message })
+ inbox.out_of_hours_call_audio.attach(io: StringIO.new('audio'), filename: 'saved.mp3', content_type: 'audio/mpeg')
+ old_blob = inbox.out_of_hours_call_audio.blob
+ allow(Llm::TextToSpeechService).to receive(:available_for?).and_return(true)
+ expect(Llm::TextToSpeechService).not_to receive(:new)
+
+ described_class.new(inbox: inbox, enabled: false, message: message).perform
+ described_class.new(inbox: inbox, enabled: true, message: message).perform
+
+ expect(inbox.reload.out_of_hours_call_audio.blob).to eq(old_blob)
+ end
+end