Compare commits
23
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
949a728977 | ||
|
|
2437da5339 | ||
|
|
2abb7759f2 | ||
|
|
ca1069241f | ||
|
|
a744b1e247 | ||
|
|
559a052e42 | ||
|
|
f855429d9a | ||
|
|
97b30127a6 | ||
|
|
3a7c418139 | ||
|
|
f2e3e5a83f | ||
|
|
23fac0e7b1 | ||
|
|
02ff710709 | ||
|
|
3f9864c74f | ||
|
|
0b9b137723 | ||
|
|
42e392eca4 | ||
|
|
e668f9da20 | ||
|
|
65a78c7c20 | ||
|
|
86d0955794 | ||
|
|
d720e013d4 | ||
|
|
2f52af6e2d | ||
|
|
d59415ff5d | ||
|
|
14e4ec81c6 | ||
|
|
cbd24dbdb2 |
+1
-1
@@ -1 +1 @@
|
||||
4.16.1
|
||||
4.16.0
|
||||
|
||||
@@ -3,6 +3,8 @@ class Campaigns::CampaignConversationBuilder
|
||||
|
||||
def perform
|
||||
@contact_inbox = ContactInbox.find(@contact_inbox_id)
|
||||
return unless @contact_inbox.inbox.active?
|
||||
|
||||
@campaign = @contact_inbox.inbox.campaigns.find_by!(display_id: campaign_display_id)
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
|
||||
@@ -2,6 +2,8 @@ class ConversationBuilder
|
||||
pattr_initialize [:params!, :contact_inbox!]
|
||||
|
||||
def perform
|
||||
raise CustomExceptions::InboxDisabled unless @contact_inbox.inbox.active?
|
||||
|
||||
look_up_exising_conversation || create_new_conversation
|
||||
end
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ class Messages::Facebook::MessageBuilder < Messages::Messenger::MessageBuilder
|
||||
def perform
|
||||
# This channel might require reauthorization, may be owner might have changed the fb password
|
||||
return if @inbox.channel.reauthorization_required?
|
||||
return unless @inbox.active?
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
build_contact_inbox
|
||||
|
||||
@@ -10,6 +10,7 @@ class Messages::Instagram::BaseMessageBuilder < Messages::Messenger::MessageBuil
|
||||
|
||||
def perform
|
||||
return if @inbox.channel.reauthorization_required?
|
||||
return unless @inbox.active?
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
build_message
|
||||
|
||||
@@ -22,14 +22,15 @@ class Messages::MessageBuilder
|
||||
end
|
||||
|
||||
def perform
|
||||
raise CustomExceptions::InboxDisabled unless @conversation.inbox.active?
|
||||
|
||||
@message = @conversation.messages.build(message_params)
|
||||
process_attachments
|
||||
process_emails
|
||||
# When the message has no quoted content, it will just be rendered as a regular message
|
||||
# The frontend is equipped to handle this case
|
||||
process_email_content
|
||||
@message.save!
|
||||
@message
|
||||
@message.tap(&:save!)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
class Api::V1::Accounts::Conversations::MessagesController < Api::V1::Accounts::Conversations::BaseController
|
||||
before_action :ensure_api_inbox, only: :update
|
||||
before_action :ensure_inbox_active, only: [:create, :retry]
|
||||
|
||||
def index
|
||||
@messages = message_finder.perform
|
||||
@@ -9,6 +10,8 @@ class Api::V1::Accounts::Conversations::MessagesController < Api::V1::Accounts::
|
||||
user = Current.user || @resource
|
||||
mb = Messages::MessageBuilder.new(user, @conversation, params)
|
||||
@message = mb.perform
|
||||
rescue CustomExceptions::InboxDisabled
|
||||
render_inbox_disabled_error
|
||||
rescue StandardError => e
|
||||
render_could_not_create_error(e.message)
|
||||
end
|
||||
@@ -32,6 +35,8 @@ class Api::V1::Accounts::Conversations::MessagesController < Api::V1::Accounts::
|
||||
service.perform
|
||||
message.update!(content_attributes: {})
|
||||
::SendReplyJob.perform_later(message.id)
|
||||
rescue CustomExceptions::InboxDisabled
|
||||
render_inbox_disabled_error
|
||||
rescue StandardError => e
|
||||
render_could_not_create_error(e.message)
|
||||
end
|
||||
@@ -80,4 +85,8 @@ class Api::V1::Accounts::Conversations::MessagesController < Api::V1::Accounts::
|
||||
# Only API inboxes can update messages
|
||||
render json: { error: 'Message status update is only allowed for API inboxes' }, status: :forbidden unless @conversation.inbox.api?
|
||||
end
|
||||
|
||||
def ensure_inbox_active
|
||||
render_inbox_disabled_error unless @conversation.inbox.active?
|
||||
end
|
||||
end
|
||||
|
||||
@@ -198,6 +198,7 @@ class Api::V1::Accounts::ConversationsController < Api::V1::Accounts::BaseContro
|
||||
|
||||
@inbox = Current.account.inboxes.find(params[:inbox_id])
|
||||
authorize @inbox, :show?
|
||||
render_inbox_disabled_error unless @inbox.active?
|
||||
end
|
||||
|
||||
def contact
|
||||
@@ -214,6 +215,7 @@ class Api::V1::Accounts::ConversationsController < Api::V1::Accounts::BaseContro
|
||||
# and deprecate the support of passing only source_id as the param
|
||||
@contact_inbox ||= ::ContactInbox.find_by!(source_id: params[:source_id])
|
||||
authorize @contact_inbox.inbox, :show?
|
||||
render_inbox_disabled_error unless @contact_inbox.inbox.active?
|
||||
rescue ActiveRecord::RecordNotUnique
|
||||
render json: { error: 'source_id should be unique' }, status: :unprocessable_entity
|
||||
end
|
||||
@@ -221,12 +223,7 @@ class Api::V1::Accounts::ConversationsController < Api::V1::Accounts::BaseContro
|
||||
def build_contact_inbox
|
||||
return if @inbox.blank? || @contact.blank?
|
||||
|
||||
ContactInboxBuilder.new(
|
||||
contact: @contact,
|
||||
inbox: @inbox,
|
||||
source_id: params[:source_id],
|
||||
hmac_verified: hmac_verified?
|
||||
).perform
|
||||
ContactInboxBuilder.new(contact: @contact, inbox: @inbox, source_id: params[:source_id], hmac_verified: hmac_verified?).perform
|
||||
end
|
||||
|
||||
def conversation_finder
|
||||
|
||||
@@ -193,7 +193,7 @@ class Api::V1::Accounts::InboxesController < Api::V1::Accounts::BaseController
|
||||
def normalized_branded_email_layout = params[:branded_email_layout] == 'null' ? nil : params[:branded_email_layout]
|
||||
|
||||
def inbox_attributes
|
||||
[:name, :avatar, :greeting_enabled, :greeting_message, :enable_email_collect, :csat_survey_enabled,
|
||||
[:name, :avatar, :active, :greeting_enabled, :greeting_message, :enable_email_collect, :csat_survey_enabled,
|
||||
:enable_auto_assignment, :working_hours_enabled, :out_of_office_message, :timezone, :allow_messages_after_resolved,
|
||||
:lock_to_single_conversation, :portal_id, :sender_name_type, :business_name,
|
||||
{ csat_config: [:display_type, :message, :button_text, :language,
|
||||
|
||||
@@ -90,4 +90,8 @@ class Api::V1::Widget::BaseController < ApplicationController
|
||||
message_type: :incoming
|
||||
}
|
||||
end
|
||||
|
||||
def ensure_inbox_active
|
||||
render_inbox_disabled_error unless @web_widget.inbox.active?
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
class Api::V1::Widget::ConfigsController < Api::V1::Widget::BaseController
|
||||
before_action :ensure_inbox_active
|
||||
before_action :set_global_config
|
||||
|
||||
def create
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
class Api::V1::Widget::ContactsController < Api::V1::Widget::BaseController
|
||||
include WidgetHelper
|
||||
|
||||
before_action :ensure_inbox_active, only: [:update, :set_user, :destroy_custom_attributes]
|
||||
before_action :validate_hmac, only: [:set_user]
|
||||
before_action :validate_hmac_for_identified_update, only: [:update]
|
||||
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
class Api::V1::Widget::ConversationsController < Api::V1::Widget::BaseController
|
||||
include Events::Types
|
||||
|
||||
DISABLED_INBOX_ACTIONS = [
|
||||
:create, :toggle_typing, :toggle_status, :set_custom_attributes, :destroy_custom_attributes, :transcript
|
||||
].freeze
|
||||
|
||||
before_action :render_not_found_if_empty, only: [:toggle_typing, :toggle_status, :set_custom_attributes, :destroy_custom_attributes]
|
||||
before_action :ensure_inbox_active, only: DISABLED_INBOX_ACTIONS
|
||||
|
||||
def index
|
||||
@conversation = conversation
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
class Api::V1::Widget::DirectUploadsController < ActiveStorage::DirectUploadsController
|
||||
include WebsiteTokenHelper
|
||||
before_action :set_web_widget
|
||||
before_action :ensure_inbox_active
|
||||
before_action :set_contact
|
||||
|
||||
def create
|
||||
@@ -8,4 +9,15 @@ class Api::V1::Widget::DirectUploadsController < ActiveStorage::DirectUploadsCon
|
||||
|
||||
super
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def ensure_inbox_active
|
||||
return if @web_widget.inbox.active?
|
||||
|
||||
render json: {
|
||||
error: 'inbox_disabled',
|
||||
message: 'This inbox is currently disabled'
|
||||
}, status: :forbidden
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
class Api::V1::Widget::EventsController < Api::V1::Widget::BaseController
|
||||
include Events::Types
|
||||
|
||||
before_action :ensure_inbox_active
|
||||
|
||||
def create
|
||||
Rails.configuration.dispatcher.dispatch(permitted_params[:name], Time.zone.now, contact_inbox: @contact_inbox,
|
||||
event_info: permitted_params[:event_info].to_h.merge(event_info))
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
class Api::V1::Widget::Integrations::DyteController < Api::V1::Widget::BaseController
|
||||
before_action :ensure_inbox_active
|
||||
before_action :set_message
|
||||
|
||||
def add_participant_to_meeting
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
class Api::V1::Widget::LabelsController < Api::V1::Widget::BaseController
|
||||
before_action :ensure_inbox_active
|
||||
|
||||
def create
|
||||
if conversation.present? && label_defined_in_account?
|
||||
conversation.label_list.add(permitted_params[:label])
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
class Api::V1::Widget::MessagesController < Api::V1::Widget::BaseController
|
||||
before_action :ensure_inbox_active, only: [:create, :update]
|
||||
before_action :set_conversation, only: [:create]
|
||||
before_action :set_message, only: [:update]
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ module RequestExceptionHandler
|
||||
|
||||
included do
|
||||
rescue_from ActiveRecord::RecordInvalid, with: :render_record_invalid
|
||||
rescue_from CustomExceptions::InboxDisabled, with: :render_inbox_disabled_error
|
||||
rescue_from CustomExceptions::Inbox::LimitExceeded, with: :render_error_response
|
||||
end
|
||||
|
||||
@@ -45,6 +46,13 @@ module RequestExceptionHandler
|
||||
render json: { error: sanitized_error_message(error) }, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
def render_inbox_disabled_error(_exception = nil)
|
||||
render json: {
|
||||
error: 'inbox_disabled',
|
||||
message: 'This inbox is currently disabled'
|
||||
}, status: :forbidden
|
||||
end
|
||||
|
||||
def render_payment_required(message)
|
||||
render json: { error: message }, status: :payment_required
|
||||
end
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
class Platform::Api::V1::InboxesController < PlatformController
|
||||
before_action :set_account
|
||||
before_action :validate_account_permissible
|
||||
before_action :set_inbox
|
||||
|
||||
def disable
|
||||
update_active_state(false)
|
||||
end
|
||||
|
||||
def enable
|
||||
update_active_state(true)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_account
|
||||
@account = Account.find(params[:account_id])
|
||||
end
|
||||
|
||||
def validate_account_permissible
|
||||
return if @platform_app.platform_app_permissibles.find_by(permissible: @account)
|
||||
|
||||
render json: { error: 'Non permissible resource' }, status: :unauthorized
|
||||
end
|
||||
|
||||
def set_inbox
|
||||
@inbox = @account.inboxes.find(params[:id])
|
||||
end
|
||||
|
||||
def update_active_state(active)
|
||||
@inbox.update!(active: active)
|
||||
render json: { success: true, inbox_id: @inbox.id, active: @inbox.active }
|
||||
end
|
||||
end
|
||||
@@ -1,5 +1,6 @@
|
||||
class Public::Api::V1::Inboxes::ContactsController < Public::Api::V1::InboxesController
|
||||
before_action :contact_inbox, except: [:create]
|
||||
before_action :ensure_inbox_active, only: [:create, :update]
|
||||
before_action :process_hmac
|
||||
|
||||
def show; end
|
||||
@@ -50,4 +51,8 @@ class Public::Api::V1::Inboxes::ContactsController < Public::Api::V1::InboxesCon
|
||||
def permitted_params
|
||||
params.permit(:identifier, :identifier_hash, :email, :name, :avatar_url, :phone_number, custom_attributes: {})
|
||||
end
|
||||
|
||||
def ensure_inbox_active
|
||||
render_inbox_disabled_error unless @inbox_channel.inbox.active?
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
class Public::Api::V1::Inboxes::ConversationsController < Public::Api::V1::InboxesController
|
||||
include Events::Types
|
||||
before_action :set_conversation, only: [:toggle_typing, :update_last_seen, :show, :toggle_status]
|
||||
before_action :ensure_inbox_active, only: [:create, :toggle_typing, :toggle_status]
|
||||
|
||||
def index
|
||||
@conversations = @contact_inbox.hmac_verified? ? @contact_inbox.contact.conversations : @contact_inbox.conversations
|
||||
@@ -64,4 +65,8 @@ class Public::Api::V1::Inboxes::ConversationsController < Public::Api::V1::Inbox
|
||||
def conversation_params
|
||||
params.permit(custom_attributes: {})
|
||||
end
|
||||
|
||||
def ensure_inbox_active
|
||||
render_inbox_disabled_error unless @contact_inbox.inbox.active?
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
class Public::Api::V1::Inboxes::MessagesController < Public::Api::V1::InboxesController
|
||||
before_action :set_message, only: [:update]
|
||||
before_action :ensure_inbox_active, only: [:create, :update]
|
||||
|
||||
def index
|
||||
@messages = @conversation.nil? ? [] : message_finder.perform
|
||||
@@ -70,4 +71,8 @@ class Public::Api::V1::Inboxes::MessagesController < Public::Api::V1::InboxesCon
|
||||
def check_csat_locked
|
||||
(Time.zone.now.to_date - @message.created_at.to_date).to_i > 14 and @message.content_type == 'input_csat'
|
||||
end
|
||||
|
||||
def ensure_inbox_active
|
||||
render_inbox_disabled_error unless @conversation.inbox.active?
|
||||
end
|
||||
end
|
||||
|
||||
@@ -5,6 +5,7 @@ class WidgetsController < ActionController::Base
|
||||
before_action :set_global_config
|
||||
before_action :set_web_widget
|
||||
before_action :ensure_account_is_active
|
||||
before_action :ensure_inbox_active
|
||||
before_action :ensure_location_is_supported
|
||||
before_action :set_token
|
||||
before_action :set_contact
|
||||
@@ -62,6 +63,10 @@ class WidgetsController < ActionController::Base
|
||||
render json: { error: 'Account is suspended' }, status: :unauthorized unless @web_widget.inbox.account.active?
|
||||
end
|
||||
|
||||
def ensure_inbox_active
|
||||
head :not_found unless @web_widget.inbox.active?
|
||||
end
|
||||
|
||||
def ensure_location_is_supported; end
|
||||
|
||||
def additional_attributes
|
||||
|
||||
@@ -26,20 +26,13 @@ class CaptainAssistant extends ApiClient {
|
||||
});
|
||||
}
|
||||
|
||||
getMetrics({ assistantId, range, signal }) {
|
||||
getStats({ assistantId, range, signal }) {
|
||||
const requestConfig = {
|
||||
params: { range, timezone_offset: getTimezoneOffset() },
|
||||
};
|
||||
if (signal) requestConfig.signal = signal;
|
||||
|
||||
return axios.get(`${this.url}/${assistantId}/metrics`, requestConfig);
|
||||
}
|
||||
|
||||
getFaqStats({ assistantId, signal }) {
|
||||
const requestConfig = {};
|
||||
if (signal) requestConfig.signal = signal;
|
||||
|
||||
return axios.get(`${this.url}/${assistantId}/faq_stats`, requestConfig);
|
||||
return axios.get(`${this.url}/${assistantId}/stats`, requestConfig);
|
||||
}
|
||||
|
||||
getSummary({ assistantId, range, stats }) {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script setup>
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import ChannelIcon from 'dashboard/components-next/icon/ChannelIcon.vue';
|
||||
|
||||
defineProps({
|
||||
@@ -7,13 +8,21 @@ defineProps({
|
||||
default: () => {},
|
||||
},
|
||||
});
|
||||
|
||||
const { t } = useI18n();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div :title="inbox.name" class="flex items-center gap-0.5 min-w-0">
|
||||
<div :title="inbox.name" class="flex items-center gap-1 min-w-0">
|
||||
<ChannelIcon :inbox="inbox" class="size-4 flex-shrink-0 text-n-slate-11" />
|
||||
<span class="truncate text-body-main text-n-slate-11">
|
||||
{{ inbox.name }}
|
||||
</span>
|
||||
<span
|
||||
v-if="inbox.active === false"
|
||||
class="inline-flex h-4 shrink-0 items-center rounded-md bg-n-alpha-2 px-1 text-label-mini font-medium text-n-slate-11"
|
||||
>
|
||||
{{ t('INBOX_MGMT.DISABLED') }}
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script setup>
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import ChannelIcon from 'dashboard/components-next/icon/ChannelIcon.vue';
|
||||
|
||||
defineProps({
|
||||
@@ -7,13 +8,21 @@ defineProps({
|
||||
default: () => {},
|
||||
},
|
||||
});
|
||||
|
||||
const { t } = useI18n();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div :title="inbox.name" class="flex items-center gap-0.5 min-w-0">
|
||||
<div :title="inbox.name" class="flex items-center gap-1 min-w-0">
|
||||
<ChannelIcon :inbox="inbox" class="size-4 flex-shrink-0 text-n-slate-11" />
|
||||
<span class="truncate text-label-small text-n-slate-11">
|
||||
{{ inbox.name }}
|
||||
</span>
|
||||
<span
|
||||
v-if="inbox.active === false"
|
||||
class="inline-flex h-4 shrink-0 items-center rounded-md bg-n-alpha-2 px-1 text-label-mini font-medium text-n-slate-11"
|
||||
>
|
||||
{{ t('INBOX_MGMT.DISABLED') }}
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -8,8 +8,6 @@ import {
|
||||
EditorState,
|
||||
Selection,
|
||||
imageResizeView,
|
||||
toggleMark,
|
||||
wrapInList,
|
||||
} from '@chatwoot/prosemirror-schema';
|
||||
import {
|
||||
suggestionsPlugin,
|
||||
@@ -19,6 +17,8 @@ import imagePastePlugin from '@chatwoot/prosemirror-schema/src/plugins/image';
|
||||
import embedPreviewPlugin from '@chatwoot/prosemirror-schema/src/plugins/embedPreview';
|
||||
import trailingParagraphPlugin from '@chatwoot/prosemirror-schema/src/plugins/trailingParagraph';
|
||||
import { embeds as markdownEmbeds } from 'dashboard/helper/markdownEmbeds';
|
||||
import { toggleMark } from 'prosemirror-commands';
|
||||
import { wrapInList } from 'prosemirror-schema-list';
|
||||
import { toggleBlockType } from '@chatwoot/prosemirror-schema/src/menu/common';
|
||||
import { checkFileSizeLimit } from 'shared/helpers/FileHelper';
|
||||
import { isEscape } from 'shared/helpers/KeyboardHelpers';
|
||||
|
||||
@@ -33,7 +33,9 @@ import {
|
||||
// constants
|
||||
import { BUS_EVENTS } from 'shared/constants/busEvents';
|
||||
import { REPLY_POLICY } from 'shared/constants/links';
|
||||
import wootConstants from 'dashboard/constants/globals';
|
||||
import wootConstants, {
|
||||
META_RESTRICTION_STATUS_URL,
|
||||
} from 'dashboard/constants/globals';
|
||||
import { LOCAL_STORAGE_KEYS } from 'dashboard/constants/localStorage';
|
||||
import { INBOX_TYPES } from 'dashboard/helper/inbox';
|
||||
|
||||
@@ -93,6 +95,7 @@ export default {
|
||||
currentUserId: 'getCurrentUserID',
|
||||
listLoadingStatus: 'getAllMessagesLoaded',
|
||||
currentAccountId: 'getCurrentAccountId',
|
||||
isOnChatwootCloud: 'globalConfig/isOnChatwootCloud',
|
||||
}),
|
||||
isOpen() {
|
||||
return this.currentChat?.status === wootConstants.STATUS_TYPE.OPEN;
|
||||
@@ -170,6 +173,13 @@ export default {
|
||||
instagramInbox
|
||||
);
|
||||
},
|
||||
isInstagramRestrictionBannerVisible() {
|
||||
return this.isOnChatwootCloud && this.isAnInstagramChannel;
|
||||
},
|
||||
instagramRestrictionStatusUrl() {
|
||||
return META_RESTRICTION_STATUS_URL;
|
||||
},
|
||||
|
||||
replyWindowBannerMessage() {
|
||||
if (this.isAWhatsAppChannel) {
|
||||
return this.$t('CONVERSATION.TWILIO_WHATSAPP_CAN_REPLY');
|
||||
@@ -454,7 +464,15 @@ export default {
|
||||
>
|
||||
<div ref="topBannerRef">
|
||||
<Banner
|
||||
v-if="!currentChat.can_reply"
|
||||
v-if="isInstagramRestrictionBannerVisible"
|
||||
color-scheme="warning"
|
||||
class="mx-2 mt-2 overflow-hidden rounded-lg"
|
||||
:banner-message="$t('CONVERSATION.INSTAGRAM_RESTRICTION_BANNER')"
|
||||
:href-link="instagramRestrictionStatusUrl"
|
||||
:href-link-text="$t('CONVERSATION.INSTAGRAM_RESTRICTION_STATUS_LINK')"
|
||||
/>
|
||||
<Banner
|
||||
v-else-if="!currentChat.can_reply"
|
||||
color-scheme="alert"
|
||||
class="mx-2 mt-2 overflow-hidden rounded-lg"
|
||||
:banner-message="replyWindowBannerMessage"
|
||||
|
||||
@@ -78,3 +78,5 @@ export default {
|
||||
},
|
||||
};
|
||||
export const DEFAULT_REDIRECT_URL = '/app/';
|
||||
export const META_RESTRICTION_STATUS_URL =
|
||||
'https://status.chatwoot.com/incident/948346';
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
import {
|
||||
InputRule,
|
||||
inputRules,
|
||||
MessageMarkdownSerializer,
|
||||
MessageMarkdownTransformer,
|
||||
messageSchema,
|
||||
@@ -11,6 +9,7 @@ import * as Sentry from '@sentry/vue';
|
||||
import camelcaseKeys from 'camelcase-keys';
|
||||
import { FORMATTING, MARKDOWN_PATTERNS } from 'dashboard/constants/editor';
|
||||
import { INBOX_TYPES, TWILIO_CHANNEL_MEDIUM } from 'dashboard/helper/inbox';
|
||||
import { InputRule, inputRules } from 'prosemirror-inputrules';
|
||||
|
||||
/**
|
||||
* Extract text from markdown, and remove all images, code blocks, links, headers, bold, italic, lists etc.
|
||||
|
||||
@@ -44,6 +44,8 @@
|
||||
"TWILIO_WHATSAPP_CAN_REPLY": "You can only reply to this conversation using a template message due to",
|
||||
"TWILIO_WHATSAPP_24_HOURS_WINDOW": "24 hour message window restriction",
|
||||
"OLD_INSTAGRAM_INBOX_REPLY_BANNER": "This Instagram account was migrated to the new Instagram channel inbox. All new messages will show up there. You won’t be able to send messages from this conversation anymore.",
|
||||
"INSTAGRAM_RESTRICTION_BANNER": "Instagram is currently restricted. Some messages or actions may be delayed or unavailable while we restore full support.",
|
||||
"INSTAGRAM_RESTRICTION_STATUS_LINK": "View status update",
|
||||
"REPLYING_TO": "You are replying to:",
|
||||
"REMOVE_SELECTION": "Remove Selection",
|
||||
"DOWNLOAD": "Download",
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
"DESCRIPTION": "A channel is the mode of communication your customer chooses to interact with you. An inbox is where you manage interactions for a specific channel. It can include communications from various sources such as email, live chat, and social media.",
|
||||
"LEARN_MORE": "Learn more about inboxes",
|
||||
"COUNT": "{n} inbox | {n} inboxes",
|
||||
"DISABLED": "Disabled",
|
||||
"SEARCH_PLACEHOLDER": "Search inboxes...",
|
||||
"NO_RESULTS": "No inboxes found matching your search",
|
||||
"RECONNECTION_REQUIRED": "Your inbox is disconnected. You won't receive new messages until you reauthorize it.",
|
||||
@@ -58,7 +59,9 @@
|
||||
"ERROR_MESSAGE": "There was an error connecting to Instagram, please try again",
|
||||
"ERROR_AUTH": "There was an error connecting to Instagram, please try again",
|
||||
"NEW_INBOX_SUGGESTION": "This Instagram account was previously linked to a different inbox and has now been migrated here. All new messages will appear here. The old inbox will no longer be able to send or receive messages for this account.",
|
||||
"DUPLICATE_INBOX_BANNER": "This Instagram account was migrated to the new Instagram channel inbox. You won’t be able to send/receive Instagram messages from this inbox anymore."
|
||||
"DUPLICATE_INBOX_BANNER": "This Instagram account was migrated to the new Instagram channel inbox. You won’t be able to send/receive Instagram messages from this inbox anymore.",
|
||||
"SETTINGS_RESTRICTED_WARNING": "Instagram is currently restricted. Some messages or actions may be delayed or unavailable while we restore full support.",
|
||||
"STATUS_LINK": "View status update"
|
||||
},
|
||||
"TIKTOK": {
|
||||
"CONTINUE_WITH_TIKTOK": "Continue with TikTok",
|
||||
|
||||
@@ -26,28 +26,25 @@ const canDrilldown = computed(() => checkPermissions(['administrator']));
|
||||
const selectedRange = ref('this_month');
|
||||
|
||||
const assistantId = computed(() => route.params.assistantId);
|
||||
const metricStats = ref(null);
|
||||
const faqStats = ref(null);
|
||||
const isFetchingMetrics = ref(false);
|
||||
const stats = ref(null);
|
||||
const isFetching = ref(false);
|
||||
|
||||
// Increments on every fetch so a response (or retry) from a superseded
|
||||
// range/assistant can't clobber the latest request's state.
|
||||
let metricsFetchToken = 0;
|
||||
let faqStatsFetchToken = 0;
|
||||
let metricsAbortController = null;
|
||||
let faqStatsAbortController = null;
|
||||
let fetchToken = 0;
|
||||
let abortController = null;
|
||||
|
||||
const fetchMetrics = async () => {
|
||||
metricsFetchToken += 1;
|
||||
const token = metricsFetchToken;
|
||||
metricsAbortController?.abort();
|
||||
metricsAbortController = new AbortController();
|
||||
const { signal } = metricsAbortController;
|
||||
metricStats.value = null;
|
||||
isFetchingMetrics.value = true;
|
||||
const fetchStats = async () => {
|
||||
fetchToken += 1;
|
||||
const token = fetchToken;
|
||||
abortController?.abort();
|
||||
abortController = new AbortController();
|
||||
const { signal } = abortController;
|
||||
stats.value = null;
|
||||
isFetching.value = true;
|
||||
|
||||
const requestMetrics = () =>
|
||||
CaptainAssistant.getMetrics({
|
||||
const requestStats = () =>
|
||||
CaptainAssistant.getStats({
|
||||
assistantId: assistantId.value,
|
||||
range: selectedRange.value,
|
||||
signal,
|
||||
@@ -55,54 +52,25 @@ const fetchMetrics = async () => {
|
||||
|
||||
let data = null;
|
||||
try {
|
||||
({ data } = await requestMetrics());
|
||||
({ data } = await requestStats());
|
||||
} catch {
|
||||
// One silent retry before giving up, unless the request was aborted.
|
||||
try {
|
||||
if (token === metricsFetchToken && !signal.aborted)
|
||||
({ data } = await requestMetrics());
|
||||
if (token === fetchToken && !signal.aborted)
|
||||
({ data } = await requestStats());
|
||||
} catch {
|
||||
data = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (token !== metricsFetchToken || signal.aborted) return;
|
||||
metricStats.value = data;
|
||||
isFetchingMetrics.value = false;
|
||||
if (token !== fetchToken || signal.aborted) return;
|
||||
stats.value = data;
|
||||
isFetching.value = false;
|
||||
};
|
||||
|
||||
const fetchFaqStats = async () => {
|
||||
faqStatsFetchToken += 1;
|
||||
const token = faqStatsFetchToken;
|
||||
faqStatsAbortController?.abort();
|
||||
faqStatsAbortController = new AbortController();
|
||||
const { signal } = faqStatsAbortController;
|
||||
faqStats.value = null;
|
||||
onUnmounted(() => abortController?.abort());
|
||||
|
||||
try {
|
||||
const { data } = await CaptainAssistant.getFaqStats({
|
||||
assistantId: assistantId.value,
|
||||
signal,
|
||||
});
|
||||
if (token === faqStatsFetchToken && !signal.aborted) faqStats.value = data;
|
||||
} catch {
|
||||
if (token === faqStatsFetchToken && !signal.aborted) faqStats.value = null;
|
||||
}
|
||||
};
|
||||
|
||||
const summaryStats = computed(() => {
|
||||
if (!metricStats.value || !faqStats.value) return null;
|
||||
|
||||
return { ...metricStats.value, knowledge: faqStats.value };
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
metricsAbortController?.abort();
|
||||
faqStatsAbortController?.abort();
|
||||
});
|
||||
|
||||
watch([selectedRange, assistantId], fetchMetrics, { immediate: true });
|
||||
watch(assistantId, fetchFaqStats, { immediate: true });
|
||||
watch([selectedRange, assistantId], fetchStats, { immediate: true });
|
||||
|
||||
// `direction` says whether a rising trend is good ('up'), bad ('down'), or
|
||||
// neutral, so we can colour the delta independently of its sign.
|
||||
@@ -122,7 +90,7 @@ const formatDuration = hours =>
|
||||
hours >= 100 ? `${Math.round(hours / 24)}d` : `${hours}h`;
|
||||
|
||||
const metricFor = (statKey, formatValue, direction, trendKind = 'percent') => {
|
||||
const data = metricStats.value?.[statKey];
|
||||
const data = stats.value?.[statKey];
|
||||
if (!data) return { value: '—', trend: '', trendGood: null };
|
||||
|
||||
const sign = data.trend > 0 ? '+' : '';
|
||||
@@ -216,9 +184,9 @@ const closeDrilldown = () => {
|
||||
<div class="flex flex-col gap-6 pb-8">
|
||||
<InboxBanner />
|
||||
|
||||
<CoverageBanner :knowledge="faqStats ?? undefined" />
|
||||
<CoverageBanner :knowledge="stats?.knowledge" />
|
||||
|
||||
<WelcomeCard :range="selectedRange" :stats="summaryStats" />
|
||||
<WelcomeCard :range="selectedRange" :stats="stats" />
|
||||
|
||||
<div
|
||||
class="grid grid-cols-1 gap-px overflow-hidden border rounded-xl sm:grid-cols-2 lg:grid-cols-3 bg-n-weak border-n-weak"
|
||||
@@ -231,15 +199,13 @@ const closeDrilldown = () => {
|
||||
:trend="metric.trend"
|
||||
:hint="metric.hint"
|
||||
:trend-good="metric.trendGood"
|
||||
:loading="isFetchingMetrics"
|
||||
:clickable="
|
||||
canDrilldown && Boolean(metric.metric) && !isFetchingMetrics
|
||||
"
|
||||
:loading="isFetching"
|
||||
:clickable="canDrilldown && Boolean(metric.metric) && !isFetching"
|
||||
@click="openDrilldown(metric)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<KnowledgeCard :knowledge="faqStats ?? undefined" />
|
||||
<KnowledgeCard :knowledge="stats?.knowledge" />
|
||||
|
||||
<QuickLinks />
|
||||
</div>
|
||||
|
||||
@@ -142,10 +142,20 @@ const openDelete = inbox => {
|
||||
>
|
||||
<ChannelIcon class="size-6 text-n-slate-10" :inbox="inbox" />
|
||||
</div>
|
||||
<div class="flex flex-col items-start gap-1">
|
||||
<span class="block text-heading-3 text-n-slate-12 capitalize">
|
||||
{{ inbox.name }}
|
||||
</span>
|
||||
<div class="flex flex-col items-start gap-1 min-w-0">
|
||||
<div class="flex items-center gap-1.5 min-w-0">
|
||||
<span
|
||||
class="block text-heading-3 text-n-slate-12 capitalize truncate"
|
||||
>
|
||||
{{ inbox.name }}
|
||||
</span>
|
||||
<span
|
||||
v-if="inbox.active === false"
|
||||
class="inline-flex h-5 shrink-0 items-center rounded-md bg-n-alpha-2 px-1.5 text-label-mini font-medium text-n-slate-11"
|
||||
>
|
||||
{{ $t('INBOX_MGMT.DISABLED') }}
|
||||
</span>
|
||||
</div>
|
||||
<ChannelName
|
||||
:channel-type="inbox.channel_type"
|
||||
:medium="inbox.medium"
|
||||
|
||||
@@ -4,6 +4,8 @@ import { shouldBeUrl } from 'shared/helpers/Validators';
|
||||
import { useAlert } from 'dashboard/composables';
|
||||
import { useVuelidate } from '@vuelidate/core';
|
||||
import Avatar from 'next/avatar/Avatar.vue';
|
||||
import Banner from 'dashboard/components-next/banner/Banner.vue';
|
||||
import Icon from 'dashboard/components-next/icon/Icon.vue';
|
||||
import SettingIntroBanner from 'dashboard/components/widgets/SettingIntroBanner.vue';
|
||||
import SettingsToggleSection from 'dashboard/components-next/Settings/SettingsToggleSection.vue';
|
||||
import SettingsFieldSection from 'dashboard/components-next/Settings/SettingsFieldSection.vue';
|
||||
@@ -44,9 +46,11 @@ import SelectInput from 'dashboard/components-next/select/Select.vue';
|
||||
import Widget from 'dashboard/modules/widget-preview/components/Widget.vue';
|
||||
import AccessToken from 'dashboard/routes/dashboard/settings/profile/AccessToken.vue';
|
||||
import { copyTextToClipboard } from 'shared/helpers/clipboard';
|
||||
import { META_RESTRICTION_STATUS_URL } from 'dashboard/constants/globals';
|
||||
|
||||
export default {
|
||||
components: {
|
||||
Banner,
|
||||
BotConfiguration,
|
||||
CollaboratorsPage,
|
||||
ConfigurationPage,
|
||||
@@ -80,6 +84,7 @@ export default {
|
||||
WhatsappManualMigrationBanner,
|
||||
Widget,
|
||||
AccessToken,
|
||||
Icon,
|
||||
},
|
||||
mixins: [inboxMixin],
|
||||
setup() {
|
||||
@@ -343,6 +348,12 @@ export default {
|
||||
instagramUnauthorized() {
|
||||
return this.isAnInstagramChannel && this.inbox.reauthorization_required;
|
||||
},
|
||||
showInstagramRestrictionSettingsBanner() {
|
||||
return this.isOnChatwootCloud && this.isAnInstagramChannel;
|
||||
},
|
||||
metaRestrictionStatusUrl() {
|
||||
return META_RESTRICTION_STATUS_URL;
|
||||
},
|
||||
tiktokUnauthorized() {
|
||||
return this.isATiktokChannel && this.inbox.reauthorization_required;
|
||||
},
|
||||
@@ -809,6 +820,29 @@ export default {
|
||||
:class="bannerMaxWidth"
|
||||
@start="openWhatsAppManualMigrationDialog"
|
||||
/>
|
||||
<Banner
|
||||
v-if="showInstagramRestrictionSettingsBanner"
|
||||
color="amber"
|
||||
class="mx-6 mb-4 max-w-4xl"
|
||||
>
|
||||
<div class="flex items-start gap-3 text-start">
|
||||
<Icon
|
||||
icon="i-lucide-triangle-alert"
|
||||
class="flex-shrink-0 size-4 mt-0.5"
|
||||
/>
|
||||
<span>
|
||||
{{ $t('INBOX_MGMT.ADD.INSTAGRAM.SETTINGS_RESTRICTED_WARNING') }}
|
||||
<a
|
||||
:href="metaRestrictionStatusUrl"
|
||||
class="link underline"
|
||||
rel="noopener noreferrer nofollow"
|
||||
target="_blank"
|
||||
>
|
||||
{{ $t('INBOX_MGMT.ADD.INSTAGRAM.STATUS_LINK') }}
|
||||
</a>
|
||||
</span>
|
||||
</div>
|
||||
</Banner>
|
||||
|
||||
<div
|
||||
v-if="selectedTabKey === 'inbox-settings'"
|
||||
|
||||
@@ -4,6 +4,7 @@ class ConversationReplyEmailJob < ApplicationJob
|
||||
def perform(conversation_id, last_queued_id)
|
||||
conversation = Conversation.find(conversation_id)
|
||||
return unless conversation.account.active?
|
||||
return unless conversation.inbox.active?
|
||||
|
||||
if conversation.messages.incoming&.last&.content_type == 'incoming_email'
|
||||
ConversationReplyMailer.with(account: conversation.account).reply_without_summary(conversation, last_queued_id).deliver_later
|
||||
|
||||
@@ -13,6 +13,7 @@ class Inboxes::FetchImapEmailInboxesJob < ApplicationJob
|
||||
|
||||
def should_fetch_emails?(inbox)
|
||||
return false if inbox.account.suspended?
|
||||
return false unless inbox.active?
|
||||
return false unless inbox.channel.imap_enabled
|
||||
return false if inbox.channel.reauthorization_required?
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ class Inboxes::FetchImapEmailsJob < MutexApplicationJob
|
||||
private
|
||||
|
||||
def should_fetch_email?(channel)
|
||||
channel.imap_enabled? && !channel.reauthorization_required?
|
||||
channel.inbox.active? && channel.imap_enabled? && !channel.reauthorization_required?
|
||||
end
|
||||
|
||||
def process_email_for_channel(channel, interval)
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
class SendReplyJob < ApplicationJob
|
||||
queue_as :high
|
||||
|
||||
INBOX_DISABLED_ERROR = 'This inbox is currently disabled'.freeze
|
||||
|
||||
CHANNEL_SERVICES = {
|
||||
'Channel::TwitterProfile' => ::Twitter::SendOnTwitterService,
|
||||
'Channel::TwilioSms' => ::Twilio::SendOnTwilioService,
|
||||
@@ -18,6 +20,7 @@ class SendReplyJob < ApplicationJob
|
||||
def perform(message_id)
|
||||
message = Message.find(message_id)
|
||||
channel_name = message.conversation.inbox.channel.class.to_s
|
||||
return handle_disabled_inbox(message, channel_name) unless message.inbox.active?
|
||||
|
||||
return send_on_facebook_page(message) if channel_name == 'Channel::FacebookPage'
|
||||
|
||||
@@ -29,6 +32,61 @@ class SendReplyJob < ApplicationJob
|
||||
|
||||
private
|
||||
|
||||
def handle_disabled_inbox(message, channel_name)
|
||||
return unless send_service_available?(channel_name)
|
||||
return unless deliverable_reply?(message, channel_name)
|
||||
|
||||
mark_message_failed(message)
|
||||
end
|
||||
|
||||
def send_service_available?(channel_name)
|
||||
channel_name == 'Channel::FacebookPage' || CHANNEL_SERVICES.key?(channel_name)
|
||||
end
|
||||
|
||||
def deliverable_reply?(message, channel_name)
|
||||
return false unless deliverable_message?(message)
|
||||
return message.email_notifiable_message? if email_channel?(channel_name)
|
||||
return email_notification_deliverable?(message, channel_name) if email_notification_channel?(channel_name)
|
||||
|
||||
true
|
||||
end
|
||||
|
||||
def deliverable_message?(message)
|
||||
return false if message.private?
|
||||
return false unless message.outgoing? || message.template?
|
||||
return false if message.source_id.present?
|
||||
return false if message.content_type == 'voice_call'
|
||||
|
||||
true
|
||||
end
|
||||
|
||||
def email_channel?(channel_name)
|
||||
channel_name == 'Channel::Email'
|
||||
end
|
||||
|
||||
def email_notification_channel?(channel_name)
|
||||
%w[Channel::WebWidget Channel::Api].include?(channel_name)
|
||||
end
|
||||
|
||||
def email_notification_deliverable?(message, channel_name)
|
||||
return false unless message.email_notifiable_message?
|
||||
return false if message.conversation.contact.email.blank?
|
||||
return false unless message.account.within_email_rate_limit?
|
||||
|
||||
email_notification_enabled?(message.inbox, channel_name)
|
||||
end
|
||||
|
||||
def email_notification_enabled?(inbox, channel_name)
|
||||
return inbox.channel.continuity_via_email if channel_name == 'Channel::WebWidget'
|
||||
return inbox.account.feature_enabled?('email_continuity_on_api_channel') if channel_name == 'Channel::Api'
|
||||
|
||||
false
|
||||
end
|
||||
|
||||
def mark_message_failed(message)
|
||||
Messages::StatusUpdateService.new(message, 'failed', INBOX_DISABLED_ERROR).perform
|
||||
end
|
||||
|
||||
def send_on_facebook_page(message)
|
||||
if message.conversation.additional_attributes['type'] == 'instagram_direct_message'
|
||||
::Instagram::Messenger::SendOnInstagramService.new(message: message).perform
|
||||
|
||||
@@ -57,9 +57,11 @@ class Webhooks::InstagramEventsJob < MutexApplicationJob
|
||||
|
||||
next if channel.blank?
|
||||
|
||||
if (event_name = event_name(messaging))
|
||||
send(event_name, messaging, channel)
|
||||
end
|
||||
event_name = event_name(messaging)
|
||||
next if event_name.blank?
|
||||
next unless channel.inbox.active? || event_name == :read
|
||||
|
||||
send(event_name, messaging, channel)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -126,7 +128,7 @@ class Webhooks::InstagramEventsJob < MutexApplicationJob
|
||||
end
|
||||
|
||||
def event_name(messaging)
|
||||
@event_name ||= SUPPORTED_EVENTS.find { |key| messaging.key?(key) }
|
||||
SUPPORTED_EVENTS.find { |key| messaging.key?(key) }
|
||||
end
|
||||
|
||||
def message(messaging, channel)
|
||||
|
||||
@@ -4,6 +4,7 @@ class Webhooks::LineEventsJob < ApplicationJob
|
||||
def perform(params: {}, signature: '', post_body: '')
|
||||
@params = params
|
||||
return unless valid_event_payload?
|
||||
return unless @channel.inbox.active?
|
||||
return unless valid_post_body?(post_body, signature)
|
||||
|
||||
Line::IncomingMessageService.new(inbox: @channel.inbox, params: @params['line'].with_indifferent_access).perform
|
||||
|
||||
@@ -8,6 +8,7 @@ class Webhooks::SmsEventsJob < ApplicationJob
|
||||
|
||||
channel = Channel::Sms.find_by(phone_number: params[:to])
|
||||
return unless channel
|
||||
return if incoming_event?(params) && !channel.inbox.active?
|
||||
|
||||
process_event_params(channel, params)
|
||||
end
|
||||
@@ -25,4 +26,8 @@ class Webhooks::SmsEventsJob < ApplicationJob
|
||||
def delivery_event?(params)
|
||||
params[:type] == 'message-delivered' || params[:type] == 'message-failed'
|
||||
end
|
||||
|
||||
def incoming_event?(params)
|
||||
params[:type] == 'message-received'
|
||||
end
|
||||
end
|
||||
|
||||
@@ -6,7 +6,7 @@ class Webhooks::TelegramEventsJob < ApplicationJob
|
||||
|
||||
channel = Channel::Telegram.find_by(bot_token: params[:bot_token])
|
||||
|
||||
if channel_is_inactive?(channel)
|
||||
if channel_is_inactive?(channel, params)
|
||||
log_inactive_channel(channel, params)
|
||||
return
|
||||
end
|
||||
@@ -16,13 +16,18 @@ class Webhooks::TelegramEventsJob < ApplicationJob
|
||||
|
||||
private
|
||||
|
||||
def channel_is_inactive?(channel)
|
||||
def channel_is_inactive?(channel, params)
|
||||
return true if channel.blank?
|
||||
return true unless channel.account.active?
|
||||
return true unless channel.inbox.active? || update_message_event?(params)
|
||||
|
||||
false
|
||||
end
|
||||
|
||||
def update_message_event?(params)
|
||||
params.dig(:telegram, :edited_message).present? || params.dig(:telegram, :edited_business_message).present?
|
||||
end
|
||||
|
||||
def log_inactive_channel(channel, params)
|
||||
message = if channel&.id
|
||||
"Account #{channel.account.id} is not active for channel #{channel.id}"
|
||||
|
||||
@@ -21,6 +21,7 @@ class Webhooks::TiktokEventsJob < MutexApplicationJob
|
||||
def channel_is_inactive?
|
||||
return true if channel.blank?
|
||||
return true unless channel.account.active?
|
||||
return true unless channel.inbox.active? || event_name == 'im_mark_read_msg'
|
||||
|
||||
false
|
||||
end
|
||||
|
||||
@@ -8,7 +8,7 @@ class Webhooks::WhatsappEventsJob < MutexApplicationJob
|
||||
def perform(params = {})
|
||||
channel = find_channel_from_whatsapp_business_payload(params)
|
||||
|
||||
if channel_is_inactive?(channel)
|
||||
if channel_is_inactive?(channel, params)
|
||||
Rails.logger.warn("Inactive WhatsApp channel: #{channel&.phone_number || "unknown - #{params[:phone_number]}"}")
|
||||
return
|
||||
end
|
||||
@@ -124,15 +124,29 @@ class Webhooks::WhatsappEventsJob < MutexApplicationJob
|
||||
].compact_blank.first
|
||||
end
|
||||
|
||||
def channel_is_inactive?(channel)
|
||||
def channel_is_inactive?(channel, params)
|
||||
return true if channel.blank?
|
||||
# Only skip for embedded signup when reauth is required; manual flow uses API keys and should still receive webhooks
|
||||
return true if channel.reauthorization_required? && embedded_signup_channel?(channel)
|
||||
return true unless channel.account.active?
|
||||
return true unless channel.inbox.active? || existing_message_update_event?(params)
|
||||
|
||||
false
|
||||
end
|
||||
|
||||
def status_update_event?(params)
|
||||
value = params.dig(:entry, 0, :changes, 0, :value) || params
|
||||
value[:statuses].present?
|
||||
end
|
||||
|
||||
def existing_message_update_event?(params)
|
||||
status_update_event?(params) || call_event?(params)
|
||||
end
|
||||
|
||||
def call_event?(params)
|
||||
params.dig(:entry, 0, :changes, 0, :field) == 'calls'
|
||||
end
|
||||
|
||||
def embedded_signup_channel?(channel)
|
||||
(channel.provider_config || {}).to_h['source'] == 'embedded_signup'
|
||||
end
|
||||
|
||||
@@ -63,6 +63,8 @@ class AgentBotListener < BaseListener
|
||||
private
|
||||
|
||||
def agent_bots_for(inbox, conversation = nil)
|
||||
return [] unless inbox.active?
|
||||
|
||||
bots = []
|
||||
bots << conversation.assignee_agent_bot if conversation&.assignee_agent_bot.present?
|
||||
inbox_bot = active_inbox_agent_bot(inbox)
|
||||
|
||||
@@ -18,6 +18,7 @@ class AutomationRuleListener < BaseListener
|
||||
def message_created(event)
|
||||
message = event.data[:message]
|
||||
|
||||
return unless message.inbox.active?
|
||||
return if ignore_message_created_event?(event)
|
||||
|
||||
account = message.try(:account)
|
||||
@@ -39,10 +40,11 @@ class AutomationRuleListener < BaseListener
|
||||
def process_conversation_event(event, event_name)
|
||||
return if performed_by_automation?(event)
|
||||
|
||||
auto_reply_skip_events = %w[conversation_created conversation_opened]
|
||||
return if auto_reply_skip_events.include?(event_name) && ignore_auto_reply_event?(event)
|
||||
return if auto_reply_event?(event, event_name)
|
||||
|
||||
conversation = event.data[:conversation]
|
||||
return unless conversation.inbox.active?
|
||||
|
||||
account = conversation.account
|
||||
changed_attributes = event.data[:changed_attributes]
|
||||
|
||||
@@ -74,6 +76,10 @@ class AutomationRuleListener < BaseListener
|
||||
event.data[:performed_by].present? && event.data[:performed_by].instance_of?(AutomationRule)
|
||||
end
|
||||
|
||||
def auto_reply_event?(event, event_name)
|
||||
%w[conversation_created conversation_opened].include?(event_name) && ignore_auto_reply_event?(event)
|
||||
end
|
||||
|
||||
def ignore_auto_reply_event?(event)
|
||||
conversation = event.data[:conversation]
|
||||
conversation.additional_attributes['auto_reply'].present?
|
||||
|
||||
@@ -3,6 +3,7 @@ class CsatSurveyListener < BaseListener
|
||||
conversation = extract_conversation_and_account(event)[0]
|
||||
|
||||
return unless conversation.resolved?
|
||||
return unless conversation.inbox.active?
|
||||
|
||||
CsatSurveyService.new(conversation: conversation).perform
|
||||
end
|
||||
|
||||
@@ -6,6 +6,7 @@ class ReplyMailbox < ApplicationMailbox
|
||||
def process
|
||||
# Return early if no conversation was found (e.g., notification emails, suspended accounts)
|
||||
return unless @conversation
|
||||
return unless @conversation.inbox.active?
|
||||
|
||||
# Wrap everything in a transaction to ensure atomicity
|
||||
# This prevents orphan conversations if message/attachment creation fails
|
||||
|
||||
@@ -58,6 +58,7 @@ class Campaign < ApplicationRecord
|
||||
def trigger!
|
||||
return unless one_off?
|
||||
return unless feature_enabled?
|
||||
return unless inbox.active?
|
||||
return unless mark_processing!
|
||||
|
||||
execute_campaign
|
||||
|
||||
@@ -7,6 +7,8 @@ class Line::IncomingMessageService
|
||||
LINE_STICKER_IMAGE_URL = 'https://stickershop.line-scdn.net/stickershop/v1/sticker/%s/android/sticker.png'.freeze
|
||||
|
||||
def perform
|
||||
return unless @inbox.active?
|
||||
|
||||
# probably test events
|
||||
return if params[:events].blank?
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ class Mailbox::ConversationFinderStrategies::NewConversationStrategy < Mailbox::
|
||||
# The actual persistence happens in ReplyMailbox within a transaction that includes message creation.
|
||||
def find
|
||||
return nil unless @channel # No valid channel found
|
||||
return nil unless @inbox.active?
|
||||
return nil unless incoming_email_from_valid_email? # Skip edge cases
|
||||
|
||||
# Check if conversation already exists by in_reply_to
|
||||
|
||||
@@ -4,6 +4,8 @@ class Sms::IncomingMessageService
|
||||
pattr_initialize [:inbox!, :params!]
|
||||
|
||||
def perform
|
||||
return unless @inbox.active?
|
||||
|
||||
set_contact
|
||||
set_conversation
|
||||
@message = @conversation.messages.create!(
|
||||
|
||||
@@ -7,6 +7,8 @@ class Telegram::IncomingMessageService
|
||||
pattr_initialize [:inbox!, :params!]
|
||||
|
||||
def perform
|
||||
return unless @inbox.active?
|
||||
|
||||
# chatwoot doesn't support group conversations at the moment
|
||||
transform_business_message!
|
||||
return unless private_message?
|
||||
|
||||
@@ -4,6 +4,8 @@ class Tiktok::MessageService
|
||||
pattr_initialize [:channel!, :content!, :outgoing_echo]
|
||||
|
||||
def perform
|
||||
return unless channel.inbox.active?
|
||||
|
||||
if outgoing_message?
|
||||
message = find_message(tt_conversation_id, tt_message_id)
|
||||
return if message.present?
|
||||
|
||||
@@ -7,6 +7,7 @@ class Twilio::IncomingMessageService
|
||||
|
||||
def perform
|
||||
return if twilio_channel.blank?
|
||||
return unless inbox.active?
|
||||
|
||||
set_contact
|
||||
set_conversation
|
||||
|
||||
@@ -5,6 +5,8 @@ class Twitter::DirectMessageParserService < Twitter::WebhooksBaseService
|
||||
return if source_app_id == parent_app_id
|
||||
|
||||
set_inbox
|
||||
return unless @inbox.active?
|
||||
|
||||
ensure_contacts
|
||||
set_conversation
|
||||
@message = @conversation.messages.create!(
|
||||
|
||||
@@ -4,6 +4,7 @@ class Twitter::TweetParserService < Twitter::WebhooksBaseService
|
||||
def perform
|
||||
set_inbox
|
||||
|
||||
return unless @inbox.active?
|
||||
return if !tweets_enabled? || message_already_exist? || user_has_blocked?
|
||||
|
||||
create_message
|
||||
|
||||
@@ -13,6 +13,8 @@ class Whatsapp::IncomingMessageBaseService
|
||||
if processed_params.try(:[], :statuses).present?
|
||||
process_statuses
|
||||
elsif messages_data.present?
|
||||
return unless @inbox.active?
|
||||
|
||||
process_messages
|
||||
end
|
||||
end
|
||||
|
||||
@@ -2,6 +2,7 @@ json.id resource.id
|
||||
json.avatar_url resource.try(:avatar_url)
|
||||
json.channel_id resource.channel_id
|
||||
json.name resource.name
|
||||
json.active resource.active
|
||||
json.channel_type resource.channel_type
|
||||
json.greeting_enabled resource.greeting_enabled
|
||||
json.greeting_message resource.greeting_message
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
shared: &shared
|
||||
version: '4.16.1'
|
||||
version: '4.16.0'
|
||||
|
||||
development:
|
||||
<<: *shared
|
||||
|
||||
+7
-2
@@ -66,8 +66,7 @@ Rails.application.routes.draw do
|
||||
resources :assistants do
|
||||
member do
|
||||
post :playground
|
||||
get :metrics
|
||||
get :faq_stats
|
||||
get :stats
|
||||
get :summary
|
||||
get :drilldown
|
||||
end
|
||||
@@ -582,6 +581,12 @@ Rails.application.routes.draw do
|
||||
end
|
||||
end
|
||||
resources :email_channel_migrations, only: [:create]
|
||||
resources :inboxes, only: [] do
|
||||
member do
|
||||
post :disable
|
||||
post :enable
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
class AddActiveToInboxes < ActiveRecord::Migration[7.0]
|
||||
def change
|
||||
add_column :inboxes, :active, :boolean, default: true, null: false
|
||||
end
|
||||
end
|
||||
@@ -1,17 +0,0 @@
|
||||
class CreateCaptainMessageSources < ActiveRecord::Migration[7.1]
|
||||
def change
|
||||
create_table :captain_message_sources do |t|
|
||||
t.references :account, null: false, index: true
|
||||
t.references :assistant, null: false, index: true
|
||||
t.references :conversation, null: false, index: true
|
||||
t.references :message, null: false, index: true
|
||||
t.references :document, null: false, index: true
|
||||
t.bigint :assistant_response_id, null: false
|
||||
|
||||
t.timestamps
|
||||
end
|
||||
|
||||
add_index :captain_message_sources, [:message_id, :assistant_response_id],
|
||||
unique: true, name: 'idx_captain_message_sources_on_message_and_response'
|
||||
end
|
||||
end
|
||||
+2
-18
@@ -10,7 +10,7 @@
|
||||
#
|
||||
# It's strongly recommended that you check this file into your version control system.
|
||||
|
||||
ActiveRecord::Schema[7.1].define(version: 2026_07_21_100000) do
|
||||
ActiveRecord::Schema[7.1].define(version: 2026_07_13_184351) do
|
||||
# These extensions should be enabled to support this database
|
||||
enable_extension "pg_stat_statements"
|
||||
enable_extension "pg_trgm"
|
||||
@@ -477,23 +477,6 @@ ActiveRecord::Schema[7.1].define(version: 2026_07_21_100000) do
|
||||
t.index ["user_id"], name: "index_captain_message_reports_on_user_id"
|
||||
end
|
||||
|
||||
create_table "captain_message_sources", force: :cascade do |t|
|
||||
t.bigint "account_id", null: false
|
||||
t.bigint "assistant_id", null: false
|
||||
t.bigint "conversation_id", null: false
|
||||
t.bigint "message_id", null: false
|
||||
t.bigint "document_id", null: false
|
||||
t.bigint "assistant_response_id", null: false
|
||||
t.datetime "created_at", null: false
|
||||
t.datetime "updated_at", null: false
|
||||
t.index ["account_id"], name: "index_captain_message_sources_on_account_id"
|
||||
t.index ["assistant_id"], name: "index_captain_message_sources_on_assistant_id"
|
||||
t.index ["conversation_id"], name: "index_captain_message_sources_on_conversation_id"
|
||||
t.index ["document_id"], name: "index_captain_message_sources_on_document_id"
|
||||
t.index ["message_id", "assistant_response_id"], name: "idx_captain_message_sources_on_message_and_response", unique: true
|
||||
t.index ["message_id"], name: "index_captain_message_sources_on_message_id"
|
||||
end
|
||||
|
||||
create_table "captain_scenarios", force: :cascade do |t|
|
||||
t.string "title"
|
||||
t.text "description"
|
||||
@@ -1065,6 +1048,7 @@ ActiveRecord::Schema[7.1].define(version: 2026_07_21_100000) do
|
||||
t.boolean "enable_email_collect", default: true
|
||||
t.boolean "csat_survey_enabled", default: false
|
||||
t.boolean "allow_messages_after_resolved", default: true
|
||||
t.boolean "active", default: true, null: false
|
||||
t.jsonb "auto_assignment_config", default: {}
|
||||
t.boolean "lock_to_single_conversation", default: false, null: false
|
||||
t.bigint "portal_id"
|
||||
|
||||
@@ -37,23 +37,6 @@ class Captain::AssistantStatsBuilder
|
||||
build_metrics(current, previous)
|
||||
end
|
||||
|
||||
# Approved/pending FAQ counts and the document total in a single round trip.
|
||||
def faq_stats
|
||||
approved, pending, documents = Captain::AssistantResponse.by_assistant(assistant.id).reorder(nil).pick(
|
||||
Arel.sql("COUNT(*) FILTER (WHERE status = #{Captain::AssistantResponse.statuses['approved']})"),
|
||||
Arel.sql("COUNT(*) FILTER (WHERE status = #{Captain::AssistantResponse.statuses['pending']})"),
|
||||
Arel.sql("(SELECT COUNT(*) FROM captain_documents WHERE assistant_id = #{assistant.id.to_i})")
|
||||
)
|
||||
total = approved + pending
|
||||
|
||||
{
|
||||
approved: approved,
|
||||
pending: pending,
|
||||
documents: documents,
|
||||
coverage: total.zero? ? 0 : (approved.to_f / total * 100).round
|
||||
}
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
attr_reader :window
|
||||
@@ -73,7 +56,8 @@ class Captain::AssistantStatsBuilder
|
||||
handoff_rate: pack(current[:handoff], previous[:handoff], :point),
|
||||
hours_saved: pack(current[:hours_saved], previous[:hours_saved], :percent),
|
||||
reopen_rate: pack(current[:reopen], previous[:reopen], :point),
|
||||
conversation_depth: pack(current[:depth], previous[:depth], :absolute)
|
||||
conversation_depth: pack(current[:depth], previous[:depth], :absolute),
|
||||
knowledge: knowledge
|
||||
}
|
||||
end
|
||||
|
||||
@@ -89,7 +73,7 @@ class Captain::AssistantStatsBuilder
|
||||
auto_resolution: rate(resolution[:resolved], handled),
|
||||
handoff: rate(resolution[:handoff], handled),
|
||||
hours_saved: (public_count * SECONDS_SAVED_PER_REPLY / 3600.0).round,
|
||||
reopen: reopen_rate(range, resolution[:resolved]),
|
||||
reopen: reopen_rate(range),
|
||||
depth: depth_conversations.zero? ? 0 : (public_count.to_f / depth_conversations).round(1)
|
||||
}
|
||||
end
|
||||
@@ -174,9 +158,7 @@ class Captain::AssistantStatsBuilder
|
||||
# derived from the assistant's handled conversations (not current inbox membership) so a later
|
||||
# inbox reassignment doesn't drop historical resolves, and covers both the evaluated (inference)
|
||||
# and time-based (bot) resolve paths so the denominator matches auto_resolution_rate.
|
||||
def reopen_rate(range, resolved_count)
|
||||
return 0 if resolved_count.zero?
|
||||
|
||||
def reopen_rate(range)
|
||||
resolved_scope = account.reporting_events
|
||||
.where(name: RESOLVED_EVENT_NAMES, created_at: range,
|
||||
conversation_id: handled_scope(range).select(:conversation_id))
|
||||
@@ -196,7 +178,24 @@ class Captain::AssistantStatsBuilder
|
||||
'ON resolves.conversation_id = reporting_events.conversation_id ' \
|
||||
'AND reporting_events.event_end_time >= resolves.event_end_time')
|
||||
.distinct.count('reporting_events.conversation_id')
|
||||
rate(reopened, resolved_count)
|
||||
rate(reopened, resolved_scope.distinct.count(:conversation_id))
|
||||
end
|
||||
|
||||
# Approved/pending FAQ counts and the document total in a single round trip.
|
||||
def knowledge
|
||||
approved, pending, documents = Captain::AssistantResponse.by_assistant(assistant.id).reorder(nil).pick(
|
||||
Arel.sql("COUNT(*) FILTER (WHERE status = #{Captain::AssistantResponse.statuses['approved']})"),
|
||||
Arel.sql("COUNT(*) FILTER (WHERE status = #{Captain::AssistantResponse.statuses['pending']})"),
|
||||
Arel.sql("(SELECT COUNT(*) FROM captain_documents WHERE assistant_id = #{assistant.id.to_i})")
|
||||
)
|
||||
total = approved + pending
|
||||
|
||||
{
|
||||
approved: approved,
|
||||
pending: pending,
|
||||
documents: documents,
|
||||
coverage: total.zero? ? 0 : (approved.to_f / total * 100).round
|
||||
}
|
||||
end
|
||||
|
||||
def rate(numerator, denominator)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
class Api::V1::Accounts::Captain::AssistantsController < Api::V1::Accounts::BaseController
|
||||
before_action -> { check_authorization(Captain::Assistant) }
|
||||
|
||||
before_action :set_assistant, only: [:show, :update, :destroy, :playground, :metrics, :faq_stats, :summary, :drilldown]
|
||||
before_action :set_assistant, only: [:show, :update, :destroy, :playground, :stats, :summary, :drilldown]
|
||||
|
||||
def index
|
||||
@assistants = account_assistants.ordered
|
||||
@@ -42,14 +42,10 @@ class Api::V1::Accounts::Captain::AssistantsController < Api::V1::Accounts::Base
|
||||
@tools = assistant.available_agent_tools
|
||||
end
|
||||
|
||||
def metrics
|
||||
def stats
|
||||
render json: Captain::AssistantStatsBuilder.new(@assistant, params[:range], params[:timezone_offset]).metrics
|
||||
end
|
||||
|
||||
def faq_stats
|
||||
render json: Captain::AssistantStatsBuilder.new(@assistant).faq_stats
|
||||
end
|
||||
|
||||
def summary
|
||||
window = Captain::AssistantStatsWindow.new(params[:range], params[:timezone_offset])
|
||||
result = cached_or_generated_summary(window, summary_stats)
|
||||
|
||||
@@ -11,7 +11,7 @@ class Api::V1::Accounts::Captain::DocumentsController < Api::V1::Accounts::BaseC
|
||||
@documents = filtered_documents
|
||||
@documents_count = @documents.count
|
||||
@sync_interval_hours = current_sync_interval&.in_hours&.to_i
|
||||
@documents = with_document_usage(@documents).page(@current_page).per(RESULTS_PER_PAGE)
|
||||
@documents = with_responses_count(@documents).page(@current_page).per(RESULTS_PER_PAGE)
|
||||
end
|
||||
|
||||
def show; end
|
||||
@@ -61,23 +61,14 @@ class Api::V1::Accounts::Captain::DocumentsController < Api::V1::Accounts::BaseC
|
||||
apply_sort(documents, permitted_params[:sort])
|
||||
end
|
||||
|
||||
def with_document_usage(scope)
|
||||
response_counts = Captain::AssistantResponse.where(documentable_type: 'Captain::Document')
|
||||
.group(:documentable_id)
|
||||
.select('documentable_id AS document_id, COUNT(*) AS responses_count')
|
||||
source_counts = Captain::MessageSource.group(:document_id).select(
|
||||
'document_id, COUNT(DISTINCT message_id) AS used_in_answers_count, COUNT(DISTINCT conversation_id) AS used_in_conversations_count'
|
||||
)
|
||||
|
||||
scope.joins("LEFT JOIN (#{response_counts.to_sql}) response_counts ON response_counts.document_id = captain_documents.id")
|
||||
.joins("LEFT JOIN (#{source_counts.to_sql}) source_counts ON source_counts.document_id = captain_documents.id")
|
||||
.select('captain_documents.*, COALESCE(response_counts.responses_count, 0) AS responses_count, ' \
|
||||
'COALESCE(source_counts.used_in_answers_count, 0) AS used_in_answers_count, ' \
|
||||
'COALESCE(source_counts.used_in_conversations_count, 0) AS used_in_conversations_count')
|
||||
def with_responses_count(scope)
|
||||
scope.left_joins(:responses)
|
||||
.select('captain_documents.*, COUNT(captain_assistant_responses.id) AS responses_count')
|
||||
.group('captain_documents.id')
|
||||
end
|
||||
|
||||
def set_document
|
||||
@document = with_document_usage(@documents).find(permitted_params[:id])
|
||||
@document = @documents.find(permitted_params[:id])
|
||||
end
|
||||
|
||||
def set_assistant
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
class Api::V1::Accounts::WhatsappCallsController < Api::V1::Accounts::BaseController
|
||||
before_action :set_call, only: %i[show accept reject terminate upload_recording]
|
||||
before_action :set_call_context, only: :initiate
|
||||
before_action :ensure_inbox_active, only: :initiate
|
||||
before_action :ensure_calling_enabled, only: :initiate
|
||||
before_action :ensure_sdp_offer, only: :initiate
|
||||
before_action :ensure_contact_phone, only: :initiate
|
||||
@@ -96,6 +97,10 @@ class Api::V1::Accounts::WhatsappCallsController < Api::V1::Accounts::BaseContro
|
||||
render_could_not_create_error(I18n.t('errors.whatsapp.calls.not_enabled'))
|
||||
end
|
||||
|
||||
def ensure_inbox_active
|
||||
render_inbox_disabled_error unless @inbox.active?
|
||||
end
|
||||
|
||||
def ensure_sdp_offer
|
||||
return if params[:sdp_offer].present?
|
||||
|
||||
|
||||
@@ -90,10 +90,10 @@ class Twilio::VoiceController < ApplicationController
|
||||
from_number.start_with?('client:')
|
||||
end
|
||||
|
||||
# A fresh contact-initiated leg on an inbox with inbound calls turned off.
|
||||
# A fresh contact-initiated leg on an inbox that cannot receive calls.
|
||||
# Reject it so no conference, conversation, or Call row is created.
|
||||
def reject_inbound?
|
||||
twilio_direction == 'inbound' && !agent_leg?(twilio_from) && !inbox.channel.inbound_calls_enabled?
|
||||
twilio_direction == 'inbound' && !agent_leg?(twilio_from) && (!inbox.active? || !inbox.channel.inbound_calls_enabled?)
|
||||
end
|
||||
|
||||
def reject_twiml
|
||||
|
||||
@@ -68,7 +68,7 @@ class Captain::Conversation::ResponseBuilderJob < ApplicationJob
|
||||
# left is the customer-facing follow-up message.
|
||||
process_v2_handoff
|
||||
end
|
||||
capture_assistant_session(result_message: @handoff_message, credits_consumed: 0.0, capture_message_sources: false)
|
||||
capture_assistant_session(result_message: @handoff_message, credits_consumed: 0.0)
|
||||
elsif v1_handoff_requested?
|
||||
# V1 only signals via the response string — no state has been touched yet. If
|
||||
# the conversation isn't pending anymore, a human took over mid-run; bail out
|
||||
@@ -83,7 +83,7 @@ class Captain::Conversation::ResponseBuilderJob < ApplicationJob
|
||||
Rails.logger.info("[CAPTAIN][ResponseBuilderJob] Incrementing response usage for #{account.id}")
|
||||
account.increment_response_usage
|
||||
end
|
||||
capture_assistant_session(result_message: message, credits_consumed: 1.0, capture_message_sources: captain_v2_enabled?)
|
||||
capture_assistant_session(result_message: message, credits_consumed: 1.0)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -142,10 +142,9 @@ class Captain::Conversation::ResponseBuilderJob < ApplicationJob
|
||||
# Capture runs outside the delivery transaction and never raises (the service
|
||||
# swallows its own failures): a session-logging bug must never roll back the
|
||||
# customer reply or trigger the top-level handle_error handoff on top of it.
|
||||
def capture_assistant_session(result_message:, credits_consumed:, capture_message_sources:)
|
||||
def capture_assistant_session(result_message:, credits_consumed:)
|
||||
Captain::Assistant::SessionCaptureService.new(assistant: @assistant, conversation: @conversation, run_result: @run_result,
|
||||
result_message: result_message, credits_consumed: credits_consumed,
|
||||
capture_message_sources: capture_message_sources).capture
|
||||
result_message: result_message, credits_consumed: credits_consumed).capture
|
||||
end
|
||||
|
||||
def handle_error(error)
|
||||
|
||||
@@ -34,7 +34,6 @@ class Captain::Document < ApplicationRecord
|
||||
|
||||
belongs_to :assistant, class_name: 'Captain::Assistant'
|
||||
has_many :responses, class_name: 'Captain::AssistantResponse', dependent: :destroy, as: :documentable
|
||||
has_many :message_sources, class_name: 'Captain::MessageSource', dependent: :destroy_async
|
||||
belongs_to :account
|
||||
has_one_attached :pdf_file
|
||||
store_accessor :metadata, :content_fingerprint, :last_sync_error_code, :sync_step, :openai_file_id
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
# == Schema Information
|
||||
#
|
||||
# Table name: captain_message_sources
|
||||
#
|
||||
# id :bigint not null, primary key
|
||||
# created_at :datetime not null
|
||||
# updated_at :datetime not null
|
||||
# account_id :bigint not null
|
||||
# assistant_id :bigint not null
|
||||
# assistant_response_id :bigint not null
|
||||
# conversation_id :bigint not null
|
||||
# document_id :bigint not null
|
||||
# message_id :bigint not null
|
||||
#
|
||||
# Indexes
|
||||
#
|
||||
# idx_captain_message_sources_on_message_and_response (message_id,assistant_response_id) UNIQUE
|
||||
# index_captain_message_sources_on_account_id (account_id)
|
||||
# index_captain_message_sources_on_assistant_id (assistant_id)
|
||||
# index_captain_message_sources_on_conversation_id (conversation_id)
|
||||
# index_captain_message_sources_on_document_id (document_id)
|
||||
# index_captain_message_sources_on_message_id (message_id)
|
||||
#
|
||||
class Captain::MessageSource < ApplicationRecord
|
||||
self.table_name = 'captain_message_sources'
|
||||
|
||||
belongs_to :account
|
||||
belongs_to :assistant, class_name: 'Captain::Assistant'
|
||||
belongs_to :conversation, class_name: '::Conversation'
|
||||
belongs_to :message
|
||||
belongs_to :document, class_name: 'Captain::Document'
|
||||
belongs_to :assistant_response, class_name: 'Captain::AssistantResponse', optional: true
|
||||
end
|
||||
@@ -16,7 +16,6 @@ module Enterprise::Concerns::Account
|
||||
has_many :captain_documents, dependent: :destroy_async, class_name: 'Captain::Document'
|
||||
has_many :captain_custom_tools, dependent: :destroy_async, class_name: 'Captain::CustomTool'
|
||||
has_many :captain_agent_sessions, dependent: :destroy_async, class_name: 'Captain::AgentSession'
|
||||
has_many :captain_message_sources, dependent: :destroy_async, class_name: 'Captain::MessageSource'
|
||||
|
||||
has_many :copilot_threads, dependent: :destroy_async
|
||||
has_many :companies, dependent: :destroy_async
|
||||
|
||||
@@ -4,6 +4,5 @@ module Enterprise::Concerns::Message
|
||||
included do
|
||||
has_one :call, dependent: :nullify
|
||||
has_many :message_reports, class_name: 'Captain::MessageReport', dependent: :destroy_async
|
||||
has_many :captain_message_sources, class_name: 'Captain::MessageSource', dependent: :destroy_async
|
||||
end
|
||||
end
|
||||
|
||||
@@ -7,11 +7,7 @@ class Captain::AssistantPolicy < ApplicationPolicy
|
||||
true
|
||||
end
|
||||
|
||||
def metrics?
|
||||
true
|
||||
end
|
||||
|
||||
def faq_stats?
|
||||
def stats?
|
||||
true
|
||||
end
|
||||
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
class Captain::Assistant::SessionCaptureService
|
||||
SCENARIO_AGENT_REGEX = /\A#{Captain::Scenario::HANDOFF_KEY_PREFIX}_(\d+)_/
|
||||
|
||||
def initialize(assistant:, conversation:, run_result:, result_message:, **options)
|
||||
def initialize(assistant:, conversation:, run_result:, result_message:, credits_consumed:)
|
||||
@assistant = assistant
|
||||
@conversation = conversation
|
||||
@run_result = run_result
|
||||
@result_message = result_message
|
||||
@credits_consumed = options.fetch(:credits_consumed)
|
||||
@capture_message_sources = options.fetch(:capture_message_sources, false)
|
||||
@credits_consumed = credits_consumed
|
||||
end
|
||||
|
||||
def capture
|
||||
@@ -24,7 +23,7 @@ class Captain::Assistant::SessionCaptureService
|
||||
def capture!
|
||||
model = @assistant.agent_model
|
||||
|
||||
session = Captain::AgentSession.create!(
|
||||
Captain::AgentSession.create!(
|
||||
assistant: @assistant,
|
||||
session_type: :assistant,
|
||||
subject: @conversation,
|
||||
@@ -36,8 +35,6 @@ class Captain::Assistant::SessionCaptureService
|
||||
scenario_ids: scenario_ids,
|
||||
run_context: current_turn_history
|
||||
)
|
||||
capture_message_sources(metadata) if @capture_message_sources
|
||||
session
|
||||
end
|
||||
|
||||
private
|
||||
@@ -73,42 +70,6 @@ class Captain::Assistant::SessionCaptureService
|
||||
ids & @assistant.scenarios.where(id: ids).pluck(:id)
|
||||
end
|
||||
|
||||
def capture_message_sources(metadata)
|
||||
sources = Array(metadata[:message_sources])
|
||||
return if sources.empty?
|
||||
|
||||
document_ids = @assistant.documents.where(id: sources.pluck(:document_id)).pluck(:id)
|
||||
return if document_ids.empty?
|
||||
|
||||
insert_message_sources(message_source_rows(sources, document_ids))
|
||||
end
|
||||
|
||||
def message_source_rows(sources, document_ids)
|
||||
timestamp = Time.current
|
||||
sources.filter_map do |source|
|
||||
next unless document_ids.include?(source[:document_id])
|
||||
|
||||
{
|
||||
account_id: @assistant.account_id,
|
||||
assistant_id: @assistant.id,
|
||||
conversation_id: @conversation.id,
|
||||
message_id: @result_message.id,
|
||||
document_id: source[:document_id],
|
||||
assistant_response_id: source[:assistant_response_id],
|
||||
created_at: timestamp,
|
||||
updated_at: timestamp
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
def insert_message_sources(rows)
|
||||
return if rows.empty?
|
||||
|
||||
# rubocop:disable Rails/SkipsModelValidations
|
||||
Captain::MessageSource.insert_all(rows, unique_by: :idx_captain_message_sources_on_message_and_response)
|
||||
# rubocop:enable Rails/SkipsModelValidations
|
||||
end
|
||||
|
||||
# Trim to the current turn: the last user message and everything after it
|
||||
# (assistant replies, tool calls/results, handoff hops).
|
||||
def current_turn_history
|
||||
|
||||
@@ -16,6 +16,7 @@ class Voice::OutboundCallBuilder
|
||||
def perform!
|
||||
raise ArgumentError, 'Contact phone number required' if contact.phone_number.blank?
|
||||
raise ArgumentError, 'Agent required' if user.blank?
|
||||
raise CustomExceptions::InboxDisabled unless inbox.active?
|
||||
|
||||
# Claim for the caller if a reused conversation is unassigned at trigger time; wins over auto-assignment.
|
||||
# New conversations set the assignee at creation instead (see create_conversation!).
|
||||
|
||||
@@ -75,7 +75,7 @@ class Whatsapp::IncomingCallService
|
||||
end
|
||||
|
||||
def create_inbound_call(payload)
|
||||
unless inbox.channel.inbound_calls_enabled?
|
||||
unless inbox.active? && inbox.channel.inbound_calls_enabled?
|
||||
Rails.logger.info "[WHATSAPP CALL] Inbound calls disabled for inbox #{inbox.id}; rejecting call #{payload[:id]}"
|
||||
inbox.channel.provider_service.reject_call(payload[:id])
|
||||
return
|
||||
|
||||
@@ -11,10 +11,6 @@ json.file_size resource.file_size
|
||||
json.pdf_document resource.pdf_document?
|
||||
responses_count = resource.respond_to?(:responses_count) ? resource.responses_count : resource.responses.count
|
||||
json.responses_count responses_count.to_i
|
||||
used_in_answers_count = resource.respond_to?(:used_in_answers_count) ? resource.used_in_answers_count : resource.message_sources.distinct.count(:message_id)
|
||||
json.used_in_answers_count used_in_answers_count.to_i
|
||||
used_in_conversations_count = resource.respond_to?(:used_in_conversations_count) ? resource.used_in_conversations_count : resource.message_sources.distinct.count(:conversation_id)
|
||||
json.used_in_conversations_count used_in_conversations_count.to_i
|
||||
json.id resource.id
|
||||
json.name resource.name
|
||||
json.status resource.status
|
||||
|
||||
@@ -26,17 +26,8 @@ class Captain::Tools::FaqLookupTool < Captain::Tools::BasePublicTool
|
||||
metadata = tool_context.state[:cw_metadata] ||= {}
|
||||
metadata[:faq_ids] = Array(metadata[:faq_ids]) | responses.map(&:id)
|
||||
|
||||
document_ids = document_responses(responses).map(&:documentable_id)
|
||||
document_ids = responses.filter_map { |response| response.documentable_id if response.documentable_type == 'Captain::Document' }
|
||||
metadata[:document_ids] = Array(metadata[:document_ids]) | document_ids
|
||||
metadata[:message_sources] = Array(metadata[:message_sources]) | message_sources(document_responses(responses))
|
||||
end
|
||||
|
||||
def document_responses(responses)
|
||||
responses.select { |response| response.documentable_type == 'Captain::Document' }
|
||||
end
|
||||
|
||||
def message_sources(responses)
|
||||
responses.map { |response| { assistant_response_id: response.id, document_id: response.documentable_id } }
|
||||
end
|
||||
|
||||
def format_responses(responses)
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
class CustomExceptions::InboxDisabled < CustomExceptions::Base
|
||||
def initialize(data = {})
|
||||
super
|
||||
end
|
||||
|
||||
def message
|
||||
'This inbox is currently disabled'
|
||||
end
|
||||
|
||||
def error_code
|
||||
'inbox_disabled'
|
||||
end
|
||||
|
||||
def http_status
|
||||
:forbidden
|
||||
end
|
||||
end
|
||||
+5
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@chatwoot/chatwoot",
|
||||
"version": "4.16.1",
|
||||
"version": "4.16.0",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"eslint": "eslint app/**/*.{js,vue}",
|
||||
@@ -34,7 +34,7 @@
|
||||
"@amplitude/analytics-browser": "^2.11.10",
|
||||
"@breezystack/lamejs": "^1.2.7",
|
||||
"@chatwoot/ninja-keys": "1.2.3",
|
||||
"@chatwoot/prosemirror-schema": "1.3.23",
|
||||
"@chatwoot/prosemirror-schema": "1.3.22",
|
||||
"@chatwoot/utils": "^0.0.56",
|
||||
"@formkit/core": "^1.7.2",
|
||||
"@formkit/vue": "^1.7.2",
|
||||
@@ -86,6 +86,9 @@
|
||||
"mitt": "^3.0.1",
|
||||
"opus-recorder": "^8.0.5",
|
||||
"pinia": "^3.0.4",
|
||||
"prosemirror-commands": "^1.7.1",
|
||||
"prosemirror-inputrules": "^1.4.0",
|
||||
"prosemirror-schema-list": "^1.5.1",
|
||||
"qrcode": "^1.5.4",
|
||||
"semver": "7.6.3",
|
||||
"snakecase-keys": "^8.0.1",
|
||||
|
||||
Generated
+22
-6
@@ -25,8 +25,8 @@ importers:
|
||||
specifier: 1.2.3
|
||||
version: 1.2.3
|
||||
'@chatwoot/prosemirror-schema':
|
||||
specifier: 1.3.23
|
||||
version: 1.3.23
|
||||
specifier: 1.3.22
|
||||
version: 1.3.22
|
||||
'@chatwoot/utils':
|
||||
specifier: ^0.0.56
|
||||
version: 0.0.56
|
||||
@@ -180,6 +180,15 @@ importers:
|
||||
pinia:
|
||||
specifier: ^3.0.4
|
||||
version: 3.0.4(typescript@5.6.2)(vue@3.5.12(typescript@5.6.2))
|
||||
prosemirror-commands:
|
||||
specifier: ^1.7.1
|
||||
version: 1.7.1
|
||||
prosemirror-inputrules:
|
||||
specifier: ^1.4.0
|
||||
version: 1.4.0
|
||||
prosemirror-schema-list:
|
||||
specifier: ^1.5.1
|
||||
version: 1.5.1
|
||||
qrcode:
|
||||
specifier: ^1.5.4
|
||||
version: 1.5.4
|
||||
@@ -452,8 +461,8 @@ packages:
|
||||
'@chatwoot/ninja-keys@1.2.3':
|
||||
resolution: {integrity: sha512-xM8d9P5ikDMZm2WbaCTk/TW5HFauylrU3cJ75fq5je6ixKwyhl/0kZbVN/vbbZN4+AUX/OaSIn6IJbtCgIF67g==}
|
||||
|
||||
'@chatwoot/prosemirror-schema@1.3.23':
|
||||
resolution: {integrity: sha512-jGxbWELCdlVI64BJiE1wT84ekJHYDXXKiluQIKT3aKPEjPwMR48umKF3A0yHjKoR7IIxCC9oM77TvXOA0ebLtw==}
|
||||
'@chatwoot/prosemirror-schema@1.3.22':
|
||||
resolution: {integrity: sha512-0r+PT8xhQLCKCpoV9k9XVTTRECs/0Nr37wbcLsRS7yvc7WkF9FY05z2hGCRJReWmTOcmmshHtb042LVP+MyB/w==}
|
||||
|
||||
'@chatwoot/utils@0.0.56':
|
||||
resolution: {integrity: sha512-A6dmPLfTSrW4qYNY73btyi4PqpfzcXRSaucscZTQdzNqF6G/QUdgnBmHtho8HeiYby/kSHXaSxLJj+0dx3yEQQ==}
|
||||
@@ -3992,6 +4001,9 @@ packages:
|
||||
prosemirror-tables@1.5.0:
|
||||
resolution: {integrity: sha512-VMx4zlYWm7aBlZ5xtfJHpqa3Xgu3b7srV54fXYnXgsAcIGRqKSrhiK3f89omzzgaAgAtDOV4ImXnLKhVfheVNQ==}
|
||||
|
||||
prosemirror-transform@1.10.0:
|
||||
resolution: {integrity: sha512-9UOgFSgN6Gj2ekQH5CTDJ8Rp/fnKR2IkYfGdzzp5zQMFsS4zDllLVx/+jGcX86YlACpG7UR5fwAXiWzxqWtBTg==}
|
||||
|
||||
prosemirror-transform@1.12.0:
|
||||
resolution: {integrity: sha512-GxboyN4AMIsoHNtz5uf2r2Ru551i5hWeCMD6E2Ib4Eogqoub0NflniaBPVQ4MrGE5yZ8JV9tUHg9qcZTTrcN4w==}
|
||||
|
||||
@@ -5124,7 +5136,7 @@ snapshots:
|
||||
hotkeys-js: 3.8.7
|
||||
lit: 2.2.6
|
||||
|
||||
'@chatwoot/prosemirror-schema@1.3.23':
|
||||
'@chatwoot/prosemirror-schema@1.3.22':
|
||||
dependencies:
|
||||
markdown-it-sup: 2.0.0
|
||||
prosemirror-commands: 1.7.1
|
||||
@@ -9023,7 +9035,7 @@ snapshots:
|
||||
dependencies:
|
||||
prosemirror-model: 1.22.3
|
||||
prosemirror-state: 1.4.3
|
||||
prosemirror-transform: 1.12.0
|
||||
prosemirror-transform: 1.10.0
|
||||
|
||||
prosemirror-state@1.4.3:
|
||||
dependencies:
|
||||
@@ -9039,6 +9051,10 @@ snapshots:
|
||||
prosemirror-transform: 1.12.0
|
||||
prosemirror-view: 1.34.1
|
||||
|
||||
prosemirror-transform@1.10.0:
|
||||
dependencies:
|
||||
prosemirror-model: 1.22.3
|
||||
|
||||
prosemirror-transform@1.12.0:
|
||||
dependencies:
|
||||
prosemirror-model: 1.22.3
|
||||
|
||||
@@ -31,6 +31,18 @@ RSpec.describe '/api/v1/widget/config', type: :request do
|
||||
response_data = response.parsed_body
|
||||
expect(response_data.keys).to include(*response_keys)
|
||||
end
|
||||
|
||||
it 'does not initialize config or create a contact when the inbox is disabled' do
|
||||
web_widget.inbox.update!(active: false)
|
||||
|
||||
expect do
|
||||
post '/api/v1/widget/config',
|
||||
params: params,
|
||||
as: :json
|
||||
end.not_to change(Contact, :count)
|
||||
|
||||
expect(response).to have_http_status(:forbidden)
|
||||
end
|
||||
end
|
||||
|
||||
context 'with correct website token and valid X-Auth-Token' do
|
||||
@@ -48,6 +60,17 @@ RSpec.describe '/api/v1/widget/config', type: :request do
|
||||
expect(response_data['contact']['pubsub_token']).to eq(contact_inbox.pubsub_token)
|
||||
end
|
||||
|
||||
it 'does not initialize config when the inbox is disabled' do
|
||||
web_widget.inbox.update!(active: false)
|
||||
|
||||
post '/api/v1/widget/config',
|
||||
params: params,
|
||||
headers: { 'X-Auth-Token' => token },
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:forbidden)
|
||||
end
|
||||
|
||||
it 'returns 401 if account is suspended' do
|
||||
account.update!(status: :suspended)
|
||||
|
||||
|
||||
@@ -37,6 +37,18 @@ RSpec.describe '/api/v1/widget/contacts', type: :request do
|
||||
expect(ContactIdentifyAction).to have_received(:new).with(expected_params)
|
||||
expect(identify_action).to have_received(:perform)
|
||||
end
|
||||
|
||||
it 'does not update the contact when the inbox is disabled' do
|
||||
web_widget.inbox.update!(active: false)
|
||||
|
||||
patch '/api/v1/widget/contact',
|
||||
params: params,
|
||||
headers: { 'X-Auth-Token' => token },
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:forbidden)
|
||||
expect(ContactIdentifyAction).not_to have_received(:new)
|
||||
end
|
||||
end
|
||||
|
||||
context 'with update contact' do
|
||||
@@ -255,6 +267,18 @@ RSpec.describe '/api/v1/widget/contacts', type: :request do
|
||||
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
|
||||
it 'does not set user when the inbox is disabled' do
|
||||
web_widget.inbox.update!(active: false)
|
||||
|
||||
patch '/api/v1/widget/contact/set_user',
|
||||
params: params.merge(identifier_hash: correct_identifier_hash),
|
||||
headers: { 'X-Auth-Token' => token },
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:forbidden)
|
||||
expect(ContactIdentifyAction).not_to have_received(:new)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -263,19 +287,32 @@ RSpec.describe '/api/v1/widget/contacts', type: :request do
|
||||
|
||||
context 'with invalid website token' do
|
||||
it 'returns unauthorized' do
|
||||
post '/api/v1/widget/destroy_custom_attributes', params: { website_token: '' }
|
||||
post '/api/v1/widget/contact/destroy_custom_attributes', params: { website_token: '' }
|
||||
expect(response).to have_http_status(:not_found)
|
||||
end
|
||||
end
|
||||
|
||||
context 'with correct website token' do
|
||||
it 'calls destroy custom attributes' do
|
||||
post '/api/v1/widget/destroy_custom_attributes',
|
||||
post '/api/v1/widget/contact/destroy_custom_attributes',
|
||||
params: params,
|
||||
headers: { 'X-Auth-Token' => token },
|
||||
as: :json
|
||||
expect(contact.reload.custom_attributes).to eq({})
|
||||
end
|
||||
|
||||
it 'does not destroy custom attributes when the inbox is disabled' do
|
||||
contact.update!(custom_attributes: { 'test' => 'value' })
|
||||
web_widget.inbox.update!(active: false)
|
||||
|
||||
post '/api/v1/widget/contact/destroy_custom_attributes',
|
||||
params: params,
|
||||
headers: { 'X-Auth-Token' => token },
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:forbidden)
|
||||
expect(contact.reload.custom_attributes).to eq('test' => 'value')
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -43,6 +43,18 @@ RSpec.describe '/api/v1/widget/conversations/toggle_typing', type: :request do
|
||||
expect(json_response['id']).to eq(conversation.display_id)
|
||||
expect(json_response['status']).to eq(conversation.status)
|
||||
end
|
||||
|
||||
it 'returns the conversation when the inbox is disabled' do
|
||||
web_widget.inbox.update!(active: false)
|
||||
|
||||
get '/api/v1/widget/conversations',
|
||||
headers: { 'X-Auth-Token' => token },
|
||||
params: { website_token: web_widget.website_token },
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
expect(response.parsed_body['id']).to eq(conversation.display_id)
|
||||
end
|
||||
end
|
||||
|
||||
context 'with a conversation but invalid source id' do
|
||||
@@ -62,6 +74,19 @@ RSpec.describe '/api/v1/widget/conversations/toggle_typing', type: :request do
|
||||
end
|
||||
|
||||
describe 'POST /api/v1/widget/conversations' do
|
||||
it 'does not create a conversation when the inbox is disabled' do
|
||||
web_widget.inbox.update!(active: false)
|
||||
|
||||
expect do
|
||||
post '/api/v1/widget/conversations',
|
||||
headers: { 'X-Auth-Token' => token },
|
||||
params: conversation_params,
|
||||
as: :json
|
||||
end.not_to change(Conversation, :count)
|
||||
|
||||
expect(response).to have_http_status(:forbidden)
|
||||
end
|
||||
|
||||
it 'creates a conversation with correct details' do
|
||||
post '/api/v1/widget/conversations',
|
||||
headers: { 'X-Auth-Token' => token },
|
||||
@@ -244,11 +269,40 @@ RSpec.describe '/api/v1/widget/conversations/toggle_typing', type: :request do
|
||||
|
||||
expect(conversation.reload.contact_last_seen_at).not_to be_nil
|
||||
end
|
||||
|
||||
it 'updates last seen when the inbox is disabled' do
|
||||
current_time = DateTime.now.utc
|
||||
allow(DateTime).to receive(:now).and_return(current_time)
|
||||
web_widget.inbox.update!(active: false)
|
||||
|
||||
expect(Conversations::UpdateMessageStatusJob).to receive(:perform_later).with(conversation.id, current_time)
|
||||
|
||||
post '/api/v1/widget/conversations/update_last_seen',
|
||||
headers: { 'X-Auth-Token' => token },
|
||||
params: { website_token: web_widget.website_token },
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
expect(conversation.reload.contact_last_seen_at).not_to be_nil
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'POST /api/v1/widget/conversations/transcript' do
|
||||
context 'with a conversation' do
|
||||
it 'does not send transcript email when the inbox is disabled' do
|
||||
web_widget.inbox.update!(active: false)
|
||||
contact.update!(email: 'test@test.com')
|
||||
expect(ConversationReplyMailer).not_to receive(:with)
|
||||
|
||||
post '/api/v1/widget/conversations/transcript',
|
||||
headers: { 'X-Auth-Token' => token },
|
||||
params: { website_token: web_widget.website_token },
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:forbidden)
|
||||
end
|
||||
|
||||
it 'sends transcript email' do
|
||||
contact.update(email: 'test@test.com')
|
||||
mailer = double
|
||||
|
||||
@@ -34,6 +34,24 @@ RSpec.describe '/api/v1/widget/direct_uploads', type: :request do
|
||||
json_response = response.parsed_body
|
||||
expect(json_response['content_type']).to eq('image/png')
|
||||
end
|
||||
|
||||
it 'does not create direct upload when the inbox is disabled' do
|
||||
web_widget.inbox.update!(active: false)
|
||||
|
||||
post api_v1_widget_direct_uploads_url,
|
||||
params: {
|
||||
website_token: web_widget.website_token,
|
||||
blob: {
|
||||
filename: 'avatar.png',
|
||||
byte_size: '1234',
|
||||
checksum: 'dsjbsdhbfif3874823mnsdbf',
|
||||
content_type: 'image/png'
|
||||
}
|
||||
},
|
||||
headers: { 'X-Auth-Token' => token }
|
||||
|
||||
expect(response).to have_http_status(:forbidden)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -34,6 +34,20 @@ RSpec.describe '/api/v1/widget/events', type: :request do
|
||||
.with(params[:name], anything, contact_inbox: contact_inbox,
|
||||
event_info: { test_id: 'test', browser_language: nil, widget_language: nil, browser: anything })
|
||||
end
|
||||
|
||||
it 'does not dispatch events when the inbox is disabled' do
|
||||
token
|
||||
web_widget.inbox.update!(active: false)
|
||||
|
||||
expect(Rails.configuration.dispatcher).not_to receive(:dispatch)
|
||||
|
||||
post '/api/v1/widget/events',
|
||||
params: params,
|
||||
headers: { 'X-Auth-Token' => token },
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:forbidden)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -70,6 +70,17 @@ RSpec.describe '/api/v1/widget/integrations/dyte', type: :request do
|
||||
}
|
||||
)
|
||||
end
|
||||
|
||||
it 'does not add a participant when the inbox is disabled' do
|
||||
web_widget.inbox.update!(active: false)
|
||||
|
||||
post add_participant_to_meeting_api_v1_widget_integrations_dyte_url,
|
||||
headers: { 'X-Auth-Token' => token },
|
||||
params: { website_token: web_widget.website_token, message_id: integration_message.id },
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:forbidden)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -39,6 +39,18 @@ RSpec.describe '/api/v1/widget/labels', type: :request do
|
||||
expect(conversation.reload.label_list.count).to eq 1
|
||||
expect(conversation.reload.label_list.first).to eq 'customer-support'
|
||||
end
|
||||
|
||||
it 'does not add labels when the inbox is disabled' do
|
||||
web_widget.inbox.update!(active: false)
|
||||
|
||||
post '/api/v1/widget/labels',
|
||||
params: params,
|
||||
headers: { 'X-Auth-Token' => token },
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:forbidden)
|
||||
expect(conversation.reload.label_list.count).to eq 0
|
||||
end
|
||||
end
|
||||
|
||||
context 'with invalid website token' do
|
||||
@@ -67,6 +79,18 @@ RSpec.describe '/api/v1/widget/labels', type: :request do
|
||||
expect(response).to have_http_status(:success)
|
||||
expect(conversation.reload.label_list.count).to eq 0
|
||||
end
|
||||
|
||||
it 'does not remove labels when the inbox is disabled' do
|
||||
web_widget.inbox.update!(active: false)
|
||||
|
||||
delete "/api/v1/widget/labels/#{params[:label]}",
|
||||
params: params,
|
||||
headers: { 'X-Auth-Token' => token },
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:forbidden)
|
||||
expect(conversation.reload.label_list.count).to eq 1
|
||||
end
|
||||
end
|
||||
|
||||
context 'with invalid website token' do
|
||||
|
||||
@@ -28,6 +28,18 @@ RSpec.describe '/api/v1/widget/messages', type: :request do
|
||||
expect(json_response['meta']).not_to be_empty
|
||||
end
|
||||
|
||||
it 'returns messages when the inbox is disabled' do
|
||||
web_widget.inbox.update!(active: false)
|
||||
|
||||
get api_v1_widget_messages_url,
|
||||
params: { website_token: web_widget.website_token },
|
||||
headers: { 'X-Auth-Token' => token },
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
expect(response.parsed_body['payload'].length).to eq(4)
|
||||
end
|
||||
|
||||
it 'returns empty messages', :skip_before do
|
||||
get api_v1_widget_messages_url,
|
||||
params: { website_token: web_widget.website_token },
|
||||
@@ -43,6 +55,20 @@ RSpec.describe '/api/v1/widget/messages', type: :request do
|
||||
|
||||
describe 'POST /api/v1/widget/messages' do
|
||||
context 'when post request is made' do
|
||||
it 'does not create message in conversation when the inbox is disabled' do
|
||||
web_widget.inbox.update!(active: false)
|
||||
message_params = { content: 'hello world', timestamp: Time.current }
|
||||
|
||||
expect do
|
||||
post api_v1_widget_messages_url,
|
||||
params: { website_token: web_widget.website_token, message: message_params },
|
||||
headers: { 'X-Auth-Token' => token },
|
||||
as: :json
|
||||
end.not_to change(Message, :count)
|
||||
|
||||
expect(response).to have_http_status(:forbidden)
|
||||
end
|
||||
|
||||
it 'creates message in conversation' do
|
||||
conversation.destroy! # Test all params
|
||||
message_params = { content: 'hello world', timestamp: Time.current }
|
||||
@@ -213,6 +239,21 @@ RSpec.describe '/api/v1/widget/messages', type: :request do
|
||||
end
|
||||
|
||||
describe 'PUT /api/v1/widget/messages' do
|
||||
context 'when the inbox is disabled' do
|
||||
it 'does not update the message' do
|
||||
message = create(:message, content_type: 'input_email', account: account, inbox: web_widget.inbox, conversation: conversation)
|
||||
web_widget.inbox.update!(active: false)
|
||||
|
||||
put api_v1_widget_message_url(message.id),
|
||||
params: { website_token: web_widget.website_token, contact: { email: Faker::Internet.email } },
|
||||
headers: { 'X-Auth-Token' => token },
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:forbidden)
|
||||
expect(message.reload.submitted_email).to be_nil
|
||||
end
|
||||
end
|
||||
|
||||
context 'when put request targets a message from another visitor in the same inbox' do
|
||||
it 'does not update the foreign message' do
|
||||
other_contact = create(:contact, account: account, email: nil)
|
||||
|
||||
@@ -139,5 +139,18 @@ RSpec.describe 'Public Inbox Contact Conversations API', type: :request do
|
||||
expect(response).to have_http_status(:success)
|
||||
expect(conversation.reload.contact_last_seen_at).not_to eq contact_last_seen_at
|
||||
end
|
||||
|
||||
it 'updates the last seen when the inbox is disabled' do
|
||||
current_time = DateTime.now.utc
|
||||
allow(DateTime).to receive(:now).and_return(current_time)
|
||||
api_channel.inbox.update!(active: false)
|
||||
|
||||
expect(Conversations::UpdateMessageStatusJob).to receive(:perform_later).with(conversation.id, current_time)
|
||||
|
||||
post update_last_seen_path
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
expect(conversation.reload.contact_last_seen_at).not_to be_nil
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -27,7 +27,7 @@ RSpec.describe Captain::AssistantStatsBuilder do
|
||||
|
||||
expect(metrics.keys).to contain_exactly(
|
||||
:conversations_handled, :auto_resolution_rate, :handoff_rate,
|
||||
:hours_saved, :reopen_rate, :conversation_depth
|
||||
:hours_saved, :reopen_rate, :conversation_depth, :knowledge
|
||||
)
|
||||
expect(metrics[:conversations_handled]).to include(:current, :previous, :trend)
|
||||
end
|
||||
@@ -229,7 +229,7 @@ RSpec.describe Captain::AssistantStatsBuilder do
|
||||
end
|
||||
end
|
||||
|
||||
describe '#faq_stats' do
|
||||
describe '#metrics knowledge' do
|
||||
before do
|
||||
create_list(:captain_assistant_response, 3, assistant: assistant, account: account, status: :approved)
|
||||
create(:captain_assistant_response, assistant: assistant, account: account, status: :pending)
|
||||
@@ -237,7 +237,7 @@ RSpec.describe Captain::AssistantStatsBuilder do
|
||||
end
|
||||
|
||||
it 'returns approved, pending, document counts and coverage' do
|
||||
knowledge = described_class.new(assistant).faq_stats
|
||||
knowledge = described_class.new(assistant, '30').metrics[:knowledge]
|
||||
|
||||
expect(knowledge).to eq(approved: 3, pending: 1, documents: 2, coverage: 75)
|
||||
end
|
||||
@@ -245,7 +245,7 @@ RSpec.describe Captain::AssistantStatsBuilder do
|
||||
it 'reports zero coverage when there are no responses' do
|
||||
Captain::AssistantResponse.where(assistant: assistant).delete_all
|
||||
|
||||
knowledge = described_class.new(assistant).faq_stats
|
||||
knowledge = described_class.new(assistant, '30').metrics[:knowledge]
|
||||
|
||||
expect(knowledge[:coverage]).to eq(0)
|
||||
end
|
||||
|
||||
@@ -208,6 +208,18 @@ RSpec.describe 'WhatsApp Calls API', type: :request do
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
expect(response.parsed_body['error']).to eq(I18n.t('errors.whatsapp.calls.not_enabled'))
|
||||
end
|
||||
|
||||
it 'returns 403 before initiating the provider call when the inbox is disabled' do
|
||||
inbox.update!(active: false)
|
||||
allow(provider_service).to receive(:initiate_call)
|
||||
|
||||
post "/api/v1/accounts/#{account.id}/whatsapp_calls/initiate",
|
||||
params: { conversation_id: initiate_conversation.display_id, sdp_offer: 'sdp_offer' },
|
||||
headers: agent.create_new_auth_token
|
||||
|
||||
expect(response).to have_http_status(:forbidden)
|
||||
expect(provider_service).not_to have_received(:initiate_call)
|
||||
end
|
||||
end
|
||||
|
||||
describe 'POST /api/v1/accounts/:account_id/whatsapp_calls/:id/upload_recording' do
|
||||
|
||||
@@ -129,6 +129,23 @@ RSpec.describe 'Twilio::VoiceController', type: :request do
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(response.body).to include('<Reject')
|
||||
end
|
||||
|
||||
it 'rejects the inbound contact leg without building a call when the inbox is disabled' do
|
||||
inbox.update!(active: false)
|
||||
expect(Voice::InboundCallBuilder).not_to receive(:perform!)
|
||||
|
||||
expect do
|
||||
post "/twilio/voice/call/#{digits}", params: {
|
||||
'CallSid' => call_sid,
|
||||
'From' => from_number,
|
||||
'To' => to_number,
|
||||
'Direction' => 'inbound'
|
||||
}
|
||||
end.not_to change(Call, :count)
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(response.body).to include('<Reject')
|
||||
end
|
||||
end
|
||||
|
||||
describe 'POST /twilio/voice/status/:phone' do
|
||||
|
||||
@@ -12,7 +12,7 @@ RSpec.describe Captain::AssistantPolicy, type: :policy do
|
||||
let(:administrator_context) { { user: administrator, account: account, account_user: account.account_users.first } }
|
||||
let(:agent_context) { { user: agent, account: account, account_user: account.account_users.first } }
|
||||
|
||||
permissions :index?, :show?, :playground?, :metrics?, :faq_stats? do
|
||||
permissions :index?, :show?, :playground? do
|
||||
context 'when administrator' do
|
||||
it { expect(assistant_policy).to permit(administrator_context, assistant) }
|
||||
end
|
||||
|
||||
@@ -127,5 +127,20 @@ RSpec.describe Voice::OutboundCallBuilder do
|
||||
)
|
||||
end.to raise_error(ArgumentError, 'Agent required')
|
||||
end
|
||||
|
||||
it 'raises before initiating the provider call when the inbox is disabled' do
|
||||
inbox.update!(active: false)
|
||||
|
||||
expect do
|
||||
described_class.perform!(
|
||||
account: account,
|
||||
inbox: inbox,
|
||||
user: user,
|
||||
contact: contact
|
||||
)
|
||||
end.to raise_error(CustomExceptions::InboxDisabled)
|
||||
|
||||
expect(channel).not_to have_received(:initiate_call)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -44,6 +44,19 @@ describe Whatsapp::IncomingCallService do
|
||||
end
|
||||
end
|
||||
|
||||
context 'when the inbox is disabled' do
|
||||
it 'rejects the call with Meta without creating a Call or Conversation' do
|
||||
inbox.update!(active: false)
|
||||
provider_service = instance_double(Whatsapp::Providers::WhatsappCloudService, reject_call: true)
|
||||
allow(inbox.channel).to receive(:provider_service).and_return(provider_service)
|
||||
|
||||
params = call_payload(event: 'connect', session: { sdp: "v=0\r\n...sdp...", sdp_type: 'offer' })
|
||||
expect { described_class.new(inbox: inbox, params: params).perform }
|
||||
.to not_change(Call, :count).and not_change(Conversation, :count)
|
||||
expect(provider_service).to have_received(:reject_call).with(provider_call_id)
|
||||
end
|
||||
end
|
||||
|
||||
describe 'inbound connect' do
|
||||
let(:sdp_offer) { "v=0\r\n...sdp..." }
|
||||
let!(:agent) { create(:user, account: account) }
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user