Merge branch 'develop' into feat/v5-ui-redesign
This commit is contained in:
+1
-1
@@ -1 +1 @@
|
||||
4.9.1
|
||||
4.9.2
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
class V2::Reports::ChannelSummaryBuilder
|
||||
include DateRangeHelper
|
||||
|
||||
pattr_initialize [:account!, :params!]
|
||||
|
||||
def build
|
||||
conversations_by_channel_and_status.transform_values { |status_counts| build_channel_stats(status_counts) }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def conversations_by_channel_and_status
|
||||
account.conversations
|
||||
.joins(:inbox)
|
||||
.where(created_at: range)
|
||||
.group('inboxes.channel_type', 'conversations.status')
|
||||
.count
|
||||
.each_with_object({}) do |((channel_type, status), count), grouped|
|
||||
grouped[channel_type] ||= {}
|
||||
grouped[channel_type][status] = count
|
||||
end
|
||||
end
|
||||
|
||||
def build_channel_stats(status_counts)
|
||||
open_count = status_counts['open'] || 0
|
||||
resolved_count = status_counts['resolved'] || 0
|
||||
pending_count = status_counts['pending'] || 0
|
||||
snoozed_count = status_counts['snoozed'] || 0
|
||||
|
||||
{
|
||||
open: open_count,
|
||||
resolved: resolved_count,
|
||||
pending: pending_count,
|
||||
snoozed: snoozed_count,
|
||||
total: open_count + resolved_count + pending_count + snoozed_count
|
||||
}
|
||||
end
|
||||
end
|
||||
@@ -1,38 +1,27 @@
|
||||
class Api::V1::Accounts::InboxCsatTemplatesController < Api::V1::Accounts::BaseController
|
||||
DEFAULT_BUTTON_TEXT = 'Please rate us'.freeze
|
||||
DEFAULT_LANGUAGE = 'en'.freeze
|
||||
|
||||
before_action :fetch_inbox
|
||||
before_action :validate_whatsapp_channel
|
||||
|
||||
def show
|
||||
template = @inbox.csat_config&.dig('template')
|
||||
return render json: { template_exists: false } unless template
|
||||
service = CsatTemplateManagementService.new(@inbox)
|
||||
result = service.template_status
|
||||
|
||||
template_name = template['name'] || Whatsapp::CsatTemplateNameService.csat_template_name(@inbox.id)
|
||||
status_result = @inbox.channel.provider_service.get_template_status(template_name)
|
||||
|
||||
render_template_status_response(status_result, template_name)
|
||||
rescue StandardError => e
|
||||
Rails.logger.error "Error fetching CSAT template status: #{e.message}"
|
||||
render json: { error: e.message }, status: :internal_server_error
|
||||
if result[:service_error]
|
||||
render json: { error: result[:service_error] }, status: :internal_server_error
|
||||
else
|
||||
render json: result
|
||||
end
|
||||
end
|
||||
|
||||
def create
|
||||
template_params = extract_template_params
|
||||
return render_missing_message_error if template_params[:message].blank?
|
||||
|
||||
# Delete existing template even though we are using a new one.
|
||||
# We don't want too many templates in the business portfolio, but the create operation shouldn't fail if deletion fails.
|
||||
delete_existing_template_if_needed
|
||||
|
||||
result = create_template_via_provider(template_params)
|
||||
service = CsatTemplateManagementService.new(@inbox)
|
||||
result = service.create_template(template_params)
|
||||
render_template_creation_result(result)
|
||||
rescue ActionController::ParameterMissing
|
||||
render json: { error: 'Template parameters are required' }, status: :unprocessable_entity
|
||||
rescue StandardError => e
|
||||
Rails.logger.error "Error creating CSAT template: #{e.message}"
|
||||
render json: { error: 'Template creation failed' }, status: :internal_server_error
|
||||
end
|
||||
|
||||
private
|
||||
@@ -43,9 +32,9 @@ class Api::V1::Accounts::InboxCsatTemplatesController < Api::V1::Accounts::BaseC
|
||||
end
|
||||
|
||||
def validate_whatsapp_channel
|
||||
return if @inbox.whatsapp?
|
||||
return if @inbox.whatsapp? || @inbox.twilio_whatsapp?
|
||||
|
||||
render json: { error: 'CSAT template operations only available for WhatsApp channels' },
|
||||
render json: { error: 'CSAT template operations only available for WhatsApp and Twilio WhatsApp channels' },
|
||||
status: :bad_request
|
||||
end
|
||||
|
||||
@@ -57,35 +46,36 @@ class Api::V1::Accounts::InboxCsatTemplatesController < Api::V1::Accounts::BaseC
|
||||
render json: { error: 'Message is required' }, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
def create_template_via_provider(template_params)
|
||||
template_config = {
|
||||
message: template_params[:message],
|
||||
button_text: template_params[:button_text] || DEFAULT_BUTTON_TEXT,
|
||||
base_url: ENV.fetch('FRONTEND_URL', 'http://localhost:3000'),
|
||||
language: template_params[:language] || DEFAULT_LANGUAGE,
|
||||
template_name: Whatsapp::CsatTemplateNameService.csat_template_name(@inbox.id)
|
||||
}
|
||||
|
||||
@inbox.channel.provider_service.create_csat_template(template_config)
|
||||
end
|
||||
|
||||
def render_template_creation_result(result)
|
||||
if result[:success]
|
||||
render_successful_template_creation(result)
|
||||
elsif result[:service_error]
|
||||
render json: { error: result[:service_error] }, status: :internal_server_error
|
||||
else
|
||||
render_failed_template_creation(result)
|
||||
end
|
||||
end
|
||||
|
||||
def render_successful_template_creation(result)
|
||||
render json: {
|
||||
template: {
|
||||
name: result[:template_name],
|
||||
template_id: result[:template_id],
|
||||
status: 'PENDING',
|
||||
language: result[:language] || DEFAULT_LANGUAGE
|
||||
}
|
||||
}, status: :created
|
||||
if @inbox.twilio_whatsapp?
|
||||
render json: {
|
||||
template: {
|
||||
friendly_name: result[:friendly_name],
|
||||
content_sid: result[:content_sid],
|
||||
status: result[:status] || 'pending',
|
||||
language: result[:language] || 'en'
|
||||
}
|
||||
}, status: :created
|
||||
else
|
||||
render json: {
|
||||
template: {
|
||||
name: result[:template_name],
|
||||
template_id: result[:template_id],
|
||||
status: 'PENDING',
|
||||
language: result[:language] || 'en'
|
||||
}
|
||||
}, status: :created
|
||||
end
|
||||
end
|
||||
|
||||
def render_failed_template_creation(result)
|
||||
@@ -98,45 +88,6 @@ class Api::V1::Accounts::InboxCsatTemplatesController < Api::V1::Accounts::BaseC
|
||||
}, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
def delete_existing_template_if_needed
|
||||
template = @inbox.csat_config&.dig('template')
|
||||
return true if template.blank?
|
||||
|
||||
template_name = template['name']
|
||||
return true if template_name.blank?
|
||||
|
||||
template_status = @inbox.channel.provider_service.get_template_status(template_name)
|
||||
return true unless template_status[:success]
|
||||
|
||||
deletion_result = @inbox.channel.provider_service.delete_csat_template(template_name)
|
||||
if deletion_result[:success]
|
||||
Rails.logger.info "Deleted existing CSAT template '#{template_name}' for inbox #{@inbox.id}"
|
||||
true
|
||||
else
|
||||
Rails.logger.warn "Failed to delete existing CSAT template '#{template_name}' for inbox #{@inbox.id}: #{deletion_result[:response_body]}"
|
||||
false
|
||||
end
|
||||
rescue StandardError => e
|
||||
Rails.logger.error "Error during template deletion for inbox #{@inbox.id}: #{e.message}"
|
||||
false
|
||||
end
|
||||
|
||||
def render_template_status_response(status_result, template_name)
|
||||
if status_result[:success]
|
||||
render json: {
|
||||
template_exists: true,
|
||||
template_name: template_name,
|
||||
status: status_result[:template][:status],
|
||||
template_id: status_result[:template][:id]
|
||||
}
|
||||
else
|
||||
render json: {
|
||||
template_exists: false,
|
||||
error: 'Template not found'
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
def parse_whatsapp_error(response_body)
|
||||
return { user_message: nil, technical_details: nil } if response_body.blank?
|
||||
|
||||
|
||||
@@ -176,7 +176,7 @@ class Api::V1::Accounts::InboxesController < Api::V1::Accounts::BaseController
|
||||
:lock_to_single_conversation, :portal_id, :sender_name_type, :business_name,
|
||||
{ csat_config: [:display_type, :message, :button_text, :language,
|
||||
{ survey_rules: [:operator, { values: [] }],
|
||||
template: [:name, :template_id, :created_at, :language] }] }]
|
||||
template: [:name, :template_id, :friendly_name, :content_sid, :approval_sid, :created_at, :language, :status] }] }]
|
||||
end
|
||||
|
||||
def permitted_params(channel_attributes = [])
|
||||
|
||||
@@ -38,6 +38,11 @@ class Api::V2::Accounts::ReportsController < Api::V1::Accounts::BaseController
|
||||
generate_csv('teams_report', 'api/v2/accounts/reports/teams')
|
||||
end
|
||||
|
||||
def conversations_summary
|
||||
@report_data = generate_conversations_report
|
||||
generate_csv('conversations_summary_report', 'api/v2/accounts/reports/conversations_summary')
|
||||
end
|
||||
|
||||
def conversation_traffic
|
||||
@report_data = generate_conversations_heatmap_report
|
||||
timezone_offset = (params[:timezone_offset] || 0).to_f
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
class Api::V2::Accounts::SummaryReportsController < Api::V1::Accounts::BaseController
|
||||
before_action :check_authorization
|
||||
before_action :prepare_builder_params, only: [:agent, :team, :inbox, :label]
|
||||
before_action :prepare_builder_params, only: [:agent, :team, :inbox, :label, :channel]
|
||||
|
||||
def agent
|
||||
render_report_with(V2::Reports::AgentSummaryBuilder)
|
||||
@@ -18,6 +18,12 @@ class Api::V2::Accounts::SummaryReportsController < Api::V1::Accounts::BaseContr
|
||||
render_report_with(V2::Reports::LabelSummaryBuilder)
|
||||
end
|
||||
|
||||
def channel
|
||||
return render_could_not_create_error(I18n.t('errors.reports.date_range_too_long')) if date_range_too_long?
|
||||
|
||||
render_report_with(V2::Reports::ChannelSummaryBuilder)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def check_authorization
|
||||
@@ -40,4 +46,12 @@ class Api::V2::Accounts::SummaryReportsController < Api::V1::Accounts::BaseContr
|
||||
def permitted_params
|
||||
params.permit(:since, :until, :business_hours)
|
||||
end
|
||||
|
||||
def date_range_too_long?
|
||||
return false if permitted_params[:since].blank? || permitted_params[:until].blank?
|
||||
|
||||
since_time = Time.zone.at(permitted_params[:since].to_i)
|
||||
until_time = Time.zone.at(permitted_params[:until].to_i)
|
||||
(until_time - since_time) > 6.months
|
||||
end
|
||||
end
|
||||
|
||||
@@ -46,6 +46,13 @@ module Api::V2::Accounts::ReportsHelper
|
||||
end
|
||||
end
|
||||
|
||||
def generate_conversations_report
|
||||
builder = V2::Reports::Conversations::MetricBuilder.new(Current.account, build_params(type: :account))
|
||||
summary = builder.summary
|
||||
|
||||
[generate_conversation_report_metrics(summary)]
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def build_params(base_params)
|
||||
@@ -71,4 +78,16 @@ module Api::V2::Accounts::ReportsHelper
|
||||
report[:resolved_conversations_count]
|
||||
]
|
||||
end
|
||||
|
||||
def generate_conversation_report_metrics(summary)
|
||||
[
|
||||
summary[:conversations_count],
|
||||
summary[:incoming_messages_count],
|
||||
summary[:outgoing_messages_count],
|
||||
Reports::TimeFormatPresenter.new(summary[:avg_first_response_time]).format,
|
||||
Reports::TimeFormatPresenter.new(summary[:avg_resolution_time]).format,
|
||||
summary[:resolutions_count],
|
||||
Reports::TimeFormatPresenter.new(summary[:reply_time]).format
|
||||
]
|
||||
end
|
||||
end
|
||||
|
||||
@@ -61,6 +61,12 @@ class ReportsAPI extends ApiClient {
|
||||
});
|
||||
}
|
||||
|
||||
getConversationsSummaryReports({ from: since, to: until, businessHours }) {
|
||||
return axios.get(`${this.url}/conversations_summary`, {
|
||||
params: { since, until, business_hours: businessHours },
|
||||
});
|
||||
}
|
||||
|
||||
getConversationTrafficCSV({ daysBefore = 6 } = {}) {
|
||||
return axios.get(`${this.url}/conversation_traffic`, {
|
||||
params: { timezone_offset: getTimeOffset(), days_before: daysBefore },
|
||||
|
||||
@@ -5,6 +5,7 @@ import WootEditor from 'dashboard/components/widgets/WootWriter/Editor.vue';
|
||||
|
||||
const props = defineProps({
|
||||
modelValue: { type: String, default: '' },
|
||||
editorKey: { type: String, default: '' },
|
||||
label: { type: String, default: '' },
|
||||
placeholder: { type: String, default: '' },
|
||||
focusOnMount: { type: Boolean, default: false },
|
||||
@@ -96,6 +97,7 @@ watch(
|
||||
]"
|
||||
>
|
||||
<WootEditor
|
||||
:editor-id="editorKey"
|
||||
:model-value="modelValue"
|
||||
:placeholder="placeholder"
|
||||
:focus-on-mount="focusOnMount"
|
||||
@@ -152,6 +154,13 @@ watch(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.ProseMirror-menubar {
|
||||
width: fit-content !important;
|
||||
position: relative !important;
|
||||
top: unset !important;
|
||||
@apply ltr:left-[-0.188rem] rtl:right-[-0.188rem] !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+8
-1
@@ -44,6 +44,12 @@ const emit = defineEmits([
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const attachmentId = ref(0);
|
||||
const generateUid = () => {
|
||||
attachmentId.value += 1;
|
||||
return `attachment-${attachmentId.value}`;
|
||||
};
|
||||
|
||||
const uploadAttachment = ref(null);
|
||||
const isEmojiPickerOpen = ref(false);
|
||||
|
||||
@@ -176,7 +182,8 @@ const onPaste = e => {
|
||||
.filter(file => file.size > 0)
|
||||
.forEach(file => {
|
||||
const { name, type, size } = file;
|
||||
onFileUpload({ file, name, type, size });
|
||||
// Add unique ID for clipboard-pasted files
|
||||
onFileUpload({ file, name, type, size, id: generateUid() });
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
+79
-61
@@ -7,6 +7,7 @@ import {
|
||||
appendSignature,
|
||||
removeSignature,
|
||||
getEffectiveChannelType,
|
||||
stripUnsupportedMarkdown,
|
||||
} from 'dashboard/helper/editorHelper';
|
||||
import {
|
||||
buildContactableInboxesList,
|
||||
@@ -47,6 +48,8 @@ const emit = defineEmits([
|
||||
'createConversation',
|
||||
]);
|
||||
|
||||
const DEFAULT_FORMATTING = 'Context::Default';
|
||||
|
||||
const showContactsDropdown = ref(false);
|
||||
const showInboxesDropdown = ref(false);
|
||||
const showCcEmailsDropdown = ref(false);
|
||||
@@ -198,10 +201,22 @@ const setSelectedContact = async ({ value, action, ...rest }) => {
|
||||
showInboxesDropdown.value = true;
|
||||
};
|
||||
|
||||
const handleInboxAction = ({ value, action, ...rest }) => {
|
||||
const stripMessageFormatting = channelType => {
|
||||
if (!state.message || !channelType) return;
|
||||
|
||||
state.message = stripUnsupportedMarkdown(state.message, channelType, false);
|
||||
};
|
||||
|
||||
const handleInboxAction = ({ value, action, channelType, medium, ...rest }) => {
|
||||
v$.value.$reset();
|
||||
state.message = '';
|
||||
emit('updateTargetInbox', { ...rest });
|
||||
|
||||
// Strip unsupported formatting when changing the target inbox
|
||||
if (channelType) {
|
||||
const newChannelType = getEffectiveChannelType(channelType, medium);
|
||||
stripMessageFormatting(newChannelType);
|
||||
}
|
||||
|
||||
emit('updateTargetInbox', { ...rest, channelType, medium });
|
||||
showInboxesDropdown.value = false;
|
||||
state.attachedFiles = [];
|
||||
};
|
||||
@@ -221,7 +236,9 @@ const removeSignatureFromMessage = () => {
|
||||
const removeTargetInbox = value => {
|
||||
v$.value.$reset();
|
||||
removeSignatureFromMessage();
|
||||
state.message = '';
|
||||
|
||||
stripMessageFormatting(DEFAULT_FORMATTING);
|
||||
|
||||
emit('updateTargetInbox', value);
|
||||
state.attachedFiles = [];
|
||||
};
|
||||
@@ -324,67 +341,68 @@ const shouldShowMessageEditor = computed(() => {
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="w-[42rem] divide-y divide-n-strong overflow-visible transition-all duration-300 ease-in-out top-full justify-between flex flex-col bg-n-alpha-3 border border-n-strong shadow-sm backdrop-blur-[100px] rounded-xl min-w-0"
|
||||
class="w-[42rem] divide-y divide-n-strong overflow-visible transition-all duration-300 ease-in-out top-full flex flex-col bg-n-alpha-3 border border-n-strong shadow-sm backdrop-blur-[100px] rounded-xl min-w-0 max-h-[calc(100vh-8rem)]"
|
||||
>
|
||||
<ContactSelector
|
||||
:contacts="contacts"
|
||||
:selected-contact="selectedContact"
|
||||
:show-contacts-dropdown="showContactsDropdown"
|
||||
:is-loading="isLoading"
|
||||
:is-creating-contact="isCreatingContact"
|
||||
:contact-id="contactId"
|
||||
:contactable-inboxes-list="contactableInboxesList"
|
||||
:show-inboxes-dropdown="showInboxesDropdown"
|
||||
:has-errors="validationStates.isContactInvalid"
|
||||
@search-contacts="handleContactSearch"
|
||||
@set-selected-contact="setSelectedContact"
|
||||
@clear-selected-contact="clearSelectedContact"
|
||||
@update-dropdown="handleDropdownUpdate"
|
||||
/>
|
||||
<InboxEmptyState v-if="showNoInboxAlert" />
|
||||
<InboxSelector
|
||||
v-else
|
||||
:target-inbox="targetInbox"
|
||||
:selected-contact="selectedContact"
|
||||
:show-inboxes-dropdown="showInboxesDropdown"
|
||||
:contactable-inboxes-list="contactableInboxesList"
|
||||
:has-errors="validationStates.isInboxInvalid"
|
||||
@update-inbox="removeTargetInbox"
|
||||
@toggle-dropdown="showInboxesDropdown = $event"
|
||||
@handle-inbox-action="handleInboxAction"
|
||||
/>
|
||||
<div class="flex-1 overflow-y-auto divide-y divide-n-strong">
|
||||
<ContactSelector
|
||||
:contacts="contacts"
|
||||
:selected-contact="selectedContact"
|
||||
:show-contacts-dropdown="showContactsDropdown"
|
||||
:is-loading="isLoading"
|
||||
:is-creating-contact="isCreatingContact"
|
||||
:contact-id="contactId"
|
||||
:contactable-inboxes-list="contactableInboxesList"
|
||||
:show-inboxes-dropdown="showInboxesDropdown"
|
||||
:has-errors="validationStates.isContactInvalid"
|
||||
@search-contacts="handleContactSearch"
|
||||
@set-selected-contact="setSelectedContact"
|
||||
@clear-selected-contact="clearSelectedContact"
|
||||
@update-dropdown="handleDropdownUpdate"
|
||||
/>
|
||||
<InboxEmptyState v-if="showNoInboxAlert" />
|
||||
<InboxSelector
|
||||
v-else
|
||||
:target-inbox="targetInbox"
|
||||
:selected-contact="selectedContact"
|
||||
:show-inboxes-dropdown="showInboxesDropdown"
|
||||
:contactable-inboxes-list="contactableInboxesList"
|
||||
:has-errors="validationStates.isInboxInvalid"
|
||||
@update-inbox="removeTargetInbox"
|
||||
@toggle-dropdown="showInboxesDropdown = $event"
|
||||
@handle-inbox-action="handleInboxAction"
|
||||
/>
|
||||
|
||||
<EmailOptions
|
||||
v-if="inboxTypes.isEmail"
|
||||
v-model:cc-emails="state.ccEmails"
|
||||
v-model:bcc-emails="state.bccEmails"
|
||||
v-model:subject="state.subject"
|
||||
:contacts="contacts"
|
||||
:show-cc-emails-dropdown="showCcEmailsDropdown"
|
||||
:show-bcc-emails-dropdown="showBccEmailsDropdown"
|
||||
:is-loading="isLoading"
|
||||
:has-errors="validationStates.isSubjectInvalid"
|
||||
@search-cc-emails="searchCcEmails"
|
||||
@search-bcc-emails="searchBccEmails"
|
||||
@update-dropdown="handleDropdownUpdate"
|
||||
/>
|
||||
<EmailOptions
|
||||
v-if="inboxTypes.isEmail"
|
||||
v-model:cc-emails="state.ccEmails"
|
||||
v-model:bcc-emails="state.bccEmails"
|
||||
v-model:subject="state.subject"
|
||||
:contacts="contacts"
|
||||
:show-cc-emails-dropdown="showCcEmailsDropdown"
|
||||
:show-bcc-emails-dropdown="showBccEmailsDropdown"
|
||||
:is-loading="isLoading"
|
||||
:has-errors="validationStates.isSubjectInvalid"
|
||||
@search-cc-emails="searchCcEmails"
|
||||
@search-bcc-emails="searchBccEmails"
|
||||
@update-dropdown="handleDropdownUpdate"
|
||||
/>
|
||||
|
||||
<MessageEditor
|
||||
v-if="shouldShowMessageEditor"
|
||||
v-model="state.message"
|
||||
:message-signature="messageSignature"
|
||||
:send-with-signature="sendWithSignature"
|
||||
:has-errors="validationStates.isMessageInvalid"
|
||||
:has-attachments="state.attachedFiles.length > 0"
|
||||
:channel-type="inboxChannelType"
|
||||
:medium="targetInbox?.medium || ''"
|
||||
/>
|
||||
<MessageEditor
|
||||
v-if="shouldShowMessageEditor"
|
||||
v-model="state.message"
|
||||
:message-signature="messageSignature"
|
||||
:send-with-signature="sendWithSignature"
|
||||
:has-errors="validationStates.isMessageInvalid"
|
||||
:channel-type="inboxChannelType"
|
||||
:medium="targetInbox?.medium || ''"
|
||||
/>
|
||||
|
||||
<AttachmentPreviews
|
||||
v-if="state.attachedFiles.length > 0"
|
||||
:attachments="state.attachedFiles"
|
||||
@update:attachments="state.attachedFiles = $event"
|
||||
/>
|
||||
<AttachmentPreviews
|
||||
v-if="state.attachedFiles.length > 0"
|
||||
:attachments="state.attachedFiles"
|
||||
@update:attachments="state.attachedFiles = $event"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ActionButtons
|
||||
:attached-files="state.attachedFiles"
|
||||
|
||||
+1
-1
@@ -83,7 +83,7 @@ const targetInboxLabel = computed(() => {
|
||||
<DropdownMenu
|
||||
v-if="contactableInboxesList?.length > 0 && showInboxesDropdown"
|
||||
:menu-items="contactableInboxesList"
|
||||
class="ltr:left-0 rtl:right-0 z-[100] top-8 overflow-y-auto max-h-60 w-fit max-w-sm dark:!outline-n-slate-5"
|
||||
class="ltr:left-0 rtl:right-0 z-[100] top-8 overflow-y-auto max-h-56 w-fit max-w-sm dark:!outline-n-slate-5"
|
||||
@action="emit('handleInboxAction', $event)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
+3
-4
@@ -6,7 +6,6 @@ import Editor from 'dashboard/components-next/Editor/Editor.vue';
|
||||
|
||||
const props = defineProps({
|
||||
hasErrors: { type: Boolean, default: false },
|
||||
hasAttachments: { type: Boolean, default: false },
|
||||
sendWithSignature: { type: Boolean, default: false },
|
||||
messageSignature: { type: String, default: '' },
|
||||
channelType: { type: String, default: '' },
|
||||
@@ -24,14 +23,14 @@ const modelValue = defineModel({
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex-1 h-full" :class="[!hasAttachments && 'min-h-[200px]']">
|
||||
<div class="flex-1 h-full">
|
||||
<Editor
|
||||
:key="editorKey"
|
||||
v-model="modelValue"
|
||||
:editor-key="editorKey"
|
||||
:placeholder="
|
||||
t('COMPOSE_NEW_CONVERSATION.FORM.MESSAGE_EDITOR.PLACEHOLDER')
|
||||
"
|
||||
class="[&>div]:!border-transparent [&>div]:px-4 [&>div]:py-4 [&>div]:!bg-transparent h-full [&_.ProseMirror-woot-style]:!max-h-[200px]"
|
||||
class="[&>div]:!border-transparent [&>div]:px-4 [&>div]:py-4 [&>div]:!bg-transparent h-full [&_.ProseMirror-woot-style]:!max-h-[12.5rem] [&_.ProseMirror-woot-style]:!min-h-[10rem] [&_.ProseMirror-menubar]:!pt-0 [&_.mention--box]:-top-[7.5rem] [&_.mention--box]:bottom-[unset]"
|
||||
:class="
|
||||
hasErrors
|
||||
? '[&_.empty-node]:before:!text-n-ruby-9 [&_.empty-node]:dark:before:!text-n-ruby-9'
|
||||
|
||||
@@ -11,7 +11,6 @@ export const CONVERSATION_ATTRIBUTES = {
|
||||
CAMPAIGN_ID: 'campaign_id',
|
||||
LABELS: 'labels',
|
||||
BROWSER_LANGUAGE: 'browser_language',
|
||||
COUNTRY_CODE: 'country_code',
|
||||
REFERER: 'referer',
|
||||
CREATED_AT: 'created_at',
|
||||
LAST_ACTIVITY_AT: 'last_activity_at',
|
||||
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
buildAttributesFilterTypes,
|
||||
CONVERSATION_ATTRIBUTES,
|
||||
} from './helper/filterHelper';
|
||||
import countries from 'shared/constants/countries.js';
|
||||
import languages from 'dashboard/components/widgets/conversation/advancedFilterItems/languages.js';
|
||||
|
||||
/**
|
||||
@@ -218,17 +217,6 @@ export function useConversationFilterContext() {
|
||||
filterOperators: equalityOperators.value,
|
||||
attributeModel: 'additional',
|
||||
},
|
||||
{
|
||||
attributeKey: CONVERSATION_ATTRIBUTES.COUNTRY_CODE,
|
||||
value: CONVERSATION_ATTRIBUTES.COUNTRY_CODE,
|
||||
attributeName: t('FILTER.ATTRIBUTES.COUNTRY_NAME'),
|
||||
label: t('FILTER.ATTRIBUTES.COUNTRY_NAME'),
|
||||
inputType: 'searchSelect',
|
||||
options: countries,
|
||||
dataType: 'text',
|
||||
filterOperators: equalityOperators.value,
|
||||
attributeModel: 'additional',
|
||||
},
|
||||
{
|
||||
attributeKey: CONVERSATION_ATTRIBUTES.REFERER,
|
||||
value: CONVERSATION_ATTRIBUTES.REFERER,
|
||||
|
||||
@@ -230,7 +230,7 @@ const handleBlur = e => emit('blur', e);
|
||||
v-if="showDropdownMenu"
|
||||
:menu-items="filteredMenuItems"
|
||||
:is-searching="isLoading"
|
||||
class="ltr:left-0 rtl:right-0 z-[100] top-8 overflow-y-auto max-h-60 w-[inherit] max-w-md dark:!outline-n-slate-5"
|
||||
class="ltr:left-0 rtl:right-0 z-[100] top-8 overflow-y-auto max-h-56 w-[inherit] max-w-md dark:!outline-n-slate-5"
|
||||
@action="handleDropdownAction"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -78,14 +78,6 @@ const filterTypes = [
|
||||
filterOperators: OPERATOR_TYPES_1,
|
||||
attributeModel: 'additional',
|
||||
},
|
||||
{
|
||||
attributeKey: 'country_code',
|
||||
attributeI18nKey: 'COUNTRY_NAME',
|
||||
inputType: 'search_select',
|
||||
dataType: 'text',
|
||||
filterOperators: OPERATOR_TYPES_1,
|
||||
attributeModel: 'additional',
|
||||
},
|
||||
{
|
||||
attributeKey: 'referer',
|
||||
attributeI18nKey: 'REFERER_LINK',
|
||||
@@ -171,10 +163,6 @@ export const filterAttributeGroups = [
|
||||
key: 'browser_language',
|
||||
i18nKey: 'BROWSER_LANGUAGE',
|
||||
},
|
||||
{
|
||||
key: 'country_code',
|
||||
i18nKey: 'COUNTRY_NAME',
|
||||
},
|
||||
{
|
||||
key: 'referer',
|
||||
i18nKey: 'REFERER_LINK',
|
||||
|
||||
@@ -38,9 +38,14 @@ export function extractTextFromMarkdown(markdown) {
|
||||
*
|
||||
* @param {string} markdown - markdown text to process
|
||||
* @param {string} channelType - The channel type to check supported formatting
|
||||
* @param {boolean} cleanWhitespace - Whether to clean up extra whitespace and blank lines (default: true for signatures)
|
||||
* @returns {string} - The markdown with unsupported formatting removed
|
||||
*/
|
||||
export function stripUnsupportedSignatureMarkdown(markdown, channelType) {
|
||||
export function stripUnsupportedMarkdown(
|
||||
markdown,
|
||||
channelType,
|
||||
cleanWhitespace = true
|
||||
) {
|
||||
if (!markdown) return '';
|
||||
|
||||
const { marks = [], nodes = [] } = FORMATTING[channelType] || {};
|
||||
@@ -55,6 +60,9 @@ export function stripUnsupportedSignatureMarkdown(markdown, channelType) {
|
||||
);
|
||||
}, markdown);
|
||||
|
||||
if (!cleanWhitespace) return result;
|
||||
|
||||
// Clean whitespace for signatures
|
||||
return result
|
||||
.split('\n')
|
||||
.map(line => line.trim())
|
||||
@@ -155,7 +163,7 @@ export function getEffectiveChannelType(channelType, medium) {
|
||||
export function appendSignature(body, signature, channelType) {
|
||||
// Strip only unsupported formatting based on channel capabilities
|
||||
const preparedSignature = channelType
|
||||
? stripUnsupportedSignatureMarkdown(signature, channelType)
|
||||
? stripUnsupportedMarkdown(signature, channelType)
|
||||
: signature;
|
||||
const cleanedSignature = cleanSignature(preparedSignature);
|
||||
// if signature is already present, return body
|
||||
@@ -178,7 +186,7 @@ export function appendSignature(body, signature, channelType) {
|
||||
export function removeSignature(body, signature, channelType) {
|
||||
// Build unique list of signature variants to try
|
||||
const channelStripped = channelType
|
||||
? cleanSignature(stripUnsupportedSignatureMarkdown(signature, channelType))
|
||||
? cleanSignature(stripUnsupportedMarkdown(signature, channelType))
|
||||
: null;
|
||||
const signaturesToTry = [
|
||||
cleanSignature(signature),
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import DOMPurify from 'dompurify';
|
||||
|
||||
// Quote detection strategies
|
||||
const QUOTE_INDICATORS = [
|
||||
'.gmail_quote_container',
|
||||
@@ -29,7 +31,7 @@ export class EmailQuoteExtractor {
|
||||
static extractQuotes(htmlContent) {
|
||||
// Create a temporary DOM element to parse HTML
|
||||
const tempDiv = document.createElement('div');
|
||||
tempDiv.innerHTML = htmlContent;
|
||||
tempDiv.innerHTML = DOMPurify.sanitize(htmlContent);
|
||||
|
||||
// Remove elements matching class selectors
|
||||
QUOTE_INDICATORS.forEach(selector => {
|
||||
@@ -56,7 +58,7 @@ export class EmailQuoteExtractor {
|
||||
*/
|
||||
static hasQuotes(htmlContent) {
|
||||
const tempDiv = document.createElement('div');
|
||||
tempDiv.innerHTML = htmlContent;
|
||||
tempDiv.innerHTML = DOMPurify.sanitize(htmlContent);
|
||||
|
||||
// Check for class-based quotes
|
||||
// eslint-disable-next-line no-restricted-syntax
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { format, parseISO, isValid as isValidDate } from 'date-fns';
|
||||
import DOMPurify from 'dompurify';
|
||||
|
||||
/**
|
||||
* Extracts plain text from HTML content
|
||||
@@ -13,7 +14,7 @@ export const extractPlainTextFromHtml = html => {
|
||||
return html.replace(/<[^>]*>/g, ' ');
|
||||
}
|
||||
const tempDiv = document.createElement('div');
|
||||
tempDiv.innerHTML = html;
|
||||
tempDiv.innerHTML = DOMPurify.sanitize(html);
|
||||
return tempDiv.textContent || tempDiv.innerText || '';
|
||||
};
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
replaceSignature,
|
||||
cleanSignature,
|
||||
extractTextFromMarkdown,
|
||||
stripUnsupportedSignatureMarkdown,
|
||||
stripUnsupportedMarkdown,
|
||||
insertAtCursor,
|
||||
findNodeToInsertImage,
|
||||
setURLWithQueryAndSize,
|
||||
@@ -145,25 +145,19 @@ describe('appendSignature', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('stripUnsupportedSignatureMarkdown', () => {
|
||||
describe('stripUnsupportedMarkdown', () => {
|
||||
const richSignature =
|
||||
'**Bold** _italic_ [link](http://example.com) ';
|
||||
|
||||
it('keeps all formatting for Email channel (supports image, link, strong, em)', () => {
|
||||
const result = stripUnsupportedSignatureMarkdown(
|
||||
richSignature,
|
||||
'Channel::Email'
|
||||
);
|
||||
const result = stripUnsupportedMarkdown(richSignature, 'Channel::Email');
|
||||
expect(result).toContain('**Bold**');
|
||||
expect(result).toContain('_italic_');
|
||||
expect(result).toContain('[link](http://example.com)');
|
||||
expect(result).toContain('');
|
||||
});
|
||||
it('strips images but keeps bold/italic for Api channel', () => {
|
||||
const result = stripUnsupportedSignatureMarkdown(
|
||||
richSignature,
|
||||
'Channel::Api'
|
||||
);
|
||||
const result = stripUnsupportedMarkdown(richSignature, 'Channel::Api');
|
||||
expect(result).toContain('**Bold**');
|
||||
expect(result).toContain('_italic_');
|
||||
expect(result).toContain('link'); // link text kept
|
||||
@@ -171,20 +165,14 @@ describe('stripUnsupportedSignatureMarkdown', () => {
|
||||
expect(result).not.toContain('; // image removed
|
||||
});
|
||||
it('strips images but keeps bold/italic/link for Telegram channel', () => {
|
||||
const result = stripUnsupportedSignatureMarkdown(
|
||||
richSignature,
|
||||
'Channel::Telegram'
|
||||
);
|
||||
const result = stripUnsupportedMarkdown(richSignature, 'Channel::Telegram');
|
||||
expect(result).toContain('**Bold**');
|
||||
expect(result).toContain('_italic_');
|
||||
expect(result).toContain('[link](http://example.com)');
|
||||
expect(result).not.toContain(';
|
||||
});
|
||||
it('strips all formatting for SMS channel', () => {
|
||||
const result = stripUnsupportedSignatureMarkdown(
|
||||
richSignature,
|
||||
'Channel::Sms'
|
||||
);
|
||||
const result = stripUnsupportedMarkdown(richSignature, 'Channel::Sms');
|
||||
expect(result).toContain('Bold');
|
||||
expect(result).toContain('italic');
|
||||
expect(result).toContain('link');
|
||||
@@ -194,8 +182,52 @@ describe('stripUnsupportedSignatureMarkdown', () => {
|
||||
expect(result).not.toContain(';
|
||||
});
|
||||
it('returns empty string for empty input', () => {
|
||||
expect(stripUnsupportedSignatureMarkdown('', 'Channel::Api')).toBe('');
|
||||
expect(stripUnsupportedSignatureMarkdown(null, 'Channel::Api')).toBe('');
|
||||
expect(stripUnsupportedMarkdown('', 'Channel::Api')).toBe('');
|
||||
expect(stripUnsupportedMarkdown(null, 'Channel::Api')).toBe('');
|
||||
});
|
||||
|
||||
describe('with cleanWhitespace parameter', () => {
|
||||
const textWithWhitespace =
|
||||
'**Bold** text\n\nWith multiple\n\nLine breaks\n\n And spaces ';
|
||||
|
||||
it('cleans whitespace when cleanWhitespace=true (default)', () => {
|
||||
const result = stripUnsupportedMarkdown(
|
||||
textWithWhitespace,
|
||||
'Channel::Api',
|
||||
true
|
||||
);
|
||||
expect(result).toBe(
|
||||
'**Bold** text\nWith multiple\nLine breaks\nAnd spaces'
|
||||
);
|
||||
expect(result).not.toContain('\n\n');
|
||||
expect(result).not.toContain(' ');
|
||||
});
|
||||
|
||||
it('preserves whitespace when cleanWhitespace=false', () => {
|
||||
const result = stripUnsupportedMarkdown(
|
||||
textWithWhitespace,
|
||||
'Channel::Api',
|
||||
false
|
||||
);
|
||||
expect(result).toContain('\n\n');
|
||||
expect(result).toContain(' And spaces ');
|
||||
expect(result).toBe(
|
||||
'**Bold** text\n\nWith multiple\n\nLine breaks\n\n And spaces '
|
||||
);
|
||||
});
|
||||
|
||||
it('strips formatting but preserves whitespace for messages', () => {
|
||||
const messageWithFormatting = '**Bold**\n\n`code`\n\nNormal text';
|
||||
const result = stripUnsupportedMarkdown(
|
||||
messageWithFormatting,
|
||||
'Channel::Sms',
|
||||
false
|
||||
);
|
||||
expect(result).toBe('Bold\n\ncode\n\nNormal text');
|
||||
expect(result).toContain('\n\n');
|
||||
expect(result).not.toContain('**');
|
||||
expect(result).not.toContain('`');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -96,4 +96,58 @@ describe('EmailQuoteExtractor', () => {
|
||||
it('detects quotes for trailing blockquotes even when signatures follow text', () => {
|
||||
expect(EmailQuoteExtractor.hasQuotes(EMAIL_WITH_SIGNATURE)).toBe(true);
|
||||
});
|
||||
|
||||
describe('HTML sanitization', () => {
|
||||
it('removes onerror handlers from img tags in extractQuotes', () => {
|
||||
const maliciousHtml = '<p>Hello</p><img src="x" onerror="alert(1)">';
|
||||
const cleanedHtml = EmailQuoteExtractor.extractQuotes(maliciousHtml);
|
||||
|
||||
expect(cleanedHtml).not.toContain('onerror');
|
||||
expect(cleanedHtml).toContain('<p>Hello</p>');
|
||||
});
|
||||
|
||||
it('removes onerror handlers from img tags in hasQuotes', () => {
|
||||
const maliciousHtml = '<p>Hello</p><img src="x" onerror="alert(1)">';
|
||||
// Should not throw and should safely check for quotes
|
||||
const result = EmailQuoteExtractor.hasQuotes(maliciousHtml);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('removes script tags in extractQuotes', () => {
|
||||
const maliciousHtml =
|
||||
'<p>Content</p><script>alert("xss")</script><p>More</p>';
|
||||
const cleanedHtml = EmailQuoteExtractor.extractQuotes(maliciousHtml);
|
||||
|
||||
expect(cleanedHtml).not.toContain('<script');
|
||||
expect(cleanedHtml).not.toContain('alert');
|
||||
expect(cleanedHtml).toContain('<p>Content</p>');
|
||||
expect(cleanedHtml).toContain('<p>More</p>');
|
||||
});
|
||||
|
||||
it('removes onclick handlers in extractQuotes', () => {
|
||||
const maliciousHtml = '<p onclick="alert(1)">Click me</p>';
|
||||
const cleanedHtml = EmailQuoteExtractor.extractQuotes(maliciousHtml);
|
||||
|
||||
expect(cleanedHtml).not.toContain('onclick');
|
||||
expect(cleanedHtml).toContain('Click me');
|
||||
});
|
||||
|
||||
it('removes javascript: URLs in extractQuotes', () => {
|
||||
const maliciousHtml = '<a href="javascript:alert(1)">Link</a>';
|
||||
const cleanedHtml = EmailQuoteExtractor.extractQuotes(maliciousHtml);
|
||||
|
||||
// eslint-disable-next-line no-script-url
|
||||
expect(cleanedHtml).not.toContain('javascript:');
|
||||
expect(cleanedHtml).toContain('Link');
|
||||
});
|
||||
|
||||
it('removes encoded payloads with event handlers in extractQuotes', () => {
|
||||
const maliciousHtml =
|
||||
'<img src="x" id="PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg==" onerror="eval(atob(this.id))">';
|
||||
const cleanedHtml = EmailQuoteExtractor.extractQuotes(maliciousHtml);
|
||||
|
||||
expect(cleanedHtml).not.toContain('onerror');
|
||||
expect(cleanedHtml).not.toContain('eval');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -33,6 +33,26 @@ describe('quotedEmailHelper', () => {
|
||||
expect(result).toContain('Line 1');
|
||||
expect(result).toContain('Line 2');
|
||||
});
|
||||
|
||||
it('sanitizes onerror handlers from img tags', () => {
|
||||
const html = '<p>Hello</p><img src="x" onerror="alert(1)">';
|
||||
const result = extractPlainTextFromHtml(html);
|
||||
expect(result).toBe('Hello');
|
||||
});
|
||||
|
||||
it('sanitizes script tags', () => {
|
||||
const html = '<p>Safe</p><script>alert(1)</script><p>Content</p>';
|
||||
const result = extractPlainTextFromHtml(html);
|
||||
expect(result).toContain('Safe');
|
||||
expect(result).toContain('Content');
|
||||
expect(result).not.toContain('alert');
|
||||
});
|
||||
|
||||
it('sanitizes onclick handlers', () => {
|
||||
const html = '<p onclick="alert(1)">Click me</p>';
|
||||
const result = extractPlainTextFromHtml(html);
|
||||
expect(result).toBe('Click me');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getEmailSenderName', () => {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"HEADER": "Conversations",
|
||||
"LOADING_CHART": "Loading chart data...",
|
||||
"NO_ENOUGH_DATA": "We've not received enough data points to generate report, Please try again later.",
|
||||
"DOWNLOAD_AGENT_REPORTS": "Download agent reports",
|
||||
"DOWNLOAD_CONVERSATION_REPORTS": "Download conversation reports",
|
||||
"DATA_FETCHING_FAILED": "Failed to fetch data, please try again later.",
|
||||
"SUMMARY_FETCHING_FAILED": "Failed to fetch summary, please try again later.",
|
||||
"METRICS": {
|
||||
|
||||
@@ -370,7 +370,7 @@ onUnmounted(() => {
|
||||
/>
|
||||
</div>
|
||||
<section class="flex flex-col flex-grow w-full h-full overflow-hidden">
|
||||
<div class="w-full max-w-5xl mx-auto z-[60]">
|
||||
<div class="w-full max-w-5xl mx-auto z-30">
|
||||
<div class="flex flex-col w-full px-4">
|
||||
<SearchHeader
|
||||
v-model:filters="filters"
|
||||
|
||||
+59
-21
@@ -28,10 +28,15 @@ const { t } = useI18n();
|
||||
const store = useStore();
|
||||
const labels = useMapGetter('labels/getLabels');
|
||||
|
||||
const { isAWhatsAppCloudChannel: isWhatsAppChannel } = useInbox(
|
||||
const { isAWhatsAppChannel, isATwilioWhatsAppChannel } = useInbox(
|
||||
props.inbox?.id
|
||||
);
|
||||
|
||||
// Computed to check if it's any type of WhatsApp channel (Cloud or Twilio)
|
||||
const isAnyWhatsAppChannel = computed(
|
||||
() => isAWhatsAppChannel.value || isATwilioWhatsAppChannel.value
|
||||
);
|
||||
|
||||
const isUpdating = ref(false);
|
||||
const selectedLabelValues = ref([]);
|
||||
const currentLabel = ref('');
|
||||
@@ -116,7 +121,9 @@ const templateApprovalStatus = computed(() => {
|
||||
|
||||
// Handle existing template with status
|
||||
if (templateStatus.value?.template_exists && templateStatus.value.status) {
|
||||
return statusMap[templateStatus.value.status] || statusMap.PENDING;
|
||||
// Convert status to uppercase for consistency with statusMap keys
|
||||
const normalizedStatus = templateStatus.value.status.toUpperCase();
|
||||
return statusMap[normalizedStatus] || statusMap.PENDING;
|
||||
}
|
||||
|
||||
// Default case - no template exists
|
||||
@@ -155,7 +162,7 @@ const initializeState = () => {
|
||||
: [];
|
||||
|
||||
// Store original template values for change detection
|
||||
if (isWhatsAppChannel.value) {
|
||||
if (isAnyWhatsAppChannel.value) {
|
||||
originalTemplateValues.value = {
|
||||
message: state.message,
|
||||
templateButtonText: state.templateButtonText,
|
||||
@@ -165,7 +172,7 @@ const initializeState = () => {
|
||||
};
|
||||
|
||||
const checkTemplateStatus = async () => {
|
||||
if (!isWhatsAppChannel.value) return;
|
||||
if (!isAnyWhatsAppChannel.value) return;
|
||||
|
||||
try {
|
||||
templateLoading.value = true;
|
||||
@@ -195,7 +202,7 @@ const checkTemplateStatus = async () => {
|
||||
onMounted(() => {
|
||||
initializeState();
|
||||
if (!labels.value?.length) store.dispatch('labels/get');
|
||||
if (isWhatsAppChannel.value) checkTemplateStatus();
|
||||
if (isAnyWhatsAppChannel.value) checkTemplateStatus();
|
||||
});
|
||||
|
||||
watch(() => props.inbox, initializeState, { immediate: true });
|
||||
@@ -225,7 +232,7 @@ const removeLabel = label => {
|
||||
|
||||
// Check if template-related fields have changed
|
||||
const hasTemplateChanges = () => {
|
||||
if (!isWhatsAppChannel.value) return false;
|
||||
if (!isAnyWhatsAppChannel.value) return false;
|
||||
|
||||
const original = originalTemplateValues.value;
|
||||
return (
|
||||
@@ -254,10 +261,28 @@ const shouldCreateTemplate = () => {
|
||||
|
||||
// Build template config for saving
|
||||
const buildTemplateConfig = () => {
|
||||
if (!hasExistingTemplate()) return null;
|
||||
if (!hasExistingTemplate()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { template_name, template_id, template, status } =
|
||||
templateStatus.value || {};
|
||||
|
||||
if (isATwilioWhatsAppChannel.value) {
|
||||
// Twilio WhatsApp format - get from existing template config
|
||||
const existingTemplate = props.inbox?.csat_config?.template;
|
||||
|
||||
return existingTemplate
|
||||
? {
|
||||
friendly_name: existingTemplate.friendly_name,
|
||||
content_sid: existingTemplate.content_sid,
|
||||
language: existingTemplate.language || state.templateLanguage,
|
||||
status: existingTemplate.status || status,
|
||||
}
|
||||
: null;
|
||||
}
|
||||
|
||||
// WhatsApp Cloud format
|
||||
return {
|
||||
name: template_name,
|
||||
template_id,
|
||||
@@ -273,11 +298,11 @@ const updateInbox = async attributes => {
|
||||
...attributes,
|
||||
};
|
||||
|
||||
return store.dispatch('inboxes/updateInbox', payload);
|
||||
await store.dispatch('inboxes/updateInbox', payload);
|
||||
};
|
||||
|
||||
const createTemplate = async () => {
|
||||
if (!isWhatsAppChannel.value) return null;
|
||||
if (!isAnyWhatsAppChannel.value) return null;
|
||||
|
||||
const response = await store.dispatch('inboxes/createCSATTemplate', {
|
||||
inboxId: props.inbox.id,
|
||||
@@ -298,7 +323,7 @@ const performSave = async () => {
|
||||
|
||||
// For WhatsApp channels, create template first if needed
|
||||
if (
|
||||
isWhatsAppChannel.value &&
|
||||
isAnyWhatsAppChannel.value &&
|
||||
state.csatSurveyEnabled &&
|
||||
shouldCreateTemplate()
|
||||
) {
|
||||
@@ -326,13 +351,25 @@ const performSave = async () => {
|
||||
|
||||
// Use new template data if created, otherwise preserve existing template information
|
||||
if (newTemplateData) {
|
||||
csatConfig.template = {
|
||||
name: newTemplateData.name,
|
||||
template_id: newTemplateData.template_id,
|
||||
language: newTemplateData.language,
|
||||
status: newTemplateData.status,
|
||||
created_at: new Date().toISOString(),
|
||||
};
|
||||
if (isATwilioWhatsAppChannel.value) {
|
||||
// Twilio WhatsApp template format
|
||||
csatConfig.template = {
|
||||
friendly_name: newTemplateData.friendly_name,
|
||||
content_sid: newTemplateData.content_sid,
|
||||
language: newTemplateData.language,
|
||||
status: newTemplateData.status,
|
||||
created_at: new Date().toISOString(),
|
||||
};
|
||||
} else {
|
||||
// WhatsApp Cloud template format
|
||||
csatConfig.template = {
|
||||
name: newTemplateData.name,
|
||||
template_id: newTemplateData.template_id,
|
||||
language: newTemplateData.language,
|
||||
status: newTemplateData.status,
|
||||
created_at: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
} else {
|
||||
const templateConfig = buildTemplateConfig();
|
||||
if (templateConfig) {
|
||||
@@ -356,8 +393,9 @@ const performSave = async () => {
|
||||
|
||||
const saveSettings = async () => {
|
||||
// Check if we need to show confirmation dialog for WhatsApp template changes
|
||||
// This applies to both WhatsApp Cloud and Twilio WhatsApp channels
|
||||
if (
|
||||
isWhatsAppChannel.value &&
|
||||
isAnyWhatsAppChannel.value &&
|
||||
state.csatSurveyEnabled &&
|
||||
hasExistingTemplate() &&
|
||||
hasTemplateChanges()
|
||||
@@ -390,7 +428,7 @@ const handleConfirmTemplateUpdate = async () => {
|
||||
<div class="grid gap-5">
|
||||
<!-- Show display type only for non-WhatsApp channels -->
|
||||
<WithLabel
|
||||
v-if="!isWhatsAppChannel"
|
||||
v-if="!isAnyWhatsAppChannel"
|
||||
:label="$t('INBOX_MGMT.CSAT.DISPLAY_TYPE.LABEL')"
|
||||
name="display_type"
|
||||
>
|
||||
@@ -400,7 +438,7 @@ const handleConfirmTemplateUpdate = async () => {
|
||||
/>
|
||||
</WithLabel>
|
||||
|
||||
<template v-if="isWhatsAppChannel">
|
||||
<template v-if="isAnyWhatsAppChannel">
|
||||
<div
|
||||
class="flex flex-col gap-4 justify-between w-full lg:flex-row lg:gap-6"
|
||||
>
|
||||
@@ -536,7 +574,7 @@ const handleConfirmTemplateUpdate = async () => {
|
||||
</WithLabel>
|
||||
<p class="text-sm italic text-n-slate-11">
|
||||
{{
|
||||
isWhatsAppChannel
|
||||
isAnyWhatsAppChannel
|
||||
? $t('INBOX_MGMT.CSAT.WHATSAPP_NOTE')
|
||||
: $t('INBOX_MGMT.CSAT.NOTE')
|
||||
}}
|
||||
|
||||
@@ -76,14 +76,14 @@ export default {
|
||||
businessHours,
|
||||
};
|
||||
},
|
||||
downloadAgentReports() {
|
||||
downloadConversationReports() {
|
||||
const { from, to } = this;
|
||||
const fileName = generateFileName({
|
||||
type: 'agent',
|
||||
type: 'conversation',
|
||||
to,
|
||||
businessHours: this.businessHours,
|
||||
});
|
||||
this.$store.dispatch('downloadAgentReports', {
|
||||
this.$store.dispatch('downloadConversationsSummaryReports', {
|
||||
from,
|
||||
to,
|
||||
fileName,
|
||||
@@ -109,10 +109,10 @@ export default {
|
||||
<template>
|
||||
<ReportHeader :header-title="$t('REPORT.HEADER')">
|
||||
<V4Button
|
||||
:label="$t('REPORT.DOWNLOAD_AGENT_REPORTS')"
|
||||
:label="$t('REPORT.DOWNLOAD_CONVERSATION_REPORTS')"
|
||||
icon="i-ph-download-simple"
|
||||
size="sm"
|
||||
@click="downloadAgentReports"
|
||||
@click="downloadConversationReports"
|
||||
/>
|
||||
</ReportHeader>
|
||||
<div class="flex flex-col gap-3">
|
||||
|
||||
@@ -78,7 +78,6 @@ const getValueFromConversation = (conversation, attributeKey) => {
|
||||
case 'team_id':
|
||||
return conversation.meta?.team?.id;
|
||||
case 'browser_language':
|
||||
case 'country_code':
|
||||
case 'referer':
|
||||
return conversation.additional_attributes?.[attributeKey];
|
||||
default:
|
||||
|
||||
@@ -234,6 +234,19 @@ export const actions = {
|
||||
console.error(error);
|
||||
});
|
||||
},
|
||||
downloadConversationsSummaryReports(_, reportObj) {
|
||||
return Report.getConversationsSummaryReports(reportObj)
|
||||
.then(response => {
|
||||
downloadCsvFile(reportObj.fileName, response.data);
|
||||
AnalyticsHelper.track(REPORTS_EVENTS.DOWNLOAD_REPORT, {
|
||||
reportType: 'conversations_summary',
|
||||
businessHours: reportObj?.businessHours,
|
||||
});
|
||||
})
|
||||
.catch(error => {
|
||||
console.error(error);
|
||||
});
|
||||
},
|
||||
downloadLabelReports(_, reportObj) {
|
||||
return Report.getLabelReports(reportObj)
|
||||
.then(response => {
|
||||
|
||||
@@ -201,4 +201,24 @@ describe('#actions', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('#downloadConversationsSummaryReports', () => {
|
||||
it('open CSV download prompt if API is success', async () => {
|
||||
const data = `Conversations,Messages received,Messages sent,Avg first response time,Avg resolution time,Resolution count,Avg customer waiting time
|
||||
217,323,623,23 hours 22 minutes,179 days 18 hours,30,48 days 4 hours`;
|
||||
axios.get.mockResolvedValue({ data });
|
||||
const param = {
|
||||
from: 1631039400,
|
||||
to: 1635013800,
|
||||
fileName: 'conversations-summary-report-24-10-2021.csv',
|
||||
};
|
||||
actions.downloadConversationsSummaryReports(1, param);
|
||||
await flushPromises();
|
||||
|
||||
expect(DownloadHelper.downloadCsvFile).toBeCalledWith(
|
||||
param.fileName,
|
||||
data
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -82,6 +82,7 @@ export default {
|
||||
const { websiteToken, locale, widgetColor } = window.chatwootWebChannel;
|
||||
this.setLocale(locale);
|
||||
this.setWidgetColor(widgetColor);
|
||||
this.setWidgetColorVariable(widgetColor);
|
||||
setHeader(window.authToken);
|
||||
if (this.isIFrame) {
|
||||
this.registerListeners();
|
||||
@@ -114,6 +115,14 @@ export default {
|
||||
'resetCampaign',
|
||||
]),
|
||||
...mapActions('agent', ['fetchAvailableAgents']),
|
||||
setWidgetColorVariable(widgetColor) {
|
||||
if (widgetColor) {
|
||||
document.documentElement.style.setProperty(
|
||||
'--widget-color',
|
||||
widgetColor
|
||||
);
|
||||
}
|
||||
},
|
||||
scrollConversationToBottom() {
|
||||
const container = this.$el.querySelector('.conversation-wrap');
|
||||
container.scrollTop = container.scrollHeight;
|
||||
|
||||
@@ -130,7 +130,7 @@ export default {
|
||||
<div
|
||||
class="items-center flex ltr:pl-3 rtl:pr-3 ltr:pr-2 rtl:pl-2 rounded-[7px] transition-all duration-200 bg-n-background !shadow-[0_0_0_1px,0_0_2px_3px]"
|
||||
:class="{
|
||||
'!shadow-n-brand dark:!shadow-n-brand': isFocused,
|
||||
'!shadow-[var(--widget-color,#2781f6)]': isFocused,
|
||||
'!shadow-n-strong dark:!shadow-n-strong': !isFocused,
|
||||
}"
|
||||
@keydown.esc="hideEmojiPicker"
|
||||
|
||||
@@ -158,6 +158,10 @@ class Inbox < ApplicationRecord
|
||||
channel_type == 'Channel::Whatsapp'
|
||||
end
|
||||
|
||||
def twilio_whatsapp?
|
||||
channel_type == 'Channel::TwilioSms' && channel.medium == 'whatsapp'
|
||||
end
|
||||
|
||||
def assignable_agents
|
||||
(account.users.where(id: members.select(:user_id)) + account.administrators).uniq
|
||||
end
|
||||
|
||||
@@ -6,6 +6,8 @@ class CsatSurveyService
|
||||
|
||||
if whatsapp_channel? && template_available_and_approved?
|
||||
send_whatsapp_template_survey
|
||||
elsif inbox.twilio_whatsapp? && twilio_template_available_and_approved?
|
||||
send_twilio_whatsapp_template_survey
|
||||
elsif within_messaging_window?
|
||||
::MessageTemplates::Template::CsatSurvey.new(conversation: conversation).perform
|
||||
else
|
||||
@@ -45,7 +47,7 @@ class CsatSurveyService
|
||||
template_config = inbox.csat_config&.dig('template')
|
||||
return false unless template_config
|
||||
|
||||
template_name = template_config['name'] || Whatsapp::CsatTemplateNameService.csat_template_name(inbox.id)
|
||||
template_name = template_config['name'] || CsatTemplateNameService.csat_template_name(inbox.id)
|
||||
|
||||
status_result = inbox.channel.provider_service.get_template_status(template_name)
|
||||
|
||||
@@ -55,9 +57,25 @@ class CsatSurveyService
|
||||
false
|
||||
end
|
||||
|
||||
def twilio_template_available_and_approved?
|
||||
template_config = inbox.csat_config&.dig('template')
|
||||
return false unless template_config
|
||||
|
||||
content_sid = template_config['content_sid']
|
||||
return false unless content_sid
|
||||
|
||||
template_service = Twilio::CsatTemplateService.new(inbox.channel)
|
||||
status_result = template_service.get_template_status(content_sid)
|
||||
|
||||
status_result[:success] && status_result[:template][:status] == 'approved'
|
||||
rescue StandardError => e
|
||||
Rails.logger.error "Error checking Twilio CSAT template status: #{e.message}"
|
||||
false
|
||||
end
|
||||
|
||||
def send_whatsapp_template_survey
|
||||
template_config = inbox.csat_config&.dig('template')
|
||||
template_name = template_config['name'] || Whatsapp::CsatTemplateNameService.csat_template_name(inbox.id)
|
||||
template_name = template_config['name'] || CsatTemplateNameService.csat_template_name(inbox.id)
|
||||
|
||||
phone_number = conversation.contact_inbox.source_id
|
||||
template_info = build_template_info(template_name, template_config)
|
||||
@@ -95,6 +113,26 @@ class CsatSurveyService
|
||||
)
|
||||
end
|
||||
|
||||
def send_twilio_whatsapp_template_survey
|
||||
template_config = inbox.csat_config&.dig('template')
|
||||
content_sid = template_config['content_sid']
|
||||
|
||||
phone_number = conversation.contact_inbox.source_id
|
||||
content_variables = { '1' => conversation.uuid }
|
||||
message = build_csat_message
|
||||
|
||||
send_service = Twilio::SendOnTwilioService.new(message: message)
|
||||
result = send_service.send_csat_template_message(
|
||||
phone_number: phone_number,
|
||||
content_sid: content_sid,
|
||||
content_variables: content_variables
|
||||
)
|
||||
|
||||
message.update!(source_id: result[:message_id]) if result[:success] && result[:message_id].present?
|
||||
rescue StandardError => e
|
||||
Rails.logger.error "Error sending Twilio WhatsApp CSAT template for conversation #{conversation.id}: #{e.message}"
|
||||
end
|
||||
|
||||
def create_csat_not_sent_activity_message
|
||||
content = I18n.t('conversations.activity.csat.not_sent_due_to_messaging_window')
|
||||
activity_message_params = {
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
class CsatTemplateManagementService
|
||||
DEFAULT_BUTTON_TEXT = 'Please rate us'.freeze
|
||||
DEFAULT_LANGUAGE = 'en'.freeze
|
||||
|
||||
def initialize(inbox)
|
||||
@inbox = inbox
|
||||
end
|
||||
|
||||
def template_status
|
||||
template = @inbox.csat_config&.dig('template')
|
||||
return { template_exists: false } unless template
|
||||
|
||||
if @inbox.twilio_whatsapp?
|
||||
get_twilio_template_status(template)
|
||||
else
|
||||
get_whatsapp_template_status(template)
|
||||
end
|
||||
rescue StandardError => e
|
||||
Rails.logger.error "Error fetching CSAT template status: #{e.message}"
|
||||
{ service_error: e.message }
|
||||
end
|
||||
|
||||
def create_template(template_params)
|
||||
validate_template_params!(template_params)
|
||||
|
||||
delete_existing_template_if_needed
|
||||
|
||||
result = create_template_via_provider(template_params)
|
||||
update_inbox_csat_config(result) if result[:success]
|
||||
|
||||
result
|
||||
rescue StandardError => e
|
||||
Rails.logger.error "Error creating CSAT template: #{e.message}"
|
||||
{ success: false, service_error: 'Template creation failed' }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def validate_template_params!(template_params)
|
||||
raise ActionController::ParameterMissing, 'message' if template_params[:message].blank?
|
||||
end
|
||||
|
||||
def create_template_via_provider(template_params)
|
||||
if @inbox.twilio_whatsapp?
|
||||
create_twilio_template(template_params)
|
||||
else
|
||||
create_whatsapp_template(template_params)
|
||||
end
|
||||
end
|
||||
|
||||
def create_twilio_template(template_params)
|
||||
template_config = build_template_config(template_params)
|
||||
template_service = Twilio::CsatTemplateService.new(@inbox.channel)
|
||||
template_service.create_template(template_config)
|
||||
end
|
||||
|
||||
def create_whatsapp_template(template_params)
|
||||
template_config = build_template_config(template_params)
|
||||
Whatsapp::CsatTemplateService.new(@inbox.channel).create_template(template_config)
|
||||
end
|
||||
|
||||
def build_template_config(template_params)
|
||||
{
|
||||
message: template_params[:message],
|
||||
button_text: template_params[:button_text] || DEFAULT_BUTTON_TEXT,
|
||||
base_url: ENV.fetch('FRONTEND_URL', 'http://localhost:3000'),
|
||||
language: template_params[:language] || DEFAULT_LANGUAGE,
|
||||
template_name: CsatTemplateNameService.csat_template_name(@inbox.id)
|
||||
}
|
||||
end
|
||||
|
||||
def update_inbox_csat_config(result)
|
||||
current_config = @inbox.csat_config || {}
|
||||
template_data = build_template_data_from_result(result)
|
||||
updated_config = current_config.merge('template' => template_data)
|
||||
@inbox.update!(csat_config: updated_config)
|
||||
end
|
||||
|
||||
def build_template_data_from_result(result)
|
||||
if @inbox.twilio_whatsapp?
|
||||
build_twilio_template_data(result)
|
||||
else
|
||||
build_whatsapp_cloud_template_data(result)
|
||||
end
|
||||
end
|
||||
|
||||
def build_twilio_template_data(result)
|
||||
{
|
||||
'friendly_name' => result[:friendly_name],
|
||||
'content_sid' => result[:content_sid],
|
||||
'approval_sid' => result[:approval_sid],
|
||||
'language' => result[:language],
|
||||
'status' => result[:whatsapp_status] || result[:status],
|
||||
'created_at' => Time.current.iso8601
|
||||
}.compact
|
||||
end
|
||||
|
||||
def build_whatsapp_cloud_template_data(result)
|
||||
{
|
||||
'name' => result[:template_name],
|
||||
'template_id' => result[:template_id],
|
||||
'language' => result[:language],
|
||||
'created_at' => Time.current.iso8601
|
||||
}
|
||||
end
|
||||
|
||||
def get_twilio_template_status(template)
|
||||
content_sid = template['content_sid']
|
||||
return { template_exists: false } unless content_sid
|
||||
|
||||
template_service = Twilio::CsatTemplateService.new(@inbox.channel)
|
||||
status_result = template_service.get_template_status(content_sid)
|
||||
|
||||
if status_result[:success]
|
||||
{
|
||||
template_exists: true,
|
||||
friendly_name: template['friendly_name'],
|
||||
content_sid: template['content_sid'],
|
||||
status: status_result[:template][:status],
|
||||
language: template['language']
|
||||
}
|
||||
else
|
||||
{
|
||||
template_exists: false,
|
||||
error: 'Template not found'
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
def get_whatsapp_template_status(template)
|
||||
template_name = template['name'] || CsatTemplateNameService.csat_template_name(@inbox.id)
|
||||
status_result = Whatsapp::CsatTemplateService.new(@inbox.channel).get_template_status(template_name)
|
||||
|
||||
if status_result[:success]
|
||||
{
|
||||
template_exists: true,
|
||||
template_name: template_name,
|
||||
status: status_result[:template][:status],
|
||||
template_id: status_result[:template][:id]
|
||||
}
|
||||
else
|
||||
{
|
||||
template_exists: false,
|
||||
error: 'Template not found'
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
def delete_existing_template_if_needed
|
||||
template = @inbox.csat_config&.dig('template')
|
||||
return true if template.blank?
|
||||
|
||||
if @inbox.twilio_whatsapp?
|
||||
delete_existing_twilio_template(template)
|
||||
else
|
||||
delete_existing_whatsapp_template(template)
|
||||
end
|
||||
rescue StandardError => e
|
||||
Rails.logger.error "Error during template deletion for inbox #{@inbox.id}: #{e.message}"
|
||||
false
|
||||
end
|
||||
|
||||
def delete_existing_twilio_template(template)
|
||||
content_sid = template['content_sid']
|
||||
return true if content_sid.blank?
|
||||
|
||||
template_service = Twilio::CsatTemplateService.new(@inbox.channel)
|
||||
deletion_result = template_service.delete_template(nil, content_sid)
|
||||
|
||||
if deletion_result[:success]
|
||||
Rails.logger.info "Deleted existing Twilio CSAT template '#{content_sid}' for inbox #{@inbox.id}"
|
||||
true
|
||||
else
|
||||
Rails.logger.warn "Failed to delete existing Twilio CSAT template '#{content_sid}' for inbox #{@inbox.id}: #{deletion_result[:response_body]}"
|
||||
false
|
||||
end
|
||||
end
|
||||
|
||||
def delete_existing_whatsapp_template(template)
|
||||
template_name = template['name']
|
||||
return true if template_name.blank?
|
||||
|
||||
csat_template_service = Whatsapp::CsatTemplateService.new(@inbox.channel)
|
||||
template_status = csat_template_service.get_template_status(template_name)
|
||||
return true unless template_status[:success]
|
||||
|
||||
deletion_result = csat_template_service.delete_template(template_name)
|
||||
if deletion_result[:success]
|
||||
Rails.logger.info "Deleted existing CSAT template '#{template_name}' for inbox #{@inbox.id}"
|
||||
true
|
||||
else
|
||||
Rails.logger.warn "Failed to delete existing CSAT template '#{template_name}' for inbox #{@inbox.id}: #{deletion_result[:response_body]}"
|
||||
false
|
||||
end
|
||||
end
|
||||
end
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
class Whatsapp::CsatTemplateNameService
|
||||
class CsatTemplateNameService
|
||||
CSAT_BASE_NAME = 'customer_satisfaction_survey'.freeze
|
||||
|
||||
# Generates template names like: customer_satisfaction_survey_{inbox_id}_{version_number}
|
||||
@@ -0,0 +1,68 @@
|
||||
class Twilio::CsatTemplateApiClient
|
||||
def initialize(twilio_channel)
|
||||
@twilio_channel = twilio_channel
|
||||
end
|
||||
|
||||
def create_template(request_body)
|
||||
HTTParty.post(
|
||||
"#{api_base_path}/v1/Content",
|
||||
headers: api_headers,
|
||||
body: request_body.to_json
|
||||
)
|
||||
end
|
||||
|
||||
def submit_for_approval(approval_url, template_name, category)
|
||||
request_body = {
|
||||
name: template_name,
|
||||
category: category
|
||||
}
|
||||
|
||||
HTTParty.post(
|
||||
approval_url,
|
||||
headers: api_headers,
|
||||
body: request_body.to_json
|
||||
)
|
||||
end
|
||||
|
||||
def delete_template(content_sid)
|
||||
HTTParty.delete(
|
||||
"#{api_base_path}/v1/Content/#{content_sid}",
|
||||
headers: api_headers
|
||||
)
|
||||
end
|
||||
|
||||
def fetch_template(content_sid)
|
||||
HTTParty.get(
|
||||
"#{api_base_path}/v1/Content/#{content_sid}",
|
||||
headers: api_headers
|
||||
)
|
||||
end
|
||||
|
||||
def fetch_approval_status(content_sid)
|
||||
HTTParty.get(
|
||||
"#{api_base_path}/v1/Content/#{content_sid}/ApprovalRequests",
|
||||
headers: api_headers
|
||||
)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def api_headers
|
||||
{
|
||||
'Authorization' => "Basic #{encoded_credentials}",
|
||||
'Content-Type' => 'application/json'
|
||||
}
|
||||
end
|
||||
|
||||
def encoded_credentials
|
||||
if @twilio_channel.api_key_sid.present?
|
||||
Base64.strict_encode64("#{@twilio_channel.api_key_sid}:#{@twilio_channel.auth_token}")
|
||||
else
|
||||
Base64.strict_encode64("#{@twilio_channel.account_sid}:#{@twilio_channel.auth_token}")
|
||||
end
|
||||
end
|
||||
|
||||
def api_base_path
|
||||
'https://content.twilio.com'
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,204 @@
|
||||
class Twilio::CsatTemplateService
|
||||
DEFAULT_BUTTON_TEXT = 'Please rate us'.freeze
|
||||
DEFAULT_LANGUAGE = 'en'.freeze
|
||||
TEMPLATE_CATEGORY = 'UTILITY'.freeze
|
||||
TEMPLATE_STATUS_PENDING = 'PENDING'.freeze
|
||||
TEMPLATE_CONTENT_TYPE = 'twilio/call-to-action'.freeze
|
||||
|
||||
def initialize(twilio_channel)
|
||||
@twilio_channel = twilio_channel
|
||||
@api_client = Twilio::CsatTemplateApiClient.new(twilio_channel)
|
||||
end
|
||||
|
||||
def create_template(template_config)
|
||||
base_name = template_config[:template_name]
|
||||
template_name = generate_template_name(base_name)
|
||||
template_config_with_name = template_config.merge(template_name: template_name)
|
||||
|
||||
request_body = build_template_request_body(template_config_with_name)
|
||||
|
||||
# Step 1: Create template
|
||||
response = @api_client.create_template(request_body)
|
||||
|
||||
return process_template_creation_response(response, template_config_with_name) unless response.success? && response['sid']
|
||||
|
||||
# Step 2: Submit for WhatsApp approval using the approval_create URL
|
||||
approval_url = response.dig('links', 'approval_create')
|
||||
|
||||
if approval_url.present?
|
||||
approval_response = submit_for_whatsapp_approval(approval_url, template_config_with_name[:template_name])
|
||||
process_approval_response(approval_response, response, template_config_with_name)
|
||||
else
|
||||
Rails.logger.warn 'No approval_create URL provided in template creation response'
|
||||
# Fallback if no approval URL provided
|
||||
process_template_creation_response(response, template_config_with_name)
|
||||
end
|
||||
end
|
||||
|
||||
def delete_template(_template_name = nil, content_sid = nil)
|
||||
content_sid ||= current_template_sid_from_config
|
||||
return { success: false, error: 'No template to delete' } unless content_sid
|
||||
|
||||
response = @api_client.delete_template(content_sid)
|
||||
{ success: response.success?, response_body: response.body }
|
||||
end
|
||||
|
||||
def get_template_status(content_sid)
|
||||
return { success: false, error: 'No content SID provided' } unless content_sid
|
||||
|
||||
template_response = fetch_template_details(content_sid)
|
||||
return template_response unless template_response[:success]
|
||||
|
||||
approval_response = fetch_approval_status(content_sid)
|
||||
build_template_status_response(content_sid, template_response[:data], approval_response)
|
||||
rescue StandardError => e
|
||||
Rails.logger.error "Error fetching Twilio template status: #{e.message}"
|
||||
{ success: false, error: e.message }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def fetch_template_details(content_sid)
|
||||
response = @api_client.fetch_template(content_sid)
|
||||
|
||||
if response.success?
|
||||
{ success: true, data: response }
|
||||
else
|
||||
Rails.logger.error "Failed to get template details: #{response.code} - #{response.body}"
|
||||
{ success: false, error: 'Template not found' }
|
||||
end
|
||||
end
|
||||
|
||||
def fetch_approval_status(content_sid)
|
||||
@api_client.fetch_approval_status(content_sid)
|
||||
end
|
||||
|
||||
def build_template_status_response(content_sid, template_response, approval_response)
|
||||
if approval_response.success? && approval_response['whatsapp']
|
||||
build_approved_template_response(content_sid, template_response, approval_response['whatsapp'])
|
||||
else
|
||||
build_pending_template_response(content_sid, template_response)
|
||||
end
|
||||
end
|
||||
|
||||
def build_approved_template_response(content_sid, template_response, whatsapp_data)
|
||||
{
|
||||
success: true,
|
||||
template: {
|
||||
content_sid: content_sid,
|
||||
friendly_name: whatsapp_data['name'] || template_response['friendly_name'],
|
||||
status: whatsapp_data['status'] || 'pending',
|
||||
language: template_response['language'] || 'en'
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
def build_pending_template_response(content_sid, template_response)
|
||||
{
|
||||
success: true,
|
||||
template: {
|
||||
content_sid: content_sid,
|
||||
friendly_name: template_response['friendly_name'],
|
||||
status: 'pending',
|
||||
language: template_response['language'] || 'en'
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
def generate_template_name(base_name)
|
||||
current_template_name = current_template_name_from_config
|
||||
CsatTemplateNameService.generate_next_template_name(base_name, @twilio_channel.inbox.id, current_template_name)
|
||||
end
|
||||
|
||||
def current_template_name_from_config
|
||||
@twilio_channel.inbox.csat_config&.dig('template', 'friendly_name')
|
||||
end
|
||||
|
||||
def current_template_sid_from_config
|
||||
@twilio_channel.inbox.csat_config&.dig('template', 'content_sid')
|
||||
end
|
||||
|
||||
def template_exists_in_config?
|
||||
content_sid = current_template_sid_from_config
|
||||
friendly_name = current_template_name_from_config
|
||||
|
||||
content_sid.present? && friendly_name.present?
|
||||
end
|
||||
|
||||
def build_template_request_body(template_config)
|
||||
{
|
||||
friendly_name: template_config[:template_name],
|
||||
language: template_config[:language] || DEFAULT_LANGUAGE,
|
||||
variables: {
|
||||
'1' => '12345' # Example conversation UUID
|
||||
},
|
||||
types: {
|
||||
TEMPLATE_CONTENT_TYPE => {
|
||||
body: template_config[:message],
|
||||
actions: [
|
||||
{
|
||||
type: 'URL',
|
||||
title: template_config[:button_text] || DEFAULT_BUTTON_TEXT,
|
||||
url: "#{template_config[:base_url]}/survey/responses/{{1}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
def submit_for_whatsapp_approval(approval_url, template_name)
|
||||
@api_client.submit_for_approval(approval_url, template_name, TEMPLATE_CATEGORY)
|
||||
end
|
||||
|
||||
def process_template_creation_response(response, template_config = {})
|
||||
if response.success? && response['sid']
|
||||
{
|
||||
success: true,
|
||||
content_sid: response['sid'],
|
||||
friendly_name: template_config[:template_name],
|
||||
language: template_config[:language] || DEFAULT_LANGUAGE,
|
||||
status: TEMPLATE_STATUS_PENDING
|
||||
}
|
||||
else
|
||||
Rails.logger.error "Twilio template creation failed: #{response.code} - #{response.body}"
|
||||
{
|
||||
success: false,
|
||||
error: 'Template creation failed',
|
||||
response_body: response.body
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
def process_approval_response(approval_response, creation_response, template_config)
|
||||
if approval_response.success?
|
||||
build_successful_approval_response(approval_response, creation_response, template_config)
|
||||
else
|
||||
build_failed_approval_response(approval_response, creation_response, template_config)
|
||||
end
|
||||
end
|
||||
|
||||
def build_successful_approval_response(approval_response, creation_response, template_config)
|
||||
approval_data = approval_response.parsed_response
|
||||
{
|
||||
success: true,
|
||||
content_sid: creation_response['sid'],
|
||||
friendly_name: template_config[:template_name],
|
||||
language: template_config[:language] || DEFAULT_LANGUAGE,
|
||||
status: TEMPLATE_STATUS_PENDING,
|
||||
approval_sid: approval_data['sid'],
|
||||
whatsapp_status: approval_data.dig('whatsapp', 'status') || TEMPLATE_STATUS_PENDING
|
||||
}
|
||||
end
|
||||
|
||||
def build_failed_approval_response(approval_response, creation_response, template_config)
|
||||
Rails.logger.error "Twilio template approval submission failed: #{approval_response.code} - #{approval_response.body}"
|
||||
{
|
||||
success: true,
|
||||
content_sid: creation_response['sid'],
|
||||
friendly_name: template_config[:template_name],
|
||||
language: template_config[:language] || DEFAULT_LANGUAGE,
|
||||
status: 'created'
|
||||
}
|
||||
end
|
||||
end
|
||||
@@ -1,4 +1,24 @@
|
||||
class Twilio::SendOnTwilioService < Base::SendOnChannelService
|
||||
def send_csat_template_message(phone_number:, content_sid:, content_variables: {})
|
||||
send_params = {
|
||||
to: phone_number,
|
||||
content_sid: content_sid
|
||||
}
|
||||
|
||||
send_params[:content_variables] = content_variables.to_json if content_variables.present?
|
||||
send_params[:status_callback] = channel.send(:twilio_delivery_status_index_url) if channel.respond_to?(:twilio_delivery_status_index_url, true)
|
||||
|
||||
# Add messaging service or from number
|
||||
send_params = send_params.merge(channel.send(:send_message_from))
|
||||
|
||||
twilio_message = channel.send(:client).messages.create(**send_params)
|
||||
|
||||
{ success: true, message_id: twilio_message.sid }
|
||||
rescue Twilio::REST::TwilioError, Twilio::REST::RestError => e
|
||||
Rails.logger.error "Failed to send Twilio template message: #{e.message}"
|
||||
{ success: false, error: e.message }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def channel_class
|
||||
|
||||
@@ -19,7 +19,7 @@ class Whatsapp::CsatTemplateService
|
||||
end
|
||||
|
||||
def delete_template(template_name = nil)
|
||||
template_name ||= Whatsapp::CsatTemplateNameService.csat_template_name(@whatsapp_channel.inbox.id)
|
||||
template_name ||= CsatTemplateNameService.csat_template_name(@whatsapp_channel.inbox.id)
|
||||
response = HTTParty.delete(
|
||||
"#{business_account_path}/message_templates?name=#{template_name}",
|
||||
headers: api_headers
|
||||
@@ -51,7 +51,7 @@ class Whatsapp::CsatTemplateService
|
||||
|
||||
def generate_template_name(base_name)
|
||||
current_template_name = current_template_name_from_config
|
||||
Whatsapp::CsatTemplateNameService.generate_next_template_name(base_name, @whatsapp_channel.inbox.id, current_template_name)
|
||||
CsatTemplateNameService.generate_next_template_name(base_name, @whatsapp_channel.inbox.id, current_template_name)
|
||||
end
|
||||
|
||||
def current_template_name_from_config
|
||||
|
||||
@@ -67,7 +67,7 @@ class Whatsapp::Providers::WhatsappCloudService < Whatsapp::Providers::BaseServi
|
||||
end
|
||||
|
||||
def delete_csat_template(template_name = nil)
|
||||
template_name ||= Whatsapp::CsatTemplateNameService.csat_template_name(whatsapp_channel.inbox.id)
|
||||
template_name ||= CsatTemplateNameService.csat_template_name(whatsapp_channel.inbox.id)
|
||||
csat_template_service.delete_template(template_name)
|
||||
end
|
||||
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
<%= CSVSafe.generate_line [I18n.t('reports.period', since: Date.strptime(params[:since], '%s'), until: Date.strptime(params[:until], '%s'))] %>
|
||||
|
||||
<% headers = [
|
||||
I18n.t('reports.conversation_csv.conversations_count'),
|
||||
I18n.t('reports.conversation_csv.incoming_messages_count'),
|
||||
I18n.t('reports.conversation_csv.outgoing_messages_count'),
|
||||
I18n.t('reports.conversation_csv.avg_first_response_time'),
|
||||
I18n.t('reports.conversation_csv.avg_resolution_time'),
|
||||
I18n.t('reports.conversation_csv.resolution_count'),
|
||||
I18n.t('reports.conversation_csv.avg_customer_waiting_time')
|
||||
]
|
||||
%>
|
||||
<%= CSVSafe.generate_line headers -%>
|
||||
<% @report_data.each do |row| %>
|
||||
<%= CSVSafe.generate_line row -%>
|
||||
<% end %>
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
shared: &shared
|
||||
version: '4.9.1'
|
||||
version: '4.9.2'
|
||||
|
||||
development:
|
||||
<<: *shared
|
||||
|
||||
@@ -134,6 +134,8 @@ en:
|
||||
plan_not_eligible: Top-ups are only available for paid plans. Please upgrade your plan first.
|
||||
stripe_customer_not_configured: Stripe customer not configured
|
||||
no_payment_method: No payment methods found. Please add a payment method before making a purchase.
|
||||
reports:
|
||||
date_range_too_long: Date range cannot exceed 6 months
|
||||
profile:
|
||||
mfa:
|
||||
enabled: MFA enabled successfully
|
||||
@@ -170,6 +172,14 @@ en:
|
||||
avg_resolution_time: Avg resolution time
|
||||
resolution_count: Resolution Count
|
||||
avg_customer_waiting_time: Avg customer waiting time
|
||||
conversation_csv:
|
||||
conversations_count: Conversations
|
||||
incoming_messages_count: Messages received
|
||||
outgoing_messages_count: Messages sent
|
||||
avg_first_response_time: Avg first response time
|
||||
avg_resolution_time: Avg resolution time
|
||||
resolution_count: Resolution count
|
||||
avg_customer_waiting_time: Avg customer waiting time
|
||||
conversation_traffic_csv:
|
||||
timezone: Timezone
|
||||
sla_csv:
|
||||
|
||||
@@ -418,6 +418,7 @@ Rails.application.routes.draw do
|
||||
get :team
|
||||
get :inbox
|
||||
get :label
|
||||
get :channel
|
||||
end
|
||||
end
|
||||
resources :reports, only: [:index] do
|
||||
@@ -429,6 +430,7 @@ Rails.application.routes.draw do
|
||||
get :labels
|
||||
get :teams
|
||||
get :conversations
|
||||
get :conversations_summary
|
||||
get :conversation_traffic
|
||||
get :bot_metrics
|
||||
end
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
class RemoveCountryCodeFromConversationFilters < ActiveRecord::Migration[7.1]
|
||||
def up
|
||||
CustomFilter.conversation
|
||||
.where('query::text LIKE ?', '%country_code%')
|
||||
.find_each do |custom_filter|
|
||||
query = custom_filter.query || {}
|
||||
payload = query['payload']
|
||||
|
||||
next unless payload.is_a?(Array)
|
||||
|
||||
updated_payload = payload.reject do |filter|
|
||||
filter.is_a?(Hash) && filter['attribute_key'] == 'country_code'
|
||||
end
|
||||
|
||||
next if updated_payload == payload
|
||||
|
||||
if updated_payload.empty?
|
||||
custom_filter.delete
|
||||
next
|
||||
end
|
||||
|
||||
# rubocop:disable Rails/SkipsModelValidations
|
||||
# we will skip model validation, since we don't want any callbacks running
|
||||
custom_filter.update_columns(query: query.merge('payload' => updated_payload))
|
||||
# rubocop:enable Rails/SkipsModelValidations
|
||||
end
|
||||
end
|
||||
|
||||
def down
|
||||
# no-op: removed filters cannot be restored reliably
|
||||
end
|
||||
end
|
||||
+1
-1
@@ -10,7 +10,7 @@
|
||||
#
|
||||
# It's strongly recommended that you check this file into your version control system.
|
||||
|
||||
ActiveRecord::Schema[7.1].define(version: 2025_12_29_081141) do
|
||||
ActiveRecord::Schema[7.1].define(version: 2026_01_12_092041) do
|
||||
# These extensions should be enabled to support this database
|
||||
enable_extension "pg_stat_statements"
|
||||
enable_extension "pg_trgm"
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
module Captain::ChatGenerationRecorder
|
||||
extend ActiveSupport::Concern
|
||||
include Integrations::LlmInstrumentationConstants
|
||||
|
||||
private
|
||||
|
||||
def record_llm_generation(chat, message)
|
||||
return unless valid_llm_message?(message)
|
||||
|
||||
# Create a generation span with model and token info for Langfuse cost calculation.
|
||||
# Note: span duration will be near-zero since we create and end it immediately, but token counts are what Langfuse uses for cost calculation.
|
||||
tracer.in_span("llm.captain.#{feature_name}.generation") do |span|
|
||||
set_generation_span_attributes(span, chat, message)
|
||||
end
|
||||
rescue StandardError => e
|
||||
Rails.logger.warn "Failed to record LLM generation: #{e.message}"
|
||||
end
|
||||
|
||||
# Skip non-LLM messages (e.g., tool results that RubyLLM processes internally).
|
||||
# Check for assistant role rather than token presence - some providers/streaming modes
|
||||
# may not return token counts, but we still want to capture the generation for evals.
|
||||
def valid_llm_message?(message)
|
||||
message.respond_to?(:role) && message.role.to_s == 'assistant'
|
||||
end
|
||||
|
||||
def set_generation_span_attributes(span, chat, message)
|
||||
generation_attributes(chat, message).each do |key, value|
|
||||
span.set_attribute(key, value) if value
|
||||
end
|
||||
end
|
||||
|
||||
def generation_attributes(chat, message)
|
||||
{
|
||||
ATTR_GEN_AI_PROVIDER => determine_provider(model),
|
||||
ATTR_GEN_AI_REQUEST_MODEL => model,
|
||||
ATTR_GEN_AI_REQUEST_TEMPERATURE => temperature,
|
||||
ATTR_GEN_AI_USAGE_INPUT_TOKENS => message.input_tokens,
|
||||
ATTR_GEN_AI_USAGE_OUTPUT_TOKENS => message.respond_to?(:output_tokens) ? message.output_tokens : nil,
|
||||
ATTR_LANGFUSE_OBSERVATION_INPUT => format_input_messages(chat),
|
||||
ATTR_LANGFUSE_OBSERVATION_OUTPUT => message.respond_to?(:content) ? message.content.to_s : nil
|
||||
}
|
||||
end
|
||||
|
||||
def format_input_messages(chat)
|
||||
chat.messages[0...-1].map { |m| { role: m.role.to_s, content: m.content.to_s } }.to_json
|
||||
end
|
||||
end
|
||||
@@ -1,6 +1,7 @@
|
||||
module Captain::ChatHelper
|
||||
include Integrations::LlmInstrumentation
|
||||
include Captain::ChatResponseHelper
|
||||
include Captain::ChatGenerationRecorder
|
||||
|
||||
def request_chat_completion
|
||||
log_chat_completion_request
|
||||
@@ -42,8 +43,11 @@ module Captain::ChatHelper
|
||||
end
|
||||
|
||||
def setup_event_handlers(chat)
|
||||
chat.on_new_message { start_llm_turn_span(instrumentation_params(chat)) }
|
||||
chat.on_end_message { |message| end_llm_turn_span(message) }
|
||||
# NOTE: We only use on_end_message to record the generation with token counts.
|
||||
# RubyLLM callbacks fire after chunks arrive, not around the API call, so
|
||||
# span timing won't reflect actual API latency. But Langfuse calculates costs
|
||||
# from model + token counts, so this is sufficient for cost tracking.
|
||||
chat.on_end_message { |message| record_llm_generation(chat, message) }
|
||||
chat.on_tool_call { |tool_call| handle_tool_call(tool_call) }
|
||||
chat.on_tool_result { |result| handle_tool_result(result) }
|
||||
|
||||
|
||||
@@ -86,12 +86,6 @@ conversations:
|
||||
filter_operators:
|
||||
- "equal_to"
|
||||
- "not_equal_to"
|
||||
country_code:
|
||||
attribute_type: "additional_attributes"
|
||||
data_type: "text"
|
||||
filter_operators:
|
||||
- "equal_to"
|
||||
- "not_equal_to"
|
||||
referer:
|
||||
attribute_type: "additional_attributes"
|
||||
data_type: "link"
|
||||
|
||||
@@ -30,7 +30,6 @@ module Integrations::LlmInstrumentation
|
||||
result = nil
|
||||
executed = false
|
||||
tracer.in_span(params[:span_name]) do |span|
|
||||
set_request_attributes(span, params)
|
||||
set_metadata_attributes(span, params)
|
||||
|
||||
# By default, the input and output of a trace are set from the root observation
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@chatwoot/chatwoot",
|
||||
"version": "4.9.1",
|
||||
"version": "4.9.2",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"eslint": "eslint app/**/*.{js,vue}",
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe V2::Reports::ChannelSummaryBuilder do
|
||||
let!(:account) { create(:account) }
|
||||
let!(:web_widget_inbox) { create(:inbox, account: account) }
|
||||
let!(:email_inbox) { create(:inbox, :with_email, account: account) }
|
||||
let(:params) do
|
||||
{
|
||||
since: 1.week.ago.beginning_of_day,
|
||||
until: Time.current.end_of_day
|
||||
}
|
||||
end
|
||||
let(:builder) { described_class.new(account: account, params: params) }
|
||||
|
||||
describe '#build' do
|
||||
subject(:report) { builder.build }
|
||||
|
||||
context 'when there are conversations with different statuses across channels' do
|
||||
before do
|
||||
# Web widget conversations
|
||||
create(:conversation, account: account, inbox: web_widget_inbox, status: :open, created_at: 2.days.ago)
|
||||
create(:conversation, account: account, inbox: web_widget_inbox, status: :open, created_at: 3.days.ago)
|
||||
create(:conversation, account: account, inbox: web_widget_inbox, status: :resolved, created_at: 2.days.ago)
|
||||
create(:conversation, account: account, inbox: web_widget_inbox, status: :pending, created_at: 1.day.ago)
|
||||
create(:conversation, account: account, inbox: web_widget_inbox, status: :snoozed, created_at: 1.day.ago)
|
||||
|
||||
# Email conversations
|
||||
create(:conversation, account: account, inbox: email_inbox, status: :open, created_at: 2.days.ago)
|
||||
create(:conversation, account: account, inbox: email_inbox, status: :resolved, created_at: 1.day.ago)
|
||||
create(:conversation, account: account, inbox: email_inbox, status: :resolved, created_at: 3.days.ago)
|
||||
end
|
||||
|
||||
it 'returns correct counts grouped by channel type' do
|
||||
expect(report['Channel::WebWidget']).to eq(
|
||||
open: 2,
|
||||
resolved: 1,
|
||||
pending: 1,
|
||||
snoozed: 1,
|
||||
total: 5
|
||||
)
|
||||
|
||||
expect(report['Channel::Email']).to eq(
|
||||
open: 1,
|
||||
resolved: 2,
|
||||
pending: 0,
|
||||
snoozed: 0,
|
||||
total: 3
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when conversations are outside the date range' do
|
||||
before do
|
||||
create(:conversation, account: account, inbox: web_widget_inbox, status: :open, created_at: 2.days.ago)
|
||||
create(:conversation, account: account, inbox: web_widget_inbox, status: :resolved, created_at: 2.weeks.ago)
|
||||
end
|
||||
|
||||
it 'only includes conversations within the date range' do
|
||||
expect(report['Channel::WebWidget']).to eq(
|
||||
open: 1,
|
||||
resolved: 0,
|
||||
pending: 0,
|
||||
snoozed: 0,
|
||||
total: 1
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when there are no conversations' do
|
||||
it 'returns an empty hash' do
|
||||
expect(report).to eq({})
|
||||
end
|
||||
end
|
||||
|
||||
context 'when a channel has only one status type' do
|
||||
before do
|
||||
create(:conversation, account: account, inbox: web_widget_inbox, status: :resolved, created_at: 1.day.ago)
|
||||
create(:conversation, account: account, inbox: web_widget_inbox, status: :resolved, created_at: 2.days.ago)
|
||||
end
|
||||
|
||||
it 'returns zeros for other statuses' do
|
||||
expect(report['Channel::WebWidget']).to eq(
|
||||
open: 0,
|
||||
resolved: 2,
|
||||
pending: 0,
|
||||
snoozed: 0,
|
||||
total: 2
|
||||
)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -10,19 +10,14 @@ RSpec.describe 'API Base', type: :request do
|
||||
let!(:conversation) { create(:conversation, account: account) }
|
||||
|
||||
it 'sets Current attributes for the request and then returns the response' do
|
||||
# expect Current.account_user is set to the admin's account_user
|
||||
allow(Current).to receive(:user=).and_call_original
|
||||
allow(Current).to receive(:account=).and_call_original
|
||||
allow(Current).to receive(:account_user=).and_call_original
|
||||
|
||||
# This test verifies that Current.user, Current.account, and Current.account_user
|
||||
# are properly set during request processing. We verify this indirectly:
|
||||
# - A successful response proves Current.account_user was set (required for authorization)
|
||||
# - The correct conversation data proves Current.account was set (scopes the query)
|
||||
get "/api/v1/accounts/#{account.id}/conversations/#{conversation.display_id}",
|
||||
headers: { api_access_token: admin.access_token.token },
|
||||
as: :json
|
||||
|
||||
expect(Current).to have_received(:user=).with(admin).at_least(:once)
|
||||
expect(Current).to have_received(:account=).with(account).at_least(:once)
|
||||
expect(Current).to have_received(:account_user=).with(admin.account_users.first).at_least(:once)
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
expect(response.parsed_body['id']).to eq(conversation.display_id)
|
||||
end
|
||||
|
||||
@@ -9,11 +9,11 @@ RSpec.describe Api::V1::Accounts::InboxCsatTemplatesController, type: :request d
|
||||
end
|
||||
let(:whatsapp_inbox) { create(:inbox, channel: whatsapp_channel, account: account) }
|
||||
let(:web_widget_inbox) { create(:inbox, account: account) }
|
||||
let(:mock_service) { instance_double(Whatsapp::Providers::WhatsappCloudService) }
|
||||
let(:mock_service) { instance_double(Whatsapp::CsatTemplateService) }
|
||||
|
||||
before do
|
||||
create(:inbox_member, user: agent, inbox: whatsapp_inbox)
|
||||
allow(Whatsapp::Providers::WhatsappCloudService).to receive(:new).and_return(mock_service)
|
||||
allow(Whatsapp::CsatTemplateService).to receive(:new).and_return(mock_service)
|
||||
end
|
||||
|
||||
describe 'GET /api/v1/accounts/{account.id}/inboxes/{inbox.id}/csat_template' do
|
||||
@@ -32,7 +32,7 @@ RSpec.describe Api::V1::Accounts::InboxCsatTemplatesController, type: :request d
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:bad_request)
|
||||
expect(response.parsed_body['error']).to eq('CSAT template operations only available for WhatsApp channels')
|
||||
expect(response.parsed_body['error']).to eq('CSAT template operations only available for WhatsApp and Twilio WhatsApp channels')
|
||||
end
|
||||
end
|
||||
|
||||
@@ -161,7 +161,7 @@ RSpec.describe Api::V1::Accounts::InboxCsatTemplatesController, type: :request d
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:bad_request)
|
||||
expect(response.parsed_body['error']).to eq('CSAT template operations only available for WhatsApp channels')
|
||||
expect(response.parsed_body['error']).to eq('CSAT template operations only available for WhatsApp and Twilio WhatsApp channels')
|
||||
end
|
||||
end
|
||||
|
||||
@@ -195,11 +195,11 @@ RSpec.describe Api::V1::Accounts::InboxCsatTemplatesController, type: :request d
|
||||
|
||||
it 'creates template successfully' do
|
||||
allow(mock_service).to receive(:get_template_status).and_return({ success: false })
|
||||
allow(mock_service).to receive(:create_csat_template).and_return({
|
||||
success: true,
|
||||
template_name: "customer_satisfaction_survey_#{whatsapp_inbox.id}",
|
||||
template_id: '987654321'
|
||||
})
|
||||
allow(mock_service).to receive(:create_template).and_return({
|
||||
success: true,
|
||||
template_name: "customer_satisfaction_survey_#{whatsapp_inbox.id}",
|
||||
template_id: '987654321'
|
||||
})
|
||||
|
||||
post "/api/v1/accounts/#{account.id}/inboxes/#{whatsapp_inbox.id}/csat_template",
|
||||
headers: admin.create_new_auth_token,
|
||||
@@ -222,7 +222,7 @@ RSpec.describe Api::V1::Accounts::InboxCsatTemplatesController, type: :request d
|
||||
}
|
||||
|
||||
allow(mock_service).to receive(:get_template_status).and_return({ success: false })
|
||||
expect(mock_service).to receive(:create_csat_template) do |config|
|
||||
expect(mock_service).to receive(:create_template) do |config|
|
||||
expect(config[:button_text]).to eq('Please rate us')
|
||||
expect(config[:language]).to eq('en')
|
||||
expect(config[:template_name]).to eq("customer_satisfaction_survey_#{whatsapp_inbox.id}")
|
||||
@@ -249,11 +249,11 @@ RSpec.describe Api::V1::Accounts::InboxCsatTemplatesController, type: :request d
|
||||
}
|
||||
|
||||
allow(mock_service).to receive(:get_template_status).and_return({ success: false })
|
||||
allow(mock_service).to receive(:create_csat_template).and_return({
|
||||
success: false,
|
||||
error: 'Template creation failed',
|
||||
response_body: whatsapp_error_response.to_json
|
||||
})
|
||||
allow(mock_service).to receive(:create_template).and_return({
|
||||
success: false,
|
||||
error: 'Template creation failed',
|
||||
response_body: whatsapp_error_response.to_json
|
||||
})
|
||||
|
||||
post "/api/v1/accounts/#{account.id}/inboxes/#{whatsapp_inbox.id}/csat_template",
|
||||
headers: admin.create_new_auth_token,
|
||||
@@ -272,11 +272,11 @@ RSpec.describe Api::V1::Accounts::InboxCsatTemplatesController, type: :request d
|
||||
|
||||
it 'handles generic API errors' do
|
||||
allow(mock_service).to receive(:get_template_status).and_return({ success: false })
|
||||
allow(mock_service).to receive(:create_csat_template).and_return({
|
||||
success: false,
|
||||
error: 'Network timeout',
|
||||
response_body: nil
|
||||
})
|
||||
allow(mock_service).to receive(:create_template).and_return({
|
||||
success: false,
|
||||
error: 'Network timeout',
|
||||
response_body: nil
|
||||
})
|
||||
|
||||
post "/api/v1/accounts/#{account.id}/inboxes/#{whatsapp_inbox.id}/csat_template",
|
||||
headers: admin.create_new_auth_token,
|
||||
@@ -289,7 +289,7 @@ RSpec.describe Api::V1::Accounts::InboxCsatTemplatesController, type: :request d
|
||||
|
||||
it 'handles unexpected service errors' do
|
||||
allow(mock_service).to receive(:get_template_status).and_return({ success: false })
|
||||
allow(mock_service).to receive(:create_csat_template)
|
||||
allow(mock_service).to receive(:create_template)
|
||||
.and_raise(StandardError, 'Unexpected error')
|
||||
|
||||
post "/api/v1/accounts/#{account.id}/inboxes/#{whatsapp_inbox.id}/csat_template",
|
||||
@@ -312,10 +312,10 @@ RSpec.describe Api::V1::Accounts::InboxCsatTemplatesController, type: :request d
|
||||
allow(mock_service).to receive(:get_template_status)
|
||||
.with('existing_template')
|
||||
.and_return({ success: true, template: { id: '111111111' } })
|
||||
expect(mock_service).to receive(:delete_csat_template)
|
||||
expect(mock_service).to receive(:delete_template)
|
||||
.with('existing_template')
|
||||
.and_return({ success: true })
|
||||
expect(mock_service).to receive(:create_csat_template)
|
||||
expect(mock_service).to receive(:create_template)
|
||||
.and_return({
|
||||
success: true,
|
||||
template_name: "customer_satisfaction_survey_#{whatsapp_inbox.id}",
|
||||
@@ -336,13 +336,13 @@ RSpec.describe Api::V1::Accounts::InboxCsatTemplatesController, type: :request d
|
||||
})
|
||||
|
||||
allow(mock_service).to receive(:get_template_status).and_return({ success: true })
|
||||
allow(mock_service).to receive(:delete_csat_template)
|
||||
allow(mock_service).to receive(:delete_template)
|
||||
.and_return({ success: false, response_body: 'Delete failed' })
|
||||
allow(mock_service).to receive(:create_csat_template).and_return({
|
||||
success: true,
|
||||
template_name: "customer_satisfaction_survey_#{whatsapp_inbox.id}",
|
||||
template_id: '333333333'
|
||||
})
|
||||
allow(mock_service).to receive(:create_template).and_return({
|
||||
success: true,
|
||||
template_name: "customer_satisfaction_survey_#{whatsapp_inbox.id}",
|
||||
template_id: '333333333'
|
||||
})
|
||||
|
||||
post "/api/v1/accounts/#{account.id}/inboxes/#{whatsapp_inbox.id}/csat_template",
|
||||
headers: admin.create_new_auth_token,
|
||||
@@ -365,11 +365,11 @@ RSpec.describe Api::V1::Accounts::InboxCsatTemplatesController, type: :request d
|
||||
|
||||
it 'allows access when agent is assigned to inbox' do
|
||||
allow(mock_service).to receive(:get_template_status).and_return({ success: false })
|
||||
allow(mock_service).to receive(:create_csat_template).and_return({
|
||||
success: true,
|
||||
template_name: 'customer_satisfaction_survey',
|
||||
template_id: '444444444'
|
||||
})
|
||||
allow(mock_service).to receive(:create_template).and_return({
|
||||
success: true,
|
||||
template_name: 'customer_satisfaction_survey',
|
||||
template_id: '444444444'
|
||||
})
|
||||
|
||||
post "/api/v1/accounts/#{account.id}/inboxes/#{whatsapp_inbox.id}/csat_template",
|
||||
headers: agent.create_new_auth_token,
|
||||
|
||||
@@ -160,4 +160,68 @@ RSpec.describe 'Summary Reports API', type: :request do
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'GET /api/v2/accounts/:account_id/summary_reports/channel' do
|
||||
context 'when it is an unauthenticated user' do
|
||||
it 'returns unauthorized' do
|
||||
get "/api/v2/accounts/#{account.id}/summary_reports/channel"
|
||||
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when it is an authenticated user' do
|
||||
let(:params) do
|
||||
{
|
||||
since: start_of_today.to_s,
|
||||
until: end_of_today.to_s
|
||||
}
|
||||
end
|
||||
|
||||
it 'returns unauthorized for agents' do
|
||||
get "/api/v2/accounts/#{account.id}/summary_reports/channel",
|
||||
params: params,
|
||||
headers: agent.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
|
||||
it 'calls V2::Reports::ChannelSummaryBuilder with the right params if the user is an admin' do
|
||||
channel_summary_builder = double
|
||||
allow(V2::Reports::ChannelSummaryBuilder).to receive(:new).and_return(channel_summary_builder)
|
||||
allow(channel_summary_builder).to receive(:build)
|
||||
.and_return({
|
||||
'Channel::WebWidget' => { open: 5, resolved: 10, pending: 2, snoozed: 1, total: 18 }
|
||||
})
|
||||
|
||||
get "/api/v2/accounts/#{account.id}/summary_reports/channel",
|
||||
params: params,
|
||||
headers: admin.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(V2::Reports::ChannelSummaryBuilder).to have_received(:new).with(
|
||||
account: account,
|
||||
params: hash_including(since: start_of_today.to_s, until: end_of_today.to_s)
|
||||
)
|
||||
expect(channel_summary_builder).to have_received(:build)
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
json_response = response.parsed_body
|
||||
|
||||
expect(json_response['Channel::WebWidget']['open']).to eq(5)
|
||||
expect(json_response['Channel::WebWidget']['total']).to eq(18)
|
||||
end
|
||||
|
||||
it 'returns unprocessable_entity when date range exceeds 6 months' do
|
||||
get "/api/v2/accounts/#{account.id}/summary_reports/channel",
|
||||
params: { since: 1.year.ago.to_i.to_s, until: Time.current.to_i.to_s },
|
||||
headers: admin.create_new_auth_token,
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
expect(response.parsed_body['error']).to eq(I18n.t('errors.reports.date_range_too_long'))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -252,6 +252,17 @@ RSpec.describe Integrations::LlmInstrumentation do
|
||||
expect(mock_span).to have_received(:set_attribute).with('langfuse.observation.input', params[:messages].to_json)
|
||||
expect(mock_span).to have_received(:set_attribute).with('langfuse.observation.output', result_data.to_json)
|
||||
end
|
||||
|
||||
# Regression test for Langfuse double-counting bug.
|
||||
# Setting gen_ai.request.model on parent spans causes Langfuse to classify them as
|
||||
# GENERATIONs instead of SPANs, resulting in cost being counted multiple times
|
||||
# (once for the parent, once for each child GENERATION).
|
||||
# See: https://github.com/langfuse/langfuse/issues/7549
|
||||
it 'does NOT set gen_ai.request.model to avoid being classified as a GENERATION' do
|
||||
instance.instrument_agent_session(params) { 'result' }
|
||||
|
||||
expect(mock_span).not_to have_received(:set_attribute).with('gen_ai.request.model', anything)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -215,5 +215,25 @@ RSpec.describe AutomationRules::ConditionsFilterService do
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
context 'when conditions based on contact country_code' do
|
||||
before do
|
||||
conversation.update(additional_attributes: { country_code: 'US' })
|
||||
conversation.contact.update(additional_attributes: { country_code: 'IN' })
|
||||
rule.conditions = [
|
||||
{ 'values': ['IN'], 'attribute_key': 'country_code', 'query_operator': nil, 'filter_operator': 'equal_to' }
|
||||
]
|
||||
rule.save
|
||||
end
|
||||
|
||||
it 'matches against the contact additional_attributes' do
|
||||
expect(described_class.new(rule, conversation, { changed_attributes: {} }).perform).to be(true)
|
||||
end
|
||||
|
||||
it 'returns false when the contact country_code does not match' do
|
||||
conversation.contact.update(additional_attributes: { country_code: 'GB' })
|
||||
expect(described_class.new(rule, conversation, { changed_attributes: {} }).perform).to be(false)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -8,11 +8,8 @@ describe Twilio::SendOnTwilioService do
|
||||
let(:message_record_double) { double }
|
||||
|
||||
let!(:account) { create(:account) }
|
||||
let!(:widget_inbox) { create(:inbox, account: account) }
|
||||
let!(:twilio_sms) { create(:channel_twilio_sms, account: account) }
|
||||
let!(:twilio_whatsapp) { create(:channel_twilio_sms, medium: :whatsapp, account: account) }
|
||||
let!(:twilio_inbox) { create(:inbox, channel: twilio_sms, account: account) }
|
||||
let!(:twilio_whatsapp_inbox) { create(:inbox, channel: twilio_whatsapp, account: account) }
|
||||
let!(:contact) { create(:contact, account: account) }
|
||||
let(:contact_inbox) { create(:contact_inbox, contact: contact, inbox: twilio_inbox) }
|
||||
let(:conversation) { create(:conversation, contact: contact, inbox: twilio_inbox, contact_inbox: contact_inbox) }
|
||||
@@ -23,6 +20,10 @@ describe Twilio::SendOnTwilioService do
|
||||
end
|
||||
|
||||
describe '#perform' do
|
||||
let!(:widget_inbox) { create(:inbox, account: account) }
|
||||
let!(:twilio_whatsapp) { create(:channel_twilio_sms, medium: :whatsapp, account: account) }
|
||||
let!(:twilio_whatsapp_inbox) { create(:inbox, channel: twilio_whatsapp, account: account) }
|
||||
|
||||
context 'without reply' do
|
||||
it 'if message is private' do
|
||||
message = create(:message, message_type: 'outgoing', private: true, inbox: twilio_inbox, account: account)
|
||||
@@ -107,4 +108,146 @@ describe Twilio::SendOnTwilioService do
|
||||
expect(outgoing_message.reload.status).to eq('failed')
|
||||
end
|
||||
end
|
||||
|
||||
describe '#send_csat_template_message' do
|
||||
let(:test_message) { create(:message, message_type: 'outgoing', inbox: twilio_inbox, account: account, conversation: conversation) }
|
||||
let(:service) { described_class.new(message: test_message) }
|
||||
let(:mock_twilio_message) { instance_double(Twilio::REST::Api::V2010::AccountContext::MessageInstance, sid: 'SM123456789') }
|
||||
|
||||
# Test parameters defined using let statements
|
||||
let(:test_params) do
|
||||
{
|
||||
phone_number: '+1234567890',
|
||||
content_sid: 'HX123456789',
|
||||
content_variables: { '1' => 'conversation-uuid-123' }
|
||||
}
|
||||
end
|
||||
|
||||
before do
|
||||
allow(twilio_sms).to receive(:send_message_from).and_return({ from: '+0987654321' })
|
||||
allow(twilio_sms).to receive(:respond_to?).and_return(true)
|
||||
allow(twilio_sms).to receive(:twilio_delivery_status_index_url).and_return('http://localhost:3000/twilio/delivery_status')
|
||||
end
|
||||
|
||||
context 'when template message is sent successfully' do
|
||||
before do
|
||||
allow(messages_double).to receive(:create).and_return(mock_twilio_message)
|
||||
end
|
||||
|
||||
it 'sends template message with correct parameters' do
|
||||
expected_params = {
|
||||
to: test_params[:phone_number],
|
||||
content_sid: test_params[:content_sid],
|
||||
content_variables: test_params[:content_variables].to_json,
|
||||
status_callback: 'http://localhost:3000/twilio/delivery_status',
|
||||
from: '+0987654321'
|
||||
}
|
||||
|
||||
result = service.send_csat_template_message(**test_params)
|
||||
|
||||
expect(messages_double).to have_received(:create).with(expected_params)
|
||||
expect(result).to eq({ success: true, message_id: 'SM123456789' })
|
||||
end
|
||||
|
||||
it 'sends template message without content variables when empty' do
|
||||
expected_params = {
|
||||
to: test_params[:phone_number],
|
||||
content_sid: test_params[:content_sid],
|
||||
status_callback: 'http://localhost:3000/twilio/delivery_status',
|
||||
from: '+0987654321'
|
||||
}
|
||||
|
||||
result = service.send_csat_template_message(
|
||||
phone_number: test_params[:phone_number],
|
||||
content_sid: test_params[:content_sid]
|
||||
)
|
||||
|
||||
expect(messages_double).to have_received(:create).with(expected_params)
|
||||
expect(result).to eq({ success: true, message_id: 'SM123456789' })
|
||||
end
|
||||
|
||||
it 'includes custom status callback when channel supports it' do
|
||||
allow(twilio_sms).to receive(:respond_to?).and_return(true)
|
||||
allow(twilio_sms).to receive(:twilio_delivery_status_index_url).and_return('https://example.com/webhook')
|
||||
|
||||
expected_params = {
|
||||
to: test_params[:phone_number],
|
||||
content_sid: test_params[:content_sid],
|
||||
content_variables: test_params[:content_variables].to_json,
|
||||
status_callback: 'https://example.com/webhook',
|
||||
from: '+0987654321'
|
||||
}
|
||||
|
||||
service.send_csat_template_message(**test_params)
|
||||
|
||||
expect(messages_double).to have_received(:create).with(expected_params)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when Twilio API returns an error' do
|
||||
before do
|
||||
allow(Rails.logger).to receive(:error)
|
||||
end
|
||||
|
||||
it 'handles Twilio::REST::TwilioError' do
|
||||
allow(messages_double).to receive(:create).and_raise(Twilio::REST::TwilioError, 'Invalid phone number')
|
||||
|
||||
result = service.send_csat_template_message(**test_params)
|
||||
|
||||
expect(result).to eq({ success: false, error: 'Invalid phone number' })
|
||||
expect(Rails.logger).to have_received(:error).with('Failed to send Twilio template message: Invalid phone number')
|
||||
end
|
||||
|
||||
it 'handles Twilio API errors' do
|
||||
allow(messages_double).to receive(:create).and_raise(Twilio::REST::TwilioError, 'Content template not found')
|
||||
|
||||
result = service.send_csat_template_message(**test_params)
|
||||
|
||||
expect(result).to eq({ success: false, error: 'Content template not found' })
|
||||
expect(Rails.logger).to have_received(:error).with('Failed to send Twilio template message: Content template not found')
|
||||
end
|
||||
end
|
||||
|
||||
context 'with parameter handling' do
|
||||
before do
|
||||
allow(messages_double).to receive(:create).and_return(mock_twilio_message)
|
||||
end
|
||||
|
||||
it 'handles empty content_variables hash' do
|
||||
expected_params = {
|
||||
to: test_params[:phone_number],
|
||||
content_sid: test_params[:content_sid],
|
||||
status_callback: 'http://localhost:3000/twilio/delivery_status',
|
||||
from: '+0987654321'
|
||||
}
|
||||
|
||||
service.send_csat_template_message(
|
||||
phone_number: test_params[:phone_number],
|
||||
content_sid: test_params[:content_sid],
|
||||
content_variables: {}
|
||||
)
|
||||
|
||||
expect(messages_double).to have_received(:create).with(expected_params)
|
||||
end
|
||||
|
||||
it 'converts content_variables to JSON when present' do
|
||||
variables = { '1' => 'test-uuid', '2' => 'another-value' }
|
||||
expected_params = {
|
||||
to: test_params[:phone_number],
|
||||
content_sid: test_params[:content_sid],
|
||||
content_variables: variables.to_json,
|
||||
status_callback: 'http://localhost:3000/twilio/delivery_status',
|
||||
from: '+0987654321'
|
||||
}
|
||||
|
||||
service.send_csat_template_message(
|
||||
phone_number: test_params[:phone_number],
|
||||
content_sid: test_params[:content_sid],
|
||||
content_variables: variables
|
||||
)
|
||||
|
||||
expect(messages_double).to have_received(:create).with(expected_params)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -223,6 +223,8 @@ account_summary:
|
||||
$ref: './resource/reports/summary.yml'
|
||||
agent_conversation_metrics:
|
||||
$ref: './resource/reports/conversation/agent.yml'
|
||||
channel_summary:
|
||||
$ref: './resource/reports/channel_summary.yml'
|
||||
|
||||
contact_detail:
|
||||
$ref: ./resource/contact_detail.yml
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
type: object
|
||||
description: Channel summary report containing conversation counts grouped by channel type and status. Available in version 4.10.0+.
|
||||
additionalProperties:
|
||||
type: object
|
||||
description: Conversation statistics for a specific channel type (e.g., Channel::WebWidget, Channel::Api)
|
||||
properties:
|
||||
open:
|
||||
type: number
|
||||
description: Number of open conversations
|
||||
resolved:
|
||||
type: number
|
||||
description: Number of resolved conversations
|
||||
pending:
|
||||
type: number
|
||||
description: Number of pending conversations
|
||||
snoozed:
|
||||
type: number
|
||||
description: Number of snoozed conversations
|
||||
total:
|
||||
type: number
|
||||
description: Total number of conversations
|
||||
example:
|
||||
Channel::WebWidget:
|
||||
open: 10
|
||||
resolved: 20
|
||||
pending: 5
|
||||
snoozed: 2
|
||||
total: 37
|
||||
Channel::Api:
|
||||
open: 5
|
||||
resolved: 15
|
||||
pending: 3
|
||||
snoozed: 1
|
||||
total: 24
|
||||
@@ -0,0 +1,30 @@
|
||||
tags:
|
||||
- Reports
|
||||
operationId: get-channel-summary-report
|
||||
summary: Get conversation statistics grouped by channel type
|
||||
security:
|
||||
- userApiKey: []
|
||||
description: |
|
||||
Get conversation counts grouped by channel type and status for a given date range.
|
||||
Returns statistics for each channel type including open, resolved, pending, snoozed, and total conversation counts.
|
||||
|
||||
**Note:** This API endpoint is available only in Chatwoot version 4.10.0 and above. The date range is limited to a maximum of 6 months.
|
||||
responses:
|
||||
'200':
|
||||
description: Success
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/channel_summary'
|
||||
'400':
|
||||
description: Date range exceeds 6 months limit
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/bad_request_error'
|
||||
'403':
|
||||
description: Access denied
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/bad_request_error'
|
||||
@@ -639,6 +639,28 @@
|
||||
get:
|
||||
$ref: './application/reports/conversation/agent.yml'
|
||||
|
||||
# Channel summary report (Available in 4.10.0+)
|
||||
/api/v2/accounts/{account_id}/summary_reports/channel:
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/account_id'
|
||||
- in: query
|
||||
name: since
|
||||
schema:
|
||||
type: string
|
||||
description: The timestamp from where report should start (Unix timestamp).
|
||||
- in: query
|
||||
name: until
|
||||
schema:
|
||||
type: string
|
||||
description: The timestamp from where report should stop (Unix timestamp).
|
||||
- in: query
|
||||
name: business_hours
|
||||
schema:
|
||||
type: boolean
|
||||
description: Whether to filter by business hours.
|
||||
get:
|
||||
$ref: './application/reports/channel_summary.yml'
|
||||
|
||||
# Conversations Messages
|
||||
/accounts/{account_id}/conversations/{conversation_id}/messages:
|
||||
parameters:
|
||||
|
||||
@@ -7870,6 +7870,82 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v2/accounts/{account_id}/summary_reports/channel": {
|
||||
"parameters": [
|
||||
{
|
||||
"$ref": "#/components/parameters/account_id"
|
||||
},
|
||||
{
|
||||
"in": "query",
|
||||
"name": "since",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "The timestamp from where report should start (Unix timestamp)."
|
||||
},
|
||||
{
|
||||
"in": "query",
|
||||
"name": "until",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "The timestamp from where report should stop (Unix timestamp)."
|
||||
},
|
||||
{
|
||||
"in": "query",
|
||||
"name": "business_hours",
|
||||
"schema": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"description": "Whether to filter by business hours."
|
||||
}
|
||||
],
|
||||
"get": {
|
||||
"tags": [
|
||||
"Reports"
|
||||
],
|
||||
"operationId": "get-channel-summary-report",
|
||||
"summary": "Get conversation statistics grouped by channel type",
|
||||
"security": [
|
||||
{
|
||||
"userApiKey": []
|
||||
}
|
||||
],
|
||||
"description": "Get conversation counts grouped by channel type and status for a given date range.\nReturns statistics for each channel type including open, resolved, pending, snoozed, and total conversation counts.\n\n**Note:** This API endpoint is available only in Chatwoot version 4.10.0 and above. The date range is limited to a maximum of 6 months.\n",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Success",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/channel_summary"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Date range exceeds 6 months limit",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/bad_request_error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"403": {
|
||||
"description": "Access denied",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/bad_request_error"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/accounts/{account_id}/conversations/{conversation_id}/messages": {
|
||||
"parameters": [
|
||||
{
|
||||
@@ -11659,6 +11735,52 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"channel_summary": {
|
||||
"type": "object",
|
||||
"description": "Channel summary report containing conversation counts grouped by channel type and status. Available in version 4.10.0+.",
|
||||
"additionalProperties": {
|
||||
"type": "object",
|
||||
"description": "Conversation statistics for a specific channel type (e.g., Channel::WebWidget, Channel::Api)",
|
||||
"properties": {
|
||||
"open": {
|
||||
"type": "number",
|
||||
"description": "Number of open conversations"
|
||||
},
|
||||
"resolved": {
|
||||
"type": "number",
|
||||
"description": "Number of resolved conversations"
|
||||
},
|
||||
"pending": {
|
||||
"type": "number",
|
||||
"description": "Number of pending conversations"
|
||||
},
|
||||
"snoozed": {
|
||||
"type": "number",
|
||||
"description": "Number of snoozed conversations"
|
||||
},
|
||||
"total": {
|
||||
"type": "number",
|
||||
"description": "Total number of conversations"
|
||||
}
|
||||
}
|
||||
},
|
||||
"example": {
|
||||
"Channel::WebWidget": {
|
||||
"open": 10,
|
||||
"resolved": 20,
|
||||
"pending": 5,
|
||||
"snoozed": 2,
|
||||
"total": 37
|
||||
},
|
||||
"Channel::Api": {
|
||||
"open": 5,
|
||||
"resolved": 15,
|
||||
"pending": 3,
|
||||
"snoozed": 1,
|
||||
"total": 24
|
||||
}
|
||||
}
|
||||
},
|
||||
"contact_detail": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
@@ -6412,6 +6412,82 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v2/accounts/{account_id}/summary_reports/channel": {
|
||||
"parameters": [
|
||||
{
|
||||
"$ref": "#/components/parameters/account_id"
|
||||
},
|
||||
{
|
||||
"in": "query",
|
||||
"name": "since",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "The timestamp from where report should start (Unix timestamp)."
|
||||
},
|
||||
{
|
||||
"in": "query",
|
||||
"name": "until",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "The timestamp from where report should stop (Unix timestamp)."
|
||||
},
|
||||
{
|
||||
"in": "query",
|
||||
"name": "business_hours",
|
||||
"schema": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"description": "Whether to filter by business hours."
|
||||
}
|
||||
],
|
||||
"get": {
|
||||
"tags": [
|
||||
"Reports"
|
||||
],
|
||||
"operationId": "get-channel-summary-report",
|
||||
"summary": "Get conversation statistics grouped by channel type",
|
||||
"security": [
|
||||
{
|
||||
"userApiKey": []
|
||||
}
|
||||
],
|
||||
"description": "Get conversation counts grouped by channel type and status for a given date range.\nReturns statistics for each channel type including open, resolved, pending, snoozed, and total conversation counts.\n\n**Note:** This API endpoint is available only in Chatwoot version 4.10.0 and above. The date range is limited to a maximum of 6 months.\n",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Success",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/channel_summary"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Date range exceeds 6 months limit",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/bad_request_error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"403": {
|
||||
"description": "Access denied",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/bad_request_error"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"components": {
|
||||
@@ -10166,6 +10242,52 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"channel_summary": {
|
||||
"type": "object",
|
||||
"description": "Channel summary report containing conversation counts grouped by channel type and status. Available in version 4.10.0+.",
|
||||
"additionalProperties": {
|
||||
"type": "object",
|
||||
"description": "Conversation statistics for a specific channel type (e.g., Channel::WebWidget, Channel::Api)",
|
||||
"properties": {
|
||||
"open": {
|
||||
"type": "number",
|
||||
"description": "Number of open conversations"
|
||||
},
|
||||
"resolved": {
|
||||
"type": "number",
|
||||
"description": "Number of resolved conversations"
|
||||
},
|
||||
"pending": {
|
||||
"type": "number",
|
||||
"description": "Number of pending conversations"
|
||||
},
|
||||
"snoozed": {
|
||||
"type": "number",
|
||||
"description": "Number of snoozed conversations"
|
||||
},
|
||||
"total": {
|
||||
"type": "number",
|
||||
"description": "Total number of conversations"
|
||||
}
|
||||
}
|
||||
},
|
||||
"example": {
|
||||
"Channel::WebWidget": {
|
||||
"open": 10,
|
||||
"resolved": 20,
|
||||
"pending": 5,
|
||||
"snoozed": 2,
|
||||
"total": 37
|
||||
},
|
||||
"Channel::Api": {
|
||||
"open": 5,
|
||||
"resolved": 15,
|
||||
"pending": 3,
|
||||
"snoozed": 1,
|
||||
"total": 24
|
||||
}
|
||||
}
|
||||
},
|
||||
"contact_detail": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
@@ -4378,6 +4378,52 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"channel_summary": {
|
||||
"type": "object",
|
||||
"description": "Channel summary report containing conversation counts grouped by channel type and status. Available in version 4.10.0+.",
|
||||
"additionalProperties": {
|
||||
"type": "object",
|
||||
"description": "Conversation statistics for a specific channel type (e.g., Channel::WebWidget, Channel::Api)",
|
||||
"properties": {
|
||||
"open": {
|
||||
"type": "number",
|
||||
"description": "Number of open conversations"
|
||||
},
|
||||
"resolved": {
|
||||
"type": "number",
|
||||
"description": "Number of resolved conversations"
|
||||
},
|
||||
"pending": {
|
||||
"type": "number",
|
||||
"description": "Number of pending conversations"
|
||||
},
|
||||
"snoozed": {
|
||||
"type": "number",
|
||||
"description": "Number of snoozed conversations"
|
||||
},
|
||||
"total": {
|
||||
"type": "number",
|
||||
"description": "Total number of conversations"
|
||||
}
|
||||
}
|
||||
},
|
||||
"example": {
|
||||
"Channel::WebWidget": {
|
||||
"open": 10,
|
||||
"resolved": 20,
|
||||
"pending": 5,
|
||||
"snoozed": 2,
|
||||
"total": 37
|
||||
},
|
||||
"Channel::Api": {
|
||||
"open": 5,
|
||||
"resolved": 15,
|
||||
"pending": 3,
|
||||
"snoozed": 1,
|
||||
"total": 24
|
||||
}
|
||||
}
|
||||
},
|
||||
"contact_detail": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
@@ -3793,6 +3793,52 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"channel_summary": {
|
||||
"type": "object",
|
||||
"description": "Channel summary report containing conversation counts grouped by channel type and status. Available in version 4.10.0+.",
|
||||
"additionalProperties": {
|
||||
"type": "object",
|
||||
"description": "Conversation statistics for a specific channel type (e.g., Channel::WebWidget, Channel::Api)",
|
||||
"properties": {
|
||||
"open": {
|
||||
"type": "number",
|
||||
"description": "Number of open conversations"
|
||||
},
|
||||
"resolved": {
|
||||
"type": "number",
|
||||
"description": "Number of resolved conversations"
|
||||
},
|
||||
"pending": {
|
||||
"type": "number",
|
||||
"description": "Number of pending conversations"
|
||||
},
|
||||
"snoozed": {
|
||||
"type": "number",
|
||||
"description": "Number of snoozed conversations"
|
||||
},
|
||||
"total": {
|
||||
"type": "number",
|
||||
"description": "Total number of conversations"
|
||||
}
|
||||
}
|
||||
},
|
||||
"example": {
|
||||
"Channel::WebWidget": {
|
||||
"open": 10,
|
||||
"resolved": 20,
|
||||
"pending": 5,
|
||||
"snoozed": 2,
|
||||
"total": 37
|
||||
},
|
||||
"Channel::Api": {
|
||||
"open": 5,
|
||||
"resolved": 15,
|
||||
"pending": 3,
|
||||
"snoozed": 1,
|
||||
"total": 24
|
||||
}
|
||||
}
|
||||
},
|
||||
"contact_detail": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
@@ -4554,6 +4554,52 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"channel_summary": {
|
||||
"type": "object",
|
||||
"description": "Channel summary report containing conversation counts grouped by channel type and status. Available in version 4.10.0+.",
|
||||
"additionalProperties": {
|
||||
"type": "object",
|
||||
"description": "Conversation statistics for a specific channel type (e.g., Channel::WebWidget, Channel::Api)",
|
||||
"properties": {
|
||||
"open": {
|
||||
"type": "number",
|
||||
"description": "Number of open conversations"
|
||||
},
|
||||
"resolved": {
|
||||
"type": "number",
|
||||
"description": "Number of resolved conversations"
|
||||
},
|
||||
"pending": {
|
||||
"type": "number",
|
||||
"description": "Number of pending conversations"
|
||||
},
|
||||
"snoozed": {
|
||||
"type": "number",
|
||||
"description": "Number of snoozed conversations"
|
||||
},
|
||||
"total": {
|
||||
"type": "number",
|
||||
"description": "Total number of conversations"
|
||||
}
|
||||
}
|
||||
},
|
||||
"example": {
|
||||
"Channel::WebWidget": {
|
||||
"open": 10,
|
||||
"resolved": 20,
|
||||
"pending": 5,
|
||||
"snoozed": 2,
|
||||
"total": 37
|
||||
},
|
||||
"Channel::Api": {
|
||||
"open": 5,
|
||||
"resolved": 15,
|
||||
"pending": 3,
|
||||
"snoozed": 1,
|
||||
"total": 24
|
||||
}
|
||||
}
|
||||
},
|
||||
"contact_detail": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
Reference in New Issue
Block a user