Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a7edbe3a2b | ||
|
|
bac921133a | ||
|
|
8818d276b9 | ||
|
|
90b9dba9f9 | ||
|
|
2a21d075f6 | ||
|
|
b8545019e1 | ||
|
|
6a7ca9dd3b | ||
|
|
6c9efc4e92 | ||
|
|
34d8741b9b | ||
|
|
7bf76057c2 | ||
|
|
a3c7f3b204 | ||
|
|
49b0ab0e1f |
+3
-3
@@ -272,9 +272,9 @@ AZURE_APP_SECRET=
|
|||||||
# ENABLE_SIDEKIQ_DEQUEUE_LOGGER=false
|
# ENABLE_SIDEKIQ_DEQUEUE_LOGGER=false
|
||||||
|
|
||||||
|
|
||||||
# AI powered features
|
# AI powered features (Captain)
|
||||||
## OpenAI key
|
# The OpenAI API key and endpoint for Captain are not configured via .env.
|
||||||
# OPENAI_API_KEY=
|
# Set them at Super Admin > App Configs > Captain (CAPTAIN_OPEN_AI_API_KEY, CAPTAIN_OPEN_AI_ENDPOINT).
|
||||||
|
|
||||||
# Housekeeping/Performance related configurations
|
# Housekeeping/Performance related configurations
|
||||||
# Set to true if you want to remove stale contact inboxes
|
# Set to true if you want to remove stale contact inboxes
|
||||||
|
|||||||
@@ -0,0 +1,213 @@
|
|||||||
|
class V2::Reports::DrilldownBuilder
|
||||||
|
include DateRangeHelper
|
||||||
|
include TimezoneHelper
|
||||||
|
|
||||||
|
DEFAULT_GROUP_BY = 'day'.freeze
|
||||||
|
DEFAULT_PAGE = 1
|
||||||
|
DEFAULT_PER_PAGE = 25
|
||||||
|
MAX_PER_PAGE = 100
|
||||||
|
SUPPORTED_GROUP_BY = %w[hour day week month year].freeze
|
||||||
|
SUPPORTED_DIMENSION_TYPES = %w[account inbox agent label team].freeze
|
||||||
|
MESSAGE_METRICS = {
|
||||||
|
'incoming_messages_count' => :incoming,
|
||||||
|
'outgoing_messages_count' => :outgoing
|
||||||
|
}.freeze
|
||||||
|
MESSAGE_EVENT_METRICS = %w[avg_first_response_time reply_time].freeze
|
||||||
|
|
||||||
|
pattr_initialize :account, :params
|
||||||
|
|
||||||
|
def self.supported_dimension_type?(type) = SUPPORTED_DIMENSION_TYPES.include?((type.presence || 'account').to_s)
|
||||||
|
|
||||||
|
def build
|
||||||
|
records = paginated_records.to_a
|
||||||
|
{ meta: meta, payload: records.map { |record| record_serializer(records).serialize(record) } }
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def meta
|
||||||
|
{
|
||||||
|
metric: metric,
|
||||||
|
record_type: record_type,
|
||||||
|
bucket: {
|
||||||
|
since: bucket_range.begin.to_i,
|
||||||
|
until: bucket_range.end.to_i
|
||||||
|
},
|
||||||
|
current_page: current_page,
|
||||||
|
per_page: per_page,
|
||||||
|
total_count: paginated_records.total_count,
|
||||||
|
conversation_count: conversation_count
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
def conversation_count
|
||||||
|
return paginated_records.total_count if conversation_metric?
|
||||||
|
|
||||||
|
drilldown_scope.except(:includes).reorder(nil).distinct.count(:conversation_id)
|
||||||
|
end
|
||||||
|
|
||||||
|
def paginated_records
|
||||||
|
@paginated_records ||= drilldown_scope.page(current_page).per(per_page)
|
||||||
|
end
|
||||||
|
|
||||||
|
def drilldown_scope
|
||||||
|
if message_metric?
|
||||||
|
message_scope
|
||||||
|
elsif conversation_metric?
|
||||||
|
conversation_scope
|
||||||
|
else
|
||||||
|
reporting_event_scope
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def message_scope
|
||||||
|
scope.messages
|
||||||
|
.where(account_id: account.id, created_at: bucket_range)
|
||||||
|
.public_send(MESSAGE_METRICS.fetch(metric))
|
||||||
|
.includes(:sender, conversation: [:assignee, :contact, :inbox])
|
||||||
|
.reorder(created_at: :desc)
|
||||||
|
end
|
||||||
|
|
||||||
|
def conversation_scope
|
||||||
|
scope.conversations
|
||||||
|
.where(account_id: account.id, created_at: bucket_range)
|
||||||
|
.includes(:assignee, :contact, :inbox)
|
||||||
|
.order(created_at: :desc)
|
||||||
|
end
|
||||||
|
|
||||||
|
def reporting_event_scope
|
||||||
|
events = scope.reporting_events
|
||||||
|
.where(account_id: account.id, name: raw_event_name, created_at: bucket_range)
|
||||||
|
.includes(:user, :inbox, conversation: [:assignee, :contact, :inbox])
|
||||||
|
.order(created_at: :desc)
|
||||||
|
|
||||||
|
if raw_count_strategy == :exclude_bot_handoffs
|
||||||
|
events = events.where.not(conversation_id: bot_handoff_conversation_ids_subquery)
|
||||||
|
elsif raw_count_strategy == :distinct_conversation
|
||||||
|
events = events.where(id: distinct_conversation_event_ids(events))
|
||||||
|
end
|
||||||
|
|
||||||
|
events
|
||||||
|
end
|
||||||
|
|
||||||
|
def bot_handoff_conversation_ids_subquery
|
||||||
|
scope.reporting_events
|
||||||
|
.where(account_id: account.id, name: :conversation_bot_handoff, created_at: range)
|
||||||
|
.where.not(conversation_id: nil)
|
||||||
|
.select(:conversation_id)
|
||||||
|
end
|
||||||
|
|
||||||
|
def distinct_conversation_event_ids(events)
|
||||||
|
events.reorder(nil)
|
||||||
|
.where.not(conversation_id: nil)
|
||||||
|
.select('MAX(reporting_events.id)')
|
||||||
|
.group(:conversation_id)
|
||||||
|
end
|
||||||
|
|
||||||
|
def record_serializer(records)
|
||||||
|
@record_serializer ||= V2::Reports::DrilldownRecordSerializer.new(
|
||||||
|
account,
|
||||||
|
metric,
|
||||||
|
use_business_hours?,
|
||||||
|
records
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
def bucket_range
|
||||||
|
@bucket_range ||= begin
|
||||||
|
bucket_start = Time.zone.at(params[:bucket_timestamp].to_i).in_time_zone(timezone)
|
||||||
|
bucket_end = bucket_end_for(bucket_start)
|
||||||
|
requested_start = Time.zone.at(params[:since].to_i)
|
||||||
|
requested_end = Time.zone.at(params[:until].to_i)
|
||||||
|
|
||||||
|
[bucket_start, requested_start].max...[bucket_end, requested_end].min
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def bucket_end_for(bucket_start)
|
||||||
|
{
|
||||||
|
'hour' => bucket_start + 1.hour,
|
||||||
|
'day' => bucket_start + 1.day,
|
||||||
|
'week' => bucket_start + 1.week,
|
||||||
|
'month' => bucket_start + 1.month,
|
||||||
|
'year' => bucket_start + 1.year
|
||||||
|
}.fetch(group_by)
|
||||||
|
end
|
||||||
|
|
||||||
|
def scope
|
||||||
|
case dimension_type
|
||||||
|
when 'account' then account
|
||||||
|
when 'inbox' then inbox
|
||||||
|
when 'agent' then user
|
||||||
|
when 'label' then label
|
||||||
|
when 'team' then team
|
||||||
|
else
|
||||||
|
raise ArgumentError, "Unsupported drilldown dimension type: #{dimension_type}"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def inbox = @inbox ||= account.inboxes.find(params[:id])
|
||||||
|
|
||||||
|
def user = @user ||= account.users.find(params[:id])
|
||||||
|
|
||||||
|
def label = @label ||= account.labels.find(params[:id])
|
||||||
|
|
||||||
|
def team = @team ||= account.teams.find(params[:id])
|
||||||
|
|
||||||
|
def metric
|
||||||
|
params[:metric].to_s
|
||||||
|
end
|
||||||
|
|
||||||
|
def report_metric
|
||||||
|
@report_metric ||= Reports::ReportMetricRegistry.fetch(metric)
|
||||||
|
end
|
||||||
|
|
||||||
|
def raw_event_name
|
||||||
|
report_metric&.raw_event_name
|
||||||
|
end
|
||||||
|
|
||||||
|
def raw_count_strategy
|
||||||
|
report_metric&.raw_count_strategy
|
||||||
|
end
|
||||||
|
|
||||||
|
def record_type
|
||||||
|
return 'message' if message_metric? || MESSAGE_EVENT_METRICS.include?(metric)
|
||||||
|
|
||||||
|
'conversation'
|
||||||
|
end
|
||||||
|
|
||||||
|
def message_metric?
|
||||||
|
MESSAGE_METRICS.key?(metric)
|
||||||
|
end
|
||||||
|
|
||||||
|
def conversation_metric?
|
||||||
|
metric == 'conversations_count'
|
||||||
|
end
|
||||||
|
|
||||||
|
def dimension_type
|
||||||
|
(params[:type].presence || 'account').to_s
|
||||||
|
end
|
||||||
|
|
||||||
|
def group_by
|
||||||
|
@group_by ||= SUPPORTED_GROUP_BY.include?(params[:group_by].to_s) ? params[:group_by].to_s : DEFAULT_GROUP_BY
|
||||||
|
end
|
||||||
|
|
||||||
|
def timezone
|
||||||
|
@timezone ||= timezone_name_from_offset(params[:timezone_offset])
|
||||||
|
end
|
||||||
|
|
||||||
|
def current_page
|
||||||
|
[params[:page].to_i, DEFAULT_PAGE].max
|
||||||
|
end
|
||||||
|
|
||||||
|
def per_page
|
||||||
|
requested_per_page = params[:per_page].to_i
|
||||||
|
requested_per_page = DEFAULT_PER_PAGE if requested_per_page <= 0
|
||||||
|
|
||||||
|
[requested_per_page, MAX_PER_PAGE].min
|
||||||
|
end
|
||||||
|
|
||||||
|
def use_business_hours?
|
||||||
|
ActiveModel::Type::Boolean.new.cast(params[:business_hours])
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
class V2::Reports::DrilldownRecordSerializer
|
||||||
|
MESSAGE_EVENT_METRICS = %w[avg_first_response_time reply_time].freeze
|
||||||
|
|
||||||
|
attr_reader :account, :metric, :use_business_hours, :records
|
||||||
|
|
||||||
|
def initialize(account, metric, use_business_hours, records = [])
|
||||||
|
@account = account
|
||||||
|
@metric = metric
|
||||||
|
@use_business_hours = use_business_hours
|
||||||
|
@records = records
|
||||||
|
end
|
||||||
|
|
||||||
|
def serialize(record)
|
||||||
|
return serialize_message(record) if record.is_a?(Message)
|
||||||
|
return serialize_conversation_event(record) if record.is_a?(ReportingEvent)
|
||||||
|
|
||||||
|
serialize_conversation(record)
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def serialize_message(message, metric_value: nil, occurred_at: nil)
|
||||||
|
{
|
||||||
|
record_type: 'message',
|
||||||
|
conversation: conversation_attributes(message.conversation),
|
||||||
|
message: message_attributes(message),
|
||||||
|
metric_value: metric_value,
|
||||||
|
occurred_at: (occurred_at || message.created_at).to_i
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
def serialize_conversation_event(event)
|
||||||
|
inferred_message = inferred_message_for(event)
|
||||||
|
if inferred_message.present?
|
||||||
|
return serialize_message(
|
||||||
|
inferred_message,
|
||||||
|
metric_value: event_metric_value(event),
|
||||||
|
occurred_at: event_timestamp(event)
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
serialize_conversation(
|
||||||
|
event.conversation,
|
||||||
|
metric_value: event_metric_value(event),
|
||||||
|
occurred_at: event_timestamp(event),
|
||||||
|
event_name: event.name
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
def serialize_conversation(conversation, metric_value: nil, occurred_at: nil, event_name: nil)
|
||||||
|
serialized_record = {
|
||||||
|
record_type: 'conversation',
|
||||||
|
conversation: conversation_attributes(conversation),
|
||||||
|
message: nil,
|
||||||
|
metric_value: metric_value,
|
||||||
|
occurred_at: (occurred_at || conversation&.created_at)&.to_i
|
||||||
|
}
|
||||||
|
serialized_record[:event_name] = event_name if event_name.present?
|
||||||
|
serialized_record
|
||||||
|
end
|
||||||
|
|
||||||
|
def conversation_attributes(conversation)
|
||||||
|
return {} if conversation.blank?
|
||||||
|
|
||||||
|
{
|
||||||
|
id: conversation.id,
|
||||||
|
display_id: conversation.display_id,
|
||||||
|
contact_id: conversation.contact_id,
|
||||||
|
contact_name: conversation.contact&.name,
|
||||||
|
inbox_id: conversation.inbox_id,
|
||||||
|
inbox_name: conversation.inbox&.name,
|
||||||
|
assignee_id: conversation.assignee_id,
|
||||||
|
assignee_name: conversation.assignee&.name,
|
||||||
|
status: conversation.status,
|
||||||
|
created_at: conversation.created_at.to_i,
|
||||||
|
last_activity_at: conversation.last_activity_at.to_i,
|
||||||
|
last_message: last_message_attributes(conversation)
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
def message_attributes(message)
|
||||||
|
{
|
||||||
|
id: message.id,
|
||||||
|
content: message.content,
|
||||||
|
message_type: message.message_type,
|
||||||
|
sender_name: message.sender&.try(:name),
|
||||||
|
created_at: message.created_at.to_i
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
def last_message_attributes(conversation)
|
||||||
|
message = latest_messages_by_conversation_id[conversation.id]
|
||||||
|
return if message.blank?
|
||||||
|
|
||||||
|
message_attributes(message)
|
||||||
|
end
|
||||||
|
|
||||||
|
def inferred_message_for(event)
|
||||||
|
return unless MESSAGE_EVENT_METRICS.include?(metric)
|
||||||
|
return if event.conversation.blank? || event.event_end_time.blank?
|
||||||
|
|
||||||
|
inferred_messages_by_event_id[event.id]
|
||||||
|
end
|
||||||
|
|
||||||
|
def first_response_event_with_user?(event)
|
||||||
|
metric == 'avg_first_response_time' && event.user_id.present?
|
||||||
|
end
|
||||||
|
|
||||||
|
def message_inference_range(event)
|
||||||
|
(event.event_end_time - 1.second)..(event.event_end_time + 1.second)
|
||||||
|
end
|
||||||
|
|
||||||
|
def event_metric_value(event)
|
||||||
|
use_business_hours ? event.value_in_business_hours : event.value
|
||||||
|
end
|
||||||
|
|
||||||
|
def event_timestamp(event)
|
||||||
|
event.event_end_time || event.created_at
|
||||||
|
end
|
||||||
|
|
||||||
|
def latest_messages_by_conversation_id
|
||||||
|
@latest_messages_by_conversation_id ||= if conversation_ids.blank?
|
||||||
|
{}
|
||||||
|
else
|
||||||
|
latest_messages.index_by(&:conversation_id)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def latest_messages
|
||||||
|
Message
|
||||||
|
.where(account_id: account.id, conversation_id: conversation_ids)
|
||||||
|
.where.not(message_type: :activity)
|
||||||
|
.select('DISTINCT ON (messages.conversation_id) messages.*')
|
||||||
|
.reorder(Arel.sql('messages.conversation_id, messages.created_at DESC, messages.id DESC'))
|
||||||
|
.includes(:sender)
|
||||||
|
end
|
||||||
|
|
||||||
|
def inferred_messages_by_event_id
|
||||||
|
@inferred_messages_by_event_id ||= inference_events.each_with_object({}) do |event, messages_by_event_id|
|
||||||
|
messages_by_event_id[event.id] = inferred_message_candidates.find do |message|
|
||||||
|
message_matches_event?(message, event)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def inferred_message_candidates
|
||||||
|
@inferred_message_candidates ||= if inference_events.blank?
|
||||||
|
[]
|
||||||
|
else
|
||||||
|
inferred_messages.to_a
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def inferred_messages
|
||||||
|
Message
|
||||||
|
.where(account_id: account.id, conversation_id: inference_events.map(&:conversation_id).uniq)
|
||||||
|
.where(created_at: inference_time_range)
|
||||||
|
.where(message_type: %i[outgoing template])
|
||||||
|
.includes(:sender)
|
||||||
|
.reorder(created_at: :desc, id: :desc)
|
||||||
|
end
|
||||||
|
|
||||||
|
def message_matches_event?(message, event)
|
||||||
|
message.conversation_id == event.conversation_id &&
|
||||||
|
message.created_at.between?(
|
||||||
|
message_inference_range(event).begin,
|
||||||
|
message_inference_range(event).end
|
||||||
|
) &&
|
||||||
|
message_sender_matches_event?(message, event)
|
||||||
|
end
|
||||||
|
|
||||||
|
def message_sender_matches_event?(message, event)
|
||||||
|
return true unless first_response_event_with_user?(event)
|
||||||
|
|
||||||
|
message.sender_id == event.user_id && message.sender_type == 'User'
|
||||||
|
end
|
||||||
|
|
||||||
|
def inference_time_range
|
||||||
|
event_end_times = inference_events.map(&:event_end_time)
|
||||||
|
|
||||||
|
(event_end_times.min - 1.second)..(event_end_times.max + 1.second)
|
||||||
|
end
|
||||||
|
|
||||||
|
def inference_events
|
||||||
|
@inference_events ||= records.select do |record|
|
||||||
|
record.is_a?(ReportingEvent) && record.conversation_id.present? && record.event_end_time.present?
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def conversation_ids
|
||||||
|
@conversation_ids ||= records.filter_map { |record| conversation_id_for(record) }.uniq
|
||||||
|
end
|
||||||
|
|
||||||
|
def conversation_id_for(record)
|
||||||
|
return record.conversation_id if record.is_a?(Message) || record.is_a?(ReportingEvent)
|
||||||
|
|
||||||
|
record.id
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -40,8 +40,8 @@ class Api::V1::Accounts::ArticlesController < Api::V1::Accounts::BaseController
|
|||||||
end
|
end
|
||||||
|
|
||||||
def reorder
|
def reorder
|
||||||
Article.update_positions(portal: @portal, positions_hash: params[:positions_hash])
|
positions = Article.update_positions(portal: @portal, positions_hash: params[:positions_hash])
|
||||||
head :ok
|
render json: { positions: positions }
|
||||||
end
|
end
|
||||||
|
|
||||||
private
|
private
|
||||||
|
|||||||
@@ -51,6 +51,13 @@ class Api::V2::Accounts::ReportsController < Api::V1::Accounts::BaseController
|
|||||||
generate_csv('conversation_traffic_reports', 'api/v2/accounts/reports/conversation_traffic')
|
generate_csv('conversation_traffic_reports', 'api/v2/accounts/reports/conversation_traffic')
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def drilldown
|
||||||
|
return head :unauthorized unless Current.account_user.administrator?
|
||||||
|
return head :unprocessable_entity unless valid_drilldown_params?
|
||||||
|
|
||||||
|
render json: V2::Reports::DrilldownBuilder.new(Current.account, drilldown_params).build
|
||||||
|
end
|
||||||
|
|
||||||
def conversations
|
def conversations
|
||||||
return head :unprocessable_entity if params[:type].blank?
|
return head :unprocessable_entity if params[:type].blank?
|
||||||
|
|
||||||
@@ -133,6 +140,22 @@ class Api::V2::Accounts::ReportsController < Api::V1::Accounts::BaseController
|
|||||||
})
|
})
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def drilldown_params
|
||||||
|
permitted_params = params.permit(
|
||||||
|
:metric, :id, :since, :until, :group_by, :timezone_offset, :bucket_timestamp, :page, :per_page
|
||||||
|
).to_h.symbolize_keys
|
||||||
|
permitted_params.merge(
|
||||||
|
type: (params[:type].presence || 'account').to_sym,
|
||||||
|
business_hours: ActiveModel::Type::Boolean.new.cast(params[:business_hours])
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
def valid_drilldown_params?
|
||||||
|
%i[metric bucket_timestamp since until].all? { |param| params[param].present? } &&
|
||||||
|
Reports::ReportMetricRegistry.supported?(params[:metric]) &&
|
||||||
|
V2::Reports::DrilldownBuilder.supported_dimension_type?(params[:type]) && Reports::DrilldownTimestampValidator.valid?(params)
|
||||||
|
end
|
||||||
|
|
||||||
def conversation_params
|
def conversation_params
|
||||||
{
|
{
|
||||||
type: params[:type].to_sym,
|
type: params[:type].to_sym,
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ saml:
|
|||||||
enterprise: true
|
enterprise: true
|
||||||
custom_branding:
|
custom_branding:
|
||||||
name: 'Custom Branding'
|
name: 'Custom Branding'
|
||||||
description: 'Apply your own branding to this installation.'
|
description: 'Apply your own branding to this installation, including email template layout customization.'
|
||||||
enabled: <%= (ChatwootHub.pricing_plan != 'community') %>
|
enabled: <%= (ChatwootHub.pricing_plan != 'community') %>
|
||||||
icon: 'icon-paint-brush-line'
|
icon: 'icon-paint-brush-line'
|
||||||
config_key: 'custom_branding'
|
config_key: 'custom_branding'
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
module SuperAdmin::NavigationHelper
|
module SuperAdmin::NavigationHelper
|
||||||
def settings_open?
|
def settings_open?
|
||||||
params[:controller].in? %w[super_admin/settings super_admin/app_configs]
|
return false if params[:controller] == 'super_admin/email_layouts' && params[:account_id].present?
|
||||||
|
|
||||||
|
params[:controller].in? %w[super_admin/settings super_admin/app_configs super_admin/email_layouts]
|
||||||
end
|
end
|
||||||
|
|
||||||
def settings_pages
|
def settings_pages
|
||||||
|
|||||||
@@ -1,10 +1,6 @@
|
|||||||
/* global axios */
|
/* global axios */
|
||||||
import ApiClient from '../ApiClient';
|
import ApiClient from '../ApiClient';
|
||||||
|
|
||||||
// Viewer's UTC offset in hours, matching the reports API convention so the
|
|
||||||
// backend can anchor calendar ranges to the viewer's day.
|
|
||||||
const getTimezoneOffset = () => -new Date().getTimezoneOffset() / 60;
|
|
||||||
|
|
||||||
class CaptainAssistant extends ApiClient {
|
class CaptainAssistant extends ApiClient {
|
||||||
constructor() {
|
constructor() {
|
||||||
super('captain/assistants', { accountScoped: true });
|
super('captain/assistants', { accountScoped: true });
|
||||||
@@ -25,18 +21,6 @@ class CaptainAssistant extends ApiClient {
|
|||||||
message_history: messageHistory,
|
message_history: messageHistory,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
getStats({ assistantId, range }) {
|
|
||||||
return axios.get(`${this.url}/${assistantId}/stats`, {
|
|
||||||
params: { range, timezone_offset: getTimezoneOffset() },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
getSummary({ assistantId, range }) {
|
|
||||||
return axios.get(`${this.url}/${assistantId}/summary`, {
|
|
||||||
params: { range, timezone_offset: getTimezoneOffset() },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export default new CaptainAssistant();
|
export default new CaptainAssistant();
|
||||||
|
|||||||
@@ -31,6 +31,42 @@ class ReportsAPI extends ApiClient {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
getDrilldown({
|
||||||
|
metric,
|
||||||
|
bucketTimestamp,
|
||||||
|
from,
|
||||||
|
to,
|
||||||
|
type = 'account',
|
||||||
|
id,
|
||||||
|
groupBy,
|
||||||
|
businessHours,
|
||||||
|
page,
|
||||||
|
perPage,
|
||||||
|
signal,
|
||||||
|
}) {
|
||||||
|
const requestConfig = {
|
||||||
|
params: {
|
||||||
|
metric,
|
||||||
|
bucket_timestamp: bucketTimestamp,
|
||||||
|
since: from,
|
||||||
|
until: to,
|
||||||
|
type,
|
||||||
|
id,
|
||||||
|
group_by: groupBy,
|
||||||
|
business_hours: businessHours,
|
||||||
|
timezone_offset: getTimeOffset(),
|
||||||
|
page,
|
||||||
|
per_page: perPage,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
if (signal) {
|
||||||
|
requestConfig.signal = signal;
|
||||||
|
}
|
||||||
|
|
||||||
|
return axios.get(`${this.url}/drilldown`, requestConfig);
|
||||||
|
}
|
||||||
|
|
||||||
// eslint-disable-next-line default-param-last
|
// eslint-disable-next-line default-param-last
|
||||||
getSummary(since, until, type = 'account', id, groupBy, businessHours) {
|
getSummary(since, until, type = 'account', id, groupBy, businessHours) {
|
||||||
return axios.get(`${this.url}/summary`, {
|
return axios.get(`${this.url}/summary`, {
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import reportsAPI from '../reports';
|
import reportsAPI from '../reports';
|
||||||
import ApiClient from '../ApiClient';
|
import ApiClient from '../ApiClient';
|
||||||
|
|
||||||
|
const timezoneOffset = () => -new Date().getTimezoneOffset() / 60;
|
||||||
|
|
||||||
describe('#Reports API', () => {
|
describe('#Reports API', () => {
|
||||||
it('creates correct instance', () => {
|
it('creates correct instance', () => {
|
||||||
expect(reportsAPI).toBeInstanceOf(ApiClient);
|
expect(reportsAPI).toBeInstanceOf(ApiClient);
|
||||||
@@ -11,6 +13,7 @@ describe('#Reports API', () => {
|
|||||||
expect(reportsAPI).toHaveProperty('update');
|
expect(reportsAPI).toHaveProperty('update');
|
||||||
expect(reportsAPI).toHaveProperty('delete');
|
expect(reportsAPI).toHaveProperty('delete');
|
||||||
expect(reportsAPI).toHaveProperty('getReports');
|
expect(reportsAPI).toHaveProperty('getReports');
|
||||||
|
expect(reportsAPI).toHaveProperty('getDrilldown');
|
||||||
expect(reportsAPI).toHaveProperty('getSummary');
|
expect(reportsAPI).toHaveProperty('getSummary');
|
||||||
expect(reportsAPI).toHaveProperty('getAgentReports');
|
expect(reportsAPI).toHaveProperty('getAgentReports');
|
||||||
expect(reportsAPI).toHaveProperty('getLabelReports');
|
expect(reportsAPI).toHaveProperty('getLabelReports');
|
||||||
@@ -42,11 +45,14 @@ describe('#Reports API', () => {
|
|||||||
});
|
});
|
||||||
expect(axiosMock.get).toHaveBeenCalledWith('/api/v2/reports', {
|
expect(axiosMock.get).toHaveBeenCalledWith('/api/v2/reports', {
|
||||||
params: {
|
params: {
|
||||||
|
business_hours: undefined,
|
||||||
|
group_by: undefined,
|
||||||
|
id: undefined,
|
||||||
metric: 'conversations_count',
|
metric: 'conversations_count',
|
||||||
since: 1621103400,
|
since: 1621103400,
|
||||||
until: 1621621800,
|
until: 1621621800,
|
||||||
type: 'account',
|
type: 'account',
|
||||||
timezone_offset: -0,
|
timezone_offset: timezoneOffset(),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -59,13 +65,70 @@ describe('#Reports API', () => {
|
|||||||
group_by: undefined,
|
group_by: undefined,
|
||||||
id: undefined,
|
id: undefined,
|
||||||
since: 1621103400,
|
since: 1621103400,
|
||||||
timezone_offset: -0,
|
timezone_offset: timezoneOffset(),
|
||||||
type: 'account',
|
type: 'account',
|
||||||
until: 1621621800,
|
until: 1621621800,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('#getDrilldown', () => {
|
||||||
|
reportsAPI.getDrilldown({
|
||||||
|
metric: 'incoming_messages_count',
|
||||||
|
bucketTimestamp: 1621103400,
|
||||||
|
from: 1621103400,
|
||||||
|
to: 1621621800,
|
||||||
|
type: 'inbox',
|
||||||
|
id: 1,
|
||||||
|
groupBy: 'day',
|
||||||
|
businessHours: false,
|
||||||
|
page: 2,
|
||||||
|
perPage: 25,
|
||||||
|
});
|
||||||
|
expect(axiosMock.get).toHaveBeenCalledWith('/api/v2/reports/drilldown', {
|
||||||
|
params: {
|
||||||
|
metric: 'incoming_messages_count',
|
||||||
|
bucket_timestamp: 1621103400,
|
||||||
|
since: 1621103400,
|
||||||
|
until: 1621621800,
|
||||||
|
type: 'inbox',
|
||||||
|
id: 1,
|
||||||
|
group_by: 'day',
|
||||||
|
business_hours: false,
|
||||||
|
timezone_offset: timezoneOffset(),
|
||||||
|
page: 2,
|
||||||
|
per_page: 25,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('#getDrilldown with abort signal', () => {
|
||||||
|
const controller = new AbortController();
|
||||||
|
|
||||||
|
reportsAPI.getDrilldown({
|
||||||
|
metric: 'incoming_messages_count',
|
||||||
|
bucketTimestamp: 1621103400,
|
||||||
|
signal: controller.signal,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(axiosMock.get).toHaveBeenCalledWith('/api/v2/reports/drilldown', {
|
||||||
|
params: {
|
||||||
|
metric: 'incoming_messages_count',
|
||||||
|
bucket_timestamp: 1621103400,
|
||||||
|
since: undefined,
|
||||||
|
until: undefined,
|
||||||
|
type: 'account',
|
||||||
|
id: undefined,
|
||||||
|
group_by: undefined,
|
||||||
|
business_hours: undefined,
|
||||||
|
timezone_offset: timezoneOffset(),
|
||||||
|
page: undefined,
|
||||||
|
per_page: undefined,
|
||||||
|
},
|
||||||
|
signal: controller.signal,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
it('#getAgentReports', () => {
|
it('#getAgentReports', () => {
|
||||||
reportsAPI.getAgentReports({
|
reportsAPI.getAgentReports({
|
||||||
from: 1621103400,
|
from: 1621103400,
|
||||||
|
|||||||
+7
-1
@@ -16,6 +16,10 @@ const props = defineProps({
|
|||||||
type: Array,
|
type: Array,
|
||||||
required: true,
|
required: true,
|
||||||
},
|
},
|
||||||
|
contact: {
|
||||||
|
type: Object,
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
@@ -49,7 +53,9 @@ const unreadMessagesCount = computed(() => {
|
|||||||
|
|
||||||
const hasSlaThreshold = computed(() => {
|
const hasSlaThreshold = computed(() => {
|
||||||
return (
|
return (
|
||||||
slaCardLabelRef.value?.hasSlaThreshold && props.conversation?.slaPolicyId
|
!props.contact?.blocked &&
|
||||||
|
slaCardLabelRef.value?.hasSlaThreshold &&
|
||||||
|
props.conversation?.appliedSla?.id
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
+1
@@ -126,6 +126,7 @@ const onCardClick = e => {
|
|||||||
v-show="!showMessagePreviewWithoutMeta"
|
v-show="!showMessagePreviewWithoutMeta"
|
||||||
ref="cardMessagePreviewWithMetaRef"
|
ref="cardMessagePreviewWithMetaRef"
|
||||||
:conversation="conversation"
|
:conversation="conversation"
|
||||||
|
:contact="contact"
|
||||||
:account-labels="accountLabels"
|
:account-labels="accountLabels"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+3
-1
@@ -51,7 +51,9 @@ const unreadCount = computed(() => props.chat.unread_count);
|
|||||||
const slaCardLabel = useTemplateRef('slaCardLabel');
|
const slaCardLabel = useTemplateRef('slaCardLabel');
|
||||||
|
|
||||||
const hasSlaPolicyId = computed(
|
const hasSlaPolicyId = computed(
|
||||||
() => props.chat?.sla_policy_id || slaCardLabel.value?.hasSlaThreshold
|
() =>
|
||||||
|
!props.currentContact?.blocked &&
|
||||||
|
(props.chat?.applied_sla?.id || slaCardLabel.value?.hasSlaThreshold)
|
||||||
);
|
);
|
||||||
|
|
||||||
const selectedModel = computed({
|
const selectedModel = computed({
|
||||||
|
|||||||
+4
-11
@@ -1,6 +1,6 @@
|
|||||||
<script setup>
|
<script setup>
|
||||||
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
|
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
|
||||||
import { evaluateSLAStatus } from '@chatwoot/utils';
|
import { evaluateSLAStatus } from 'dashboard/helper/slaHelper';
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
conversation: {
|
conversation: {
|
||||||
@@ -19,16 +19,8 @@ const slaStatus = ref({
|
|||||||
icon: null,
|
icon: null,
|
||||||
});
|
});
|
||||||
|
|
||||||
// TODO: Remove this once we update the helper from utils
|
|
||||||
// https://github.com/chatwoot/utils/blob/main/src/sla.ts#L73
|
|
||||||
const convertObjectCamelCaseToSnakeCase = object => {
|
|
||||||
return Object.keys(object).reduce((acc, key) => {
|
|
||||||
acc[key.replace(/([A-Z])/g, '_$1').toLowerCase()] = object[key];
|
|
||||||
return acc;
|
|
||||||
}, {});
|
|
||||||
};
|
|
||||||
|
|
||||||
const appliedSLA = computed(() => props.conversation?.appliedSla);
|
const appliedSLA = computed(() => props.conversation?.appliedSla);
|
||||||
|
const slaEvents = computed(() => props.conversation?.slaEvents);
|
||||||
const isSlaMissed = computed(() => slaStatus.value?.isSlaMissed);
|
const isSlaMissed = computed(() => slaStatus.value?.isSlaMissed);
|
||||||
|
|
||||||
const hasSlaThreshold = computed(() => {
|
const hasSlaThreshold = computed(() => {
|
||||||
@@ -41,8 +33,9 @@ const slaStatusText = computed(() => {
|
|||||||
|
|
||||||
const updateSlaStatus = () => {
|
const updateSlaStatus = () => {
|
||||||
slaStatus.value = evaluateSLAStatus({
|
slaStatus.value = evaluateSLAStatus({
|
||||||
appliedSla: convertObjectCamelCaseToSnakeCase(appliedSLA.value || {}),
|
appliedSla: appliedSLA.value || {},
|
||||||
chat: props.conversation,
|
chat: props.conversation,
|
||||||
|
slaEvents: slaEvents.value || [],
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<script setup>
|
<script setup>
|
||||||
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
|
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
|
||||||
import { evaluateSLAStatus } from '@chatwoot/utils';
|
import { evaluateSLAStatus } from 'dashboard/helper/slaHelper';
|
||||||
|
|
||||||
import Icon from 'dashboard/components-next/icon/Icon.vue';
|
import Icon from 'dashboard/components-next/icon/Icon.vue';
|
||||||
import Label from 'dashboard/components-next/label/Label.vue';
|
import Label from 'dashboard/components-next/label/Label.vue';
|
||||||
@@ -27,6 +27,7 @@ defineOptions({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const appliedSLA = computed(() => props.chat?.applied_sla);
|
const appliedSLA = computed(() => props.chat?.applied_sla);
|
||||||
|
const slaEvents = computed(() => props.chat?.sla_events);
|
||||||
const hasSlaThreshold = computed(() => slaStatus.value?.threshold);
|
const hasSlaThreshold = computed(() => slaStatus.value?.threshold);
|
||||||
const isSlaMissed = computed(() => slaStatus.value?.isSlaMissed);
|
const isSlaMissed = computed(() => slaStatus.value?.isSlaMissed);
|
||||||
|
|
||||||
@@ -34,6 +35,7 @@ const updateSlaStatus = () => {
|
|||||||
slaStatus.value = evaluateSLAStatus({
|
slaStatus.value = evaluateSLAStatus({
|
||||||
appliedSla: appliedSLA.value || {},
|
appliedSla: appliedSLA.value || {},
|
||||||
chat: props.chat,
|
chat: props.chat,
|
||||||
|
slaEvents: slaEvents.value || [],
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
+378
@@ -0,0 +1,378 @@
|
|||||||
|
<script setup>
|
||||||
|
import { computed, ref, watch, nextTick, onBeforeUnmount } from 'vue';
|
||||||
|
import { useEventListener, onKeyStroke, useRafFn } from '@vueuse/core';
|
||||||
|
import Icon from 'dashboard/components-next/icon/Icon.vue';
|
||||||
|
|
||||||
|
// Reorderable list with cross-page drag. It must stay mounted during a page
|
||||||
|
// fetch — hide the list spinner while `dragging`, or the held item is lost.
|
||||||
|
const props = defineProps({
|
||||||
|
items: { type: Array, required: true },
|
||||||
|
itemKey: { type: String, default: 'id' },
|
||||||
|
disabled: { type: Boolean, default: false },
|
||||||
|
currentPage: { type: Number, default: 1 },
|
||||||
|
totalPages: { type: Number, default: 1 },
|
||||||
|
});
|
||||||
|
const emit = defineEmits(['reorder', 'navigatePage', 'dragging']);
|
||||||
|
|
||||||
|
const DRAG_THRESHOLD = 5;
|
||||||
|
const EDGE_BAND = 72; // px from a side that arms a page turn
|
||||||
|
const AUTO_PAGE_DELAY = 600; // ms hovering an edge before it flips
|
||||||
|
const SCROLL_BAND = 60; // px from top/bottom that autoscrolls the list
|
||||||
|
const SCROLL_STEP = 10; // px scrolled per frame while parked at an edge
|
||||||
|
const PILL = 36; // px, the page-turn arrow button on each edge
|
||||||
|
|
||||||
|
const root = ref(null);
|
||||||
|
const isDragging = ref(false);
|
||||||
|
const dragged = ref(null);
|
||||||
|
const pointer = ref({ x: 0, y: 0 });
|
||||||
|
const insertBefore = ref(null); // key the gap sits before, null = end of list
|
||||||
|
const activeEdge = ref(null);
|
||||||
|
const bounds = ref({ left: 0, right: 0, top: 0, bottom: 0 }); // visible list rect
|
||||||
|
const grab = ref({ dx: 0, dy: 0 }); // cursor offset inside the grabbed card
|
||||||
|
const dragHeight = ref(0);
|
||||||
|
|
||||||
|
let press = null; // pending press, before it becomes a drag
|
||||||
|
let dwell = null; // timer that flips the page after hovering an edge
|
||||||
|
let paging = false; // waiting for a flipped page to load
|
||||||
|
let scroller = null; // scrollable ancestor, found when a drag begins
|
||||||
|
let scrollDir = 0; // -1 up, +1 down, 0 idle
|
||||||
|
let sourcePage = 1; // page the drag started on, to resolve cross-page end-drops
|
||||||
|
|
||||||
|
const keyOf = item => String(item?.[props.itemKey]);
|
||||||
|
const others = item => props.items.filter(o => keyOf(o) !== keyOf(item));
|
||||||
|
const isRTL = () =>
|
||||||
|
document.querySelector('#app[dir]')?.getAttribute('dir') === 'rtl';
|
||||||
|
const canPage = dir =>
|
||||||
|
dir === 'next' ? props.currentPage < props.totalPages : props.currentPage > 1;
|
||||||
|
|
||||||
|
// Key of the item after `key` in `list`, or null when it is the last one.
|
||||||
|
const keyAfter = (list, key) => {
|
||||||
|
const next = list[list.findIndex(o => keyOf(o) === key) + 1];
|
||||||
|
return next ? keyOf(next) : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const edges = computed(() =>
|
||||||
|
['prev', 'next'].filter(canPage).map(dir => {
|
||||||
|
const onLeft = isRTL() ? dir === 'next' : dir === 'prev';
|
||||||
|
return {
|
||||||
|
dir,
|
||||||
|
onLeft,
|
||||||
|
icon: onLeft ? 'i-lucide-chevrons-left' : 'i-lucide-chevrons-right',
|
||||||
|
};
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
// Cursor overlay: an edge glow band, a page-turn arrow per edge, and a ghost of
|
||||||
|
// the dragged row that follows the cursor and shrinks when aimed at an edge.
|
||||||
|
const EDGE_BAND_W = 80; // px width of the glow band on each pageable edge
|
||||||
|
const bandStyle = onLeft => {
|
||||||
|
const x = onLeft ? bounds.value.left : bounds.value.right - EDGE_BAND_W;
|
||||||
|
return {
|
||||||
|
width: `${EDGE_BAND_W}px`,
|
||||||
|
height: `${bounds.value.bottom - bounds.value.top}px`,
|
||||||
|
transform: `translate(${x}px, ${bounds.value.top}px)`,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
const pillStyle = onLeft => {
|
||||||
|
const x = onLeft ? bounds.value.left + 12 : bounds.value.right - PILL - 12;
|
||||||
|
return { transform: `translate(${x}px, ${pointer.value.y - PILL / 2}px)` };
|
||||||
|
};
|
||||||
|
const ghostStyle = computed(() => ({
|
||||||
|
width: `${bounds.value.right - bounds.value.left}px`,
|
||||||
|
transform: `translate(${pointer.value.x - grab.value.dx}px, ${pointer.value.y - grab.value.dy}px)`,
|
||||||
|
}));
|
||||||
|
const scaleStyle = computed(() => ({
|
||||||
|
transformOrigin: `${grab.value.dx}px ${grab.value.dy}px`,
|
||||||
|
}));
|
||||||
|
|
||||||
|
// The list as shown mid-drag: the dragged row slotted into the gap at `insertBefore`.
|
||||||
|
const displayItems = computed(() => {
|
||||||
|
if (!isDragging.value || !dragged.value) return props.items;
|
||||||
|
const rest = others(dragged.value);
|
||||||
|
const at = rest.findIndex(o => keyOf(o) === insertBefore.value);
|
||||||
|
rest.splice(at === -1 ? rest.length : at, 0, dragged.value);
|
||||||
|
return rest;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Move the gap when the cursor crosses the midpoint of the card it is over.
|
||||||
|
const aim = () => {
|
||||||
|
const card = document
|
||||||
|
.elementFromPoint(pointer.value.x, pointer.value.y)
|
||||||
|
?.closest('[data-drag-id]');
|
||||||
|
const key = card?.dataset.dragId;
|
||||||
|
if (!key || key === keyOf(dragged.value)) return;
|
||||||
|
|
||||||
|
const { top, height } = card.getBoundingClientRect();
|
||||||
|
const above = pointer.value.y < top + height / 2;
|
||||||
|
insertBefore.value = above ? key : keyAfter(others(dragged.value), key);
|
||||||
|
};
|
||||||
|
|
||||||
|
const flip = dir => {
|
||||||
|
if (paging || !isDragging.value) return;
|
||||||
|
paging = true;
|
||||||
|
emit('navigatePage', props.currentPage + (dir === 'next' ? 1 : -1));
|
||||||
|
};
|
||||||
|
|
||||||
|
const aimEdge = x => {
|
||||||
|
const rect = root.value?.getBoundingClientRect();
|
||||||
|
if (!rect) return;
|
||||||
|
// Clip the list rect to the scroll viewport so the glow band and its top/bottom
|
||||||
|
// fade always sit on the visible edges, not the far ends of the full content.
|
||||||
|
const view = scroller?.getBoundingClientRect();
|
||||||
|
const viewTop = Math.max(view?.top ?? 0, 0);
|
||||||
|
const viewBottom = Math.min(
|
||||||
|
view?.bottom ?? window.innerHeight,
|
||||||
|
window.innerHeight
|
||||||
|
);
|
||||||
|
bounds.value = {
|
||||||
|
left: rect.left,
|
||||||
|
right: rect.right,
|
||||||
|
top: Math.max(rect.top, viewTop),
|
||||||
|
bottom: Math.min(rect.bottom, viewBottom),
|
||||||
|
};
|
||||||
|
|
||||||
|
let dir = null;
|
||||||
|
if (x <= rect.left + EDGE_BAND) dir = isRTL() ? 'next' : 'prev';
|
||||||
|
else if (x >= rect.right - EDGE_BAND) dir = isRTL() ? 'prev' : 'next';
|
||||||
|
if (dir && !canPage(dir)) dir = null;
|
||||||
|
if (dir === activeEdge.value) return;
|
||||||
|
|
||||||
|
activeEdge.value = dir;
|
||||||
|
clearTimeout(dwell);
|
||||||
|
if (dir) dwell = setTimeout(() => flip(dir), AUTO_PAGE_DELAY);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Nearest scrollable ancestor, so a drag can reach rows that are off-screen.
|
||||||
|
const scrollParent = () => {
|
||||||
|
let el = root.value?.parentElement;
|
||||||
|
while (el) {
|
||||||
|
const { overflowY } = getComputedStyle(el);
|
||||||
|
if (overflowY === 'auto' || overflowY === 'scroll') return el;
|
||||||
|
el = el.parentElement;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
// While parked at the top/bottom edge, keep scrolling and re-aim as rows slide by.
|
||||||
|
const { pause: pauseScroll, resume: resumeScroll } = useRafFn(
|
||||||
|
() => {
|
||||||
|
if (!scroller || !scrollDir) return;
|
||||||
|
scroller.scrollTop += scrollDir * SCROLL_STEP;
|
||||||
|
aim();
|
||||||
|
aimEdge(pointer.value.x);
|
||||||
|
},
|
||||||
|
{ immediate: false }
|
||||||
|
);
|
||||||
|
|
||||||
|
const updateAutoScroll = y => {
|
||||||
|
if (!scroller) return;
|
||||||
|
const rect = scroller.getBoundingClientRect();
|
||||||
|
const atTop = scroller.scrollTop <= 0;
|
||||||
|
const atBottom =
|
||||||
|
scroller.scrollTop >= scroller.scrollHeight - scroller.clientHeight;
|
||||||
|
if (y < rect.top + SCROLL_BAND && !atTop) scrollDir = -1;
|
||||||
|
else if (y > rect.bottom - SCROLL_BAND && !atBottom) scrollDir = 1;
|
||||||
|
else scrollDir = 0;
|
||||||
|
if (scrollDir) resumeScroll();
|
||||||
|
else pauseScroll();
|
||||||
|
};
|
||||||
|
|
||||||
|
const reset = () => {
|
||||||
|
isDragging.value = false;
|
||||||
|
dragged.value = null;
|
||||||
|
insertBefore.value = null;
|
||||||
|
activeEdge.value = null;
|
||||||
|
clearTimeout(dwell);
|
||||||
|
paging = false;
|
||||||
|
scrollDir = 0;
|
||||||
|
scroller = null;
|
||||||
|
pauseScroll();
|
||||||
|
document.body.classList.remove('select-none');
|
||||||
|
emit('dragging', false);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Positions sit on a gap-of-10 grid; a midpoint (±5 at the ends) slots between two rows.
|
||||||
|
// Cross-page end-drops are the tricky case: moving an item off its source page pulls the
|
||||||
|
// target page's boundary row into the vacated slot. So at the leading edge after moving
|
||||||
|
// DOWN (or the trailing edge after moving UP) we land between the two boundary rows, or
|
||||||
|
// the item sorts onto the adjacent page and vanishes from view.
|
||||||
|
const drop = (item, rawBefore) => {
|
||||||
|
const pos = o => o?.position || 0;
|
||||||
|
const mid = (a, b) => Math.floor((pos(a) + pos(b)) / 2);
|
||||||
|
const rest = others(item);
|
||||||
|
// No other rows to position against — e.g. the lone article on a page dropped
|
||||||
|
// without crossing to another page. Leave the order untouched.
|
||||||
|
if (!rest.length) return;
|
||||||
|
// A page flip can leave the aimed key pointing at a row that is no longer on
|
||||||
|
// this page. Like displayItems, resolve an unknown key to null (end of list),
|
||||||
|
// so what the user sees and what we save agree.
|
||||||
|
const before = rest.some(o => keyOf(o) === rawBefore) ? rawBefore : null;
|
||||||
|
const movedDown = props.currentPage > sourcePage;
|
||||||
|
const movedUp = props.currentPage < sourcePage;
|
||||||
|
|
||||||
|
let position;
|
||||||
|
if (before === null) {
|
||||||
|
position =
|
||||||
|
movedUp && rest.length >= 2
|
||||||
|
? mid(rest.at(-2), rest.at(-1))
|
||||||
|
: pos(rest.at(-1)) + 5;
|
||||||
|
} else {
|
||||||
|
const i = rest.findIndex(o => keyOf(o) === before);
|
||||||
|
if (i > 0) {
|
||||||
|
position = mid(rest[i - 1], rest[i]);
|
||||||
|
} else if (movedDown) {
|
||||||
|
// Top-of-page after moving down: the old first row slid up into the source
|
||||||
|
// page's gap, so land just after it to stay this page's first.
|
||||||
|
position = rest.length >= 2 ? mid(rest[0], rest[1]) : pos(rest[0]) + 5;
|
||||||
|
} else {
|
||||||
|
position = pos(rest[0]) - 5;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
emit('reorder', { [item[props.itemKey]]: position });
|
||||||
|
};
|
||||||
|
|
||||||
|
const startDrag = () => {
|
||||||
|
isDragging.value = true;
|
||||||
|
dragged.value = press.item;
|
||||||
|
grab.value = { dx: press.dx, dy: press.dy };
|
||||||
|
dragHeight.value = press.h;
|
||||||
|
insertBefore.value = keyAfter(props.items, keyOf(press.item));
|
||||||
|
sourcePage = props.currentPage;
|
||||||
|
scroller = scrollParent();
|
||||||
|
document.body.classList.add('select-none');
|
||||||
|
emit('dragging', true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const onPointerDown = (item, e) => {
|
||||||
|
if (e.button !== 0 || props.disabled) return;
|
||||||
|
if (e.target.closest('button, a, input, [role="button"]')) return;
|
||||||
|
const rect = e.currentTarget.getBoundingClientRect();
|
||||||
|
press = {
|
||||||
|
item,
|
||||||
|
x: e.clientX,
|
||||||
|
y: e.clientY,
|
||||||
|
dx: e.clientX - rect.left,
|
||||||
|
dy: e.clientY - rect.top,
|
||||||
|
h: rect.height,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
useEventListener(window, 'pointermove', e => {
|
||||||
|
if (!press) return;
|
||||||
|
if (!isDragging.value) {
|
||||||
|
const moved = Math.hypot(e.clientX - press.x, e.clientY - press.y);
|
||||||
|
if (moved < DRAG_THRESHOLD) return;
|
||||||
|
startDrag();
|
||||||
|
}
|
||||||
|
e.preventDefault();
|
||||||
|
pointer.value = { x: e.clientX, y: e.clientY };
|
||||||
|
aim();
|
||||||
|
aimEdge(e.clientX);
|
||||||
|
updateAutoScroll(e.clientY);
|
||||||
|
});
|
||||||
|
|
||||||
|
useEventListener(window, 'pointerup', () => {
|
||||||
|
if (!press) return;
|
||||||
|
press = null;
|
||||||
|
if (!isDragging.value) return; // a press without movement is a click
|
||||||
|
const item = dragged.value;
|
||||||
|
const before = insertBefore.value;
|
||||||
|
const flipping = paging;
|
||||||
|
reset();
|
||||||
|
if (!flipping) drop(item, before);
|
||||||
|
});
|
||||||
|
|
||||||
|
// When the flipped page loads, re-aim under the held cursor so a parked edge keeps flipping.
|
||||||
|
watch(
|
||||||
|
() => props.items,
|
||||||
|
() => {
|
||||||
|
if (!isDragging.value || !paging) return;
|
||||||
|
paging = false;
|
||||||
|
nextTick(() => {
|
||||||
|
if (!isDragging.value) return;
|
||||||
|
aim();
|
||||||
|
activeEdge.value = null;
|
||||||
|
aimEdge(pointer.value.x);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
onKeyStroke('Escape', () => {
|
||||||
|
if (!isDragging.value) return;
|
||||||
|
press = null;
|
||||||
|
reset();
|
||||||
|
});
|
||||||
|
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
clearTimeout(dwell);
|
||||||
|
document.body.classList.remove('select-none');
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div ref="root" class="relative w-full h-full">
|
||||||
|
<ul class="w-full h-full space-y-4">
|
||||||
|
<li
|
||||||
|
v-for="(item, index) in displayItems"
|
||||||
|
:key="keyOf(item)"
|
||||||
|
:data-drag-id="keyOf(item)"
|
||||||
|
class="relative list-none"
|
||||||
|
:class="{ 'cursor-grab': !disabled && !isDragging }"
|
||||||
|
@pointerdown="onPointerDown(item, $event)"
|
||||||
|
@dragstart.prevent
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
v-if="isDragging && keyOf(item) === keyOf(dragged)"
|
||||||
|
:style="{ height: `${dragHeight}px` }"
|
||||||
|
class="border-2 border-dashed rounded-2xl border-n-brand/50 bg-n-brand/5"
|
||||||
|
/>
|
||||||
|
<slot v-else name="item" :item="item" :index="index" />
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<Teleport v-if="isDragging" to="body">
|
||||||
|
<div
|
||||||
|
v-for="edge in edges"
|
||||||
|
:key="`band-${edge.dir}`"
|
||||||
|
:style="bandStyle(edge.onLeft)"
|
||||||
|
class="fixed top-0 left-0 z-40 pointer-events-none from-n-brand/15 to-transparent transition-opacity duration-200 [mask-image:linear-gradient(to_bottom,transparent,#000_56px,#000_calc(100%_-_56px),transparent)] [-webkit-mask-image:linear-gradient(to_bottom,transparent,#000_56px,#000_calc(100%_-_56px),transparent)]"
|
||||||
|
:class="[
|
||||||
|
edge.onLeft ? 'bg-gradient-to-r' : 'bg-gradient-to-l',
|
||||||
|
activeEdge === edge.dir ? 'opacity-100' : 'opacity-0',
|
||||||
|
]"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div
|
||||||
|
v-for="edge in edges"
|
||||||
|
:key="edge.dir"
|
||||||
|
:style="pillStyle(edge.onLeft)"
|
||||||
|
class="fixed top-0 left-0 z-50 flex items-center justify-center transition-all duration-150 border rounded-full pointer-events-none size-9 backdrop-blur-sm"
|
||||||
|
:class="
|
||||||
|
activeEdge === edge.dir
|
||||||
|
? 'scale-110 border-n-brand bg-n-brand/20 text-n-brand shadow-md'
|
||||||
|
: 'opacity-70 border-n-weak/60 bg-n-solid-1/70 text-n-slate-10'
|
||||||
|
"
|
||||||
|
>
|
||||||
|
<Icon
|
||||||
|
:icon="edge.icon"
|
||||||
|
class="size-4"
|
||||||
|
:class="activeEdge === edge.dir && 'animate-pulse'"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div
|
||||||
|
v-if="dragged"
|
||||||
|
:style="ghostStyle"
|
||||||
|
class="fixed top-0 left-0 z-50 pointer-events-none select-none"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
:style="scaleStyle"
|
||||||
|
class="transition-transform duration-150 shadow-2xl rounded-2xl"
|
||||||
|
:class="{ 'scale-50': activeEdge }"
|
||||||
|
>
|
||||||
|
<slot name="ghost" :item="dragged" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Teleport>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
+222
@@ -0,0 +1,222 @@
|
|||||||
|
import { mount } from '@vue/test-utils';
|
||||||
|
import { h, nextTick } from 'vue';
|
||||||
|
import DraggableReorderList from '../DraggableReorderList.vue';
|
||||||
|
|
||||||
|
// The component is pointer-driven, so we drive it through real pointer events on
|
||||||
|
// window while mocking the layout APIs jsdom does not implement: elementFromPoint
|
||||||
|
// (which card is under the cursor) and getBoundingClientRect (its geometry).
|
||||||
|
const elementAtPoint = { current: null };
|
||||||
|
|
||||||
|
const move = (clientX, clientY) =>
|
||||||
|
window.dispatchEvent(new MouseEvent('pointermove', { clientX, clientY }));
|
||||||
|
const release = () => window.dispatchEvent(new MouseEvent('pointerup'));
|
||||||
|
|
||||||
|
// Stack the rows 50px apart, each 40px tall, inside a 500px-wide list.
|
||||||
|
const stubGeometry = wrapper => {
|
||||||
|
wrapper.element.getBoundingClientRect = () => ({
|
||||||
|
left: 0,
|
||||||
|
right: 500,
|
||||||
|
top: 0,
|
||||||
|
bottom: 600,
|
||||||
|
});
|
||||||
|
wrapper.findAll('[data-drag-id]').forEach((li, index) => {
|
||||||
|
const top = index * 50;
|
||||||
|
li.element.getBoundingClientRect = () => ({
|
||||||
|
top,
|
||||||
|
height: 40,
|
||||||
|
bottom: top + 40,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const mountList = (props = {}) =>
|
||||||
|
mount(DraggableReorderList, {
|
||||||
|
props: { items: [], ...props },
|
||||||
|
slots: {
|
||||||
|
item: scope => h('div', { class: 'card' }, scope.item.title),
|
||||||
|
ghost: scope => h('div', { class: 'ghost' }, scope.item.title),
|
||||||
|
},
|
||||||
|
global: { stubs: { Icon: true, teleport: true } },
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('DraggableReorderList', () => {
|
||||||
|
let wrapper;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
elementAtPoint.current = null;
|
||||||
|
document.elementFromPoint = vi.fn(() => elementAtPoint.current);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
wrapper?.unmount();
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
const startDragging = async id => {
|
||||||
|
stubGeometry(wrapper);
|
||||||
|
wrapper.find(`[data-drag-id="${id}"]`).element.dispatchEvent(
|
||||||
|
new MouseEvent('pointerdown', {
|
||||||
|
button: 0,
|
||||||
|
clientX: 250,
|
||||||
|
clientY: 20,
|
||||||
|
bubbles: true,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
await nextTick();
|
||||||
|
};
|
||||||
|
|
||||||
|
it('renders each item through the item slot', () => {
|
||||||
|
wrapper = mountList({
|
||||||
|
items: [
|
||||||
|
{ id: 1, title: 'Alpha' },
|
||||||
|
{ id: 2, title: 'Beta' },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const cards = wrapper.findAll('.card');
|
||||||
|
expect(cards).toHaveLength(2);
|
||||||
|
expect(cards[0].text()).toBe('Alpha');
|
||||||
|
expect(wrapper.find('[data-drag-id="1"]').exists()).toBe(true);
|
||||||
|
expect(wrapper.find('[data-drag-id="2"]').exists()).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows a grab affordance only when enabled', () => {
|
||||||
|
wrapper = mountList({ items: [{ id: 1, title: 'Alpha' }] });
|
||||||
|
expect(wrapper.find('[data-drag-id="1"]').classes()).toContain(
|
||||||
|
'cursor-grab'
|
||||||
|
);
|
||||||
|
|
||||||
|
wrapper.unmount();
|
||||||
|
wrapper = mountList({ items: [{ id: 1, title: 'Alpha' }], disabled: true });
|
||||||
|
expect(wrapper.find('[data-drag-id="1"]').classes()).not.toContain(
|
||||||
|
'cursor-grab'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not start a drag when disabled', async () => {
|
||||||
|
wrapper = mountList({
|
||||||
|
items: [
|
||||||
|
{ id: 1, title: 'Alpha' },
|
||||||
|
{ id: 2, title: 'Beta' },
|
||||||
|
],
|
||||||
|
disabled: true,
|
||||||
|
});
|
||||||
|
await startDragging(1);
|
||||||
|
move(250, 200);
|
||||||
|
await nextTick();
|
||||||
|
|
||||||
|
expect(wrapper.emitted('dragging')).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('emits dragging true then false across a drag', async () => {
|
||||||
|
wrapper = mountList({
|
||||||
|
items: [
|
||||||
|
{ id: 1, title: 'Alpha' },
|
||||||
|
{ id: 2, title: 'Beta' },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
await startDragging(1);
|
||||||
|
elementAtPoint.current = wrapper.find('[data-drag-id="2"]').element;
|
||||||
|
move(250, 60);
|
||||||
|
await nextTick();
|
||||||
|
|
||||||
|
expect(wrapper.emitted('dragging')[0]).toEqual([true]);
|
||||||
|
|
||||||
|
release();
|
||||||
|
await nextTick();
|
||||||
|
expect(wrapper.emitted('dragging')[1]).toEqual([false]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('emits the midpoint position when dropped between two rows', async () => {
|
||||||
|
wrapper = mountList({
|
||||||
|
items: [
|
||||||
|
{ id: 1, title: 'Alpha', position: 10 },
|
||||||
|
{ id: 2, title: 'Beta', position: 20 },
|
||||||
|
{ id: 3, title: 'Gamma', position: 30 },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
await startDragging(1);
|
||||||
|
|
||||||
|
// Hover the lower half of Beta (top 50, height 40 → midpoint 70) so the gap
|
||||||
|
// sits before Gamma; dropping there lands halfway between Beta and Gamma.
|
||||||
|
elementAtPoint.current = wrapper.find('[data-drag-id="2"]').element;
|
||||||
|
move(250, 85);
|
||||||
|
await nextTick();
|
||||||
|
release();
|
||||||
|
await nextTick();
|
||||||
|
|
||||||
|
expect(wrapper.emitted('reorder')[0][0]).toEqual({ 1: 25 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not reorder when the only row on a page is dropped in place', async () => {
|
||||||
|
// P1: dragging the lone article on a later page and releasing without
|
||||||
|
// crossing to another page must be a no-op, not move it to the top.
|
||||||
|
wrapper = mountList({
|
||||||
|
items: [{ id: 5, title: 'Solo', position: 260 }],
|
||||||
|
currentPage: 2,
|
||||||
|
totalPages: 2,
|
||||||
|
});
|
||||||
|
await startDragging(5);
|
||||||
|
move(250, 300);
|
||||||
|
await nextTick();
|
||||||
|
release();
|
||||||
|
await nextTick();
|
||||||
|
|
||||||
|
expect(wrapper.emitted('dragging')).toEqual([[true], [false]]);
|
||||||
|
expect(wrapper.emitted('reorder')).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('turns the page after dwelling on a pageable edge', async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
wrapper = mountList({
|
||||||
|
items: [
|
||||||
|
{ id: 1, title: 'Alpha', position: 10 },
|
||||||
|
{ id: 2, title: 'Beta', position: 20 },
|
||||||
|
],
|
||||||
|
currentPage: 1,
|
||||||
|
totalPages: 2,
|
||||||
|
});
|
||||||
|
await startDragging(1);
|
||||||
|
|
||||||
|
// Drag to the right edge over blank space (no card) and hold.
|
||||||
|
elementAtPoint.current = null;
|
||||||
|
move(490, 20);
|
||||||
|
await nextTick();
|
||||||
|
vi.advanceTimersByTime(600);
|
||||||
|
|
||||||
|
expect(wrapper.emitted('navigatePage')[0]).toEqual([2]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('can still turn pages after releasing during a pending flip', async () => {
|
||||||
|
// Releasing while a flip fetch is in flight must clear paging state, or every
|
||||||
|
// later drag would be stuck unable to navigate.
|
||||||
|
vi.useFakeTimers();
|
||||||
|
wrapper = mountList({
|
||||||
|
items: [
|
||||||
|
{ id: 1, title: 'Alpha', position: 10 },
|
||||||
|
{ id: 2, title: 'Beta', position: 20 },
|
||||||
|
],
|
||||||
|
currentPage: 1,
|
||||||
|
totalPages: 2,
|
||||||
|
});
|
||||||
|
|
||||||
|
// First drag: park at the edge to start a flip, then release before the new
|
||||||
|
// page arrives (items never change here).
|
||||||
|
await startDragging(1);
|
||||||
|
elementAtPoint.current = null;
|
||||||
|
move(490, 20);
|
||||||
|
await nextTick();
|
||||||
|
vi.advanceTimersByTime(600);
|
||||||
|
release();
|
||||||
|
await nextTick();
|
||||||
|
|
||||||
|
// Second drag must be able to flip again.
|
||||||
|
await startDragging(1);
|
||||||
|
elementAtPoint.current = null;
|
||||||
|
move(490, 20);
|
||||||
|
await nextTick();
|
||||||
|
vi.advanceTimersByTime(600);
|
||||||
|
|
||||||
|
expect(wrapper.emitted('navigatePage')).toEqual([[2], [2]]);
|
||||||
|
});
|
||||||
|
});
|
||||||
+68
-72
@@ -1,6 +1,5 @@
|
|||||||
<script setup>
|
<script setup>
|
||||||
import { ref, computed, watch } from 'vue';
|
import { computed, ref } from 'vue';
|
||||||
import Draggable from 'vuedraggable';
|
|
||||||
import { useMapGetter, useStore } from 'dashboard/composables/store.js';
|
import { useMapGetter, useStore } from 'dashboard/composables/store.js';
|
||||||
import { useRouter, useRoute } from 'vue-router';
|
import { useRouter, useRoute } from 'vue-router';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
@@ -10,6 +9,7 @@ import { getArticleStatus } from 'dashboard/helper/portalHelper.js';
|
|||||||
import wootConstants from 'dashboard/constants/globals';
|
import wootConstants from 'dashboard/constants/globals';
|
||||||
|
|
||||||
import ArticleCard from 'dashboard/components-next/HelpCenter/ArticleCard/ArticleCard.vue';
|
import ArticleCard from 'dashboard/components-next/HelpCenter/ArticleCard/ArticleCard.vue';
|
||||||
|
import DraggableReorderList from 'dashboard/components-next/DraggableReorderList/DraggableReorderList.vue';
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
articles: {
|
articles: {
|
||||||
@@ -28,9 +28,22 @@ const props = defineProps({
|
|||||||
type: Boolean,
|
type: Boolean,
|
||||||
default: false,
|
default: false,
|
||||||
},
|
},
|
||||||
|
currentPage: {
|
||||||
|
type: Number,
|
||||||
|
default: 1,
|
||||||
|
},
|
||||||
|
totalPages: {
|
||||||
|
type: Number,
|
||||||
|
default: 1,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const emit = defineEmits(['translateArticle', 'toggleSelect']);
|
const emit = defineEmits([
|
||||||
|
'translateArticle',
|
||||||
|
'toggleSelect',
|
||||||
|
'navigatePage',
|
||||||
|
'dragging',
|
||||||
|
]);
|
||||||
|
|
||||||
const { ARTICLE_STATUS_TYPES } = wootConstants;
|
const { ARTICLE_STATUS_TYPES } = wootConstants;
|
||||||
|
|
||||||
@@ -39,14 +52,14 @@ const route = useRoute();
|
|||||||
const store = useStore();
|
const store = useStore();
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
|
|
||||||
const localArticles = ref(props.articles);
|
|
||||||
const hoveredArticleId = ref(null);
|
const hoveredArticleId = ref(null);
|
||||||
|
|
||||||
const dragEnabled = computed(() => {
|
const dragEnabled = computed(() => {
|
||||||
|
const canReorder = props.articles?.length > 1 || props.totalPages > 1;
|
||||||
return (
|
return (
|
||||||
props.isCategoryArticles &&
|
props.isCategoryArticles &&
|
||||||
!props.isSearching &&
|
!props.isSearching &&
|
||||||
localArticles.value?.length > 1 &&
|
canReorder &&
|
||||||
props.selectedArticleIds.size === 0
|
props.selectedArticleIds.size === 0
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
@@ -63,6 +76,10 @@ const handleCardHover = (isHovered, id) => {
|
|||||||
|
|
||||||
const getCategoryById = useMapGetter('categories/categoryById');
|
const getCategoryById = useMapGetter('categories/categoryById');
|
||||||
|
|
||||||
|
const getCategory = categoryId => {
|
||||||
|
return getCategoryById.value(categoryId) || { name: '', icon: '' };
|
||||||
|
};
|
||||||
|
|
||||||
const openArticle = id => {
|
const openArticle = id => {
|
||||||
const { tab, categorySlug, locale } = route.params;
|
const { tab, categorySlug, locale } = route.params;
|
||||||
if (props.isCategoryArticles) {
|
if (props.isCategoryArticles) {
|
||||||
@@ -83,38 +100,25 @@ const openArticle = id => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const onReorder = async reorderedGroup => {
|
const onReorder = async positionsHash => {
|
||||||
|
const [movedId] = Object.keys(positionsHash);
|
||||||
|
// A same-page reorder updates optimistically in the store, so it needs no
|
||||||
|
// refetch. Only a cross-page drop must refresh, to pull the moved article
|
||||||
|
// onto this page in its new spot.
|
||||||
|
const isCrossPage = !props.articles.some(
|
||||||
|
article => String(article.id) === movedId
|
||||||
|
);
|
||||||
try {
|
try {
|
||||||
await store.dispatch('articles/reorder', {
|
await store.dispatch('articles/reorder', {
|
||||||
reorderedGroup,
|
reorderedGroup: positionsHash,
|
||||||
portalSlug: route.params.portalSlug,
|
portalSlug: route.params.portalSlug,
|
||||||
});
|
});
|
||||||
|
if (isCrossPage) emit('navigatePage', props.currentPage);
|
||||||
} catch {
|
} catch {
|
||||||
useAlert(t('HELP_CENTER.REORDER_ARTICLE.API.ERROR_MESSAGE'));
|
useAlert(t('HELP_CENTER.REORDER_ARTICLE.API.ERROR_MESSAGE'));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const onDragEnd = () => {
|
|
||||||
// Collect and sort existing positions, falling back to index+1 for null/0 values
|
|
||||||
const sortedArticlePositions = localArticles.value
|
|
||||||
.map((article, index) => article.position || index + 1)
|
|
||||||
.sort((a, b) => a - b);
|
|
||||||
|
|
||||||
const orderedArticles = localArticles.value.map(article => article.id);
|
|
||||||
|
|
||||||
// Create a map of article IDs to their new positions
|
|
||||||
const reorderedGroup = orderedArticles.reduce((obj, key, index) => {
|
|
||||||
obj[key] = sortedArticlePositions[index];
|
|
||||||
return obj;
|
|
||||||
}, {});
|
|
||||||
|
|
||||||
onReorder(reorderedGroup);
|
|
||||||
};
|
|
||||||
|
|
||||||
const getCategory = categoryId => {
|
|
||||||
return getCategoryById.value(categoryId) || { name: '', icon: '' };
|
|
||||||
};
|
|
||||||
|
|
||||||
const getStatusMessage = (status, isSuccess) => {
|
const getStatusMessage = (status, isSuccess) => {
|
||||||
const messageType = isSuccess ? 'SUCCESS' : 'ERROR';
|
const messageType = isSuccess ? 'SUCCESS' : 'ERROR';
|
||||||
const statusMap = {
|
const statusMap = {
|
||||||
@@ -184,54 +188,46 @@ const updateArticle = ({ action, value, id }) => {
|
|||||||
const status = action !== 'delete' ? getArticleStatus(value) : null;
|
const status = action !== 'delete' ? getArticleStatus(value) : null;
|
||||||
handleArticleAction(action, { status, id });
|
handleArticleAction(action, { status, id });
|
||||||
};
|
};
|
||||||
|
|
||||||
// Watch for changes in the articles prop and update the localArticles ref
|
|
||||||
watch(
|
|
||||||
() => props.articles,
|
|
||||||
newArticles => {
|
|
||||||
localArticles.value = newArticles;
|
|
||||||
},
|
|
||||||
{ deep: true }
|
|
||||||
);
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<Draggable
|
<DraggableReorderList
|
||||||
v-model="localArticles"
|
:items="articles"
|
||||||
:disabled="!dragEnabled"
|
:disabled="!dragEnabled"
|
||||||
item-key="id"
|
:current-page="currentPage"
|
||||||
tag="ul"
|
:total-pages="totalPages"
|
||||||
ghost-class="article-ghost-class"
|
@reorder="onReorder"
|
||||||
class="w-full h-full space-y-4"
|
@navigate-page="page => emit('navigatePage', page)"
|
||||||
@end="onDragEnd"
|
@dragging="value => emit('dragging', value)"
|
||||||
>
|
>
|
||||||
<template #item="{ element }">
|
<template #item="{ item }">
|
||||||
<li class="list-none rounded-2xl">
|
<ArticleCard
|
||||||
<ArticleCard
|
:id="item.id"
|
||||||
:id="element.id"
|
:title="item.title"
|
||||||
:key="element.id"
|
:status="item.status"
|
||||||
:title="element.title"
|
:author="item.author"
|
||||||
:status="element.status"
|
:category="getCategory(item.category.id)"
|
||||||
:author="element.author"
|
:views="item.views || 0"
|
||||||
:category="getCategory(element.category.id)"
|
:updated-at="item.updatedAt"
|
||||||
:views="element.views || 0"
|
:is-selected="selectedArticleIds.has(item.id)"
|
||||||
:updated-at="element.updatedAt"
|
selectable
|
||||||
:is-selected="selectedArticleIds.has(element.id)"
|
:show-selection-control="shouldShowSelectionControl(item.id)"
|
||||||
selectable
|
@open-article="openArticle"
|
||||||
:show-selection-control="shouldShowSelectionControl(element.id)"
|
@article-action="updateArticle"
|
||||||
:class="{ 'cursor-grab': dragEnabled }"
|
@toggle-select="emit('toggleSelect', $event)"
|
||||||
@open-article="openArticle"
|
@hover="isHovered => handleCardHover(isHovered, item.id)"
|
||||||
@article-action="updateArticle"
|
/>
|
||||||
@toggle-select="emit('toggleSelect', $event)"
|
|
||||||
@hover="isHovered => handleCardHover(isHovered, element.id)"
|
|
||||||
/>
|
|
||||||
</li>
|
|
||||||
</template>
|
</template>
|
||||||
</Draggable>
|
<template #ghost="{ item }">
|
||||||
|
<ArticleCard
|
||||||
|
:id="item.id"
|
||||||
|
:title="item.title"
|
||||||
|
:status="item.status"
|
||||||
|
:author="item.author"
|
||||||
|
:category="getCategory(item.category.id)"
|
||||||
|
:views="item.views || 0"
|
||||||
|
:updated-at="item.updatedAt"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
</DraggableReorderList>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style lang="scss" scoped>
|
|
||||||
.article-ghost-class {
|
|
||||||
@apply opacity-50 bg-n-solid-1;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
|
|||||||
+8
-1
@@ -70,6 +70,7 @@ const isFeatureEnabledonAccount = useMapGetter(
|
|||||||
);
|
);
|
||||||
|
|
||||||
const selectedArticleIds = ref(new Set());
|
const selectedArticleIds = ref(new Set());
|
||||||
|
const isArticleDragging = ref(false);
|
||||||
const deleteConfirmDialogRef = ref(null);
|
const deleteConfirmDialogRef = ref(null);
|
||||||
const isCategoryMenuOpen = ref(false);
|
const isCategoryMenuOpen = ref(false);
|
||||||
const searchQuery = ref(route.query.search || '');
|
const searchQuery = ref(route.query.search || '');
|
||||||
@@ -148,6 +149,8 @@ const articlesCount = computed(() => {
|
|||||||
return Number(countMap[tab] || countMap['']);
|
return Number(countMap[tab] || countMap['']);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const totalPages = computed(() => Math.ceil(articlesCount.value / 25) || 1);
|
||||||
|
|
||||||
const showArticleHeaderControls = computed(
|
const showArticleHeaderControls = computed(
|
||||||
() => !props.isCategoryArticles && !isSwitchingPortal.value
|
() => !props.isCategoryArticles && !isSwitchingPortal.value
|
||||||
);
|
);
|
||||||
@@ -343,7 +346,7 @@ watch(
|
|||||||
</template>
|
</template>
|
||||||
<template #content>
|
<template #content>
|
||||||
<div
|
<div
|
||||||
v-if="isLoading"
|
v-if="isLoading && !isArticleDragging"
|
||||||
class="flex items-center justify-center py-10 text-n-slate-11"
|
class="flex items-center justify-center py-10 text-n-slate-11"
|
||||||
>
|
>
|
||||||
<Spinner />
|
<Spinner />
|
||||||
@@ -453,9 +456,13 @@ watch(
|
|||||||
:is-category-articles="isCategoryArticles"
|
:is-category-articles="isCategoryArticles"
|
||||||
:is-searching="isSearching"
|
:is-searching="isSearching"
|
||||||
:selected-article-ids="selectedArticleIds"
|
:selected-article-ids="selectedArticleIds"
|
||||||
|
:current-page="Number(meta.currentPage)"
|
||||||
|
:total-pages="totalPages"
|
||||||
class="relative z-0"
|
class="relative z-0"
|
||||||
@translate-article="handleTranslateArticle"
|
@translate-article="handleTranslateArticle"
|
||||||
@toggle-select="handleToggleSelect"
|
@toggle-select="handleToggleSelect"
|
||||||
|
@navigate-page="handlePageChange"
|
||||||
|
@dragging="isArticleDragging = $event"
|
||||||
/>
|
/>
|
||||||
</template>
|
</template>
|
||||||
<ArticleEmptyState
|
<ArticleEmptyState
|
||||||
|
|||||||
@@ -182,8 +182,7 @@ const handleCreateAssistant = () => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="flex items-center gap-2">
|
<div class="flex gap-2">
|
||||||
<slot name="headerActions" />
|
|
||||||
<slot name="search" />
|
<slot name="search" />
|
||||||
<div
|
<div
|
||||||
v-if="!showPaywall && buttonLabel"
|
v-if="!showPaywall && buttonLabel"
|
||||||
|
|||||||
-88
@@ -1,88 +0,0 @@
|
|||||||
<script setup>
|
|
||||||
import { computed, ref } from 'vue';
|
|
||||||
import { useRoute, useRouter } from 'vue-router';
|
|
||||||
import { LocalStorage } from 'shared/helpers/localStorage';
|
|
||||||
|
|
||||||
const props = defineProps({
|
|
||||||
knowledge: {
|
|
||||||
type: Object,
|
|
||||||
default: () => ({ approved: 0, pending: 0, documents: 0, coverage: 0 }),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const route = useRoute();
|
|
||||||
const router = useRouter();
|
|
||||||
|
|
||||||
// Dismissal is remembered per assistant for 24 hours (setFlag's default expiry).
|
|
||||||
const DISMISS_STORE = 'captain_overview_coverage_banner';
|
|
||||||
|
|
||||||
const accountId = computed(() => route.params.accountId);
|
|
||||||
const assistantId = computed(() => route.params.assistantId);
|
|
||||||
|
|
||||||
const dismissed = ref(
|
|
||||||
LocalStorage.getFlag(DISMISS_STORE, accountId.value, assistantId.value)
|
|
||||||
);
|
|
||||||
|
|
||||||
// Thin coverage paired with a large review backlog: approving the pending FAQs
|
|
||||||
// is the quickest lever to lift auto-resolution, so nudge the team to act.
|
|
||||||
const COVERAGE_THRESHOLD = 85;
|
|
||||||
const PENDING_THRESHOLD = 100;
|
|
||||||
|
|
||||||
const showBanner = computed(
|
|
||||||
() =>
|
|
||||||
!dismissed.value &&
|
|
||||||
(props.knowledge?.coverage ?? 0) < COVERAGE_THRESHOLD &&
|
|
||||||
(props.knowledge?.pending ?? 0) > PENDING_THRESHOLD
|
|
||||||
);
|
|
||||||
|
|
||||||
const dismiss = () => {
|
|
||||||
LocalStorage.setFlag(DISMISS_STORE, accountId.value, assistantId.value);
|
|
||||||
dismissed.value = true;
|
|
||||||
};
|
|
||||||
|
|
||||||
const goToPending = () => {
|
|
||||||
router.push({
|
|
||||||
name: 'captain_assistants_responses_pending',
|
|
||||||
params: {
|
|
||||||
accountId: route.params.accountId,
|
|
||||||
assistantId: route.params.assistantId,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
};
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<div
|
|
||||||
v-if="showBanner"
|
|
||||||
class="flex items-center justify-between gap-3 px-3 py-2 text-sm border rounded-xl bg-n-amber-3 border-n-amber-4 text-n-amber-11"
|
|
||||||
>
|
|
||||||
<div class="flex items-center gap-2 min-w-0">
|
|
||||||
<span class="shrink-0 i-lucide-triangle-alert size-4" />
|
|
||||||
<span class="truncate">
|
|
||||||
{{
|
|
||||||
$t('CAPTAIN.OVERVIEW.COVERAGE_BANNER.TEXT', {
|
|
||||||
count: knowledge.pending,
|
|
||||||
coverage: knowledge.coverage,
|
|
||||||
})
|
|
||||||
}}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<div class="flex items-center gap-1 shrink-0">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="px-3 py-1 rounded-lg bg-n-amber-4 hover:bg-n-amber-5"
|
|
||||||
@click="goToPending"
|
|
||||||
>
|
|
||||||
{{ $t('CAPTAIN.OVERVIEW.COVERAGE_BANNER.ACTION') }}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="grid rounded-lg size-7 place-content-center hover:bg-n-amber-4"
|
|
||||||
:aria-label="$t('CAPTAIN.OVERVIEW.COVERAGE_BANNER.DISMISS')"
|
|
||||||
@click="dismiss"
|
|
||||||
>
|
|
||||||
<span class="i-lucide-x size-4" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
-79
@@ -1,79 +0,0 @@
|
|||||||
<script setup>
|
|
||||||
import { computed } from 'vue';
|
|
||||||
|
|
||||||
defineProps({
|
|
||||||
// Selected day-range, used only for the chart's start-axis label.
|
|
||||||
range: { type: String, default: '30' },
|
|
||||||
});
|
|
||||||
|
|
||||||
// Daily assistant credit usage (sample data) rendered as a lightweight bar
|
|
||||||
// chart, so we avoid pulling in a chart library for placeholder visuals.
|
|
||||||
const creditUsage = {
|
|
||||||
total: '48,210',
|
|
||||||
trend: '+18.2%',
|
|
||||||
daily: [
|
|
||||||
120, 145, 132, 160, 175, 158, 190, 210, 195, 230, 220, 245, 260, 240, 275,
|
|
||||||
290, 270, 310, 295, 330, 350, 325, 360, 380, 355, 400, 420, 395, 440, 465,
|
|
||||||
],
|
|
||||||
};
|
|
||||||
|
|
||||||
// Bar heights as a percentage of the peak day, with a small floor so even the
|
|
||||||
// lowest day stays visible.
|
|
||||||
const bars = computed(() => {
|
|
||||||
const max = Math.max(...creditUsage.daily);
|
|
||||||
return creditUsage.daily.map((value, index) => ({
|
|
||||||
key: index,
|
|
||||||
value,
|
|
||||||
height: Math.max(6, Math.round((value / max) * 100)),
|
|
||||||
}));
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<section class="flex flex-col gap-4">
|
|
||||||
<div class="flex items-start justify-between gap-4">
|
|
||||||
<div class="flex flex-col gap-1">
|
|
||||||
<h3 class="text-base font-medium text-n-slate-12">
|
|
||||||
{{ $t('CAPTAIN.OVERVIEW.CREDITS.TITLE') }}
|
|
||||||
</h3>
|
|
||||||
<div class="flex items-baseline gap-2">
|
|
||||||
<span class="text-2xl font-semibold tabular-nums text-n-slate-12">
|
|
||||||
{{ creditUsage.total }}
|
|
||||||
</span>
|
|
||||||
<span class="text-sm text-n-slate-11">
|
|
||||||
{{ $t('CAPTAIN.OVERVIEW.CREDITS.UNIT') }}
|
|
||||||
</span>
|
|
||||||
<span class="text-sm font-medium tabular-nums text-n-slate-11">
|
|
||||||
{{ creditUsage.trend }}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="flex items-center gap-2 mt-1">
|
|
||||||
<span class="rounded-full size-2.5 bg-n-brand" />
|
|
||||||
<span class="text-xs text-n-slate-11">
|
|
||||||
{{ $t('CAPTAIN.OVERVIEW.CREDITS.LEGEND') }}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="p-5 border rounded-xl bg-n-solid-1 border-n-weak">
|
|
||||||
<div class="flex items-end gap-1 h-40">
|
|
||||||
<div
|
|
||||||
v-for="bar in bars"
|
|
||||||
:key="bar.key"
|
|
||||||
v-tooltip="`${bar.value} ${$t('CAPTAIN.OVERVIEW.CREDITS.UNIT')}`"
|
|
||||||
class="flex-1 rounded-t transition-colors bg-n-brand/70 hover:bg-n-brand"
|
|
||||||
:style="{ height: `${bar.height}%` }"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div class="flex items-center justify-between mt-3">
|
|
||||||
<span class="text-xs text-n-slate-10">
|
|
||||||
{{ $t('CAPTAIN.OVERVIEW.CREDITS.AXIS_START', { count: range }) }}
|
|
||||||
</span>
|
|
||||||
<span class="text-xs text-n-slate-10">
|
|
||||||
{{ $t('CAPTAIN.OVERVIEW.CREDITS.AXIS_END') }}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
</template>
|
|
||||||
-73
@@ -1,73 +0,0 @@
|
|||||||
<script setup>
|
|
||||||
import { computed, ref, watch } from 'vue';
|
|
||||||
import { useRoute, useRouter } from 'vue-router';
|
|
||||||
import { useStore, useMapGetter } from 'dashboard/composables/store';
|
|
||||||
|
|
||||||
const route = useRoute();
|
|
||||||
const router = useRouter();
|
|
||||||
const store = useStore();
|
|
||||||
|
|
||||||
const dismissed = ref(false);
|
|
||||||
|
|
||||||
const assistantId = computed(() => route.params.assistantId);
|
|
||||||
const inboxes = useMapGetter('captainInboxes/getRecords');
|
|
||||||
const uiFlags = useMapGetter('captainInboxes/getUIFlags');
|
|
||||||
|
|
||||||
// Only surface once we know the assistant has no connected inboxes.
|
|
||||||
const showBanner = computed(
|
|
||||||
() =>
|
|
||||||
!dismissed.value &&
|
|
||||||
!uiFlags.value.fetchingList &&
|
|
||||||
inboxes.value.length === 0
|
|
||||||
);
|
|
||||||
|
|
||||||
watch(
|
|
||||||
assistantId,
|
|
||||||
id => {
|
|
||||||
dismissed.value = false;
|
|
||||||
if (id) store.dispatch('captainInboxes/get', { assistantId: id });
|
|
||||||
},
|
|
||||||
{ immediate: true }
|
|
||||||
);
|
|
||||||
|
|
||||||
const goToInboxes = () => {
|
|
||||||
router.push({
|
|
||||||
name: 'captain_assistants_inboxes_index',
|
|
||||||
params: {
|
|
||||||
accountId: route.params.accountId,
|
|
||||||
assistantId: assistantId.value,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
};
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<div
|
|
||||||
v-if="showBanner"
|
|
||||||
class="flex items-center justify-between gap-3 px-3 py-2 text-sm border rounded-xl bg-n-amber-3 border-n-amber-4 text-n-amber-11"
|
|
||||||
>
|
|
||||||
<div class="flex items-center gap-2 min-w-0">
|
|
||||||
<span class="shrink-0 i-lucide-triangle-alert size-4" />
|
|
||||||
<span class="truncate">
|
|
||||||
{{ $t('CAPTAIN.OVERVIEW.INBOX_BANNER.TEXT') }}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<div class="flex items-center gap-1 shrink-0">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="px-3 py-1 rounded-lg bg-n-amber-4 hover:bg-n-amber-5"
|
|
||||||
@click="goToInboxes"
|
|
||||||
>
|
|
||||||
{{ $t('CAPTAIN.OVERVIEW.INBOX_BANNER.ACTION') }}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="grid rounded-lg size-7 place-content-center hover:bg-n-amber-4"
|
|
||||||
:aria-label="$t('CAPTAIN.OVERVIEW.INBOX_BANNER.DISMISS')"
|
|
||||||
@click="dismissed = true"
|
|
||||||
>
|
|
||||||
<span class="i-lucide-x size-4" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
-87
@@ -1,87 +0,0 @@
|
|||||||
<script setup>
|
|
||||||
import { computed } from 'vue';
|
|
||||||
import { useRoute } from 'vue-router';
|
|
||||||
import { useI18n } from 'vue-i18n';
|
|
||||||
|
|
||||||
const props = defineProps({
|
|
||||||
knowledge: {
|
|
||||||
type: Object,
|
|
||||||
default: () => ({ approved: 0, pending: 0, documents: 0, coverage: 0 }),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const { t } = useI18n();
|
|
||||||
const route = useRoute();
|
|
||||||
|
|
||||||
const approvedPct = computed(() => props.knowledge.coverage ?? 0);
|
|
||||||
|
|
||||||
const linkTo = routeName => ({
|
|
||||||
name: routeName,
|
|
||||||
params: {
|
|
||||||
accountId: route.params.accountId,
|
|
||||||
assistantId: route.params.assistantId,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const stats = computed(() => [
|
|
||||||
{
|
|
||||||
key: 'approved',
|
|
||||||
value: props.knowledge.approved,
|
|
||||||
label: t('CAPTAIN.OVERVIEW.KNOWLEDGE.APPROVED'),
|
|
||||||
to: linkTo('captain_assistants_responses_index'),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: 'pending',
|
|
||||||
value: props.knowledge.pending,
|
|
||||||
label: t('CAPTAIN.OVERVIEW.KNOWLEDGE.PENDING'),
|
|
||||||
to: linkTo('captain_assistants_responses_pending'),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: 'documents',
|
|
||||||
value: props.knowledge.documents,
|
|
||||||
label: t('CAPTAIN.OVERVIEW.KNOWLEDGE.DOCUMENTS'),
|
|
||||||
to: linkTo('captain_assistants_documents_index'),
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<div
|
|
||||||
class="flex flex-col gap-4 p-5 border rounded-xl bg-n-solid-1 border-n-weak"
|
|
||||||
>
|
|
||||||
<div class="flex items-center justify-between">
|
|
||||||
<span class="text-sm font-medium text-n-slate-12">
|
|
||||||
{{ $t('CAPTAIN.OVERVIEW.KNOWLEDGE.TITLE') }}
|
|
||||||
</span>
|
|
||||||
<span class="text-sm tabular-nums text-n-slate-11">
|
|
||||||
{{ $t('CAPTAIN.OVERVIEW.KNOWLEDGE.COVERAGE', { pct: approvedPct }) }}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<div class="w-full h-2 overflow-hidden rounded-full bg-n-alpha-2">
|
|
||||||
<div
|
|
||||||
class="h-full rounded-full bg-n-brand"
|
|
||||||
:style="{ width: `${approvedPct}%` }"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div class="grid grid-cols-3 gap-3">
|
|
||||||
<RouterLink
|
|
||||||
v-for="stat in stats"
|
|
||||||
:key="stat.key"
|
|
||||||
:to="stat.to"
|
|
||||||
class="flex flex-col gap-1 group/stat"
|
|
||||||
>
|
|
||||||
<span class="text-xl font-semibold tabular-nums text-n-slate-12">
|
|
||||||
{{ stat.value }}
|
|
||||||
</span>
|
|
||||||
<span
|
|
||||||
class="inline-flex items-center gap-1 text-xs transition-colors text-n-slate-11 group-hover/stat:text-n-slate-12"
|
|
||||||
>
|
|
||||||
{{ stat.label }}
|
|
||||||
<span
|
|
||||||
class="transition-opacity opacity-0 i-lucide-arrow-up-right size-3 group-hover/stat:opacity-100"
|
|
||||||
/>
|
|
||||||
</span>
|
|
||||||
</RouterLink>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
-40
@@ -1,40 +0,0 @@
|
|||||||
<script setup>
|
|
||||||
import { computed } from 'vue';
|
|
||||||
|
|
||||||
const props = defineProps({
|
|
||||||
label: { type: String, required: true },
|
|
||||||
value: { type: String, required: true },
|
|
||||||
trend: { type: String, default: '' },
|
|
||||||
hint: { type: String, default: '' },
|
|
||||||
// null = neutral, true = good direction, false = bad direction
|
|
||||||
trendGood: { type: Boolean, default: null },
|
|
||||||
});
|
|
||||||
|
|
||||||
const trendClass = computed(() => {
|
|
||||||
if (props.trendGood === null) return 'text-n-slate-11';
|
|
||||||
return props.trendGood ? 'text-n-teal-11' : 'text-n-ruby-11';
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<div class="flex flex-col gap-3 p-5 group bg-n-solid-1">
|
|
||||||
<div class="flex items-center gap-1.5">
|
|
||||||
<span class="text-sm font-medium text-n-slate-11">{{ label }}</span>
|
|
||||||
<span
|
|
||||||
v-if="hint"
|
|
||||||
v-tooltip="hint"
|
|
||||||
class="transition-opacity opacity-0 cursor-help i-lucide-info size-3.5 text-n-slate-10 group-hover:opacity-100"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div class="flex items-end justify-between gap-2">
|
|
||||||
<span
|
|
||||||
class="text-3xl font-semibold tracking-tight tabular-nums text-n-slate-12"
|
|
||||||
>
|
|
||||||
{{ value }}
|
|
||||||
</span>
|
|
||||||
<span class="text-sm font-medium tabular-nums" :class="trendClass">
|
|
||||||
{{ trend }}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
-81
@@ -1,81 +0,0 @@
|
|||||||
<script setup>
|
|
||||||
import { computed } from 'vue';
|
|
||||||
import { useRoute, RouterLink } from 'vue-router';
|
|
||||||
import { useI18n } from 'vue-i18n';
|
|
||||||
import { useAccount } from 'dashboard/composables/useAccount';
|
|
||||||
import { getHelpUrlForFeature } from 'dashboard/helper/featureHelper';
|
|
||||||
|
|
||||||
const { t } = useI18n();
|
|
||||||
const route = useRoute();
|
|
||||||
const { isOnChatwootCloud } = useAccount();
|
|
||||||
|
|
||||||
const assistantParams = computed(() => ({
|
|
||||||
accountId: route.params.accountId,
|
|
||||||
assistantId: route.params.assistantId,
|
|
||||||
}));
|
|
||||||
|
|
||||||
const links = computed(() => [
|
|
||||||
{
|
|
||||||
key: 'docs',
|
|
||||||
title: t('CAPTAIN.OVERVIEW.LINKS.DOCS.TITLE'),
|
|
||||||
description: t('CAPTAIN.OVERVIEW.LINKS.DOCS.DESCRIPTION'),
|
|
||||||
icon: 'i-lucide-book-open',
|
|
||||||
href: getHelpUrlForFeature('captain'),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: 'playground',
|
|
||||||
title: t('CAPTAIN.OVERVIEW.LINKS.PLAYGROUND.TITLE'),
|
|
||||||
description: t('CAPTAIN.OVERVIEW.LINKS.PLAYGROUND.DESCRIPTION'),
|
|
||||||
icon: 'i-lucide-flask-conical',
|
|
||||||
to: {
|
|
||||||
name: 'captain_assistants_playground_index',
|
|
||||||
params: assistantParams.value,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: 'billing',
|
|
||||||
title: t('CAPTAIN.OVERVIEW.LINKS.BILLING.TITLE'),
|
|
||||||
description: t('CAPTAIN.OVERVIEW.LINKS.BILLING.DESCRIPTION'),
|
|
||||||
icon: 'i-lucide-credit-card',
|
|
||||||
to: {
|
|
||||||
name: 'billing_settings_index',
|
|
||||||
params: { accountId: route.params.accountId },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<div v-if="isOnChatwootCloud" class="grid grid-cols-1 gap-4 sm:grid-cols-3">
|
|
||||||
<component
|
|
||||||
:is="link.href ? 'a' : RouterLink"
|
|
||||||
v-for="link in links"
|
|
||||||
:key="link.key"
|
|
||||||
:href="link.href"
|
|
||||||
:to="link.to"
|
|
||||||
:target="link.href ? '_blank' : undefined"
|
|
||||||
:rel="link.href ? 'noopener noreferrer' : undefined"
|
|
||||||
class="flex items-center gap-3 p-4 transition-colors border rounded-xl bg-n-solid-1 border-n-weak hover:bg-n-alpha-1 group/link"
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
class="grid rounded-lg size-9 shrink-0 place-content-center bg-n-alpha-2 text-n-slate-11"
|
|
||||||
>
|
|
||||||
<span :class="link.icon" class="size-4" />
|
|
||||||
</span>
|
|
||||||
<div class="flex flex-col min-w-0">
|
|
||||||
<span class="text-sm font-medium text-n-slate-12">
|
|
||||||
{{ link.title }}
|
|
||||||
</span>
|
|
||||||
<span class="text-xs truncate text-n-slate-11">
|
|
||||||
{{ link.description }}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<span
|
|
||||||
:class="
|
|
||||||
link.href ? 'i-lucide-arrow-up-right' : 'i-lucide-chevron-right'
|
|
||||||
"
|
|
||||||
class="ml-auto transition-opacity opacity-0 size-4 text-n-slate-10 group-hover/link:opacity-100"
|
|
||||||
/>
|
|
||||||
</component>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
-79
@@ -1,79 +0,0 @@
|
|||||||
<script setup>
|
|
||||||
import { computed } from 'vue';
|
|
||||||
import { useToggle } from '@vueuse/core';
|
|
||||||
import { useI18n } from 'vue-i18n';
|
|
||||||
import { vOnClickOutside } from '@vueuse/components';
|
|
||||||
import Button from 'dashboard/components-next/button/Button.vue';
|
|
||||||
import DropdownMenu from 'dashboard/components-next/dropdown-menu/DropdownMenu.vue';
|
|
||||||
|
|
||||||
const modelValue = defineModel({ type: String, default: '30' });
|
|
||||||
|
|
||||||
const { t } = useI18n();
|
|
||||||
const [showDropdown, toggleDropdown] = useToggle();
|
|
||||||
|
|
||||||
const DAY_RANGES = ['7', '30', '90'];
|
|
||||||
|
|
||||||
const decorate = item => ({
|
|
||||||
...item,
|
|
||||||
action: 'select',
|
|
||||||
isSelected: item.value === modelValue.value,
|
|
||||||
});
|
|
||||||
|
|
||||||
const menuSections = computed(() => {
|
|
||||||
const dayItems = DAY_RANGES.map(value =>
|
|
||||||
decorate({
|
|
||||||
value,
|
|
||||||
label: t('CAPTAIN.OVERVIEW.RANGES.LAST_DAYS', { count: value }),
|
|
||||||
})
|
|
||||||
);
|
|
||||||
const monthItems = [
|
|
||||||
decorate({
|
|
||||||
value: 'this_month',
|
|
||||||
label: t('CAPTAIN.OVERVIEW.RANGES.THIS_MONTH'),
|
|
||||||
}),
|
|
||||||
decorate({
|
|
||||||
value: 'last_month',
|
|
||||||
label: t('CAPTAIN.OVERVIEW.RANGES.LAST_MONTH'),
|
|
||||||
}),
|
|
||||||
];
|
|
||||||
return [{ items: dayItems }, { items: monthItems }];
|
|
||||||
});
|
|
||||||
|
|
||||||
const menuItems = computed(() =>
|
|
||||||
menuSections.value.flatMap(section => section.items)
|
|
||||||
);
|
|
||||||
|
|
||||||
const selectedLabel = computed(
|
|
||||||
() => menuItems.value.find(item => item.isSelected)?.label || ''
|
|
||||||
);
|
|
||||||
|
|
||||||
const handleAction = ({ value }) => {
|
|
||||||
toggleDropdown(false);
|
|
||||||
modelValue.value = value;
|
|
||||||
};
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<div
|
|
||||||
v-on-click-outside="() => toggleDropdown(false)"
|
|
||||||
class="relative flex items-center group"
|
|
||||||
>
|
|
||||||
<Button
|
|
||||||
sm
|
|
||||||
slate
|
|
||||||
faded
|
|
||||||
trailing-icon
|
|
||||||
icon="i-lucide-chevron-down"
|
|
||||||
:label="selectedLabel"
|
|
||||||
class="rounded-md group-hover:bg-n-alpha-2"
|
|
||||||
@click="toggleDropdown()"
|
|
||||||
/>
|
|
||||||
<DropdownMenu
|
|
||||||
v-if="showDropdown"
|
|
||||||
:menu-items="menuItems"
|
|
||||||
:menu-sections="menuSections"
|
|
||||||
class="mt-1 ltr:right-0 rtl:left-0 top-full"
|
|
||||||
@action="handleAction($event)"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
-76
@@ -1,76 +0,0 @@
|
|||||||
<script setup>
|
|
||||||
import { computed } from 'vue';
|
|
||||||
import { useI18n } from 'vue-i18n';
|
|
||||||
|
|
||||||
const { t } = useI18n();
|
|
||||||
|
|
||||||
// Flagged responses broken down by report reason, mapped from
|
|
||||||
// captain_message_reports.report_reason (sample data).
|
|
||||||
const flagReasons = [
|
|
||||||
{
|
|
||||||
key: 'incorrect',
|
|
||||||
label: t('CAPTAIN.OVERVIEW.FLAG_REASONS.INCORRECT'),
|
|
||||||
count: 11,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: 'incomplete',
|
|
||||||
label: t('CAPTAIN.OVERVIEW.FLAG_REASONS.INCOMPLETE'),
|
|
||||||
count: 7,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: 'outdated',
|
|
||||||
label: t('CAPTAIN.OVERVIEW.FLAG_REASONS.OUTDATED'),
|
|
||||||
count: 4,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: 'inappropriate',
|
|
||||||
label: t('CAPTAIN.OVERVIEW.FLAG_REASONS.INAPPROPRIATE'),
|
|
||||||
count: 2,
|
|
||||||
},
|
|
||||||
{ key: 'other', label: t('CAPTAIN.OVERVIEW.FLAG_REASONS.OTHER'), count: 3 },
|
|
||||||
];
|
|
||||||
|
|
||||||
const total = computed(() =>
|
|
||||||
flagReasons.reduce((sum, reason) => sum + reason.count, 0)
|
|
||||||
);
|
|
||||||
|
|
||||||
// Flagged responses as a share of all Captain replies (sample data).
|
|
||||||
const rate = '1.3%';
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<div
|
|
||||||
class="flex flex-col gap-4 p-5 border rounded-xl bg-n-solid-1 border-n-weak"
|
|
||||||
>
|
|
||||||
<div class="flex items-center justify-between">
|
|
||||||
<span class="text-sm font-medium text-n-slate-12">
|
|
||||||
{{ $t('CAPTAIN.OVERVIEW.FLAGGED.TITLE') }}
|
|
||||||
</span>
|
|
||||||
<span class="text-sm tabular-nums text-n-slate-11">
|
|
||||||
{{ $t('CAPTAIN.OVERVIEW.FLAGGED.TOTAL', { count: total, rate }) }}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<div class="flex flex-col gap-3">
|
|
||||||
<div
|
|
||||||
v-for="reason in flagReasons"
|
|
||||||
:key="reason.key"
|
|
||||||
class="flex items-center gap-3"
|
|
||||||
>
|
|
||||||
<span class="w-28 text-xs truncate text-n-slate-11 shrink-0">
|
|
||||||
{{ reason.label }}
|
|
||||||
</span>
|
|
||||||
<div class="flex-1 h-2 overflow-hidden rounded-full bg-n-alpha-2">
|
|
||||||
<div
|
|
||||||
class="h-full rounded-full bg-n-amber-9"
|
|
||||||
:style="{ width: `${Math.round((reason.count / total) * 100)}%` }"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<span
|
|
||||||
class="w-6 text-xs font-medium text-right tabular-nums text-n-slate-12"
|
|
||||||
>
|
|
||||||
{{ reason.count }}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
-109
@@ -1,109 +0,0 @@
|
|||||||
<script setup>
|
|
||||||
import { computed, ref, watch } from 'vue';
|
|
||||||
import { useRoute } from 'vue-router';
|
|
||||||
import CaptainAssistant from 'dashboard/api/captain/assistant';
|
|
||||||
|
|
||||||
const props = defineProps({
|
|
||||||
range: {
|
|
||||||
type: String,
|
|
||||||
default: '30',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const route = useRoute();
|
|
||||||
const assistantId = computed(() => route.params.assistantId);
|
|
||||||
|
|
||||||
// Markdown summary generated by the model from the assistant's stats (served by
|
|
||||||
// the captain/assistants/:id/summary endpoint). Numbers are emphasised with
|
|
||||||
// **bold** so we can highlight them.
|
|
||||||
const welcomeMarkdown = ref('');
|
|
||||||
const isLoading = ref(false);
|
|
||||||
|
|
||||||
const fetchSummary = async () => {
|
|
||||||
isLoading.value = true;
|
|
||||||
try {
|
|
||||||
const { data } = await CaptainAssistant.getSummary({
|
|
||||||
assistantId: assistantId.value,
|
|
||||||
range: props.range,
|
|
||||||
});
|
|
||||||
welcomeMarkdown.value = data.message ?? '';
|
|
||||||
} catch {
|
|
||||||
welcomeMarkdown.value = '';
|
|
||||||
} finally {
|
|
||||||
isLoading.value = false;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
watch([() => props.range, assistantId], fetchSummary, { immediate: true });
|
|
||||||
|
|
||||||
// Split a line on **bold** runs so we can render emphasised numbers as
|
|
||||||
// brand-highlighted spans with Tailwind (instead of styling raw HTML).
|
|
||||||
const parseSegments = text => {
|
|
||||||
const parts = [];
|
|
||||||
const regex = /\*\*(.+?)\*\*/g;
|
|
||||||
let lastIndex = 0;
|
|
||||||
let match = regex.exec(text);
|
|
||||||
while (match) {
|
|
||||||
if (match.index > lastIndex) {
|
|
||||||
parts.push({ text: text.slice(lastIndex, match.index) });
|
|
||||||
}
|
|
||||||
parts.push({ text: match[1], bold: true });
|
|
||||||
lastIndex = regex.lastIndex;
|
|
||||||
match = regex.exec(text);
|
|
||||||
}
|
|
||||||
if (lastIndex < text.length) {
|
|
||||||
parts.push({ text: text.slice(lastIndex) });
|
|
||||||
}
|
|
||||||
return parts.map((part, index) => ({ ...part, key: index }));
|
|
||||||
};
|
|
||||||
|
|
||||||
// Break the markdown into paragraphs on blank lines so newline breaks survive
|
|
||||||
// (a single <p> would collapse them), each parsed into highlightable segments.
|
|
||||||
const paragraphs = computed(() =>
|
|
||||||
welcomeMarkdown.value
|
|
||||||
.split(/\n{2,}/)
|
|
||||||
.map(block => block.trim())
|
|
||||||
.filter(Boolean)
|
|
||||||
.map((block, index) => ({ key: index, segments: parseSegments(block) }))
|
|
||||||
);
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<!-- eslint-disable-next-line vue/no-root-v-if -->
|
|
||||||
<template>
|
|
||||||
<div v-if="isLoading || welcomeMarkdown" class="flex flex-col gap-3">
|
|
||||||
<div class="flex items-center gap-1.5 text-n-slate-10">
|
|
||||||
<span class="i-lucide-sparkles size-3.5" />
|
|
||||||
<span class="text-xs">
|
|
||||||
{{ $t('CAPTAIN.OVERVIEW.WELCOME.LABEL') }}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<div
|
|
||||||
v-if="isLoading"
|
|
||||||
class="flex flex-col gap-5"
|
|
||||||
:aria-label="$t('CAPTAIN.OVERVIEW.WELCOME.LOADING')"
|
|
||||||
>
|
|
||||||
<div class="flex flex-col gap-2.5">
|
|
||||||
<div class="w-full h-5 rounded bg-n-slate-3 animate-pulse" />
|
|
||||||
<div class="w-11/12 h-5 rounded bg-n-slate-3 animate-pulse" />
|
|
||||||
<div class="w-4/6 h-5 rounded bg-n-slate-3 animate-pulse" />
|
|
||||||
</div>
|
|
||||||
<div class="w-5/6 h-5 rounded bg-n-slate-3 animate-pulse" />
|
|
||||||
</div>
|
|
||||||
<template v-else>
|
|
||||||
<p
|
|
||||||
v-for="paragraph in paragraphs"
|
|
||||||
:key="paragraph.key"
|
|
||||||
class="text-lg leading-relaxed text-n-slate-12"
|
|
||||||
>
|
|
||||||
<template v-for="segment in paragraph.segments" :key="segment.key">
|
|
||||||
<span
|
|
||||||
v-if="segment.bold"
|
|
||||||
class="font-bold tabular-nums text-n-brand"
|
|
||||||
>{{ segment.text }}</span
|
|
||||||
>
|
|
||||||
<template v-else>{{ segment.text }}</template>
|
|
||||||
</template>
|
|
||||||
</p>
|
|
||||||
</template>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
@@ -440,14 +440,6 @@ const menuItems = computed(() => {
|
|||||||
label: t('SIDEBAR.CAPTAIN'),
|
label: t('SIDEBAR.CAPTAIN'),
|
||||||
activeOn: ['captain_assistants_create_index'],
|
activeOn: ['captain_assistants_create_index'],
|
||||||
children: [
|
children: [
|
||||||
{
|
|
||||||
name: 'Overview',
|
|
||||||
label: t('SIDEBAR.CAPTAIN_OVERVIEW'),
|
|
||||||
activeOn: ['captain_assistants_overview_index'],
|
|
||||||
to: accountScopedRoute('captain_assistants_index', {
|
|
||||||
navigationPath: 'captain_assistants_overview_index',
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
name: 'FAQs',
|
name: 'FAQs',
|
||||||
label: t('SIDEBAR.CAPTAIN_RESPONSES'),
|
label: t('SIDEBAR.CAPTAIN_RESPONSES'),
|
||||||
|
|||||||
@@ -123,6 +123,10 @@ onMounted(() => {
|
|||||||
a {
|
a {
|
||||||
@apply p-4;
|
@apply p-4;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.ProseMirror a {
|
||||||
|
@apply p-0;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -57,7 +57,9 @@ const showMetaSection = computed(() => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
const hasSlaPolicyId = computed(() => props.chat?.sla_policy_id);
|
const hasSlaPolicyId = computed(
|
||||||
|
() => props.chat?.applied_sla?.id && !props.currentContact?.blocked
|
||||||
|
);
|
||||||
|
|
||||||
const showLabelsSection = computed(() => {
|
const showLabelsSection = computed(() => {
|
||||||
return props.chat.labels?.length > 0 || hasSlaPolicyId.value;
|
return props.chat.labels?.length > 0 || hasSlaPolicyId.value;
|
||||||
|
|||||||
@@ -93,7 +93,9 @@ const hasMultipleInboxes = computed(
|
|||||||
() => store.getters['inboxes/getInboxes'].length > 1
|
() => store.getters['inboxes/getInboxes'].length > 1
|
||||||
);
|
);
|
||||||
|
|
||||||
const hasSlaPolicyId = computed(() => props.chat?.sla_policy_id);
|
const hasSlaPolicyId = computed(
|
||||||
|
() => props.chat?.applied_sla?.id && !currentContact.value?.blocked
|
||||||
|
);
|
||||||
|
|
||||||
const copyConversationId = async () => {
|
const copyConversationId = async () => {
|
||||||
try {
|
try {
|
||||||
|
|||||||
+2
-1
@@ -1,7 +1,7 @@
|
|||||||
<script setup>
|
<script setup>
|
||||||
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
|
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
import { evaluateSLAStatus } from '@chatwoot/utils';
|
import { evaluateSLAStatus } from 'dashboard/helper/slaHelper';
|
||||||
import SLAPopoverCard from './SLAPopoverCard.vue';
|
import SLAPopoverCard from './SLAPopoverCard.vue';
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
@@ -61,6 +61,7 @@ const updateSlaStatus = () => {
|
|||||||
slaStatus.value = evaluateSLAStatus({
|
slaStatus.value = evaluateSLAStatus({
|
||||||
appliedSla: appliedSLA.value,
|
appliedSla: appliedSLA.value,
|
||||||
chat: props.chat,
|
chat: props.chat,
|
||||||
|
slaEvents: slaEvents.value || [],
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
+60
@@ -0,0 +1,60 @@
|
|||||||
|
import { shallowMount } from '@vue/test-utils';
|
||||||
|
import ConversationCard from '../ConversationCard.vue';
|
||||||
|
|
||||||
|
const defaultChat = {
|
||||||
|
id: 1,
|
||||||
|
labels: [],
|
||||||
|
messages: [],
|
||||||
|
priority: null,
|
||||||
|
unread_count: 0,
|
||||||
|
timestamp: 1700000000,
|
||||||
|
created_at: 1700000000,
|
||||||
|
};
|
||||||
|
|
||||||
|
const mountComponent = (chat, currentContact = {}) =>
|
||||||
|
shallowMount(ConversationCard, {
|
||||||
|
props: {
|
||||||
|
chat: { ...defaultChat, ...chat },
|
||||||
|
currentContact: {
|
||||||
|
name: 'Jane Doe',
|
||||||
|
thumbnail: '',
|
||||||
|
availability_status: 'offline',
|
||||||
|
...currentContact,
|
||||||
|
},
|
||||||
|
inbox: { id: 1 },
|
||||||
|
},
|
||||||
|
global: {
|
||||||
|
stubs: {
|
||||||
|
'fluent-icon': true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ConversationCard', () => {
|
||||||
|
it('does not reserve the labels row when only a persisted SLA policy id is present', () => {
|
||||||
|
const wrapper = mountComponent({ sla_policy_id: 1, applied_sla: null });
|
||||||
|
|
||||||
|
expect(wrapper.findComponent({ name: 'CardLabels' }).exists()).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the labels row when an active applied SLA is present', () => {
|
||||||
|
const wrapper = mountComponent({
|
||||||
|
sla_policy_id: 1,
|
||||||
|
applied_sla: { id: 1 },
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(wrapper.findComponent({ name: 'CardLabels' }).exists()).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not reserve the labels row when the contact is blocked', () => {
|
||||||
|
const wrapper = mountComponent(
|
||||||
|
{
|
||||||
|
sla_policy_id: 1,
|
||||||
|
applied_sla: { id: 1 },
|
||||||
|
},
|
||||||
|
{ blocked: true }
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(wrapper.findComponent({ name: 'CardLabels' }).exists()).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -161,6 +161,7 @@ const buildCallActions = ({ callsStore, whatsappSession, t }) => {
|
|||||||
return { conferenceSid: joinResponse?.conference_sid };
|
return { conferenceSid: joinResponse?.conference_sid };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
useAlert(error?.response?.data?.error || t('CONTACT_PANEL.CALL_FAILED'));
|
useAlert(error?.response?.data?.error || t('CONTACT_PANEL.CALL_FAILED'));
|
||||||
|
// 409 = the call already ended before accept landed (e.g. caller hung up mid-ring).
|
||||||
if (error?.response?.status === 409) {
|
if (error?.response?.status === 409) {
|
||||||
TwilioVoiceClient.endClientCall();
|
TwilioVoiceClient.endClientCall();
|
||||||
markDismissed(callSid);
|
markDismissed(callSid);
|
||||||
|
|||||||
@@ -188,6 +188,16 @@ export const ARTICLE_EDITOR_MENU_OPTIONS = [
|
|||||||
'insertTable',
|
'insertTable',
|
||||||
];
|
];
|
||||||
|
|
||||||
|
// [text](url) -> "text: url" (drop label if it equals the URL). Keep serializer
|
||||||
|
// escapes; the re-parse renders them literally, unescaping would crash it.
|
||||||
|
const flattenLink = (_match, text, url) => {
|
||||||
|
const cleanUrl = url
|
||||||
|
.trim()
|
||||||
|
.replace(/\s+["'(].*$/, '')
|
||||||
|
.replace(/^<|>$/g, '');
|
||||||
|
return text === cleanUrl ? cleanUrl : `${text}: ${cleanUrl}`;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Markdown formatting patterns for stripping unsupported formatting.
|
* Markdown formatting patterns for stripping unsupported formatting.
|
||||||
*
|
*
|
||||||
@@ -264,7 +274,12 @@ export const MARKDOWN_PATTERNS = [
|
|||||||
{
|
{
|
||||||
type: 'link', // PM: link
|
type: 'link', // PM: link
|
||||||
patterns: [
|
patterns: [
|
||||||
{ pattern: /\[([^\]]+)\]\([^)]+\)/g, replacement: '$1' }, // [text](url) -> text
|
// Escape-aware label + URL captures so a \] or \) can't cut the match
|
||||||
|
// short and leave link markup that crashes the re-parse.
|
||||||
|
{
|
||||||
|
pattern: /\[((?:\\.|[^\]\\])*)\]\(((?:\\.|[^)\\])*)\)/g,
|
||||||
|
replacement: flattenLink,
|
||||||
|
},
|
||||||
{ pattern: /<([a-zA-Z][a-zA-Z0-9+.-]*:[^\s>]+)>/g, replacement: '$1' }, // <https://...>, <mailto:...>, <tel:...>, <ftp://...>, etc
|
{ pattern: /<([a-zA-Z][a-zA-Z0-9+.-]*:[^\s>]+)>/g, replacement: '$1' }, // <https://...>, <mailto:...>, <tel:...>, <ftp://...>, etc
|
||||||
{ pattern: /<([^\s@]+@[^\s@>]+)>/g, replacement: '$1' }, // <user@example.com> -> user@example.com
|
{ pattern: /<([^\s@]+@[^\s@>]+)>/g, replacement: '$1' }, // <user@example.com> -> user@example.com
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -19,7 +19,6 @@ const FEATURE_HELP_URLS = {
|
|||||||
webhook: 'https://chwt.app/hc/webhooks',
|
webhook: 'https://chwt.app/hc/webhooks',
|
||||||
billing: 'https://chwt.app/pricing',
|
billing: 'https://chwt.app/pricing',
|
||||||
saml: 'https://chwt.app/hc/saml',
|
saml: 'https://chwt.app/hc/saml',
|
||||||
captain: 'https://chwt.app/captain-docs',
|
|
||||||
captain_billing: 'https://chwt.app/hc/captain_billing',
|
captain_billing: 'https://chwt.app/hc/captain_billing',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,150 @@
|
|||||||
|
import { useCamelCase } from 'dashboard/composables/useTransformKeys';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Formats seconds into a human-readable time string
|
||||||
|
* @param {number} seconds - The time in seconds (can be negative for overdue)
|
||||||
|
* @returns {string} Formatted time string like "2h 30m" or "1d 4h"
|
||||||
|
*/
|
||||||
|
const formatSLATime = seconds => {
|
||||||
|
const absSeconds = Math.abs(seconds);
|
||||||
|
|
||||||
|
const units = {
|
||||||
|
y: 31536000,
|
||||||
|
mo: 2592000,
|
||||||
|
d: 86400,
|
||||||
|
h: 3600,
|
||||||
|
m: 60,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (absSeconds < 60) {
|
||||||
|
return '1m';
|
||||||
|
}
|
||||||
|
|
||||||
|
const parts = [];
|
||||||
|
let remaining = absSeconds;
|
||||||
|
|
||||||
|
Object.entries(units).forEach(([unit, value]) => {
|
||||||
|
if (parts.length >= 2) return;
|
||||||
|
const count = Math.floor(remaining / value);
|
||||||
|
if (count > 0) {
|
||||||
|
parts.push(`${count}${unit}`);
|
||||||
|
remaining -= count * value;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return parts.join(' ');
|
||||||
|
};
|
||||||
|
|
||||||
|
const toUnixTimestamp = value => {
|
||||||
|
if (!value || typeof value === 'number') return value;
|
||||||
|
|
||||||
|
const numericValue = Number(value);
|
||||||
|
if (!Number.isNaN(numericValue)) return numericValue;
|
||||||
|
|
||||||
|
const parsedTimestamp = Date.parse(value);
|
||||||
|
return Number.isNaN(parsedTimestamp)
|
||||||
|
? value
|
||||||
|
: Math.floor(parsedTimestamp / 1000);
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Evaluates SLA status using backend-computed due times
|
||||||
|
* @param {Object} params - Parameters object
|
||||||
|
* @param {Object} params.appliedSla - The applied SLA with due_at timestamps
|
||||||
|
* @param {Object} params.chat - The conversation object
|
||||||
|
* @param {Array} params.slaEvents - Recorded SLA miss events for this conversation
|
||||||
|
* @returns {Object} SLA status with type, threshold, icon, and isSlaMissed
|
||||||
|
*/
|
||||||
|
export const evaluateSLAStatus = ({ appliedSla, chat, slaEvents = [] }) => {
|
||||||
|
const emptyStatus = { type: '', threshold: '', icon: '', isSlaMissed: false };
|
||||||
|
|
||||||
|
if (!appliedSla || !chat) {
|
||||||
|
return emptyStatus;
|
||||||
|
}
|
||||||
|
|
||||||
|
const sla = useCamelCase(appliedSla);
|
||||||
|
const conversation = useCamelCase(chat);
|
||||||
|
const events = useCamelCase(slaEvents || []);
|
||||||
|
const currentTime = Math.floor(Date.now() / 1000);
|
||||||
|
const slaStatuses = [];
|
||||||
|
|
||||||
|
const dueAtByType = {
|
||||||
|
FRT: sla.slaFrtDueAt,
|
||||||
|
RT: sla.slaRtDueAt,
|
||||||
|
};
|
||||||
|
const slaTypes = ['FRT', 'NRT', 'RT'];
|
||||||
|
|
||||||
|
events.forEach(event => {
|
||||||
|
const type = event.eventType?.toUpperCase();
|
||||||
|
if (!slaTypes.includes(type)) return;
|
||||||
|
|
||||||
|
const missedAt =
|
||||||
|
type === 'NRT' ? event.createdAt : dueAtByType[type] || event.createdAt;
|
||||||
|
if (!missedAt) return;
|
||||||
|
|
||||||
|
slaStatuses.push({
|
||||||
|
type,
|
||||||
|
threshold: missedAt - currentTime,
|
||||||
|
icon: 'flame',
|
||||||
|
isSlaMissed: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const firstReplyCreatedAt = toUnixTimestamp(conversation.firstReplyCreatedAt);
|
||||||
|
const shouldCheckFirstResponse =
|
||||||
|
!firstReplyCreatedAt || firstReplyCreatedAt > sla.slaFrtDueAt;
|
||||||
|
|
||||||
|
// Check FRT - until first reply is made on time
|
||||||
|
if (sla.slaFrtDueAt && shouldCheckFirstResponse) {
|
||||||
|
const threshold = sla.slaFrtDueAt - currentTime;
|
||||||
|
slaStatuses.push({
|
||||||
|
type: 'FRT',
|
||||||
|
threshold,
|
||||||
|
icon: threshold <= 0 ? 'flame' : 'alarm',
|
||||||
|
isSlaMissed: threshold <= 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check NRT - only if first reply made and waiting for response
|
||||||
|
if (sla.slaNrtDueAt && firstReplyCreatedAt && conversation.waitingSince) {
|
||||||
|
const threshold = sla.slaNrtDueAt - currentTime;
|
||||||
|
slaStatuses.push({
|
||||||
|
type: 'NRT',
|
||||||
|
threshold,
|
||||||
|
icon: threshold <= 0 ? 'flame' : 'alarm',
|
||||||
|
isSlaMissed: threshold <= 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check RT - only if conversation is unresolved
|
||||||
|
if (sla.slaRtDueAt && conversation.status !== 'resolved') {
|
||||||
|
const threshold = sla.slaRtDueAt - currentTime;
|
||||||
|
slaStatuses.push({
|
||||||
|
type: 'RT',
|
||||||
|
threshold,
|
||||||
|
icon: threshold <= 0 ? 'flame' : 'alarm',
|
||||||
|
isSlaMissed: threshold <= 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (slaStatuses.length === 0) {
|
||||||
|
return emptyStatus;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Show existing breaches before upcoming deadlines, then pick the closest timer.
|
||||||
|
slaStatuses.sort((a, b) => {
|
||||||
|
if (a.isSlaMissed !== b.isSlaMissed) {
|
||||||
|
return a.isSlaMissed ? -1 : 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Math.abs(a.threshold) - Math.abs(b.threshold);
|
||||||
|
});
|
||||||
|
const mostUrgent = slaStatuses[0];
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: mostUrgent.type,
|
||||||
|
threshold: formatSLATime(mostUrgent.threshold),
|
||||||
|
icon: mostUrgent.icon,
|
||||||
|
isSlaMissed: mostUrgent.isSlaMissed,
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -1,4 +1,9 @@
|
|||||||
import { EditorState, EditorView } from '@chatwoot/prosemirror-schema';
|
import {
|
||||||
|
EditorState,
|
||||||
|
EditorView,
|
||||||
|
buildMessageSchema,
|
||||||
|
MessageMarkdownTransformer,
|
||||||
|
} from '@chatwoot/prosemirror-schema';
|
||||||
import { FORMATTING } from 'dashboard/constants/editor';
|
import { FORMATTING } from 'dashboard/constants/editor';
|
||||||
import { Schema } from 'prosemirror-model';
|
import { Schema } from 'prosemirror-model';
|
||||||
import {
|
import {
|
||||||
@@ -978,13 +983,77 @@ describe('stripUnsupportedFormatting', () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('strips links but keeps text', () => {
|
it('keeps link text and URL when schema does not support links', () => {
|
||||||
expect(
|
expect(
|
||||||
stripUnsupportedFormatting(
|
stripUnsupportedFormatting(
|
||||||
'Check [this link](https://example.com)',
|
'Check [this link](https://example.com)',
|
||||||
emptySchema
|
emptySchema
|
||||||
)
|
)
|
||||||
).toBe('Check this link');
|
).toBe('Check this link: https://example.com');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('drops the hidden link title when preserving the URL', () => {
|
||||||
|
expect(
|
||||||
|
stripUnsupportedFormatting(
|
||||||
|
'Check [docs](https://example.com "Docs")',
|
||||||
|
emptySchema
|
||||||
|
)
|
||||||
|
).toBe('Check docs: https://example.com');
|
||||||
|
|
||||||
|
expect(
|
||||||
|
stripUnsupportedFormatting(
|
||||||
|
'Check [docs](<https://example.com> "Docs")',
|
||||||
|
emptySchema
|
||||||
|
)
|
||||||
|
).toBe('Check docs: https://example.com');
|
||||||
|
});
|
||||||
|
|
||||||
|
// Output is re-parsed before sending, so assert the final text
|
||||||
|
// (strip + re-parse); the re-parse turns serializer escapes into literals.
|
||||||
|
describe('links round-trip through re-parse without crashing', () => {
|
||||||
|
const smsSchema = buildMessageSchema([], []); // no marks, no nodes
|
||||||
|
const sendAs = md =>
|
||||||
|
new MessageMarkdownTransformer(smsSchema).parse(
|
||||||
|
stripUnsupportedFormatting(md, smsSchema)
|
||||||
|
).textContent;
|
||||||
|
|
||||||
|
it('keeps escaped parens/underscores anywhere in the URL', () => {
|
||||||
|
expect(
|
||||||
|
sendAs('See [wiki](https://en.wikipedia.org/wiki/Foo\\_\\(bar\\))')
|
||||||
|
).toBe('See wiki: https://en.wikipedia.org/wiki/Foo_(bar)');
|
||||||
|
expect(sendAs('See [wiki](https://host/a\\_\\(b\\)c)')).toBe(
|
||||||
|
'See wiki: https://host/a_(b)c'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('drops the label when it equals the URL even when escaped', () => {
|
||||||
|
expect(
|
||||||
|
sendAs(
|
||||||
|
'[www.example.com/Foo\\_\\(bar\\)](www.example.com/Foo\\_\\(bar\\))'
|
||||||
|
)
|
||||||
|
).toBe('www.example.com/Foo_(bar)');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not reintroduce emphasis from an escaped label', () => {
|
||||||
|
expect(sendAs('[Use \\_id\\_](https://example.com)')).toBe(
|
||||||
|
'Use _id_: https://example.com'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('flattens a label containing an escaped closing bracket', () => {
|
||||||
|
expect(sendAs('[FAQ \\[v2\\]](https://example.com)')).toBe(
|
||||||
|
'FAQ [v2]: https://example.com'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('leaves bare URLs untouched so channels can auto-link them', () => {
|
||||||
|
expect(
|
||||||
|
stripUnsupportedFormatting('Visit www.example.com now', emptySchema)
|
||||||
|
).toBe('Visit www.example.com now');
|
||||||
|
expect(
|
||||||
|
stripUnsupportedFormatting('Visit <https://example.com>', emptySchema)
|
||||||
|
).toBe('Visit https://example.com');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('converts autolinks to plain URLs when schema does not support links', () => {
|
it('converts autolinks to plain URLs when schema does not support links', () => {
|
||||||
@@ -1049,7 +1118,7 @@ describe('stripUnsupportedFormatting', () => {
|
|||||||
it('handles complex content with multiple formatting types', () => {
|
it('handles complex content with multiple formatting types', () => {
|
||||||
const content =
|
const content =
|
||||||
'**Bold** and *italic* with `code` and [link](url)\n- list item';
|
'**Bold** and *italic* with `code` and [link](url)\n- list item';
|
||||||
const expected = 'Bold and italic with code and link\nlist item';
|
const expected = 'Bold and italic with code and link: url\nlist item';
|
||||||
expect(stripUnsupportedFormatting(content, emptySchema)).toBe(expected);
|
expect(stripUnsupportedFormatting(content, emptySchema)).toBe(expected);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,450 @@
|
|||||||
|
import { evaluateSLAStatus } from '../slaHelper';
|
||||||
|
|
||||||
|
describe('#SLA Helpers', () => {
|
||||||
|
const currentTimestamp = 1700000000; // Fixed timestamp for testing
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
vi.setSystemTime(currentTimestamp * 1000);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('evaluateSLAStatus', () => {
|
||||||
|
describe('when inputs are invalid', () => {
|
||||||
|
it('returns empty status when appliedSla is null', () => {
|
||||||
|
const result = evaluateSLAStatus({ appliedSla: null, chat: {} });
|
||||||
|
expect(result).toEqual({
|
||||||
|
type: '',
|
||||||
|
threshold: '',
|
||||||
|
icon: '',
|
||||||
|
isSlaMissed: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns empty status when chat is null', () => {
|
||||||
|
const result = evaluateSLAStatus({ appliedSla: {}, chat: null });
|
||||||
|
expect(result).toEqual({
|
||||||
|
type: '',
|
||||||
|
threshold: '',
|
||||||
|
icon: '',
|
||||||
|
isSlaMissed: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('FRT (First Response Time)', () => {
|
||||||
|
it('returns FRT status when first reply not made and within threshold', () => {
|
||||||
|
const appliedSla = { sla_frt_due_at: currentTimestamp + 3600 }; // 1 hour from now
|
||||||
|
const chat = { first_reply_created_at: null, status: 'open' };
|
||||||
|
|
||||||
|
const result = evaluateSLAStatus({ appliedSla, chat });
|
||||||
|
|
||||||
|
expect(result.type).toBe('FRT');
|
||||||
|
expect(result.threshold).toBe('1h');
|
||||||
|
expect(result.icon).toBe('alarm');
|
||||||
|
expect(result.isSlaMissed).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns missed FRT status when threshold is exceeded', () => {
|
||||||
|
const appliedSla = { sla_frt_due_at: currentTimestamp - 1800 }; // 30 min ago
|
||||||
|
const chat = { first_reply_created_at: null, status: 'open' };
|
||||||
|
|
||||||
|
const result = evaluateSLAStatus({ appliedSla, chat });
|
||||||
|
|
||||||
|
expect(result.type).toBe('FRT');
|
||||||
|
expect(result.threshold).toBe('30m');
|
||||||
|
expect(result.icon).toBe('flame');
|
||||||
|
expect(result.isSlaMissed).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not return FRT when first reply was made before due time', () => {
|
||||||
|
const appliedSla = { sla_frt_due_at: currentTimestamp + 3600 };
|
||||||
|
const chat = {
|
||||||
|
first_reply_created_at: currentTimestamp - 1000,
|
||||||
|
status: 'open',
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = evaluateSLAStatus({ appliedSla, chat });
|
||||||
|
|
||||||
|
expect(result.type).not.toBe('FRT');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not return FRT when first reply was made at due time', () => {
|
||||||
|
const appliedSla = {
|
||||||
|
sla_frt_due_at: currentTimestamp - 600,
|
||||||
|
sla_rt_due_at: currentTimestamp + 1800,
|
||||||
|
};
|
||||||
|
const chat = {
|
||||||
|
first_reply_created_at: currentTimestamp - 600,
|
||||||
|
status: 'open',
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = evaluateSLAStatus({ appliedSla, chat });
|
||||||
|
|
||||||
|
expect(result.type).toBe('RT');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns missed FRT when first reply was made after due time', () => {
|
||||||
|
const appliedSla = {
|
||||||
|
sla_frt_due_at: currentTimestamp - 600,
|
||||||
|
sla_rt_due_at: currentTimestamp + 1800,
|
||||||
|
};
|
||||||
|
const chat = {
|
||||||
|
first_reply_created_at: currentTimestamp - 300,
|
||||||
|
status: 'open',
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = evaluateSLAStatus({ appliedSla, chat });
|
||||||
|
|
||||||
|
expect(result.type).toBe('FRT');
|
||||||
|
expect(result.threshold).toBe('10m');
|
||||||
|
expect(result.icon).toBe('flame');
|
||||||
|
expect(result.isSlaMissed).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns missed FRT when live first reply timestamp is an ISO string after due time', () => {
|
||||||
|
const appliedSla = {
|
||||||
|
sla_frt_due_at: currentTimestamp - 600,
|
||||||
|
sla_rt_due_at: currentTimestamp + 1800,
|
||||||
|
};
|
||||||
|
const chat = {
|
||||||
|
first_reply_created_at: new Date(
|
||||||
|
(currentTimestamp - 300) * 1000
|
||||||
|
).toISOString(),
|
||||||
|
status: 'open',
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = evaluateSLAStatus({ appliedSla, chat });
|
||||||
|
|
||||||
|
expect(result.type).toBe('FRT');
|
||||||
|
expect(result.threshold).toBe('10m');
|
||||||
|
expect(result.icon).toBe('flame');
|
||||||
|
expect(result.isSlaMissed).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses the due time for a missed FRT event created after the deadline', () => {
|
||||||
|
const appliedSla = { sla_frt_due_at: currentTimestamp - 3600 };
|
||||||
|
const chat = { first_reply_created_at: null, status: 'open' };
|
||||||
|
const slaEvents = [
|
||||||
|
{ event_type: 'frt', created_at: currentTimestamp - 1800 },
|
||||||
|
];
|
||||||
|
|
||||||
|
const result = evaluateSLAStatus({ appliedSla, chat, slaEvents });
|
||||||
|
|
||||||
|
expect(result.type).toBe('FRT');
|
||||||
|
expect(result.threshold).toBe('1h');
|
||||||
|
expect(result.icon).toBe('flame');
|
||||||
|
expect(result.isSlaMissed).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('NRT (Next Response Time)', () => {
|
||||||
|
it('returns NRT status when waiting for response and within threshold', () => {
|
||||||
|
const appliedSla = { sla_nrt_due_at: currentTimestamp + 1800 }; // 30 min from now
|
||||||
|
const chat = {
|
||||||
|
first_reply_created_at: currentTimestamp - 7200,
|
||||||
|
waiting_since: currentTimestamp - 600,
|
||||||
|
status: 'open',
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = evaluateSLAStatus({ appliedSla, chat });
|
||||||
|
|
||||||
|
expect(result.type).toBe('NRT');
|
||||||
|
expect(result.threshold).toBe('30m');
|
||||||
|
expect(result.icon).toBe('alarm');
|
||||||
|
expect(result.isSlaMissed).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns missed NRT status when threshold is exceeded', () => {
|
||||||
|
const appliedSla = { sla_nrt_due_at: currentTimestamp - 900 }; // 15 min ago
|
||||||
|
const chat = {
|
||||||
|
first_reply_created_at: currentTimestamp - 7200,
|
||||||
|
waiting_since: currentTimestamp - 2700,
|
||||||
|
status: 'open',
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = evaluateSLAStatus({ appliedSla, chat });
|
||||||
|
|
||||||
|
expect(result.type).toBe('NRT');
|
||||||
|
expect(result.threshold).toBe('15m');
|
||||||
|
expect(result.icon).toBe('flame');
|
||||||
|
expect(result.isSlaMissed).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not return NRT when not waiting for response', () => {
|
||||||
|
const appliedSla = { sla_nrt_due_at: currentTimestamp + 1800 };
|
||||||
|
const chat = {
|
||||||
|
first_reply_created_at: currentTimestamp - 7200,
|
||||||
|
waiting_since: null,
|
||||||
|
status: 'open',
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = evaluateSLAStatus({ appliedSla, chat });
|
||||||
|
|
||||||
|
expect(result.type).not.toBe('NRT');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns missed NRT when a recorded NRT miss exists after response', () => {
|
||||||
|
const appliedSla = { sla_rt_due_at: currentTimestamp + 1800 };
|
||||||
|
const chat = {
|
||||||
|
first_reply_created_at: currentTimestamp - 7200,
|
||||||
|
waiting_since: null,
|
||||||
|
status: 'open',
|
||||||
|
};
|
||||||
|
const slaEvents = [
|
||||||
|
{ event_type: 'nrt', created_at: currentTimestamp - 900 },
|
||||||
|
];
|
||||||
|
|
||||||
|
const result = evaluateSLAStatus({ appliedSla, chat, slaEvents });
|
||||||
|
|
||||||
|
expect(result.type).toBe('NRT');
|
||||||
|
expect(result.threshold).toBe('15m');
|
||||||
|
expect(result.icon).toBe('flame');
|
||||||
|
expect(result.isSlaMissed).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses the recorded event time for a missed NRT with a new active NRT timer', () => {
|
||||||
|
const appliedSla = {
|
||||||
|
sla_nrt_due_at: currentTimestamp + 300,
|
||||||
|
sla_rt_due_at: currentTimestamp + 1800,
|
||||||
|
};
|
||||||
|
const chat = {
|
||||||
|
first_reply_created_at: currentTimestamp - 7200,
|
||||||
|
waiting_since: currentTimestamp - 60,
|
||||||
|
status: 'open',
|
||||||
|
};
|
||||||
|
const slaEvents = [
|
||||||
|
{ event_type: 'nrt', created_at: currentTimestamp - 1800 },
|
||||||
|
];
|
||||||
|
|
||||||
|
const result = evaluateSLAStatus({ appliedSla, chat, slaEvents });
|
||||||
|
|
||||||
|
expect(result.type).toBe('NRT');
|
||||||
|
expect(result.threshold).toBe('30m');
|
||||||
|
expect(result.icon).toBe('flame');
|
||||||
|
expect(result.isSlaMissed).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not return NRT when first reply not made', () => {
|
||||||
|
const appliedSla = { sla_nrt_due_at: currentTimestamp + 1800 };
|
||||||
|
const chat = {
|
||||||
|
first_reply_created_at: null,
|
||||||
|
waiting_since: currentTimestamp - 600,
|
||||||
|
status: 'open',
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = evaluateSLAStatus({ appliedSla, chat });
|
||||||
|
|
||||||
|
expect(result.type).not.toBe('NRT');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('RT (Resolution Time)', () => {
|
||||||
|
it('returns RT status when conversation is open and within threshold', () => {
|
||||||
|
const appliedSla = { sla_rt_due_at: currentTimestamp + 7200 }; // 2 hours from now
|
||||||
|
const chat = {
|
||||||
|
first_reply_created_at: currentTimestamp - 3600,
|
||||||
|
status: 'open',
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = evaluateSLAStatus({ appliedSla, chat });
|
||||||
|
|
||||||
|
expect(result.type).toBe('RT');
|
||||||
|
expect(result.threshold).toBe('2h');
|
||||||
|
expect(result.icon).toBe('alarm');
|
||||||
|
expect(result.isSlaMissed).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(['pending', 'snoozed'])(
|
||||||
|
'returns RT status when conversation is %s and within threshold',
|
||||||
|
status => {
|
||||||
|
const appliedSla = { sla_rt_due_at: currentTimestamp + 7200 };
|
||||||
|
const chat = {
|
||||||
|
first_reply_created_at: currentTimestamp - 3600,
|
||||||
|
status,
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = evaluateSLAStatus({ appliedSla, chat });
|
||||||
|
|
||||||
|
expect(result.type).toBe('RT');
|
||||||
|
expect(result.threshold).toBe('2h');
|
||||||
|
expect(result.icon).toBe('alarm');
|
||||||
|
expect(result.isSlaMissed).toBe(false);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
it('returns missed RT status when threshold is exceeded', () => {
|
||||||
|
const appliedSla = { sla_rt_due_at: currentTimestamp - 3600 }; // 1 hour ago
|
||||||
|
const chat = {
|
||||||
|
first_reply_created_at: currentTimestamp - 7200,
|
||||||
|
status: 'open',
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = evaluateSLAStatus({ appliedSla, chat });
|
||||||
|
|
||||||
|
expect(result.type).toBe('RT');
|
||||||
|
expect(result.threshold).toBe('1h');
|
||||||
|
expect(result.icon).toBe('flame');
|
||||||
|
expect(result.isSlaMissed).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses the due time for a missed RT event created after the deadline', () => {
|
||||||
|
const appliedSla = { sla_rt_due_at: currentTimestamp - 3600 };
|
||||||
|
const chat = {
|
||||||
|
first_reply_created_at: currentTimestamp - 7200,
|
||||||
|
status: 'open',
|
||||||
|
};
|
||||||
|
const slaEvents = [
|
||||||
|
{ event_type: 'rt', created_at: currentTimestamp - 1800 },
|
||||||
|
];
|
||||||
|
|
||||||
|
const result = evaluateSLAStatus({ appliedSla, chat, slaEvents });
|
||||||
|
|
||||||
|
expect(result.type).toBe('RT');
|
||||||
|
expect(result.threshold).toBe('1h');
|
||||||
|
expect(result.icon).toBe('flame');
|
||||||
|
expect(result.isSlaMissed).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not return RT when conversation is resolved', () => {
|
||||||
|
const appliedSla = { sla_rt_due_at: currentTimestamp + 7200 };
|
||||||
|
const chat = {
|
||||||
|
first_reply_created_at: currentTimestamp - 3600,
|
||||||
|
status: 'resolved',
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = evaluateSLAStatus({ appliedSla, chat });
|
||||||
|
|
||||||
|
expect(result.type).toBe('');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('priority selection', () => {
|
||||||
|
it('returns most urgent SLA when multiple are active', () => {
|
||||||
|
const appliedSla = {
|
||||||
|
sla_frt_due_at: currentTimestamp + 7200, // 2h - less urgent
|
||||||
|
sla_nrt_due_at: currentTimestamp + 1800, // 30m - most urgent
|
||||||
|
sla_rt_due_at: currentTimestamp + 3600, // 1h
|
||||||
|
};
|
||||||
|
const chat = {
|
||||||
|
first_reply_created_at: null,
|
||||||
|
waiting_since: currentTimestamp - 600,
|
||||||
|
status: 'open',
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = evaluateSLAStatus({ appliedSla, chat });
|
||||||
|
|
||||||
|
// FRT is selected because first_reply_created_at is null
|
||||||
|
// NRT is not checked when first_reply_created_at is null
|
||||||
|
expect(result.type).toBe('RT');
|
||||||
|
expect(result.threshold).toBe('1h');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns most urgent missed SLA over upcoming SLA', () => {
|
||||||
|
const appliedSla = {
|
||||||
|
sla_nrt_due_at: currentTimestamp - 300, // 5m overdue - most urgent by absolute value
|
||||||
|
sla_rt_due_at: currentTimestamp + 3600, // 1h remaining
|
||||||
|
};
|
||||||
|
const chat = {
|
||||||
|
first_reply_created_at: currentTimestamp - 7200,
|
||||||
|
waiting_since: currentTimestamp - 2100,
|
||||||
|
status: 'open',
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = evaluateSLAStatus({ appliedSla, chat });
|
||||||
|
|
||||||
|
expect(result.type).toBe('NRT');
|
||||||
|
expect(result.isSlaMissed).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns an existing missed SLA over a closer upcoming SLA', () => {
|
||||||
|
const appliedSla = {
|
||||||
|
sla_frt_due_at: currentTimestamp - 7200, // 2h overdue
|
||||||
|
sla_rt_due_at: currentTimestamp + 300, // 5m remaining
|
||||||
|
};
|
||||||
|
const chat = {
|
||||||
|
first_reply_created_at: null,
|
||||||
|
status: 'open',
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = evaluateSLAStatus({ appliedSla, chat });
|
||||||
|
|
||||||
|
expect(result.type).toBe('FRT');
|
||||||
|
expect(result.threshold).toBe('2h');
|
||||||
|
expect(result.isSlaMissed).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('time formatting', () => {
|
||||||
|
it('formats time in days and hours', () => {
|
||||||
|
const appliedSla = { sla_rt_due_at: currentTimestamp + 90000 }; // 25 hours
|
||||||
|
const chat = { status: 'open' };
|
||||||
|
|
||||||
|
const result = evaluateSLAStatus({ appliedSla, chat });
|
||||||
|
|
||||||
|
expect(result.threshold).toBe('1d 1h');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('formats time less than a minute as 1m', () => {
|
||||||
|
const appliedSla = { sla_frt_due_at: currentTimestamp + 30 }; // 30 seconds
|
||||||
|
const chat = { first_reply_created_at: null, status: 'open' };
|
||||||
|
|
||||||
|
const result = evaluateSLAStatus({ appliedSla, chat });
|
||||||
|
|
||||||
|
expect(result.threshold).toBe('1m');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('formats months correctly', () => {
|
||||||
|
const appliedSla = {
|
||||||
|
sla_rt_due_at: currentTimestamp + 2592000 + 86400,
|
||||||
|
}; // 1 month + 1 day
|
||||||
|
const chat = { status: 'open' };
|
||||||
|
|
||||||
|
const result = evaluateSLAStatus({ appliedSla, chat });
|
||||||
|
|
||||||
|
expect(result.threshold).toBe('1mo 1d');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('empty status scenarios', () => {
|
||||||
|
it('returns empty when no SLA thresholds are set', () => {
|
||||||
|
const appliedSla = {};
|
||||||
|
const chat = { status: 'open' };
|
||||||
|
|
||||||
|
const result = evaluateSLAStatus({ appliedSla, chat });
|
||||||
|
|
||||||
|
expect(result).toEqual({
|
||||||
|
type: '',
|
||||||
|
threshold: '',
|
||||||
|
icon: '',
|
||||||
|
isSlaMissed: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns empty when all conditions are met', () => {
|
||||||
|
const appliedSla = {
|
||||||
|
sla_frt_due_at: currentTimestamp + 3600,
|
||||||
|
sla_nrt_due_at: currentTimestamp + 1800,
|
||||||
|
sla_rt_due_at: currentTimestamp + 7200,
|
||||||
|
};
|
||||||
|
const chat = {
|
||||||
|
first_reply_created_at: currentTimestamp - 3600, // FRT already hit
|
||||||
|
waiting_since: null, // Not waiting, so NRT not applicable
|
||||||
|
status: 'resolved', // RT not applicable
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = evaluateSLAStatus({ appliedSla, chat });
|
||||||
|
|
||||||
|
expect(result).toEqual({
|
||||||
|
type: '',
|
||||||
|
threshold: '',
|
||||||
|
icon: '',
|
||||||
|
isSlaMissed: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,4 +1,7 @@
|
|||||||
import { CONTENT_TYPES } from 'dashboard/components-next/message/constants';
|
import {
|
||||||
|
CONTENT_TYPES,
|
||||||
|
VOICE_CALL_STATUS,
|
||||||
|
} from 'dashboard/components-next/message/constants';
|
||||||
import { MESSAGE_TYPE } from 'shared/constants/messages';
|
import { MESSAGE_TYPE } from 'shared/constants/messages';
|
||||||
import { useCallsStore } from 'dashboard/stores/calls';
|
import { useCallsStore } from 'dashboard/stores/calls';
|
||||||
import types from 'dashboard/store/mutation-types';
|
import types from 'dashboard/store/mutation-types';
|
||||||
@@ -101,6 +104,7 @@ export function handleVoiceCallCreated(
|
|||||||
callSid,
|
callSid,
|
||||||
callId,
|
callId,
|
||||||
provider,
|
provider,
|
||||||
|
status,
|
||||||
callDirection,
|
callDirection,
|
||||||
conversationId,
|
conversationId,
|
||||||
inboxId,
|
inboxId,
|
||||||
@@ -108,6 +112,11 @@ export function handleVoiceCallCreated(
|
|||||||
senderId,
|
senderId,
|
||||||
} = extractCallData(message);
|
} = extractCallData(message);
|
||||||
|
|
||||||
|
// A voice_call message can be created already terminal when the caller hangs
|
||||||
|
// up before connect. Only ring while the call is actually ringing; mirrors the
|
||||||
|
// guard in seedCallsFromHydratedMessages.
|
||||||
|
if (status !== VOICE_CALL_STATUS.RINGING) return;
|
||||||
|
|
||||||
if (
|
if (
|
||||||
!shouldShowCall({
|
!shouldShowCall({
|
||||||
callDirection,
|
callDirection,
|
||||||
|
|||||||
@@ -392,93 +392,6 @@
|
|||||||
"CAPTAIN": {
|
"CAPTAIN": {
|
||||||
"NAME": "Captain",
|
"NAME": "Captain",
|
||||||
"HEADER_KNOW_MORE": "Know more",
|
"HEADER_KNOW_MORE": "Know more",
|
||||||
"OVERVIEW": {
|
|
||||||
"HEADER": "Overview",
|
|
||||||
"WELCOME": {
|
|
||||||
"LABEL": "Captain summary",
|
|
||||||
"LOADING": "Generating summary…"
|
|
||||||
},
|
|
||||||
"INBOX_BANNER": {
|
|
||||||
"TEXT": "This assistant isn't connected to any inbox yet, so it won't respond to conversations.",
|
|
||||||
"ACTION": "Connect inbox",
|
|
||||||
"DISMISS": "Dismiss"
|
|
||||||
},
|
|
||||||
"COVERAGE_BANNER": {
|
|
||||||
"TEXT": "{count} FAQs are pending review, keeping coverage at {coverage}%. Approve them so your assistant can resolve more on its own.",
|
|
||||||
"ACTION": "Review FAQs",
|
|
||||||
"DISMISS": "Dismiss"
|
|
||||||
},
|
|
||||||
"RANGES": {
|
|
||||||
"LAST_DAYS": "Last {count} days",
|
|
||||||
"THIS_MONTH": "This month",
|
|
||||||
"LAST_MONTH": "Last month"
|
|
||||||
},
|
|
||||||
"METRICS": {
|
|
||||||
"HANDLED": {
|
|
||||||
"LABEL": "Conversations handled",
|
|
||||||
"HINT": "Distinct conversations this assistant replied in."
|
|
||||||
},
|
|
||||||
"AUTO_RESOLUTION": {
|
|
||||||
"LABEL": "Auto-resolution rate",
|
|
||||||
"HINT": "Share of handled conversations closed without a human reply."
|
|
||||||
},
|
|
||||||
"HANDOFF": {
|
|
||||||
"LABEL": "Handoff rate",
|
|
||||||
"HINT": "Share of handled conversations escalated to a human agent."
|
|
||||||
},
|
|
||||||
"HOURS_SAVED": {
|
|
||||||
"LABEL": "Hours saved",
|
|
||||||
"HINT": "Estimate: Captain replies times the team's average response time. Directional, not measured labor."
|
|
||||||
},
|
|
||||||
"REOPEN": {
|
|
||||||
"LABEL": "Reopen rate",
|
|
||||||
"HINT": "Auto-resolved conversations that were reopened afterwards."
|
|
||||||
},
|
|
||||||
"DEPTH": {
|
|
||||||
"LABEL": "Messages / conversation",
|
|
||||||
"HINT": "Average replies the assistant sends per conversation."
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"KNOWLEDGE": {
|
|
||||||
"TITLE": "Knowledge coverage",
|
|
||||||
"COVERAGE": "{pct}% approved",
|
|
||||||
"APPROVED": "Approved FAQs",
|
|
||||||
"PENDING": "Pending FAQs",
|
|
||||||
"DOCUMENTS": "Documents"
|
|
||||||
},
|
|
||||||
"FLAGGED": {
|
|
||||||
"TITLE": "Response quality",
|
|
||||||
"TOTAL": "{count} flagged · {rate}"
|
|
||||||
},
|
|
||||||
"CREDITS": {
|
|
||||||
"TITLE": "Credit usage",
|
|
||||||
"UNIT": "credits",
|
|
||||||
"LEGEND": "Daily credits used",
|
|
||||||
"AXIS_START": "{count}d ago",
|
|
||||||
"AXIS_END": "Today"
|
|
||||||
},
|
|
||||||
"LINKS": {
|
|
||||||
"DOCS": {
|
|
||||||
"TITLE": "Captain docs",
|
|
||||||
"DESCRIPTION": "Guides and how-tos for Captain"
|
|
||||||
},
|
|
||||||
"PLAYGROUND": {
|
|
||||||
"TITLE": "Playground",
|
|
||||||
"DESCRIPTION": "Test this assistant's replies"
|
|
||||||
},
|
|
||||||
"BILLING": {
|
|
||||||
"TITLE": "Billing",
|
|
||||||
"DESCRIPTION": "Manage credits and plan"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"FLAG_REASONS": {
|
|
||||||
"INCORRECT": "Incorrect info",
|
|
||||||
"INCOMPLETE": "Incomplete",
|
|
||||||
"OUTDATED": "Outdated",
|
|
||||||
"INAPPROPRIATE": "Inappropriate",
|
|
||||||
"OTHER": "Other"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"ASSISTANT_SWITCHER": {
|
"ASSISTANT_SWITCHER": {
|
||||||
"ASSISTANTS": "Assistants",
|
"ASSISTANTS": "Assistants",
|
||||||
"SWITCH_ASSISTANT": "Switch between assistants",
|
"SWITCH_ASSISTANT": "Switch between assistants",
|
||||||
|
|||||||
@@ -121,6 +121,26 @@
|
|||||||
"CLEAR_FILTER": "Clear filter",
|
"CLEAR_FILTER": "Clear filter",
|
||||||
"EMPTY_LIST": "No results found"
|
"EMPTY_LIST": "No results found"
|
||||||
},
|
},
|
||||||
|
"DRILLDOWN": {
|
||||||
|
"TITLE": "{metric} details",
|
||||||
|
"RESULT_COUNT_CONVERSATION": "{count} conversation | {count} conversations",
|
||||||
|
"RESULT_COUNT_MESSAGE": "{count} message | {count} messages",
|
||||||
|
"EMPTY": "No records found for this bar.",
|
||||||
|
"ERROR": "Could not load records. Please try again.",
|
||||||
|
"ADMIN_ONLY": "Only administrators can drill down into report records.",
|
||||||
|
"LOAD_MORE": "Load more",
|
||||||
|
"CLOSE": "Close details",
|
||||||
|
"PREVIOUS_BUCKET": "Previous bar",
|
||||||
|
"NEXT_BUCKET": "Next bar",
|
||||||
|
"UNKNOWN_CONTACT": "Unknown contact",
|
||||||
|
"UNKNOWN_INBOX": "Unknown inbox",
|
||||||
|
"UNASSIGNED_AGENT": "Unassigned",
|
||||||
|
"NO_MESSAGE_CONTENT": "No message content",
|
||||||
|
"MESSAGE_CREATED_AT": "Message created at {time}",
|
||||||
|
"EVENT_OCCURRED_AT": "Event occurred at {time}",
|
||||||
|
"INCOMING_MESSAGE": "Incoming message",
|
||||||
|
"OUTGOING_MESSAGE": "Outgoing message"
|
||||||
|
},
|
||||||
"PAGINATION": {
|
"PAGINATION": {
|
||||||
"RESULTS": "Showing {start} to {end} of {total} results",
|
"RESULTS": "Showing {start} to {end} of {total} results",
|
||||||
"PER_PAGE_TEMPLATE": "{size} / page"
|
"PER_PAGE_TEMPLATE": "{size} / page"
|
||||||
|
|||||||
@@ -324,7 +324,6 @@
|
|||||||
"ALL_COMPANIES": "All Companies",
|
"ALL_COMPANIES": "All Companies",
|
||||||
"CAPTAIN": "Captain",
|
"CAPTAIN": "Captain",
|
||||||
"CAPTAIN_ASSISTANTS": "Assistants",
|
"CAPTAIN_ASSISTANTS": "Assistants",
|
||||||
"CAPTAIN_OVERVIEW": "Overview",
|
|
||||||
"CAPTAIN_DOCUMENTS": "Documents",
|
"CAPTAIN_DOCUMENTS": "Documents",
|
||||||
"CAPTAIN_RESPONSES": "FAQs",
|
"CAPTAIN_RESPONSES": "FAQs",
|
||||||
"CAPTAIN_TOOLS": "Tools",
|
"CAPTAIN_TOOLS": "Tools",
|
||||||
|
|||||||
@@ -1,147 +0,0 @@
|
|||||||
<script setup>
|
|
||||||
import { computed, ref, watch } from 'vue';
|
|
||||||
import { useI18n } from 'vue-i18n';
|
|
||||||
import { useRoute } from 'vue-router';
|
|
||||||
import { FEATURE_FLAGS } from 'dashboard/featureFlags';
|
|
||||||
import CaptainAssistant from 'dashboard/api/captain/assistant';
|
|
||||||
|
|
||||||
import PageLayout from 'dashboard/components-next/captain/PageLayout.vue';
|
|
||||||
import RangeSelector from 'dashboard/components-next/captain/pageComponents/overview/RangeSelector.vue';
|
|
||||||
import WelcomeCard from 'dashboard/components-next/captain/pageComponents/overview/WelcomeCard.vue';
|
|
||||||
import MetricCard from 'dashboard/components-next/captain/pageComponents/overview/MetricCard.vue';
|
|
||||||
import KnowledgeCard from 'dashboard/components-next/captain/pageComponents/overview/KnowledgeCard.vue';
|
|
||||||
import QuickLinks from 'dashboard/components-next/captain/pageComponents/overview/QuickLinks.vue';
|
|
||||||
import InboxBanner from 'dashboard/components-next/captain/pageComponents/overview/InboxBanner.vue';
|
|
||||||
import CoverageBanner from 'dashboard/components-next/captain/pageComponents/overview/CoverageBanner.vue';
|
|
||||||
|
|
||||||
const { t } = useI18n();
|
|
||||||
const route = useRoute();
|
|
||||||
|
|
||||||
const selectedRange = ref('this_month');
|
|
||||||
|
|
||||||
const assistantId = computed(() => route.params.assistantId);
|
|
||||||
const stats = ref(null);
|
|
||||||
|
|
||||||
const fetchStats = async () => {
|
|
||||||
try {
|
|
||||||
const { data } = await CaptainAssistant.getStats({
|
|
||||||
assistantId: assistantId.value,
|
|
||||||
range: selectedRange.value,
|
|
||||||
});
|
|
||||||
stats.value = data;
|
|
||||||
} catch {
|
|
||||||
stats.value = null;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
watch([selectedRange, assistantId], fetchStats, { immediate: true });
|
|
||||||
|
|
||||||
// `direction` says whether a rising trend is good ('up'), bad ('down'), or
|
|
||||||
// neutral, so we can colour the delta independently of its sign.
|
|
||||||
const resolveTrendGood = (trendValue, direction) => {
|
|
||||||
if (direction === 'neutral' || trendValue === 0) return null;
|
|
||||||
return direction === 'up' ? trendValue > 0 : trendValue < 0;
|
|
||||||
};
|
|
||||||
|
|
||||||
// Trend units mirror the backend pack mode: a relative percent change ('%') for
|
|
||||||
// :percent metrics, a percentage-point delta (' pts') for rate metrics packed as
|
|
||||||
// :point, and a plain number for :absolute counts like conversation depth.
|
|
||||||
const TREND_SUFFIX = { percent: '%', point: ' pts', absolute: '' };
|
|
||||||
|
|
||||||
const metricFor = (statKey, formatValue, direction, trendKind = 'percent') => {
|
|
||||||
const data = stats.value?.[statKey];
|
|
||||||
if (!data) return { value: '—', trend: '', trendGood: null };
|
|
||||||
|
|
||||||
const sign = data.trend > 0 ? '+' : '';
|
|
||||||
return {
|
|
||||||
value: formatValue(data.current),
|
|
||||||
trend: `${sign}${data.trend}${TREND_SUFFIX[trendKind]}`,
|
|
||||||
trendGood: resolveTrendGood(data.trend, direction),
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
const metrics = computed(() => [
|
|
||||||
{
|
|
||||||
key: 'handled',
|
|
||||||
label: t('CAPTAIN.OVERVIEW.METRICS.HANDLED.LABEL'),
|
|
||||||
hint: t('CAPTAIN.OVERVIEW.METRICS.HANDLED.HINT'),
|
|
||||||
...metricFor('conversations_handled', v => v.toLocaleString(), 'up'),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: 'autoResolution',
|
|
||||||
label: t('CAPTAIN.OVERVIEW.METRICS.AUTO_RESOLUTION.LABEL'),
|
|
||||||
hint: t('CAPTAIN.OVERVIEW.METRICS.AUTO_RESOLUTION.HINT'),
|
|
||||||
...metricFor('auto_resolution_rate', v => `${v}%`, 'up', 'point'),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: 'handoff',
|
|
||||||
label: t('CAPTAIN.OVERVIEW.METRICS.HANDOFF.LABEL'),
|
|
||||||
hint: t('CAPTAIN.OVERVIEW.METRICS.HANDOFF.HINT'),
|
|
||||||
...metricFor('handoff_rate', v => `${v}%`, 'down', 'point'),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: 'hoursSaved',
|
|
||||||
label: t('CAPTAIN.OVERVIEW.METRICS.HOURS_SAVED.LABEL'),
|
|
||||||
hint: t('CAPTAIN.OVERVIEW.METRICS.HOURS_SAVED.HINT'),
|
|
||||||
...metricFor('hours_saved', v => `${v}h`, 'up'),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: 'reopen',
|
|
||||||
label: t('CAPTAIN.OVERVIEW.METRICS.REOPEN.LABEL'),
|
|
||||||
hint: t('CAPTAIN.OVERVIEW.METRICS.REOPEN.HINT'),
|
|
||||||
...metricFor('reopen_rate', v => `${v}%`, 'down', 'point'),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: 'depth',
|
|
||||||
label: t('CAPTAIN.OVERVIEW.METRICS.DEPTH.LABEL'),
|
|
||||||
hint: t('CAPTAIN.OVERVIEW.METRICS.DEPTH.HINT'),
|
|
||||||
...metricFor(
|
|
||||||
'conversation_depth',
|
|
||||||
v => v.toFixed(1),
|
|
||||||
'neutral',
|
|
||||||
'absolute'
|
|
||||||
),
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<PageLayout
|
|
||||||
:header-title="$t('CAPTAIN.OVERVIEW.HEADER')"
|
|
||||||
:is-empty="false"
|
|
||||||
:show-pagination-footer="false"
|
|
||||||
:show-know-more="false"
|
|
||||||
:feature-flag="FEATURE_FLAGS.CAPTAIN"
|
|
||||||
>
|
|
||||||
<template #headerActions>
|
|
||||||
<RangeSelector v-model="selectedRange" />
|
|
||||||
</template>
|
|
||||||
<template #body>
|
|
||||||
<div class="flex flex-col gap-6">
|
|
||||||
<InboxBanner />
|
|
||||||
|
|
||||||
<CoverageBanner :knowledge="stats?.knowledge" />
|
|
||||||
|
|
||||||
<WelcomeCard :range="selectedRange" />
|
|
||||||
|
|
||||||
<div
|
|
||||||
class="grid grid-cols-1 gap-px overflow-hidden border rounded-xl sm:grid-cols-2 lg:grid-cols-3 bg-n-weak border-n-weak"
|
|
||||||
>
|
|
||||||
<MetricCard
|
|
||||||
v-for="metric in metrics"
|
|
||||||
:key="metric.key"
|
|
||||||
:label="metric.label"
|
|
||||||
:value="metric.value"
|
|
||||||
:trend="metric.trend"
|
|
||||||
:hint="metric.hint"
|
|
||||||
:trend-good="metric.trendGood"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<KnowledgeCard :knowledge="stats?.knowledge" />
|
|
||||||
|
|
||||||
<QuickLinks />
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
</PageLayout>
|
|
||||||
</template>
|
|
||||||
@@ -6,7 +6,6 @@ import CaptainPageRouteView from './pages/CaptainPageRouteView.vue';
|
|||||||
import AssistantsIndexPage from './pages/AssistantsIndexPage.vue';
|
import AssistantsIndexPage from './pages/AssistantsIndexPage.vue';
|
||||||
import AssistantEmptyStateIndex from './assistants/Index.vue';
|
import AssistantEmptyStateIndex from './assistants/Index.vue';
|
||||||
|
|
||||||
import AssistantOverviewIndex from './assistants/overview/Index.vue';
|
|
||||||
import AssistantSettingsIndex from './assistants/settings/Settings.vue';
|
import AssistantSettingsIndex from './assistants/settings/Settings.vue';
|
||||||
import AssistantInboxesIndex from './assistants/inboxes/Index.vue';
|
import AssistantInboxesIndex from './assistants/inboxes/Index.vue';
|
||||||
import AssistantPlaygroundIndex from './assistants/playground/Index.vue';
|
import AssistantPlaygroundIndex from './assistants/playground/Index.vue';
|
||||||
@@ -37,12 +36,6 @@ const metaV2 = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const assistantRoutes = [
|
const assistantRoutes = [
|
||||||
{
|
|
||||||
path: frontendURL('accounts/:accountId/captain/:assistantId/overview'),
|
|
||||||
component: AssistantOverviewIndex,
|
|
||||||
name: 'captain_assistants_overview_index',
|
|
||||||
meta,
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
path: frontendURL('accounts/:accountId/captain/:assistantId/faqs'),
|
path: frontendURL('accounts/:accountId/captain/:assistantId/faqs'),
|
||||||
component: ResponsesIndex,
|
component: ResponsesIndex,
|
||||||
|
|||||||
@@ -53,7 +53,6 @@ const routeToLastActiveAssistant = () => {
|
|||||||
|
|
||||||
const { navigationPath } = route.params;
|
const { navigationPath } = route.params;
|
||||||
const isAValidRoute = [
|
const isAValidRoute = [
|
||||||
'captain_assistants_overview_index', // Overview page
|
|
||||||
'captain_assistants_responses_index', // Faq page
|
'captain_assistants_responses_index', // Faq page
|
||||||
'captain_assistants_documents_index', // Document page
|
'captain_assistants_documents_index', // Document page
|
||||||
'captain_assistants_scenarios_index', // Scenario page
|
'captain_assistants_scenarios_index', // Scenario page
|
||||||
|
|||||||
@@ -149,9 +149,5 @@ export default {
|
|||||||
|
|
||||||
:deep(.ProseMirror-woot-style) {
|
:deep(.ProseMirror-woot-style) {
|
||||||
@apply min-h-[12.5rem];
|
@apply min-h-[12.5rem];
|
||||||
|
|
||||||
p {
|
|
||||||
@apply text-base;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -153,9 +153,5 @@ export default {
|
|||||||
|
|
||||||
:deep(.ProseMirror-woot-style) {
|
:deep(.ProseMirror-woot-style) {
|
||||||
@apply min-h-[12.5rem];
|
@apply min-h-[12.5rem];
|
||||||
|
|
||||||
p {
|
|
||||||
@apply text-base;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -101,6 +101,9 @@ export default {
|
|||||||
summary-fetching-key="getBotSummaryFetchingStatus"
|
summary-fetching-key="getBotSummaryFetchingStatus"
|
||||||
:group-by="groupBy"
|
:group-by="groupBy"
|
||||||
:report-keys="reportKeys"
|
:report-keys="reportKeys"
|
||||||
|
:from="from"
|
||||||
|
:to="to"
|
||||||
|
:business-hours="businessHours"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -121,6 +121,11 @@ export default {
|
|||||||
show-group-by
|
show-group-by
|
||||||
@filter-change="onFilterChange"
|
@filter-change="onFilterChange"
|
||||||
/>
|
/>
|
||||||
<ReportContainer :group-by="groupBy" />
|
<ReportContainer
|
||||||
|
:group-by="groupBy"
|
||||||
|
:from="from"
|
||||||
|
:to="to"
|
||||||
|
:business-hours="businessHours"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -5,16 +5,38 @@ import { GROUP_BY_FILTER, METRIC_CHART } from './constants';
|
|||||||
import fromUnixTime from 'date-fns/fromUnixTime';
|
import fromUnixTime from 'date-fns/fromUnixTime';
|
||||||
import format from 'date-fns/format';
|
import format from 'date-fns/format';
|
||||||
import { formatTime } from '@chatwoot/utils';
|
import { formatTime } from '@chatwoot/utils';
|
||||||
|
import { useAlert } from 'dashboard/composables';
|
||||||
import ChartStats from './components/ChartElements/ChartStats.vue';
|
import ChartStats from './components/ChartElements/ChartStats.vue';
|
||||||
import BarChart from 'shared/components/charts/BarChart.vue';
|
import BarChart from 'shared/components/charts/BarChart.vue';
|
||||||
|
import ReportDrilldownDrawer from './components/ReportDrilldownDrawer.vue';
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
components: { ChartStats, BarChart },
|
components: { ChartStats, BarChart, ReportDrilldownDrawer },
|
||||||
props: {
|
props: {
|
||||||
groupBy: {
|
groupBy: {
|
||||||
type: Object,
|
type: Object,
|
||||||
default: () => ({}),
|
default: () => ({}),
|
||||||
},
|
},
|
||||||
|
from: {
|
||||||
|
type: Number,
|
||||||
|
default: 0,
|
||||||
|
},
|
||||||
|
to: {
|
||||||
|
type: Number,
|
||||||
|
default: 0,
|
||||||
|
},
|
||||||
|
reportType: {
|
||||||
|
type: String,
|
||||||
|
default: 'account',
|
||||||
|
},
|
||||||
|
selectedItemId: {
|
||||||
|
type: [String, Number],
|
||||||
|
default: null,
|
||||||
|
},
|
||||||
|
businessHours: {
|
||||||
|
type: Boolean,
|
||||||
|
default: false,
|
||||||
|
},
|
||||||
accountSummaryKey: {
|
accountSummaryKey: {
|
||||||
type: String,
|
type: String,
|
||||||
default: 'getAccountSummary',
|
default: 'getAccountSummary',
|
||||||
@@ -42,10 +64,27 @@ export default {
|
|||||||
);
|
);
|
||||||
return { calculateTrend, isAverageMetricType };
|
return { calculateTrend, isAverageMetricType };
|
||||||
},
|
},
|
||||||
|
data() {
|
||||||
|
return {
|
||||||
|
drilldownRequest: null,
|
||||||
|
drilldownMetric: null,
|
||||||
|
drilldownIndex: null,
|
||||||
|
};
|
||||||
|
},
|
||||||
computed: {
|
computed: {
|
||||||
...mapGetters({
|
...mapGetters({
|
||||||
accountReport: 'getAccountReports',
|
accountReport: 'getAccountReports',
|
||||||
|
currentRole: 'getCurrentRole',
|
||||||
}),
|
}),
|
||||||
|
isAdmin() {
|
||||||
|
return this.currentRole === 'administrator';
|
||||||
|
},
|
||||||
|
canDrilldownPrev() {
|
||||||
|
return this.findDrillableIndex(this.drilldownIndex - 1, -1) !== null;
|
||||||
|
},
|
||||||
|
canDrilldownNext() {
|
||||||
|
return this.findDrillableIndex(this.drilldownIndex + 1, 1) !== null;
|
||||||
|
},
|
||||||
metrics() {
|
metrics() {
|
||||||
const reportKeys = Object.keys(this.reportKeys);
|
const reportKeys = Object.keys(this.reportKeys);
|
||||||
const infoText = {
|
const infoText = {
|
||||||
@@ -139,6 +178,82 @@ export default {
|
|||||||
|
|
||||||
return options;
|
return options;
|
||||||
},
|
},
|
||||||
|
isDrilldownEnabled() {
|
||||||
|
return !!(this.from && this.to);
|
||||||
|
},
|
||||||
|
onChartElementClick(metric, event) {
|
||||||
|
if (!this.isDrilldownEnabled()) return;
|
||||||
|
|
||||||
|
const dataPoint = this.accountReport.data[metric.KEY]?.[event.dataIndex];
|
||||||
|
if (!this.canOpenDrilldown(metric, dataPoint)) return;
|
||||||
|
if (!this.isAdmin) {
|
||||||
|
useAlert(this.$t('REPORT.DRILLDOWN.ADMIN_ONLY'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.openDrilldownAt(metric, event.dataIndex);
|
||||||
|
},
|
||||||
|
openDrilldownAt(metric, dataIndex) {
|
||||||
|
const dataPoint = this.accountReport.data[metric.KEY]?.[dataIndex];
|
||||||
|
if (!this.canOpenDrilldown(metric, dataPoint)) return;
|
||||||
|
|
||||||
|
const labels = this.getCollection(metric).labels || [];
|
||||||
|
|
||||||
|
this.drilldownMetric = metric;
|
||||||
|
this.drilldownIndex = dataIndex;
|
||||||
|
this.drilldownRequest = {
|
||||||
|
metric: metric.KEY,
|
||||||
|
metricName: metric.NAME,
|
||||||
|
bucketLabel: labels[dataIndex],
|
||||||
|
bucketTimestamp: dataPoint.timestamp,
|
||||||
|
bucketValue: dataPoint.value,
|
||||||
|
isAverageMetric: this.isAverageMetricType(metric.KEY),
|
||||||
|
from: this.from,
|
||||||
|
to: this.to,
|
||||||
|
type: this.reportType,
|
||||||
|
id: this.selectedItemId,
|
||||||
|
groupBy: this.groupBy?.period,
|
||||||
|
businessHours: this.businessHours,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
navigateDrilldown(direction) {
|
||||||
|
const nextIndex = this.findDrillableIndex(
|
||||||
|
this.drilldownIndex + direction,
|
||||||
|
direction
|
||||||
|
);
|
||||||
|
if (nextIndex === null) return;
|
||||||
|
|
||||||
|
this.openDrilldownAt(this.drilldownMetric, nextIndex);
|
||||||
|
},
|
||||||
|
findDrillableIndex(startIndex, step) {
|
||||||
|
if (!this.drilldownMetric) return null;
|
||||||
|
|
||||||
|
const data = this.accountReport.data[this.drilldownMetric.KEY] || [];
|
||||||
|
for (
|
||||||
|
let index = startIndex;
|
||||||
|
index >= 0 && index < data.length;
|
||||||
|
index += step
|
||||||
|
) {
|
||||||
|
if (this.canOpenDrilldown(this.drilldownMetric, data[index]))
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
},
|
||||||
|
canOpenDrilldown(metric, dataPoint) {
|
||||||
|
if (!dataPoint) return false;
|
||||||
|
|
||||||
|
if (this.isAverageMetricType(metric.KEY)) {
|
||||||
|
return dataPoint.count > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return dataPoint.value > 0;
|
||||||
|
},
|
||||||
|
closeDrilldown() {
|
||||||
|
this.drilldownRequest = null;
|
||||||
|
this.drilldownMetric = null;
|
||||||
|
this.drilldownIndex = null;
|
||||||
|
},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
</script>
|
</script>
|
||||||
@@ -168,6 +283,8 @@ export default {
|
|||||||
v-if="accountReport.data[metric.KEY].length"
|
v-if="accountReport.data[metric.KEY].length"
|
||||||
:collection="getCollection(metric)"
|
:collection="getCollection(metric)"
|
||||||
:chart-options="getChartOptions(metric)"
|
:chart-options="getChartOptions(metric)"
|
||||||
|
:clickable="isDrilldownEnabled()"
|
||||||
|
@element-click="onChartElementClick(metric, $event)"
|
||||||
/>
|
/>
|
||||||
<span v-else class="text-sm text-n-slate-10">
|
<span v-else class="text-sm text-n-slate-10">
|
||||||
{{ $t('REPORT.NO_ENOUGH_DATA') }}
|
{{ $t('REPORT.NO_ENOUGH_DATA') }}
|
||||||
@@ -176,4 +293,23 @@ export default {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<ReportDrilldownDrawer
|
||||||
|
:id="drilldownRequest?.id"
|
||||||
|
:open="!!drilldownRequest"
|
||||||
|
:metric="drilldownRequest?.metric"
|
||||||
|
:metric-name="drilldownRequest?.metricName"
|
||||||
|
:bucket-label="drilldownRequest?.bucketLabel"
|
||||||
|
:bucket-timestamp="drilldownRequest?.bucketTimestamp"
|
||||||
|
:bucket-value="drilldownRequest?.bucketValue"
|
||||||
|
:is-average-metric="drilldownRequest?.isAverageMetric"
|
||||||
|
:from="drilldownRequest?.from"
|
||||||
|
:to="drilldownRequest?.to"
|
||||||
|
:type="drilldownRequest?.type"
|
||||||
|
:group-by="drilldownRequest?.groupBy"
|
||||||
|
:business-hours="drilldownRequest?.businessHours"
|
||||||
|
:can-prev="canDrilldownPrev"
|
||||||
|
:can-next="canDrilldownNext"
|
||||||
|
@navigate="navigateDrilldown"
|
||||||
|
@close="closeDrilldown"
|
||||||
|
/>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
+279
@@ -0,0 +1,279 @@
|
|||||||
|
<script setup>
|
||||||
|
import { computed } from 'vue';
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { useRoute } from 'vue-router';
|
||||||
|
import { formatTime } from '@chatwoot/utils';
|
||||||
|
import format from 'date-fns/format';
|
||||||
|
import fromUnixTime from 'date-fns/fromUnixTime';
|
||||||
|
import Icon from 'dashboard/components-next/icon/Icon.vue';
|
||||||
|
import TimeAgo from 'dashboard/components/ui/TimeAgo.vue';
|
||||||
|
import { frontendURL, conversationUrl } from 'dashboard/helper/URLHelper';
|
||||||
|
import { dynamicTime, shortTimestamp } from 'shared/helpers/timeHelper';
|
||||||
|
|
||||||
|
const props = defineProps({
|
||||||
|
record: {
|
||||||
|
type: Object,
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const { t } = useI18n();
|
||||||
|
const route = useRoute();
|
||||||
|
|
||||||
|
const conversation = computed(() => props.record.conversation || {});
|
||||||
|
const message = computed(() => props.record.message || {});
|
||||||
|
const isMessageRecord = computed(() => props.record.record_type === 'message');
|
||||||
|
const isEventBackedConversationRecord = computed(
|
||||||
|
() => !isMessageRecord.value && !!props.record.event_name
|
||||||
|
);
|
||||||
|
const conversationDisplayId = computed(() => conversation.value.display_id);
|
||||||
|
const conversationNumber = computed(() => `#${conversationDisplayId.value}`);
|
||||||
|
const messageDirection = computed(() => message.value.message_type);
|
||||||
|
|
||||||
|
const formatTimestamp = timestamp => {
|
||||||
|
if (!timestamp) return '';
|
||||||
|
|
||||||
|
return format(fromUnixTime(timestamp), 'dd MMM yyyy, h:mm a');
|
||||||
|
};
|
||||||
|
|
||||||
|
const compactTimestamp = timestamp => {
|
||||||
|
if (!timestamp) return '';
|
||||||
|
|
||||||
|
return shortTimestamp(dynamicTime(timestamp)).trim();
|
||||||
|
};
|
||||||
|
|
||||||
|
const metricValue = computed(() => {
|
||||||
|
const value = props.record.metric_value;
|
||||||
|
if (value === null || value === undefined) return '';
|
||||||
|
|
||||||
|
return formatTime(value) || `${value}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const previewText = computed(() => {
|
||||||
|
if (message.value.content) return message.value.content;
|
||||||
|
if (conversation.value.last_message?.content) {
|
||||||
|
return conversation.value.last_message.content;
|
||||||
|
}
|
||||||
|
|
||||||
|
return t('REPORT.DRILLDOWN.NO_MESSAGE_CONTENT');
|
||||||
|
});
|
||||||
|
|
||||||
|
const showPreview = computed(() => {
|
||||||
|
return isMessageRecord.value || conversation.value.last_message;
|
||||||
|
});
|
||||||
|
|
||||||
|
const messageCreatedTooltip = computed(() =>
|
||||||
|
t('REPORT.DRILLDOWN.MESSAGE_CREATED_AT', {
|
||||||
|
time: formatTimestamp(message.value.created_at),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
const eventOccurredTooltip = computed(() =>
|
||||||
|
t('REPORT.DRILLDOWN.EVENT_OCCURRED_AT', {
|
||||||
|
time: formatTimestamp(props.record.occurred_at),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
const directionDetails = computed(() => {
|
||||||
|
const direction = messageDirection.value;
|
||||||
|
if (!direction) return null;
|
||||||
|
|
||||||
|
const isIncoming = direction === 'incoming';
|
||||||
|
return {
|
||||||
|
icon: isIncoming ? 'i-lucide-arrow-down-left' : 'i-lucide-arrow-up-right',
|
||||||
|
tooltip: isIncoming
|
||||||
|
? t('REPORT.DRILLDOWN.INCOMING_MESSAGE')
|
||||||
|
: t('REPORT.DRILLDOWN.OUTGOING_MESSAGE'),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const conversationPath = computed(() => {
|
||||||
|
if (!conversationDisplayId.value) return '';
|
||||||
|
|
||||||
|
const path = conversationUrl({
|
||||||
|
accountId: route.params.accountId,
|
||||||
|
id: conversationDisplayId.value,
|
||||||
|
});
|
||||||
|
const params =
|
||||||
|
isMessageRecord.value && message.value.id
|
||||||
|
? { messageId: message.value.id }
|
||||||
|
: null;
|
||||||
|
|
||||||
|
return frontendURL(path, params);
|
||||||
|
});
|
||||||
|
|
||||||
|
const contactPath = computed(() => {
|
||||||
|
if (!conversation.value.contact_id) return '';
|
||||||
|
|
||||||
|
return frontendURL(
|
||||||
|
`accounts/${route.params.accountId}/contacts/${conversation.value.contact_id}`
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
const inboxPath = computed(() => {
|
||||||
|
if (!conversation.value.inbox_id) return '';
|
||||||
|
|
||||||
|
return frontendURL(
|
||||||
|
`accounts/${route.params.accountId}/inbox/${conversation.value.inbox_id}`
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
const agentPath = computed(() => {
|
||||||
|
if (!conversation.value.assignee_id) return '';
|
||||||
|
|
||||||
|
return frontendURL(
|
||||||
|
`accounts/${route.params.accountId}/reports/agents/${conversation.value.assignee_id}`
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
const metadataItems = computed(() => [
|
||||||
|
{
|
||||||
|
key: 'contact',
|
||||||
|
icon: 'i-lucide-contact',
|
||||||
|
label:
|
||||||
|
conversation.value.contact_name || t('REPORT.DRILLDOWN.UNKNOWN_CONTACT'),
|
||||||
|
path: contactPath.value,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'inbox',
|
||||||
|
icon: 'i-lucide-inbox',
|
||||||
|
label: conversation.value.inbox_name || t('REPORT.DRILLDOWN.UNKNOWN_INBOX'),
|
||||||
|
path: inboxPath.value,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'agent',
|
||||||
|
icon: 'i-lucide-user-round',
|
||||||
|
label:
|
||||||
|
conversation.value.assignee_name ||
|
||||||
|
t('REPORT.DRILLDOWN.UNASSIGNED_AGENT'),
|
||||||
|
path: agentPath.value,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
const metadataAttributes = item => {
|
||||||
|
if (!item.path) return {};
|
||||||
|
|
||||||
|
return {
|
||||||
|
href: item.path,
|
||||||
|
target: '_blank',
|
||||||
|
rel: 'noopener noreferrer',
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const metadataItemClass = item => [
|
||||||
|
'flex min-w-0 items-center gap-1 text-n-slate-10',
|
||||||
|
item.path ? 'group hover:text-n-blue-11 hover:underline' : '',
|
||||||
|
];
|
||||||
|
|
||||||
|
const metadataIconClass = item => [
|
||||||
|
'size-3 shrink-0 text-n-slate-9',
|
||||||
|
item.path ? 'group-hover:text-n-blue-11' : '',
|
||||||
|
];
|
||||||
|
|
||||||
|
const stopMetadataLinkClick = (event, item) => {
|
||||||
|
if (item.path) {
|
||||||
|
event.stopPropagation();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const openInNewTab = url => {
|
||||||
|
if (!url) return;
|
||||||
|
|
||||||
|
window.open(url, '_blank', 'noopener,noreferrer');
|
||||||
|
};
|
||||||
|
|
||||||
|
const openRecord = () => {
|
||||||
|
openInNewTab(conversationPath.value);
|
||||||
|
};
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<article
|
||||||
|
role="link"
|
||||||
|
tabindex="0"
|
||||||
|
class="cursor-pointer rounded-md border border-n-weak bg-n-solid-2 p-3 hover:bg-n-alpha-1 focus-visible:outline focus-visible:outline-2 focus-visible:outline-n-brand"
|
||||||
|
@click="openRecord"
|
||||||
|
@keydown.enter.self.prevent="openRecord"
|
||||||
|
@keydown.space.self.prevent="openRecord"
|
||||||
|
>
|
||||||
|
<div class="flex items-start justify-between gap-2">
|
||||||
|
<div class="min-w-0">
|
||||||
|
<div
|
||||||
|
class="flex items-center gap-2 text-sm font-medium leading-5 text-n-slate-12"
|
||||||
|
>
|
||||||
|
<span>{{ conversationNumber }}</span>
|
||||||
|
<span
|
||||||
|
v-if="conversation.status"
|
||||||
|
class="rounded bg-n-alpha-2 px-1.5 py-0.5 text-xs capitalize text-n-slate-11"
|
||||||
|
>
|
||||||
|
{{ conversation.status }}
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
v-if="directionDetails"
|
||||||
|
v-tooltip.top="directionDetails.tooltip"
|
||||||
|
:aria-label="directionDetails.tooltip"
|
||||||
|
class="flex size-5 items-center justify-center rounded bg-n-alpha-2 text-n-slate-11"
|
||||||
|
>
|
||||||
|
<Icon :icon="directionDetails.icon" class="size-3" />
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
v-if="metricValue"
|
||||||
|
class="rounded bg-n-alpha-2 px-1.5 py-0.5 text-xs text-n-slate-11"
|
||||||
|
>
|
||||||
|
{{ metricValue }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
class="ms-2 flex shrink-0 items-center justify-end gap-1 text-end text-xs leading-4 text-n-slate-10"
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
v-if="isMessageRecord"
|
||||||
|
v-tooltip.left="messageCreatedTooltip"
|
||||||
|
:aria-label="messageCreatedTooltip"
|
||||||
|
class="whitespace-nowrap"
|
||||||
|
>
|
||||||
|
{{ compactTimestamp(message.created_at) }}
|
||||||
|
</span>
|
||||||
|
<TimeAgo
|
||||||
|
v-else
|
||||||
|
:is-auto-refresh-enabled="false"
|
||||||
|
:conversation-id="conversation.id"
|
||||||
|
:last-activity-timestamp="conversation.last_activity_at"
|
||||||
|
:created-at-timestamp="conversation.created_at"
|
||||||
|
class="font-440 !text-xs !text-n-slate-10"
|
||||||
|
/>
|
||||||
|
<span
|
||||||
|
v-if="isEventBackedConversationRecord"
|
||||||
|
v-tooltip.left="eventOccurredTooltip"
|
||||||
|
:aria-label="eventOccurredTooltip"
|
||||||
|
class="whitespace-nowrap rounded bg-n-alpha-2 px-1 py-0.5 text-[11px] leading-4 text-n-slate-10"
|
||||||
|
>
|
||||||
|
{{ compactTimestamp(record.occurred_at) }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p
|
||||||
|
v-if="showPreview"
|
||||||
|
class="mt-2 line-clamp-1 text-sm leading-5 text-n-slate-12"
|
||||||
|
>
|
||||||
|
{{ previewText }}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div class="mt-2 grid grid-cols-3 gap-2">
|
||||||
|
<component
|
||||||
|
:is="item.path ? 'a' : 'span'"
|
||||||
|
v-for="item in metadataItems"
|
||||||
|
:key="item.key"
|
||||||
|
class="text-body-main"
|
||||||
|
v-bind="metadataAttributes(item)"
|
||||||
|
:class="metadataItemClass(item)"
|
||||||
|
@click="stopMetadataLinkClick($event, item)"
|
||||||
|
>
|
||||||
|
<Icon :icon="item.icon" :class="metadataIconClass(item)" />
|
||||||
|
<span class="truncate">{{ item.label }}</span>
|
||||||
|
</component>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
</template>
|
||||||
+315
@@ -0,0 +1,315 @@
|
|||||||
|
<script setup>
|
||||||
|
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||||
|
import { useEventListener } from '@vueuse/core';
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { formatTime } from '@chatwoot/utils';
|
||||||
|
import Button from 'dashboard/components-next/button/Button.vue';
|
||||||
|
import Spinner from 'dashboard/components-next/spinner/Spinner.vue';
|
||||||
|
import TeleportWithDirection from 'dashboard/components-next/TeleportWithDirection.vue';
|
||||||
|
import { useReportDrilldown } from '../composables/useReportDrilldown';
|
||||||
|
import ReportDrilldownCard from './ReportDrilldownCard.vue';
|
||||||
|
|
||||||
|
const props = defineProps({
|
||||||
|
open: { type: Boolean, default: false },
|
||||||
|
metric: { type: String, default: '' },
|
||||||
|
metricName: { type: String, default: '' },
|
||||||
|
bucketLabel: { type: String, default: '' },
|
||||||
|
bucketTimestamp: { type: Number, default: null },
|
||||||
|
from: { type: Number, default: null },
|
||||||
|
to: { type: Number, default: null },
|
||||||
|
type: { type: String, default: 'account' },
|
||||||
|
id: { type: [String, Number], default: null },
|
||||||
|
groupBy: { type: String, default: '' },
|
||||||
|
businessHours: { type: Boolean, default: false },
|
||||||
|
bucketValue: { type: Number, default: null },
|
||||||
|
isAverageMetric: { type: Boolean, default: false },
|
||||||
|
canPrev: { type: Boolean, default: false },
|
||||||
|
canNext: { type: Boolean, default: false },
|
||||||
|
});
|
||||||
|
|
||||||
|
const emit = defineEmits(['close', 'navigate']);
|
||||||
|
|
||||||
|
const { t } = useI18n();
|
||||||
|
const drawerRef = ref(null);
|
||||||
|
const {
|
||||||
|
records,
|
||||||
|
meta,
|
||||||
|
isFetching,
|
||||||
|
isFetchingMore,
|
||||||
|
hasError,
|
||||||
|
hasRecords,
|
||||||
|
hasMore,
|
||||||
|
open: openDrilldown,
|
||||||
|
close,
|
||||||
|
loadMore,
|
||||||
|
} = useReportDrilldown();
|
||||||
|
|
||||||
|
let previousActiveElement = null;
|
||||||
|
|
||||||
|
const isOpen = computed(() => props.open);
|
||||||
|
|
||||||
|
const title = computed(() => props.metricName || '');
|
||||||
|
|
||||||
|
const bucketValue = computed(() => {
|
||||||
|
if (props.bucketValue === null) return '';
|
||||||
|
|
||||||
|
return props.isAverageMetric
|
||||||
|
? formatTime(props.bucketValue)
|
||||||
|
: `${props.bucketValue}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
// The headline stat already shows the conversation count for conversation-count
|
||||||
|
// metrics (e.g. conversations_count), so the subtitle count would be redundant.
|
||||||
|
const isStatConversationCount = computed(
|
||||||
|
() =>
|
||||||
|
!props.isAverageMetric &&
|
||||||
|
meta.value.record_type === 'conversation' &&
|
||||||
|
props.bucketValue === meta.value.conversation_count
|
||||||
|
);
|
||||||
|
|
||||||
|
const conversationCount = computed(() => {
|
||||||
|
if (!meta.value.conversation_count || isStatConversationCount.value)
|
||||||
|
return '';
|
||||||
|
|
||||||
|
return t('REPORT.DRILLDOWN.RESULT_COUNT_CONVERSATION', {
|
||||||
|
count: meta.value.conversation_count,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Timing metrics (e.g. reply time) show a duration as the stat, so the underlying
|
||||||
|
// message count adds context. Skip it when it just mirrors the conversation count
|
||||||
|
// (e.g. first response time has one response message per conversation).
|
||||||
|
const messageCount = computed(() => {
|
||||||
|
if (
|
||||||
|
!props.isAverageMetric ||
|
||||||
|
meta.value.record_type !== 'message' ||
|
||||||
|
!meta.value.total_count ||
|
||||||
|
meta.value.total_count === meta.value.conversation_count
|
||||||
|
) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
return t('REPORT.DRILLDOWN.RESULT_COUNT_MESSAGE', {
|
||||||
|
count: meta.value.total_count,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const subtitle = computed(() =>
|
||||||
|
[props.bucketLabel, conversationCount.value, messageCount.value]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(' ⋅ ')
|
||||||
|
);
|
||||||
|
|
||||||
|
const restoreFocus = () => {
|
||||||
|
if (previousActiveElement?.isConnected) {
|
||||||
|
previousActiveElement.focus();
|
||||||
|
}
|
||||||
|
previousActiveElement = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const closeDrawer = () => {
|
||||||
|
close();
|
||||||
|
emit('close');
|
||||||
|
restoreFocus();
|
||||||
|
};
|
||||||
|
|
||||||
|
const recordKey = record =>
|
||||||
|
`${record.record_type}-${record.message?.id || record.conversation?.id}-${
|
||||||
|
record.occurred_at
|
||||||
|
}`;
|
||||||
|
|
||||||
|
const rememberActiveElement = () => {
|
||||||
|
if (previousActiveElement) return;
|
||||||
|
|
||||||
|
previousActiveElement =
|
||||||
|
document.activeElement instanceof HTMLElement
|
||||||
|
? document.activeElement
|
||||||
|
: null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const focusDrawer = () => {
|
||||||
|
nextTick(() => drawerRef.value?.focus());
|
||||||
|
};
|
||||||
|
|
||||||
|
const fetchDrilldown = () => {
|
||||||
|
openDrilldown({
|
||||||
|
metric: props.metric,
|
||||||
|
bucketTimestamp: props.bucketTimestamp,
|
||||||
|
from: props.from,
|
||||||
|
to: props.to,
|
||||||
|
type: props.type,
|
||||||
|
id: props.id,
|
||||||
|
groupBy: props.groupBy,
|
||||||
|
businessHours: props.businessHours,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const navigate = direction => {
|
||||||
|
if (direction < 0 && !props.canPrev) return;
|
||||||
|
if (direction > 0 && !props.canNext) return;
|
||||||
|
|
||||||
|
emit('navigate', direction);
|
||||||
|
};
|
||||||
|
|
||||||
|
const onKeydown = event => {
|
||||||
|
if (!isOpen.value) return;
|
||||||
|
|
||||||
|
if (event.key === 'Escape') {
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
closeDrawer();
|
||||||
|
} else if (event.key === 'ArrowLeft') {
|
||||||
|
navigate(-1);
|
||||||
|
} else if (event.key === 'ArrowRight') {
|
||||||
|
navigate(1);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEventListener(document, 'keydown', onKeydown);
|
||||||
|
|
||||||
|
watch(
|
||||||
|
() => props.open,
|
||||||
|
isDrawerOpen => {
|
||||||
|
if (!isDrawerOpen) {
|
||||||
|
close();
|
||||||
|
restoreFocus();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
rememberActiveElement();
|
||||||
|
fetchDrilldown();
|
||||||
|
focusDrawer();
|
||||||
|
},
|
||||||
|
{ immediate: true }
|
||||||
|
);
|
||||||
|
|
||||||
|
watch(
|
||||||
|
() => [props.metric, props.bucketTimestamp],
|
||||||
|
() => {
|
||||||
|
if (props.open) fetchDrilldown();
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
restoreFocus();
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<TeleportWithDirection to="body">
|
||||||
|
<Transition name="report-drilldown-fade">
|
||||||
|
<div
|
||||||
|
v-if="isOpen"
|
||||||
|
class="fixed inset-0 z-50 bg-black/30"
|
||||||
|
role="presentation"
|
||||||
|
@click.self="closeDrawer"
|
||||||
|
>
|
||||||
|
<aside
|
||||||
|
ref="drawerRef"
|
||||||
|
class="fixed inset-y-0 end-0 flex w-full max-w-xl flex-col bg-n-solid-1 shadow-xl outline outline-1 outline-n-container"
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
:aria-label="title"
|
||||||
|
tabindex="-1"
|
||||||
|
>
|
||||||
|
<header
|
||||||
|
class="flex items-start justify-between gap-4 border-b border-n-weak px-6 py-5"
|
||||||
|
>
|
||||||
|
<div class="min-w-0">
|
||||||
|
<h2 class="truncate text-base font-medium text-n-slate-12">
|
||||||
|
{{ title }}
|
||||||
|
</h2>
|
||||||
|
<p
|
||||||
|
v-if="bucketValue"
|
||||||
|
class="mt-1 text-xl font-semibold text-n-slate-12"
|
||||||
|
>
|
||||||
|
{{ bucketValue }}
|
||||||
|
</p>
|
||||||
|
<div
|
||||||
|
class="text-sm text-n-slate-11"
|
||||||
|
:class="{
|
||||||
|
'mt-2': bucketValue,
|
||||||
|
'mt-1': !bucketValue,
|
||||||
|
}"
|
||||||
|
>
|
||||||
|
{{ subtitle }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex shrink-0 items-center gap-1">
|
||||||
|
<Button
|
||||||
|
ghost
|
||||||
|
slate
|
||||||
|
size="sm"
|
||||||
|
icon="i-ph-caret-left"
|
||||||
|
class="rtl:rotate-180"
|
||||||
|
:disabled="!canPrev"
|
||||||
|
:aria-label="$t('REPORT.DRILLDOWN.PREVIOUS_BUCKET')"
|
||||||
|
@click="navigate(-1)"
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
ghost
|
||||||
|
slate
|
||||||
|
size="sm"
|
||||||
|
icon="i-ph-caret-right"
|
||||||
|
class="rtl:rotate-180"
|
||||||
|
:disabled="!canNext"
|
||||||
|
:aria-label="$t('REPORT.DRILLDOWN.NEXT_BUCKET')"
|
||||||
|
@click="navigate(1)"
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
ghost
|
||||||
|
slate
|
||||||
|
size="sm"
|
||||||
|
icon="i-ph-x"
|
||||||
|
:aria-label="$t('REPORT.DRILLDOWN.CLOSE')"
|
||||||
|
@click="closeDrawer"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div class="min-h-0 flex-1 overflow-y-auto px-5 py-3">
|
||||||
|
<div
|
||||||
|
v-if="isFetching"
|
||||||
|
class="flex h-40 items-center justify-center"
|
||||||
|
>
|
||||||
|
<Spinner />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div
|
||||||
|
v-else-if="hasError"
|
||||||
|
class="flex h-40 items-center justify-center text-sm text-n-ruby-11"
|
||||||
|
>
|
||||||
|
{{ $t('REPORT.DRILLDOWN.ERROR') }}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div
|
||||||
|
v-else-if="!hasRecords"
|
||||||
|
class="flex h-40 items-center justify-center text-sm text-n-slate-10"
|
||||||
|
>
|
||||||
|
{{ $t('REPORT.DRILLDOWN.EMPTY') }}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else class="flex flex-col gap-2">
|
||||||
|
<ReportDrilldownCard
|
||||||
|
v-for="record in records"
|
||||||
|
:key="recordKey(record)"
|
||||||
|
:record="record"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
v-if="hasMore"
|
||||||
|
faded
|
||||||
|
slate
|
||||||
|
size="sm"
|
||||||
|
class="mx-auto mt-2"
|
||||||
|
:label="$t('REPORT.DRILLDOWN.LOAD_MORE')"
|
||||||
|
:is-loading="isFetchingMore"
|
||||||
|
@click="loadMore"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
</div>
|
||||||
|
</Transition>
|
||||||
|
</TeleportWithDirection>
|
||||||
|
</template>
|
||||||
@@ -69,6 +69,9 @@ export default {
|
|||||||
isAgentType() {
|
isAgentType() {
|
||||||
return this.type === 'agent';
|
return this.type === 'agent';
|
||||||
},
|
},
|
||||||
|
selectedFilterId() {
|
||||||
|
return this.selectedFilter?.id || null;
|
||||||
|
},
|
||||||
reportKeys() {
|
reportKeys() {
|
||||||
return {
|
return {
|
||||||
CONVERSATIONS: 'conversations_count',
|
CONVERSATIONS: 'conversations_count',
|
||||||
@@ -181,5 +184,10 @@ export default {
|
|||||||
v-if="filterItemsList.length"
|
v-if="filterItemsList.length"
|
||||||
:group-by="groupBy"
|
:group-by="groupBy"
|
||||||
:report-keys="reportKeys"
|
:report-keys="reportKeys"
|
||||||
|
:from="from"
|
||||||
|
:to="to"
|
||||||
|
:report-type="type"
|
||||||
|
:selected-item-id="selectedFilterId"
|
||||||
|
:business-hours="businessHours"
|
||||||
/>
|
/>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
+195
@@ -0,0 +1,195 @@
|
|||||||
|
import { mount } from '@vue/test-utils';
|
||||||
|
import ReportDrilldownCard from '../ReportDrilldownCard.vue';
|
||||||
|
|
||||||
|
vi.mock('vue-router', () => ({
|
||||||
|
useRoute: () => ({
|
||||||
|
params: {
|
||||||
|
accountId: 1,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('vue-i18n', () => ({
|
||||||
|
useI18n: () => ({
|
||||||
|
t: (key, params = {}) => {
|
||||||
|
if (key === 'REPORT.DRILLDOWN.MESSAGE_CREATED_AT') {
|
||||||
|
return `Message created at ${params.time}`;
|
||||||
|
}
|
||||||
|
if (key === 'REPORT.DRILLDOWN.EVENT_OCCURRED_AT') {
|
||||||
|
return `Event occurred at ${params.time}`;
|
||||||
|
}
|
||||||
|
if (key === 'REPORT.DRILLDOWN.INCOMING_MESSAGE') {
|
||||||
|
return 'Incoming message';
|
||||||
|
}
|
||||||
|
if (key === 'REPORT.DRILLDOWN.OUTGOING_MESSAGE') {
|
||||||
|
return 'Outgoing message';
|
||||||
|
}
|
||||||
|
return key;
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('shared/helpers/timeHelper', () => ({
|
||||||
|
dynamicTime: timestamp => {
|
||||||
|
const timestamps = {
|
||||||
|
1621103500: '2 minutes ago',
|
||||||
|
1621103400: '4 days ago',
|
||||||
|
1621103700: '4 days ago',
|
||||||
|
};
|
||||||
|
return timestamps[timestamp] || 'less than a minute ago';
|
||||||
|
},
|
||||||
|
shortTimestamp: time => {
|
||||||
|
const timestamps = {
|
||||||
|
'2 minutes ago': '2m',
|
||||||
|
'4 days ago': '4d',
|
||||||
|
};
|
||||||
|
return timestamps[time] || 'now';
|
||||||
|
},
|
||||||
|
dateFormat: timestamp => `date-${timestamp}`,
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe('ReportDrilldownCard.vue', () => {
|
||||||
|
const record = {
|
||||||
|
record_type: 'message',
|
||||||
|
conversation: {
|
||||||
|
id: 10,
|
||||||
|
display_id: 42,
|
||||||
|
contact_id: 11,
|
||||||
|
contact_name: 'Jane',
|
||||||
|
inbox_id: 12,
|
||||||
|
inbox_name: 'Website',
|
||||||
|
assignee_id: 13,
|
||||||
|
assignee_name: 'Alex',
|
||||||
|
status: 'open',
|
||||||
|
created_at: 1621103400,
|
||||||
|
last_activity_at: 1621103700,
|
||||||
|
last_message: {
|
||||||
|
id: 100,
|
||||||
|
content: 'Latest reply',
|
||||||
|
message_type: 'outgoing',
|
||||||
|
created_at: 1621103600,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
message: {
|
||||||
|
id: 99,
|
||||||
|
content: 'Need help',
|
||||||
|
message_type: 'incoming',
|
||||||
|
created_at: 1621103500,
|
||||||
|
},
|
||||||
|
metric_value: null,
|
||||||
|
occurred_at: 1621103500,
|
||||||
|
};
|
||||||
|
|
||||||
|
const mountCard = (props = {}) =>
|
||||||
|
mount(ReportDrilldownCard, {
|
||||||
|
props: {
|
||||||
|
record,
|
||||||
|
...props,
|
||||||
|
},
|
||||||
|
global: {
|
||||||
|
mocks: {
|
||||||
|
$t: key => key,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.spyOn(window, 'open').mockImplementation(() => {});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('opens the card conversation link in a new tab', async () => {
|
||||||
|
const wrapper = mountCard();
|
||||||
|
|
||||||
|
expect(wrapper.text()).toContain('#42');
|
||||||
|
expect(wrapper.text()).toContain('Need help');
|
||||||
|
expect(wrapper.find('.i-lucide-arrow-down-left').exists()).toBe(true);
|
||||||
|
expect(wrapper.find('[aria-label="Incoming message"]').exists()).toBe(true);
|
||||||
|
|
||||||
|
await wrapper.find('[role="link"]').trigger('click');
|
||||||
|
|
||||||
|
expect(window.open).toHaveBeenCalledWith(
|
||||||
|
'/app/accounts/1/conversations/42?messageId=99',
|
||||||
|
'_blank',
|
||||||
|
'noopener,noreferrer'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders only message created timestamp for message rows', () => {
|
||||||
|
const wrapper = mountCard();
|
||||||
|
const messageCreatedLabel = wrapper
|
||||||
|
.findAll('[aria-label]')
|
||||||
|
.map(timestamp => timestamp.attributes('aria-label'))
|
||||||
|
.find(label => label.includes('Message created at'));
|
||||||
|
|
||||||
|
expect(wrapper.text()).toContain('2m');
|
||||||
|
expect(wrapper.text()).not.toContain('4d • 4d');
|
||||||
|
expect(messageCreatedLabel).toContain('Message created at');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders separate contact, inbox, and agent links', async () => {
|
||||||
|
const wrapper = mountCard();
|
||||||
|
const links = wrapper.findAll('a');
|
||||||
|
|
||||||
|
expect(links.map(link => link.attributes('href'))).toEqual([
|
||||||
|
'/app/accounts/1/contacts/11',
|
||||||
|
'/app/accounts/1/inbox/12',
|
||||||
|
'/app/accounts/1/reports/agents/13',
|
||||||
|
]);
|
||||||
|
expect(links.every(link => link.attributes('target') === '_blank')).toBe(
|
||||||
|
true
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
links.every(link => link.classes().includes('text-n-slate-10'))
|
||||||
|
).toBe(true);
|
||||||
|
expect(
|
||||||
|
links.every(link => !link.classes().includes('text-n-blue-11'))
|
||||||
|
).toBe(true);
|
||||||
|
expect(wrapper.find('.i-lucide-contact').exists()).toBe(true);
|
||||||
|
expect(wrapper.find('.i-lucide-inbox').exists()).toBe(true);
|
||||||
|
expect(wrapper.find('.i-lucide-user-round').exists()).toBe(true);
|
||||||
|
|
||||||
|
await links[0].trigger('click');
|
||||||
|
|
||||||
|
expect(window.open).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders the last message for conversation rows', () => {
|
||||||
|
const wrapper = mountCard({
|
||||||
|
record: {
|
||||||
|
...record,
|
||||||
|
record_type: 'conversation',
|
||||||
|
message: null,
|
||||||
|
occurred_at: 1621103500,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(wrapper.text()).toContain('Latest reply');
|
||||||
|
expect(wrapper.text()).toContain('4d • 4d');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders event time alongside TimeAgo for event-backed conversation rows', () => {
|
||||||
|
const wrapper = mountCard({
|
||||||
|
record: {
|
||||||
|
...record,
|
||||||
|
record_type: 'conversation',
|
||||||
|
message: null,
|
||||||
|
event_name: 'conversation_bot_handoff',
|
||||||
|
occurred_at: 1621103500,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const eventOccurredLabel = wrapper
|
||||||
|
.findAll('[aria-label]')
|
||||||
|
.map(timestamp => timestamp.attributes('aria-label'))
|
||||||
|
.find(label => label.includes('Event occurred at'));
|
||||||
|
|
||||||
|
expect(wrapper.text()).toContain('Latest reply');
|
||||||
|
expect(wrapper.text()).toContain('4d • 4d');
|
||||||
|
expect(wrapper.text()).toContain('2m');
|
||||||
|
expect(eventOccurredLabel).toContain('Event occurred at');
|
||||||
|
});
|
||||||
|
});
|
||||||
+352
@@ -0,0 +1,352 @@
|
|||||||
|
import { flushPromises, mount } from '@vue/test-utils';
|
||||||
|
import { nextTick } from 'vue';
|
||||||
|
import { formatTime } from '@chatwoot/utils';
|
||||||
|
import ReportsAPI from 'dashboard/api/reports';
|
||||||
|
import ReportDrilldownDrawer from '../ReportDrilldownDrawer.vue';
|
||||||
|
|
||||||
|
vi.mock('dashboard/api/reports', () => ({
|
||||||
|
default: {
|
||||||
|
getDrilldown: vi.fn(),
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('vue-i18n', () => ({
|
||||||
|
useI18n: () => ({
|
||||||
|
t: (key, params = {}) => {
|
||||||
|
if (key === 'REPORT.DRILLDOWN.TITLE') {
|
||||||
|
return `${params.metric} details`;
|
||||||
|
}
|
||||||
|
if (key === 'REPORT.DRILLDOWN.RESULT_COUNT_CONVERSATION') {
|
||||||
|
return `${params.count} conversations`;
|
||||||
|
}
|
||||||
|
if (key === 'REPORT.DRILLDOWN.RESULT_COUNT_MESSAGE') {
|
||||||
|
return `${params.count} messages`;
|
||||||
|
}
|
||||||
|
return key;
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe('ReportDrilldownDrawer.vue', () => {
|
||||||
|
const request = {
|
||||||
|
metric: 'incoming_messages_count',
|
||||||
|
metricName: 'Messages received',
|
||||||
|
bucketLabel: '20-May',
|
||||||
|
bucketTimestamp: 1621103400,
|
||||||
|
from: 1621103400,
|
||||||
|
to: 1621621800,
|
||||||
|
type: 'account',
|
||||||
|
groupBy: 'day',
|
||||||
|
businessHours: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
const payload = [
|
||||||
|
{
|
||||||
|
record_type: 'message',
|
||||||
|
conversation: {
|
||||||
|
id: 10,
|
||||||
|
display_id: 42,
|
||||||
|
contact_id: 11,
|
||||||
|
contact_name: 'Jane',
|
||||||
|
inbox_id: 12,
|
||||||
|
inbox_name: 'Website',
|
||||||
|
assignee_id: 13,
|
||||||
|
assignee_name: 'Alex',
|
||||||
|
status: 'open',
|
||||||
|
created_at: 1621103400,
|
||||||
|
last_activity_at: 1621103700,
|
||||||
|
last_message: {
|
||||||
|
id: 100,
|
||||||
|
content: 'Latest reply',
|
||||||
|
message_type: 'outgoing',
|
||||||
|
created_at: 1621103600,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
message: {
|
||||||
|
id: 99,
|
||||||
|
content: 'Need help',
|
||||||
|
message_type: 'incoming',
|
||||||
|
created_at: 1621103500,
|
||||||
|
},
|
||||||
|
metric_value: null,
|
||||||
|
occurred_at: 1621103500,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const mountDrawer = options =>
|
||||||
|
mount(ReportDrilldownDrawer, {
|
||||||
|
props: { open: true, ...request, ...options?.props },
|
||||||
|
attachTo: options?.attachTo,
|
||||||
|
global: {
|
||||||
|
stubs: {
|
||||||
|
TeleportWithDirection: {
|
||||||
|
template: '<div><slot /></div>',
|
||||||
|
},
|
||||||
|
Transition: false,
|
||||||
|
Spinner: true,
|
||||||
|
Button: {
|
||||||
|
props: ['label'],
|
||||||
|
emits: ['click'],
|
||||||
|
template:
|
||||||
|
'<button @click="$emit(\'click\')">{{ label }}<slot /></button>',
|
||||||
|
},
|
||||||
|
ReportDrilldownCard: {
|
||||||
|
props: ['record'],
|
||||||
|
template:
|
||||||
|
'<div data-testid="drilldown-card">#{{ record.conversation.display_id }}</div>',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
mocks: {
|
||||||
|
$t: key => key,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
ReportsAPI.getDrilldown.mockResolvedValue({
|
||||||
|
data: {
|
||||||
|
meta: {
|
||||||
|
total_count: 1,
|
||||||
|
current_page: 1,
|
||||||
|
record_type: 'message',
|
||||||
|
conversation_count: 1,
|
||||||
|
},
|
||||||
|
payload,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('loads and renders drilldown cards for the request', async () => {
|
||||||
|
const wrapper = mountDrawer();
|
||||||
|
await flushPromises();
|
||||||
|
|
||||||
|
expect(ReportsAPI.getDrilldown).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
metric: 'incoming_messages_count',
|
||||||
|
bucketTimestamp: 1621103400,
|
||||||
|
page: 1,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
expect(wrapper.text()).toContain('Messages received');
|
||||||
|
expect(wrapper.text()).toContain('1 conversations');
|
||||||
|
expect(wrapper.find('[data-testid="drilldown-card"]').text()).toBe('#42');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the bucket aggregate value for average metrics', async () => {
|
||||||
|
const wrapper = mountDrawer({
|
||||||
|
props: {
|
||||||
|
metric: 'avg_first_response_time',
|
||||||
|
metricName: 'First response time',
|
||||||
|
isAverageMetric: true,
|
||||||
|
bucketValue: 2580,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await flushPromises();
|
||||||
|
|
||||||
|
expect(wrapper.text()).toContain(formatTime(2580));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows both conversation and message counts when they differ (reply time)', async () => {
|
||||||
|
ReportsAPI.getDrilldown.mockResolvedValue({
|
||||||
|
data: {
|
||||||
|
meta: {
|
||||||
|
total_count: 8,
|
||||||
|
current_page: 1,
|
||||||
|
record_type: 'message',
|
||||||
|
conversation_count: 5,
|
||||||
|
},
|
||||||
|
payload,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const wrapper = mountDrawer({
|
||||||
|
props: {
|
||||||
|
metric: 'reply_time',
|
||||||
|
isAverageMetric: true,
|
||||||
|
bucketValue: 2580,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await flushPromises();
|
||||||
|
|
||||||
|
expect(wrapper.text()).toContain('5 conversations');
|
||||||
|
expect(wrapper.text()).toContain('8 messages');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('hides the message count when it matches the conversation count (first response time)', async () => {
|
||||||
|
ReportsAPI.getDrilldown.mockResolvedValue({
|
||||||
|
data: {
|
||||||
|
meta: {
|
||||||
|
total_count: 5,
|
||||||
|
current_page: 1,
|
||||||
|
record_type: 'message',
|
||||||
|
conversation_count: 5,
|
||||||
|
},
|
||||||
|
payload,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const wrapper = mountDrawer({
|
||||||
|
props: {
|
||||||
|
metric: 'avg_first_response_time',
|
||||||
|
isAverageMetric: true,
|
||||||
|
bucketValue: 2580,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await flushPromises();
|
||||||
|
|
||||||
|
expect(wrapper.text()).toContain('5 conversations');
|
||||||
|
expect(wrapper.text()).not.toContain('messages');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the plain count as the bucket value for count metrics', async () => {
|
||||||
|
const wrapper = mountDrawer({ props: { bucketValue: 128 } });
|
||||||
|
await flushPromises();
|
||||||
|
|
||||||
|
expect(wrapper.text()).toContain('128');
|
||||||
|
expect(wrapper.text()).not.toContain(formatTime(128));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('hides the redundant subtitle count for conversation-count metrics', async () => {
|
||||||
|
ReportsAPI.getDrilldown.mockResolvedValue({
|
||||||
|
data: {
|
||||||
|
meta: {
|
||||||
|
total_count: 5,
|
||||||
|
current_page: 1,
|
||||||
|
record_type: 'conversation',
|
||||||
|
conversation_count: 5,
|
||||||
|
},
|
||||||
|
payload,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const wrapper = mountDrawer({
|
||||||
|
props: { metric: 'conversations_count', bucketValue: 5 },
|
||||||
|
});
|
||||||
|
await flushPromises();
|
||||||
|
|
||||||
|
expect(wrapper.text()).toContain('5');
|
||||||
|
expect(wrapper.text()).not.toContain('conversations');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the subtitle count when it differs from the stat value', async () => {
|
||||||
|
ReportsAPI.getDrilldown.mockResolvedValue({
|
||||||
|
data: {
|
||||||
|
meta: {
|
||||||
|
total_count: 8,
|
||||||
|
current_page: 1,
|
||||||
|
record_type: 'conversation',
|
||||||
|
conversation_count: 5,
|
||||||
|
},
|
||||||
|
payload,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const wrapper = mountDrawer({
|
||||||
|
props: { metric: 'resolutions_count', bucketValue: 8 },
|
||||||
|
});
|
||||||
|
await flushPromises();
|
||||||
|
|
||||||
|
expect(wrapper.text()).toContain('5 conversations');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('anchors the drawer to the inline-end edge so it flips in RTL', async () => {
|
||||||
|
const wrapper = mountDrawer();
|
||||||
|
await flushPromises();
|
||||||
|
|
||||||
|
const drawer = wrapper.get('[role="dialog"]');
|
||||||
|
expect(drawer.classes()).toContain('end-0');
|
||||||
|
expect(drawer.classes()).not.toContain('right-0');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('flips the navigation caret icons in RTL', async () => {
|
||||||
|
const wrapper = mountDrawer({ props: { canPrev: true, canNext: true } });
|
||||||
|
await flushPromises();
|
||||||
|
|
||||||
|
expect(
|
||||||
|
wrapper.get('[aria-label="REPORT.DRILLDOWN.PREVIOUS_BUCKET"]').classes()
|
||||||
|
).toContain('rtl:rotate-180');
|
||||||
|
expect(
|
||||||
|
wrapper.get('[aria-label="REPORT.DRILLDOWN.NEXT_BUCKET"]').classes()
|
||||||
|
).toContain('rtl:rotate-180');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('emits close when the drawer close button is clicked', async () => {
|
||||||
|
const wrapper = mountDrawer();
|
||||||
|
await flushPromises();
|
||||||
|
|
||||||
|
await wrapper.get('[aria-label="REPORT.DRILLDOWN.CLOSE"]').trigger('click');
|
||||||
|
|
||||||
|
expect(wrapper.emitted('close')).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('emits navigate when the next button is clicked', async () => {
|
||||||
|
const wrapper = mountDrawer({ props: { canNext: true } });
|
||||||
|
await flushPromises();
|
||||||
|
|
||||||
|
await wrapper
|
||||||
|
.get('[aria-label="REPORT.DRILLDOWN.NEXT_BUCKET"]')
|
||||||
|
.trigger('click');
|
||||||
|
|
||||||
|
expect(wrapper.emitted('navigate')).toStrictEqual([[1]]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not emit navigate past the available range', async () => {
|
||||||
|
const wrapper = mountDrawer({ props: { canPrev: false } });
|
||||||
|
await flushPromises();
|
||||||
|
|
||||||
|
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowLeft' }));
|
||||||
|
|
||||||
|
expect(wrapper.emitted('navigate')).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('moves focus into the drawer when opened', async () => {
|
||||||
|
const target = document.createElement('div');
|
||||||
|
document.body.appendChild(target);
|
||||||
|
const wrapper = mountDrawer({ attachTo: target });
|
||||||
|
await flushPromises();
|
||||||
|
await nextTick();
|
||||||
|
|
||||||
|
expect(document.activeElement).toBe(
|
||||||
|
wrapper.find('[role="dialog"]').element
|
||||||
|
);
|
||||||
|
|
||||||
|
wrapper.unmount();
|
||||||
|
target.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('closes on Escape even when focus is outside the drawer', async () => {
|
||||||
|
const target = document.createElement('div');
|
||||||
|
document.body.appendChild(target);
|
||||||
|
const wrapper = mountDrawer({ attachTo: target });
|
||||||
|
await flushPromises();
|
||||||
|
|
||||||
|
document.body.focus();
|
||||||
|
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
|
||||||
|
|
||||||
|
expect(wrapper.emitted('close')).toBeTruthy();
|
||||||
|
|
||||||
|
wrapper.unmount();
|
||||||
|
target.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('restores focus to the previously focused element when closed', async () => {
|
||||||
|
const opener = document.createElement('button');
|
||||||
|
const target = document.createElement('div');
|
||||||
|
document.body.appendChild(opener);
|
||||||
|
document.body.appendChild(target);
|
||||||
|
opener.focus();
|
||||||
|
|
||||||
|
const wrapper = mountDrawer({ attachTo: target });
|
||||||
|
await flushPromises();
|
||||||
|
await nextTick();
|
||||||
|
|
||||||
|
await wrapper.get('[aria-label="REPORT.DRILLDOWN.CLOSE"]').trigger('click');
|
||||||
|
|
||||||
|
expect(document.activeElement).toBe(opener);
|
||||||
|
|
||||||
|
wrapper.unmount();
|
||||||
|
target.remove();
|
||||||
|
opener.remove();
|
||||||
|
});
|
||||||
|
});
|
||||||
+124
@@ -0,0 +1,124 @@
|
|||||||
|
import { flushPromises, mount } from '@vue/test-utils';
|
||||||
|
import ReportsAPI from 'dashboard/api/reports';
|
||||||
|
import { useReportDrilldown } from '../useReportDrilldown';
|
||||||
|
|
||||||
|
vi.mock('dashboard/api/reports', () => ({
|
||||||
|
default: {
|
||||||
|
getDrilldown: vi.fn(),
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
const deferredPromise = () => {
|
||||||
|
let resolve;
|
||||||
|
let reject;
|
||||||
|
const promise = new Promise((resolvePromise, rejectPromise) => {
|
||||||
|
resolve = resolvePromise;
|
||||||
|
reject = rejectPromise;
|
||||||
|
});
|
||||||
|
|
||||||
|
return { promise, resolve, reject };
|
||||||
|
};
|
||||||
|
|
||||||
|
const drilldownRequest = overrides => ({
|
||||||
|
metric: 'conversations_count',
|
||||||
|
bucketTimestamp: 1,
|
||||||
|
from: 1621103400,
|
||||||
|
to: 1621621800,
|
||||||
|
type: 'account',
|
||||||
|
groupBy: 'day',
|
||||||
|
businessHours: false,
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('useReportDrilldown', () => {
|
||||||
|
const mountComposable = () =>
|
||||||
|
mount({
|
||||||
|
setup() {
|
||||||
|
return useReportDrilldown();
|
||||||
|
},
|
||||||
|
template: '<div />',
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not request drilldown again for an identical active request', async () => {
|
||||||
|
const request = deferredPromise();
|
||||||
|
ReportsAPI.getDrilldown.mockReturnValue(request.promise);
|
||||||
|
|
||||||
|
const wrapper = mountComposable();
|
||||||
|
wrapper.vm.open(drilldownRequest());
|
||||||
|
wrapper.vm.open(drilldownRequest());
|
||||||
|
|
||||||
|
expect(ReportsAPI.getDrilldown).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('aborts an in-flight request when a newer request is opened', async () => {
|
||||||
|
const firstRequest = deferredPromise();
|
||||||
|
const secondRequest = deferredPromise();
|
||||||
|
let firstSignal;
|
||||||
|
|
||||||
|
ReportsAPI.getDrilldown
|
||||||
|
.mockImplementationOnce(({ signal }) => {
|
||||||
|
firstSignal = signal;
|
||||||
|
return firstRequest.promise;
|
||||||
|
})
|
||||||
|
.mockReturnValueOnce(secondRequest.promise);
|
||||||
|
|
||||||
|
const wrapper = mountComposable();
|
||||||
|
wrapper.vm.open(drilldownRequest({ bucketTimestamp: 1 }));
|
||||||
|
wrapper.vm.open(drilldownRequest({ bucketTimestamp: 2 }));
|
||||||
|
|
||||||
|
expect(firstSignal.aborted).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('passes an abort signal to drilldown requests', async () => {
|
||||||
|
const request = deferredPromise();
|
||||||
|
ReportsAPI.getDrilldown.mockReturnValue(request.promise);
|
||||||
|
|
||||||
|
const wrapper = mountComposable();
|
||||||
|
wrapper.vm.open(drilldownRequest());
|
||||||
|
|
||||||
|
expect(ReportsAPI.getDrilldown).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
page: 1,
|
||||||
|
signal: expect.any(AbortSignal),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignores stale responses when a newer request is opened first', async () => {
|
||||||
|
const firstRequest = deferredPromise();
|
||||||
|
const secondRequest = deferredPromise();
|
||||||
|
ReportsAPI.getDrilldown
|
||||||
|
.mockReturnValueOnce(firstRequest.promise)
|
||||||
|
.mockReturnValueOnce(secondRequest.promise);
|
||||||
|
|
||||||
|
const wrapper = mountComposable();
|
||||||
|
wrapper.vm.open(drilldownRequest({ bucketTimestamp: 1 }));
|
||||||
|
wrapper.vm.open(drilldownRequest({ bucketTimestamp: 2 }));
|
||||||
|
|
||||||
|
secondRequest.resolve({
|
||||||
|
data: {
|
||||||
|
meta: { current_page: 1, total_count: 1 },
|
||||||
|
payload: [{ id: 'second' }],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await flushPromises();
|
||||||
|
|
||||||
|
expect(wrapper.vm.records).toEqual([{ id: 'second' }]);
|
||||||
|
expect(wrapper.vm.meta).toEqual({ current_page: 1, total_count: 1 });
|
||||||
|
|
||||||
|
firstRequest.resolve({
|
||||||
|
data: {
|
||||||
|
meta: { current_page: 1, total_count: 1 },
|
||||||
|
payload: [{ id: 'first' }],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await flushPromises();
|
||||||
|
|
||||||
|
expect(wrapper.vm.records).toEqual([{ id: 'second' }]);
|
||||||
|
expect(wrapper.vm.meta).toEqual({ current_page: 1, total_count: 1 });
|
||||||
|
});
|
||||||
|
});
|
||||||
+138
@@ -0,0 +1,138 @@
|
|||||||
|
import { computed, ref } from 'vue';
|
||||||
|
import ReportsAPI from 'dashboard/api/reports';
|
||||||
|
|
||||||
|
export function useReportDrilldown() {
|
||||||
|
const activeRequest = ref(null);
|
||||||
|
const records = ref([]);
|
||||||
|
const meta = ref({});
|
||||||
|
const isFetching = ref(false);
|
||||||
|
const isFetchingMore = ref(false);
|
||||||
|
const hasError = ref(false);
|
||||||
|
let requestToken = 0;
|
||||||
|
let activeRequestController = null;
|
||||||
|
let activeRequestFingerprint = null;
|
||||||
|
|
||||||
|
const hasRecords = computed(() => records.value.length > 0);
|
||||||
|
const hasMore = computed(() => {
|
||||||
|
return records.value.length < (meta.value.total_count || 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
const isCurrentRequest = token =>
|
||||||
|
token === requestToken && !!activeRequest.value;
|
||||||
|
|
||||||
|
const requestFingerprint = request =>
|
||||||
|
JSON.stringify({
|
||||||
|
metric: request.metric,
|
||||||
|
bucketTimestamp: request.bucketTimestamp,
|
||||||
|
from: request.from,
|
||||||
|
to: request.to,
|
||||||
|
type: request.type,
|
||||||
|
id: request.id,
|
||||||
|
groupBy: request.groupBy,
|
||||||
|
businessHours: request.businessHours,
|
||||||
|
});
|
||||||
|
|
||||||
|
const abortActiveRequest = () => {
|
||||||
|
if (!activeRequestController) return;
|
||||||
|
|
||||||
|
activeRequestController.abort();
|
||||||
|
activeRequestController = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const isAbortError = error =>
|
||||||
|
error?.name === 'AbortError' ||
|
||||||
|
error?.name === 'CanceledError' ||
|
||||||
|
error?.code === 'ERR_CANCELED';
|
||||||
|
|
||||||
|
const fetchPage = async (page, token = requestToken) => {
|
||||||
|
if (!activeRequest.value) return;
|
||||||
|
|
||||||
|
const request = activeRequest.value;
|
||||||
|
const controller = new AbortController();
|
||||||
|
const loadingState = page === 1 ? isFetching : isFetchingMore;
|
||||||
|
activeRequestController = controller;
|
||||||
|
loadingState.value = true;
|
||||||
|
hasError.value = false;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await ReportsAPI.getDrilldown({
|
||||||
|
...request,
|
||||||
|
page,
|
||||||
|
signal: controller.signal,
|
||||||
|
});
|
||||||
|
if (!isCurrentRequest(token)) return;
|
||||||
|
|
||||||
|
meta.value = response.data.meta || {};
|
||||||
|
records.value =
|
||||||
|
page === 1
|
||||||
|
? response.data.payload || []
|
||||||
|
: [...records.value, ...(response.data.payload || [])];
|
||||||
|
} catch (error) {
|
||||||
|
if (!isCurrentRequest(token) || isAbortError(error)) return;
|
||||||
|
|
||||||
|
hasError.value = true;
|
||||||
|
} finally {
|
||||||
|
if (activeRequestController === controller) {
|
||||||
|
activeRequestController = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isCurrentRequest(token)) {
|
||||||
|
loadingState.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const open = async request => {
|
||||||
|
const fingerprint = requestFingerprint(request);
|
||||||
|
if (activeRequestFingerprint === fingerprint) return;
|
||||||
|
|
||||||
|
abortActiveRequest();
|
||||||
|
requestToken += 1;
|
||||||
|
activeRequestFingerprint = fingerprint;
|
||||||
|
activeRequest.value = request;
|
||||||
|
records.value = [];
|
||||||
|
meta.value = {};
|
||||||
|
hasError.value = false;
|
||||||
|
isFetchingMore.value = false;
|
||||||
|
await fetchPage(1, requestToken);
|
||||||
|
};
|
||||||
|
|
||||||
|
const close = () => {
|
||||||
|
abortActiveRequest();
|
||||||
|
requestToken += 1;
|
||||||
|
activeRequestFingerprint = null;
|
||||||
|
activeRequest.value = null;
|
||||||
|
records.value = [];
|
||||||
|
meta.value = {};
|
||||||
|
hasError.value = false;
|
||||||
|
isFetching.value = false;
|
||||||
|
isFetchingMore.value = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadMore = () => {
|
||||||
|
if (
|
||||||
|
!activeRequest.value ||
|
||||||
|
!hasMore.value ||
|
||||||
|
isFetching.value ||
|
||||||
|
isFetchingMore.value
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchPage((meta.value.current_page || 1) + 1, requestToken);
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
activeRequest,
|
||||||
|
records,
|
||||||
|
meta,
|
||||||
|
isFetching,
|
||||||
|
isFetchingMore,
|
||||||
|
hasError,
|
||||||
|
hasRecords,
|
||||||
|
hasMore,
|
||||||
|
open,
|
||||||
|
close,
|
||||||
|
loadMore,
|
||||||
|
};
|
||||||
|
}
|
||||||
+179
@@ -0,0 +1,179 @@
|
|||||||
|
import { shallowMount } from '@vue/test-utils';
|
||||||
|
import { useAlert } from 'dashboard/composables';
|
||||||
|
import ReportContainer from '../ReportContainer.vue';
|
||||||
|
|
||||||
|
vi.mock('dashboard/composables', () => ({
|
||||||
|
useAlert: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('dashboard/composables/useReportMetrics', () => ({
|
||||||
|
useReportMetrics: () => ({
|
||||||
|
calculateTrend: () => 0,
|
||||||
|
isAverageMetricType: key =>
|
||||||
|
['avg_first_response_time', 'avg_resolution_time', 'reply_time'].includes(
|
||||||
|
key
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe('ReportContainer.vue', () => {
|
||||||
|
const mountComponent = ({
|
||||||
|
dataPoint = { value: 2, timestamp: 1621103400 },
|
||||||
|
data,
|
||||||
|
reportKey = 'conversations_count',
|
||||||
|
role = 'administrator',
|
||||||
|
} = {}) =>
|
||||||
|
shallowMount(ReportContainer, {
|
||||||
|
props: {
|
||||||
|
from: 1621103400,
|
||||||
|
to: 1621621800,
|
||||||
|
groupBy: { period: 'day' },
|
||||||
|
reportType: 'inbox',
|
||||||
|
selectedItemId: 1,
|
||||||
|
businessHours: true,
|
||||||
|
reportKeys: {
|
||||||
|
CONVERSATIONS: reportKey,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
global: {
|
||||||
|
mocks: {
|
||||||
|
$t: key => key,
|
||||||
|
$store: {
|
||||||
|
getters: {
|
||||||
|
getAccountReports: {
|
||||||
|
isFetching: {
|
||||||
|
[reportKey]: false,
|
||||||
|
},
|
||||||
|
data: {
|
||||||
|
[reportKey]: data || [dataPoint],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
getCurrentRole: role,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
stubs: {
|
||||||
|
ChartStats: true,
|
||||||
|
ReportDrilldownDrawer: {
|
||||||
|
name: 'ReportDrilldownDrawer',
|
||||||
|
props: [
|
||||||
|
'open',
|
||||||
|
'metric',
|
||||||
|
'metricName',
|
||||||
|
'bucketLabel',
|
||||||
|
'bucketTimestamp',
|
||||||
|
'bucketValue',
|
||||||
|
'isAverageMetric',
|
||||||
|
'from',
|
||||||
|
'to',
|
||||||
|
'type',
|
||||||
|
'id',
|
||||||
|
'groupBy',
|
||||||
|
'businessHours',
|
||||||
|
'canPrev',
|
||||||
|
'canNext',
|
||||||
|
],
|
||||||
|
emits: ['navigate', 'close'],
|
||||||
|
template: '<div />',
|
||||||
|
},
|
||||||
|
BarChart: {
|
||||||
|
name: 'BarChart',
|
||||||
|
props: ['collection', 'chartOptions', 'clickable'],
|
||||||
|
emits: ['elementClick'],
|
||||||
|
template:
|
||||||
|
'<button data-test-id="bar-chart" @click="$emit(\'elementClick\', { dataIndex: 0, label: \'20-May\', value: 2 })" />',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('opens a drilldown request with report context when a non-zero bar is clicked', async () => {
|
||||||
|
const wrapper = mountComponent();
|
||||||
|
|
||||||
|
await wrapper.find('[data-test-id="bar-chart"]').trigger('click');
|
||||||
|
|
||||||
|
const drawer = wrapper.findComponent({ name: 'ReportDrilldownDrawer' });
|
||||||
|
expect(drawer.props('open')).toBe(true);
|
||||||
|
expect(drawer.props()).toMatchObject({
|
||||||
|
metric: 'conversations_count',
|
||||||
|
metricName: 'REPORT.METRICS.CONVERSATIONS.NAME',
|
||||||
|
bucketLabel: '15-May',
|
||||||
|
bucketTimestamp: 1621103400,
|
||||||
|
from: 1621103400,
|
||||||
|
to: 1621621800,
|
||||||
|
type: 'inbox',
|
||||||
|
id: 1,
|
||||||
|
groupBy: 'day',
|
||||||
|
businessHours: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows an alert and does not open drilldown for non-admin users', async () => {
|
||||||
|
const wrapper = mountComponent({ role: 'agent' });
|
||||||
|
|
||||||
|
await wrapper.find('[data-test-id="bar-chart"]').trigger('click');
|
||||||
|
|
||||||
|
expect(useAlert).toHaveBeenCalledWith('REPORT.DRILLDOWN.ADMIN_ONLY');
|
||||||
|
expect(
|
||||||
|
wrapper.findComponent({ name: 'ReportDrilldownDrawer' }).props('open')
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not open drilldown for zero-value count bars', async () => {
|
||||||
|
const wrapper = mountComponent({
|
||||||
|
dataPoint: { value: 0, timestamp: 1621103400 },
|
||||||
|
});
|
||||||
|
|
||||||
|
await wrapper.find('[data-test-id="bar-chart"]').trigger('click');
|
||||||
|
|
||||||
|
expect(
|
||||||
|
wrapper.findComponent({ name: 'ReportDrilldownDrawer' }).props('open')
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('opens average metric drilldown when the bucket has contributing records', async () => {
|
||||||
|
const wrapper = mountComponent({
|
||||||
|
reportKey: 'avg_first_response_time',
|
||||||
|
dataPoint: { value: 90, count: 2, timestamp: 1621103400 },
|
||||||
|
});
|
||||||
|
|
||||||
|
await wrapper.find('[data-test-id="bar-chart"]').trigger('click');
|
||||||
|
|
||||||
|
const drawer = wrapper.findComponent({ name: 'ReportDrilldownDrawer' });
|
||||||
|
expect(drawer.props('open')).toBe(true);
|
||||||
|
expect(drawer.props()).toMatchObject({
|
||||||
|
metric: 'avg_first_response_time',
|
||||||
|
bucketTimestamp: 1621103400,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('navigates to adjacent drillable buckets within the report range', async () => {
|
||||||
|
const wrapper = mountComponent({
|
||||||
|
data: [
|
||||||
|
{ value: 2, timestamp: 1621103400 },
|
||||||
|
{ value: 0, timestamp: 1621189800 },
|
||||||
|
{ value: 5, timestamp: 1621276200 },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
await wrapper.find('[data-test-id="bar-chart"]').trigger('click');
|
||||||
|
|
||||||
|
const drawer = wrapper.findComponent({ name: 'ReportDrilldownDrawer' });
|
||||||
|
// Opened on the first bucket: no previous, but a later drillable bucket exists.
|
||||||
|
expect(drawer.props('bucketTimestamp')).toBe(1621103400);
|
||||||
|
expect(drawer.props('canPrev')).toBe(false);
|
||||||
|
expect(drawer.props('canNext')).toBe(true);
|
||||||
|
|
||||||
|
// Skips the zero-value middle bucket and lands on the last drillable one.
|
||||||
|
drawer.vm.$emit('navigate', 1);
|
||||||
|
await wrapper.vm.$nextTick();
|
||||||
|
|
||||||
|
expect(drawer.props('bucketTimestamp')).toBe(1621276200);
|
||||||
|
expect(drawer.props('canPrev')).toBe(true);
|
||||||
|
expect(drawer.props('canNext')).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -157,11 +157,13 @@ export const actions = {
|
|||||||
// Update positions in the store immediately so subsequent mutations preserve correct positions
|
// Update positions in the store immediately so subsequent mutations preserve correct positions
|
||||||
commit(types.SET_ARTICLE_POSITIONS, reorderedGroup);
|
commit(types.SET_ARTICLE_POSITIONS, reorderedGroup);
|
||||||
try {
|
try {
|
||||||
await articlesAPI.reorderArticles({
|
const { data } = await articlesAPI.reorderArticles({
|
||||||
portalSlug,
|
portalSlug,
|
||||||
reorderedGroup,
|
reorderedGroup,
|
||||||
categorySlug,
|
categorySlug,
|
||||||
});
|
});
|
||||||
|
// Adopt the backend's re-spaced positions so the next reorder isn't computed from stale local values.
|
||||||
|
if (data?.positions) commit(types.SET_ARTICLE_POSITIONS, data.positions);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
commit(types.SET_ARTICLE_POSITIONS, oldPositions);
|
commit(types.SET_ARTICLE_POSITIONS, oldPositions);
|
||||||
throw error;
|
throw error;
|
||||||
|
|||||||
@@ -314,6 +314,25 @@ describe('#actions', () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('adopts the backend re-spaced positions when the response returns them', async () => {
|
||||||
|
const serverPositions = { 1: 10, 2: 30, 3: 20 };
|
||||||
|
axios.post.mockResolvedValue({ data: { positions: serverPositions } });
|
||||||
|
|
||||||
|
await actions.reorder(
|
||||||
|
{ commit, state },
|
||||||
|
{
|
||||||
|
portalSlug: 'test-portal',
|
||||||
|
categorySlug: 'test-category',
|
||||||
|
reorderedGroup: { 3: 25 },
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(commit).toHaveBeenCalledWith(
|
||||||
|
types.default.SET_ARTICLE_POSITIONS,
|
||||||
|
serverPositions
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
it('rolls back positions and throws when API call fails', async () => {
|
it('rolls back positions and throws when API call fails', async () => {
|
||||||
axios.post.mockRejectedValue({ message: 'Network error' });
|
axios.post.mockRejectedValue({ message: 'Network error' });
|
||||||
const reorderedGroup = { 1: 1, 2: 2 };
|
const reorderedGroup = { 1: 1, 2: 2 };
|
||||||
|
|||||||
@@ -19,8 +19,14 @@ const props = defineProps({
|
|||||||
type: Object,
|
type: Object,
|
||||||
default: () => ({}),
|
default: () => ({}),
|
||||||
},
|
},
|
||||||
|
clickable: {
|
||||||
|
type: Boolean,
|
||||||
|
default: false,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const emit = defineEmits(['elementClick']);
|
||||||
|
|
||||||
ChartJS.register(Title, Tooltip, BarElement, CategoryScale, LinearScale);
|
ChartJS.register(Title, Tooltip, BarElement, CategoryScale, LinearScale);
|
||||||
|
|
||||||
const fontFamily =
|
const fontFamily =
|
||||||
@@ -67,8 +73,39 @@ const defaultChartOptions = {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleClick = (event, elements, chart) => {
|
||||||
|
props.chartOptions.onClick?.(event, elements, chart);
|
||||||
|
|
||||||
|
if (!props.clickable || !elements.length) return;
|
||||||
|
|
||||||
|
const { datasetIndex, index } = elements[0];
|
||||||
|
const dataset = props.collection.datasets?.[datasetIndex] || {};
|
||||||
|
|
||||||
|
emit('elementClick', {
|
||||||
|
datasetIndex,
|
||||||
|
dataIndex: index,
|
||||||
|
dataset,
|
||||||
|
label: props.collection.labels?.[index],
|
||||||
|
value: dataset.data?.[index],
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleHover = (event, elements, chart) => {
|
||||||
|
props.chartOptions.onHover?.(event, elements, chart);
|
||||||
|
|
||||||
|
if (!event?.native?.target) return;
|
||||||
|
|
||||||
|
event.native.target.style.cursor =
|
||||||
|
props.clickable && elements.length ? 'pointer' : 'default';
|
||||||
|
};
|
||||||
|
|
||||||
const options = computed(() => {
|
const options = computed(() => {
|
||||||
return { ...defaultChartOptions, ...props.chartOptions };
|
return {
|
||||||
|
...defaultChartOptions,
|
||||||
|
...props.chartOptions,
|
||||||
|
onClick: handleClick,
|
||||||
|
onHover: handleHover,
|
||||||
|
};
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import { shallowMount } from '@vue/test-utils';
|
||||||
|
import BarChart from '../charts/BarChart.vue';
|
||||||
|
|
||||||
|
vi.mock('vue-chartjs', () => ({
|
||||||
|
Bar: {
|
||||||
|
name: 'Bar',
|
||||||
|
props: ['data', 'options'],
|
||||||
|
template: '<canvas />',
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe('BarChart.vue', () => {
|
||||||
|
it('emits the clicked chart element when clickable', () => {
|
||||||
|
const wrapper = shallowMount(BarChart, {
|
||||||
|
props: {
|
||||||
|
clickable: true,
|
||||||
|
collection: {
|
||||||
|
labels: ['20-May'],
|
||||||
|
datasets: [{ type: 'bar', data: [3] }],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const options = wrapper.findComponent({ name: 'Bar' }).props('options');
|
||||||
|
options.onClick({}, [{ datasetIndex: 0, index: 0 }], {});
|
||||||
|
|
||||||
|
expect(wrapper.emitted('elementClick')[0][0]).toEqual({
|
||||||
|
datasetIndex: 0,
|
||||||
|
dataIndex: 0,
|
||||||
|
dataset: { type: 'bar', data: [3] },
|
||||||
|
label: '20-May',
|
||||||
|
value: 3,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not emit when chart is not clickable', () => {
|
||||||
|
const wrapper = shallowMount(BarChart, {
|
||||||
|
props: {
|
||||||
|
clickable: false,
|
||||||
|
collection: {
|
||||||
|
labels: ['20-May'],
|
||||||
|
datasets: [{ type: 'bar', data: [3] }],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const options = wrapper.findComponent({ name: 'Bar' }).props('options');
|
||||||
|
options.onClick({}, [{ datasetIndex: 0, index: 0 }], {});
|
||||||
|
|
||||||
|
expect(wrapper.emitted('elementClick')).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -16,12 +16,12 @@ class ReportingEventListener < BaseListener
|
|||||||
user_id: conversation.assignee_id,
|
user_id: conversation.assignee_id,
|
||||||
conversation_id: conversation.id,
|
conversation_id: conversation.id,
|
||||||
event_start_time: conversation.created_at,
|
event_start_time: conversation.created_at,
|
||||||
event_end_time: event_end_time,
|
event_end_time: event_end_time
|
||||||
**actor_attributes(actor_from_event(event))
|
|
||||||
)
|
)
|
||||||
|
|
||||||
create_bot_resolved_event(conversation, reporting_event)
|
create_bot_resolved_event(conversation, reporting_event)
|
||||||
persist_reporting_event(reporting_event)
|
reporting_event.save!
|
||||||
|
safe_rollup(reporting_event)
|
||||||
end
|
end
|
||||||
|
|
||||||
def first_reply_created(event)
|
def first_reply_created(event)
|
||||||
@@ -39,11 +39,11 @@ class ReportingEventListener < BaseListener
|
|||||||
user_id: message.sender_id,
|
user_id: message.sender_id,
|
||||||
conversation_id: conversation.id,
|
conversation_id: conversation.id,
|
||||||
event_start_time: last_non_human_activity(conversation),
|
event_start_time: last_non_human_activity(conversation),
|
||||||
event_end_time: message.created_at,
|
event_end_time: message.created_at
|
||||||
**actor_attributes(actor_from_event(event) || message.sender)
|
|
||||||
)
|
)
|
||||||
|
|
||||||
persist_reporting_event(reporting_event)
|
reporting_event.save!
|
||||||
|
safe_rollup(reporting_event)
|
||||||
end
|
end
|
||||||
|
|
||||||
def reply_created(event)
|
def reply_created(event)
|
||||||
@@ -65,10 +65,10 @@ class ReportingEventListener < BaseListener
|
|||||||
user_id: conversation.assignee_id,
|
user_id: conversation.assignee_id,
|
||||||
conversation_id: conversation.id,
|
conversation_id: conversation.id,
|
||||||
event_start_time: waiting_since,
|
event_start_time: waiting_since,
|
||||||
event_end_time: message.created_at,
|
event_end_time: message.created_at
|
||||||
**actor_attributes(actor_from_event(event) || message.sender)
|
|
||||||
)
|
)
|
||||||
persist_reporting_event(reporting_event)
|
reporting_event.save!
|
||||||
|
safe_rollup(reporting_event)
|
||||||
end
|
end
|
||||||
|
|
||||||
def conversation_bot_handoff(event)
|
def conversation_bot_handoff(event)
|
||||||
@@ -92,10 +92,10 @@ class ReportingEventListener < BaseListener
|
|||||||
user_id: conversation.assignee_id,
|
user_id: conversation.assignee_id,
|
||||||
conversation_id: conversation.id,
|
conversation_id: conversation.id,
|
||||||
event_start_time: conversation.created_at,
|
event_start_time: conversation.created_at,
|
||||||
event_end_time: event_end_time,
|
event_end_time: event_end_time
|
||||||
**actor_attributes(actor_from_event(event))
|
|
||||||
)
|
)
|
||||||
persist_reporting_event(reporting_event)
|
reporting_event.save!
|
||||||
|
safe_rollup(reporting_event)
|
||||||
end
|
end
|
||||||
|
|
||||||
def conversation_captain_inference_resolved(event)
|
def conversation_captain_inference_resolved(event)
|
||||||
@@ -116,53 +116,43 @@ class ReportingEventListener < BaseListener
|
|||||||
name: 'conversation_resolved'
|
name: 'conversation_resolved'
|
||||||
).where('event_end_time <= ?', event_end_time).order(event_end_time: :desc).first
|
).where('event_end_time <= ?', event_end_time).order(event_end_time: :desc).first
|
||||||
|
|
||||||
create_conversation_opened_event(
|
# For first-time openings, value is 0
|
||||||
conversation,
|
# For reopenings, calculate time since resolution
|
||||||
conversation_opened_event_attributes(conversation, last_resolved_event, event_end_time),
|
if last_resolved_event
|
||||||
actor_from_event(event)
|
time_since_resolved = event_end_time.to_i - last_resolved_event.event_end_time.to_i
|
||||||
)
|
business_hours_value = business_hours(conversation.inbox, last_resolved_event.event_end_time, event_end_time)
|
||||||
|
start_time = last_resolved_event.event_end_time
|
||||||
|
else
|
||||||
|
time_since_resolved = 0
|
||||||
|
business_hours_value = 0
|
||||||
|
start_time = conversation.created_at
|
||||||
|
end
|
||||||
|
|
||||||
|
create_conversation_opened_event(conversation, time_since_resolved, business_hours_value, start_time, event_end_time)
|
||||||
end
|
end
|
||||||
|
|
||||||
private
|
private
|
||||||
|
|
||||||
def conversation_opened_event_attributes(conversation, last_resolved_event, event_end_time)
|
def create_conversation_opened_event(conversation, time_since_resolved, business_hours_value, start_time, event_end_time)
|
||||||
return first_conversation_opened_event_attributes(conversation, event_end_time) if last_resolved_event.blank?
|
|
||||||
|
|
||||||
{
|
|
||||||
value: event_end_time.to_i - last_resolved_event.event_end_time.to_i,
|
|
||||||
value_in_business_hours: business_hours(conversation.inbox, last_resolved_event.event_end_time, event_end_time),
|
|
||||||
event_start_time: last_resolved_event.event_end_time,
|
|
||||||
event_end_time: event_end_time
|
|
||||||
}
|
|
||||||
end
|
|
||||||
|
|
||||||
def first_conversation_opened_event_attributes(conversation, event_end_time)
|
|
||||||
{
|
|
||||||
value: 0,
|
|
||||||
value_in_business_hours: 0,
|
|
||||||
event_start_time: conversation.created_at,
|
|
||||||
event_end_time: event_end_time
|
|
||||||
}
|
|
||||||
end
|
|
||||||
|
|
||||||
def create_conversation_opened_event(conversation, event_attributes, actor)
|
|
||||||
reporting_event = ReportingEvent.new(
|
reporting_event = ReportingEvent.new(
|
||||||
name: 'conversation_opened',
|
name: 'conversation_opened',
|
||||||
|
value: time_since_resolved,
|
||||||
|
value_in_business_hours: business_hours_value,
|
||||||
account_id: conversation.account_id,
|
account_id: conversation.account_id,
|
||||||
inbox_id: conversation.inbox_id,
|
inbox_id: conversation.inbox_id,
|
||||||
user_id: conversation.assignee_id,
|
user_id: conversation.assignee_id,
|
||||||
conversation_id: conversation.id,
|
conversation_id: conversation.id,
|
||||||
**event_attributes,
|
event_start_time: start_time,
|
||||||
**actor_attributes(actor)
|
event_end_time: event_end_time
|
||||||
)
|
)
|
||||||
persist_reporting_event(reporting_event, rollup: false)
|
reporting_event.save!
|
||||||
end
|
end
|
||||||
|
|
||||||
def create_captain_inference_event(event, event_name)
|
def create_captain_inference_event(event, event_name)
|
||||||
conversation = extract_conversation_and_account(event)[0]
|
conversation = extract_conversation_and_account(event)[0]
|
||||||
time_to_event = event.timestamp.to_i - conversation.created_at.to_i
|
time_to_event = event.timestamp.to_i - conversation.created_at.to_i
|
||||||
|
|
||||||
reporting_event = ReportingEvent.new(
|
ReportingEvent.create!(
|
||||||
name: event_name,
|
name: event_name,
|
||||||
value: time_to_event,
|
value: time_to_event,
|
||||||
account_id: conversation.account_id,
|
account_id: conversation.account_id,
|
||||||
@@ -170,10 +160,8 @@ class ReportingEventListener < BaseListener
|
|||||||
user_id: conversation.assignee_id,
|
user_id: conversation.assignee_id,
|
||||||
conversation_id: conversation.id,
|
conversation_id: conversation.id,
|
||||||
event_start_time: conversation.created_at,
|
event_start_time: conversation.created_at,
|
||||||
event_end_time: event.timestamp,
|
event_end_time: event.timestamp
|
||||||
**actor_attributes(actor_from_event(event))
|
|
||||||
)
|
)
|
||||||
persist_reporting_event(reporting_event, rollup: false)
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def create_bot_resolved_event(conversation, reporting_event)
|
def create_bot_resolved_event(conversation, reporting_event)
|
||||||
@@ -183,29 +171,8 @@ class ReportingEventListener < BaseListener
|
|||||||
|
|
||||||
bot_resolved_event = reporting_event.dup
|
bot_resolved_event = reporting_event.dup
|
||||||
bot_resolved_event.name = 'conversation_bot_resolved'
|
bot_resolved_event.name = 'conversation_bot_resolved'
|
||||||
persist_reporting_event(bot_resolved_event)
|
bot_resolved_event.save!
|
||||||
end
|
safe_rollup(bot_resolved_event)
|
||||||
|
|
||||||
def persist_reporting_event(reporting_event, rollup: true)
|
|
||||||
reporting_event.save!
|
|
||||||
safe_rollup(reporting_event) if rollup
|
|
||||||
update_captain_conversation_fact(reporting_event)
|
|
||||||
end
|
|
||||||
|
|
||||||
def update_captain_conversation_fact(reporting_event)
|
|
||||||
return unless defined?(Captain::ConversationFactUpdater)
|
|
||||||
|
|
||||||
Captain::ConversationFactUpdater.record_reporting_event(reporting_event)
|
|
||||||
end
|
|
||||||
|
|
||||||
def actor_from_event(event)
|
|
||||||
event.data[:performed_by]
|
|
||||||
end
|
|
||||||
|
|
||||||
def actor_attributes(actor)
|
|
||||||
return {} if actor.blank? || actor.id.blank?
|
|
||||||
|
|
||||||
{ actor_type: actor.class.name, actor_id: actor.id }
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def safe_rollup(reporting_event)
|
def safe_rollup(reporting_event)
|
||||||
|
|||||||
+27
-1
@@ -137,15 +137,41 @@ class Article < ApplicationRecord
|
|||||||
end
|
end
|
||||||
|
|
||||||
def self.update_positions(portal:, positions_hash:)
|
def self.update_positions(portal:, positions_hash:)
|
||||||
return if positions_hash.blank?
|
return {} if positions_hash.blank?
|
||||||
|
|
||||||
|
moved_ids = positions_hash.keys.map(&:to_i)
|
||||||
|
|
||||||
transaction do
|
transaction do
|
||||||
positions_hash.each do |article_id, new_position|
|
positions_hash.each do |article_id, new_position|
|
||||||
portal.articles.find(article_id).update!(position: new_position)
|
portal.articles.find(article_id).update!(position: new_position)
|
||||||
end
|
end
|
||||||
|
# Re-space touched categories to clean gaps and return the final positions
|
||||||
|
rebalance_positions(portal, moved_ids)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def self.rebalance_positions(portal, moved_ids)
|
||||||
|
category_ids = portal.articles.where(id: moved_ids).distinct.pluck(:category_id).compact
|
||||||
|
category_ids.each_with_object({}) do |category_id, positions|
|
||||||
|
resequence_category(portal, category_id, moved_ids, positions)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.resequence_category(portal, category_id, moved_ids, positions)
|
||||||
|
ordered = portal.articles.where(category_id: category_id)
|
||||||
|
.sort_by { |article| [article.position || 0, moved_ids.include?(article.id) ? 1 : 0, article.id] }
|
||||||
|
return if ordered.length < 2 # a lone article can't collide, leave it as-is
|
||||||
|
|
||||||
|
ordered.each_with_index do |article, index|
|
||||||
|
new_position = (index + 1) * 10
|
||||||
|
positions[article.id] = new_position
|
||||||
|
next if article.position == new_position
|
||||||
|
|
||||||
|
article.update_column(:position, new_position) # rubocop:disable Rails/SkipsModelValidations
|
||||||
|
end
|
||||||
|
end
|
||||||
|
private_class_method :rebalance_positions, :resequence_category
|
||||||
|
|
||||||
private
|
private
|
||||||
|
|
||||||
def category_id_changed_action
|
def category_id_changed_action
|
||||||
|
|||||||
@@ -343,7 +343,7 @@ class Conversation < ApplicationRecord
|
|||||||
def dispatcher_dispatch(event_name, changed_attributes = nil)
|
def dispatcher_dispatch(event_name, changed_attributes = nil)
|
||||||
Rails.configuration.dispatcher.dispatch(event_name, Time.zone.now, conversation: self, notifiable_assignee_change: notifiable_assignee_change?,
|
Rails.configuration.dispatcher.dispatch(event_name, Time.zone.now, conversation: self, notifiable_assignee_change: notifiable_assignee_change?,
|
||||||
changed_attributes: changed_attributes,
|
changed_attributes: changed_attributes,
|
||||||
performed_by: Current.executed_by || Current.user)
|
performed_by: Current.executed_by)
|
||||||
end
|
end
|
||||||
|
|
||||||
def set_unread_count_deletion_data
|
def set_unread_count_deletion_data
|
||||||
|
|||||||
@@ -45,5 +45,3 @@ class CsatSurveyResponse < ApplicationRecord
|
|||||||
# filter by rating value
|
# filter by rating value
|
||||||
scope :filter_by_rating, ->(rating) { where(rating: rating) if rating.present? }
|
scope :filter_by_rating, ->(rating) { where(rating: rating) if rating.present? }
|
||||||
end
|
end
|
||||||
|
|
||||||
CsatSurveyResponse.include_mod_with('CsatSurveyResponse')
|
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ class EmailTemplate < ApplicationRecord
|
|||||||
enum :template_type, { layout: 0, content: 1 }
|
enum :template_type, { layout: 0, content: 1 }
|
||||||
belongs_to :account, optional: true
|
belongs_to :account, optional: true
|
||||||
|
|
||||||
validates :name, uniqueness: { scope: :account }
|
validates :name, uniqueness: { scope: [:account, :template_type, :locale] }
|
||||||
|
|
||||||
def self.resolver(options = {})
|
def self.resolver(options = {})
|
||||||
::EmailTemplates::DbResolverService.using self, options
|
::EmailTemplates::DbResolverService.using self, options
|
||||||
|
|||||||
@@ -34,7 +34,7 @@
|
|||||||
# index_messages_on_conversation_id (conversation_id)
|
# index_messages_on_conversation_id (conversation_id)
|
||||||
# index_messages_on_created_at (created_at)
|
# index_messages_on_created_at (created_at)
|
||||||
# index_messages_on_inbox_id (inbox_id)
|
# index_messages_on_inbox_id (inbox_id)
|
||||||
# index_messages_on_sender_and_created (sender_type,sender_id,created_at)
|
# index_messages_on_sender_type_and_sender_id (sender_type,sender_id)
|
||||||
# index_messages_on_source_id (source_id)
|
# index_messages_on_source_id (source_id)
|
||||||
#
|
#
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,6 @@
|
|||||||
# Table name: reporting_events
|
# Table name: reporting_events
|
||||||
#
|
#
|
||||||
# id :bigint not null, primary key
|
# id :bigint not null, primary key
|
||||||
# actor_type :string
|
|
||||||
# event_end_time :datetime
|
# event_end_time :datetime
|
||||||
# event_start_time :datetime
|
# event_start_time :datetime
|
||||||
# name :string
|
# name :string
|
||||||
@@ -12,22 +11,20 @@
|
|||||||
# created_at :datetime not null
|
# created_at :datetime not null
|
||||||
# updated_at :datetime not null
|
# updated_at :datetime not null
|
||||||
# account_id :integer
|
# account_id :integer
|
||||||
# actor_id :bigint
|
|
||||||
# conversation_id :integer
|
# conversation_id :integer
|
||||||
# inbox_id :integer
|
# inbox_id :integer
|
||||||
# user_id :integer
|
# user_id :integer
|
||||||
#
|
#
|
||||||
# Indexes
|
# Indexes
|
||||||
#
|
#
|
||||||
# idx_reporting_events_on_account_actor_name_created (account_id,actor_type,actor_id,name,created_at)
|
# index_reporting_events_for_response_distribution (account_id,name,inbox_id,created_at)
|
||||||
# index_reporting_events_for_response_distribution (account_id,name,inbox_id,created_at)
|
# index_reporting_events_on_account_id (account_id)
|
||||||
# index_reporting_events_on_account_id (account_id)
|
# index_reporting_events_on_conversation_id (conversation_id)
|
||||||
# index_reporting_events_on_conversation_id (conversation_id)
|
# index_reporting_events_on_created_at (created_at)
|
||||||
# index_reporting_events_on_created_at (created_at)
|
# index_reporting_events_on_inbox_id (inbox_id)
|
||||||
# index_reporting_events_on_inbox_id (inbox_id)
|
# index_reporting_events_on_name (name)
|
||||||
# index_reporting_events_on_name (name)
|
# index_reporting_events_on_user_id (user_id)
|
||||||
# index_reporting_events_on_user_id (user_id)
|
# reporting_events__account_id__name__created_at (account_id,name,created_at)
|
||||||
# reporting_events__account_id__name__created_at (account_id,name,created_at)
|
|
||||||
#
|
#
|
||||||
|
|
||||||
class ReportingEvent < ApplicationRecord
|
class ReportingEvent < ApplicationRecord
|
||||||
@@ -39,7 +36,6 @@ class ReportingEvent < ApplicationRecord
|
|||||||
belongs_to :user, optional: true
|
belongs_to :user, optional: true
|
||||||
belongs_to :inbox, optional: true
|
belongs_to :inbox, optional: true
|
||||||
belongs_to :conversation, optional: true
|
belongs_to :conversation, optional: true
|
||||||
belongs_to :actor, polymorphic: true, optional: true
|
|
||||||
|
|
||||||
# Scopes for filtering
|
# Scopes for filtering
|
||||||
scope :filter_by_date_range, lambda { |range|
|
scope :filter_by_date_range, lambda { |range|
|
||||||
|
|||||||
@@ -35,6 +35,8 @@ class ::EmailTemplates::DbResolverService < ActionView::Resolver
|
|||||||
def find_templates(name, prefix, partial, *_args)
|
def find_templates(name, prefix, partial, *_args)
|
||||||
@template_name = name
|
@template_name = name
|
||||||
@template_type = prefix.include?('layout') ? 'layout' : 'content'
|
@template_type = prefix.include?('layout') ? 'layout' : 'content'
|
||||||
|
@_prefix = prefix
|
||||||
|
@_details = _args.first || {}
|
||||||
@db_template = find_db_template
|
@db_template = find_db_template
|
||||||
|
|
||||||
return [] if @db_template.blank?
|
return [] if @db_template.blank?
|
||||||
@@ -60,11 +62,23 @@ class ::EmailTemplates::DbResolverService < ActionView::Resolver
|
|||||||
def find_account_template
|
def find_account_template
|
||||||
return unless Current.account
|
return unless Current.account
|
||||||
|
|
||||||
@@model.find_by(name: @template_name, template_type: @template_type, account: Current.account)
|
find_template_for(Current.account)
|
||||||
end
|
end
|
||||||
|
|
||||||
def find_installation_template
|
def find_installation_template
|
||||||
@@model.find_by(name: @template_name, template_type: @template_type, account: nil)
|
find_template_for(nil)
|
||||||
|
end
|
||||||
|
|
||||||
|
def find_template_for(account)
|
||||||
|
@@model.find_by(name: db_template_name, template_type: @template_type, locale: locale_from_details, account: account) ||
|
||||||
|
@@model.find_by(name: @template_name, template_type: @template_type, locale: locale_from_details, account: account)
|
||||||
|
end
|
||||||
|
|
||||||
|
def locale_from_details
|
||||||
|
return :en if @_details.blank?
|
||||||
|
|
||||||
|
locale = Array(@_details[:locale]).first
|
||||||
|
EmailTemplate.locales.key?(locale.to_s) ? locale : :en
|
||||||
end
|
end
|
||||||
|
|
||||||
# Build path with eventual prefix
|
# Build path with eventual prefix
|
||||||
@@ -72,6 +86,12 @@ class ::EmailTemplates::DbResolverService < ActionView::Resolver
|
|||||||
prefix.present? ? "#{prefix}/#{@template_name}" : @template_name
|
prefix.present? ? "#{prefix}/#{@template_name}" : @template_name
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def db_template_name
|
||||||
|
return @template_name if @template_type == 'layout'
|
||||||
|
|
||||||
|
build_path(@_prefix)
|
||||||
|
end
|
||||||
|
|
||||||
# returns a path depending if its a partial or template
|
# returns a path depending if its a partial or template
|
||||||
# params path: path/to/file.ext partial: true/false
|
# params path: path/to/file.ext partial: true/false
|
||||||
# the function appends _to make the file name _file.ext if partial: true
|
# the function appends _to make the file name _file.ext if partial: true
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
module Reports::DrilldownTimestampValidator
|
||||||
|
extend TimezoneHelper
|
||||||
|
|
||||||
|
TIMESTAMP_PARAMS = %i[bucket_timestamp since until].freeze
|
||||||
|
DEFAULT_GROUP_BY = V2::Reports::DrilldownBuilder::DEFAULT_GROUP_BY
|
||||||
|
SUPPORTED_GROUP_BY = V2::Reports::DrilldownBuilder::SUPPORTED_GROUP_BY
|
||||||
|
|
||||||
|
module_function
|
||||||
|
|
||||||
|
def valid?(params)
|
||||||
|
timestamps = TIMESTAMP_PARAMS.index_with { |param| integer_param(params[param]) }
|
||||||
|
return false if timestamps.values.any?(&:nil?)
|
||||||
|
return false unless timestamps[:since] < timestamps[:until]
|
||||||
|
|
||||||
|
bucket_overlaps_requested_range?(params, timestamps)
|
||||||
|
end
|
||||||
|
|
||||||
|
def integer_param(value)
|
||||||
|
return unless value.to_s.match?(/\A\d+\z/)
|
||||||
|
|
||||||
|
value.to_i
|
||||||
|
end
|
||||||
|
|
||||||
|
def bucket_overlaps_requested_range?(params, timestamps)
|
||||||
|
bucket_start = Time.zone.at(timestamps[:bucket_timestamp]).in_time_zone(timezone(params))
|
||||||
|
bucket_end = bucket_end_for(bucket_start, group_by(params))
|
||||||
|
requested_start = Time.zone.at(timestamps[:since])
|
||||||
|
requested_end = Time.zone.at(timestamps[:until])
|
||||||
|
|
||||||
|
bucket_start < requested_end && bucket_end > requested_start
|
||||||
|
rescue ArgumentError, RangeError
|
||||||
|
false
|
||||||
|
end
|
||||||
|
|
||||||
|
def bucket_end_for(bucket_start, group_by)
|
||||||
|
{
|
||||||
|
'hour' => bucket_start + 1.hour,
|
||||||
|
'day' => bucket_start + 1.day,
|
||||||
|
'week' => bucket_start + 1.week,
|
||||||
|
'month' => bucket_start + 1.month,
|
||||||
|
'year' => bucket_start + 1.year
|
||||||
|
}.fetch(group_by)
|
||||||
|
end
|
||||||
|
|
||||||
|
def group_by(params)
|
||||||
|
group = params[:group_by].to_s
|
||||||
|
SUPPORTED_GROUP_BY.include?(group) ? group : DEFAULT_GROUP_BY
|
||||||
|
end
|
||||||
|
|
||||||
|
def timezone(params)
|
||||||
|
timezone_name_from_offset(params[:timezone_offset])
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -58,5 +58,6 @@ json.last_non_activity_message conversation.messages.where(account_id: conversat
|
|||||||
json.last_activity_at conversation.last_activity_at.to_i
|
json.last_activity_at conversation.last_activity_at.to_i
|
||||||
json.priority conversation.priority
|
json.priority conversation.priority
|
||||||
json.waiting_since conversation.waiting_since.to_i.to_i
|
json.waiting_since conversation.waiting_since.to_i.to_i
|
||||||
json.sla_policy_id conversation.sla_policy_id
|
sla_applicable = !conversation.respond_to?(:sla_applicable?) || conversation.sla_applicable?
|
||||||
|
json.sla_policy_id sla_applicable ? conversation.sla_policy_id : nil
|
||||||
json.partial! 'enterprise/api/v1/conversations/partials/conversation', conversation: conversation if ChatwootApp.enterprise?
|
json.partial! 'enterprise/api/v1/conversations/partials/conversation', conversation: conversation if ChatwootApp.enterprise?
|
||||||
|
|||||||
@@ -14,66 +14,72 @@
|
|||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
<section class="main-content__body">
|
<section class="main-content__body relative">
|
||||||
|
<%= render partial: 'email_layout' if @config == 'custom_branding' && ChatwootApp.enterprise? %>
|
||||||
|
|
||||||
<%= form_with url: super_admin_app_config_url(config: @config) , method: :post do |form| %>
|
<%= form_with url: super_admin_app_config_url(config: @config) , method: :post do |form| %>
|
||||||
<% @allowed_configs.each do |key| %>
|
<% @allowed_configs.each do |key| %>
|
||||||
<div class="flex mb-8">
|
<div class="flex mb-8">
|
||||||
<div class="field-unit__label">
|
<div class="field-unit__label">
|
||||||
<%= form.label "app_config[#{key}]", @installation_configs[key]&.dig('display_title') || key %>
|
<%= form.label "app_config[#{key}]", @installation_configs[key]&.dig('display_title') || key %>
|
||||||
</div>
|
</div>
|
||||||
<div class="-mt-2 field-unit__field ">
|
<div class="-mt-2 field-unit__field ">
|
||||||
<% if @installation_configs[key]&.dig('type') == 'boolean' %>
|
<% if @installation_configs[key]&.dig('type') == 'boolean' %>
|
||||||
<%= form.select "app_config[#{key}]",
|
<%= form.select "app_config[#{key}]",
|
||||||
[["True", true], ["False", false]],
|
[["True", true], ["False", false]],
|
||||||
{ selected: ActiveModel::Type::Boolean.new.cast(@app_config[key]) },
|
{ selected: ActiveModel::Type::Boolean.new.cast(@app_config[key]) },
|
||||||
class: "mt-2 border border-slate-100 p-1 rounded-md"
|
class: "mt-2 border border-slate-100 p-1 rounded-md"
|
||||||
%>
|
|
||||||
<% elsif @installation_configs[key]&.dig('type') == 'code' %>
|
|
||||||
<%= form.text_area "app_config[#{key}]",
|
|
||||||
value: @app_config[key],
|
|
||||||
rows: 12,
|
|
||||||
wrap: 'off',
|
|
||||||
class: "mt-2 border font-mono text-xs border-slate-100 p-1 rounded-md overflow-scroll"
|
|
||||||
%>
|
|
||||||
<% elsif @installation_configs[key]&.dig('type') == 'secret' %>
|
|
||||||
<div class="relative">
|
|
||||||
<%= form.password_field "app_config[#{key}]",
|
|
||||||
id: "app_config_#{key}",
|
|
||||||
value: @app_config[key],
|
|
||||||
class: "mt-2 border border-slate-100 p-1.5 pr-8 rounded-md w-full"
|
|
||||||
%>
|
%>
|
||||||
<button
|
<% elsif @installation_configs[key]&.dig('type') == 'code' %>
|
||||||
type="button"
|
<%= form.text_area "app_config[#{key}]",
|
||||||
class="absolute reset-base !bg-white top-1/2 !outline-0 !text-n-slate-11 -translate-y-1/2 right-2 p-1 hover:!bg-n-slate-5 rounded-sm toggle-password"
|
value: @app_config[key],
|
||||||
data-target="app_config_<%= key %>"
|
rows: 12,
|
||||||
>
|
wrap: 'off',
|
||||||
<svg class="eye-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
|
class: "mt-2 border font-mono text-xs border-slate-100 p-1 rounded-md overflow-scroll"
|
||||||
<path d="M12 5C5.63636 5 2 12 2 12C2 12 5.63636 19 12 19C18.3636 19 22 12 22 12C22 12 18.3636 5 12 5Z"/>
|
%>
|
||||||
<path d="M12 15C13.6569 15 15 13.6569 15 12C15 10.3431 13.6569 9 12 9C10.3431 9 9 10.3431 9 12C9 13.6569 10.3431 15 12 15Z"/>
|
<% elsif @installation_configs[key]&.dig('type') == 'secret' %>
|
||||||
</svg>
|
<div class="relative">
|
||||||
</button>
|
<%= form.password_field "app_config[#{key}]",
|
||||||
</div>
|
id: "app_config_#{key}",
|
||||||
<% elsif @installation_configs[key]&.dig('type') == 'select' && @installation_configs[key]&.dig('options').present? %>
|
value: @app_config[key],
|
||||||
<%= form.select "app_config[#{key}]",
|
class: "mt-2 border border-slate-100 p-1.5 pr-8 rounded-md w-full"
|
||||||
@installation_configs[key]['options'].map { |val, label| [label, val] },
|
%>
|
||||||
{ selected: @app_config[key] },
|
<button
|
||||||
class: "mt-2 border border-slate-100 p-1 rounded-md"
|
type="button"
|
||||||
%>
|
class="absolute reset-base !bg-white top-1/2 !outline-0 !text-n-slate-11 -translate-y-1/2 right-2 p-1 hover:!bg-n-slate-5 rounded-sm toggle-password"
|
||||||
<% else %>
|
data-target="app_config_<%= key %>"
|
||||||
<%= form.text_field "app_config[#{key}]", value: @app_config[key] %>
|
>
|
||||||
<% end %>
|
<svg class="eye-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
|
||||||
<%if @installation_configs[key]&.dig('description').present? %>
|
<path d="M12 5C5.63636 5 2 12 2 12C2 12 5.63636 19 12 19C18.3636 19 22 12 22 12C22 12 18.3636 5 12 5Z"/>
|
||||||
<p class="pt-2 text-xs italic text-slate-400">
|
<path d="M12 15C13.6569 15 15 13.6569 15 12C15 10.3431 13.6569 9 12 9C10.3431 9 9 10.3431 9 12C9 13.6569 10.3431 15 12 15Z"/>
|
||||||
<%= @installation_configs[key]&.dig('description') %>
|
</svg>
|
||||||
</p>
|
</button>
|
||||||
<% end %>
|
</div>
|
||||||
|
<% elsif @installation_configs[key]&.dig('type') == 'select' && @installation_configs[key]&.dig('options').present? %>
|
||||||
|
<%= form.select "app_config[#{key}]",
|
||||||
|
@installation_configs[key]['options'].map { |val, label| [label, val] },
|
||||||
|
{ selected: @app_config[key] },
|
||||||
|
class: "mt-2 border border-slate-100 p-1 rounded-md"
|
||||||
|
%>
|
||||||
|
<% else %>
|
||||||
|
<%= form.text_field "app_config[#{key}]", value: @app_config[key] %>
|
||||||
|
<% end %>
|
||||||
|
|
||||||
|
<% if @installation_configs[key]&.dig('description').present? %>
|
||||||
|
<p class="pt-2 text-xs italic text-slate-400">
|
||||||
|
<%= @installation_configs[key]&.dig('description') %>
|
||||||
|
</p>
|
||||||
|
<% end %>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
<% end %>
|
<% end %>
|
||||||
|
|
||||||
<div class="form-actions">
|
<div class="form-actions">
|
||||||
<%= form.submit "Submit" %>
|
<%= form.submit "Submit" %>
|
||||||
</div>
|
</div>
|
||||||
<% end %>
|
<% end %>
|
||||||
|
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<% content_for :javascript do %>
|
<% content_for :javascript do %>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<li class="px-4 mb-1">
|
<li class="px-4 mb-1">
|
||||||
<% text_class_name = current_page?(url) ? 'text-woot-500 bg-slate-25' : 'text-slate-800' %>
|
<% text_class_name = local_assigns.fetch(:active, current_page?(url)) ? 'text-woot-500 bg-slate-25' : 'text-slate-800' %>
|
||||||
<%= link_to(url, class: text_class_name + " -ml-1 focus:outline-none cursor-pointer flex items-center px-2 py-1.5 text-slate-800 cursor-pointer hover:text-woot-500 hover:bg-slate-25 rounded-lg") do %>
|
<%= link_to(url, class: text_class_name + " -ml-1 focus:outline-none cursor-pointer flex items-center px-2 py-1.5 text-slate-800 cursor-pointer hover:text-woot-500 hover:bg-slate-25 rounded-lg") do %>
|
||||||
<svg width="16" height="16"><use xlink:href="#<%= icon %>" /></svg>
|
<svg width="16" height="16"><use xlink:href="#<%= icon %>" /></svg>
|
||||||
<span class="ml-2 text-sm"><%= label %></span>
|
<span class="ml-2 text-sm"><%= label %></span>
|
||||||
|
|||||||
@@ -33,12 +33,15 @@ as defined by the routes in the `admin/` namespace
|
|||||||
<ul class="my-4">
|
<ul class="my-4">
|
||||||
<%= render partial: "nav_item", locals: { icon: 'icon-grid-line', url: super_admin_root_url, label: 'Dashboard' } %>
|
<%= render partial: "nav_item", locals: { icon: 'icon-grid-line', url: super_admin_root_url, label: 'Dashboard' } %>
|
||||||
<% Administrate::Namespace.new(namespace).resources.each do |resource| %>
|
<% Administrate::Namespace.new(namespace).resources.each do |resource| %>
|
||||||
<% next if ["account_users", "access_tokens", "installation_configs", "dashboard", "devise/sessions", "app_configs", "instance_statuses", "settings", "push_diagnostics"].include? resource.resource %>
|
<% next if ["account_users", "access_tokens", "installation_configs", "dashboard", "devise/sessions", "app_configs", "instance_statuses", "settings", "push_diagnostics", "email_layouts"].include? resource.resource %>
|
||||||
<% next if resource.resource == "platform_banners" && !ChatwootApp.chatwoot_cloud? %>
|
<% next if resource.resource == "platform_banners" && !ChatwootApp.chatwoot_cloud? %>
|
||||||
|
<% resource_url = resource_index_route(resource) %>
|
||||||
|
<% active = current_page?(resource_url) || (resource.resource == 'accounts' && params[:controller] == 'super_admin/email_layouts' && params[:account_id].present?) %>
|
||||||
<%= render partial: "nav_item", locals: {
|
<%= render partial: "nav_item", locals: {
|
||||||
icon: sidebar_icons[resource.resource.to_sym],
|
icon: sidebar_icons[resource.resource.to_sym],
|
||||||
url: resource_index_route(resource),
|
url: resource_url,
|
||||||
label: display_resource_name(resource),
|
label: display_resource_name(resource),
|
||||||
|
active: active,
|
||||||
}
|
}
|
||||||
%>
|
%>
|
||||||
|
|
||||||
|
|||||||
@@ -224,8 +224,30 @@ class Rack::Attack
|
|||||||
match_data[:account_id] if match_data.present?
|
match_data[:account_id] if match_data.present?
|
||||||
end
|
end
|
||||||
|
|
||||||
|
reports_api_user_level_limit = ENV.fetch('RATE_LIMIT_REPORTS_API_USER_LEVEL', '100').to_i
|
||||||
|
reports_drilldown_api_user_level_limit = ENV.fetch(
|
||||||
|
'RATE_LIMIT_REPORTS_DRILLDOWN_API_USER_LEVEL',
|
||||||
|
[(reports_api_user_level_limit / 10), 1].max
|
||||||
|
).to_i
|
||||||
|
|
||||||
|
# Throttle drilldown requests by individual user (based on uid)
|
||||||
|
throttle('/api/v2/accounts/:account_id/reports/drilldown/user',
|
||||||
|
limit: reports_drilldown_api_user_level_limit, period: 1.minute) do |req|
|
||||||
|
match_data = %r{\A/api/v2/accounts/(?<account_id>\d+)/reports/drilldown\z}.match(req.path_without_extensions)
|
||||||
|
next unless match_data.present? && req.get?
|
||||||
|
|
||||||
|
# Extract user identification (uid for web, api_access_token for API requests)
|
||||||
|
user_uid = req.get_header('HTTP_UID')
|
||||||
|
api_access_token = req.get_header('HTTP_API_ACCESS_TOKEN') || req.get_header('api_access_token')
|
||||||
|
|
||||||
|
# Use uid if present, otherwise fallback to api_access_token for tracking
|
||||||
|
user_identifier = user_uid.presence || api_access_token.presence
|
||||||
|
|
||||||
|
"#{user_identifier}:#{match_data[:account_id]}" if user_identifier.present?
|
||||||
|
end
|
||||||
|
|
||||||
# Throttle by individual user (based on uid)
|
# Throttle by individual user (based on uid)
|
||||||
throttle('/api/v2/accounts/:account_id/reports/user', limit: ENV.fetch('RATE_LIMIT_REPORTS_API_USER_LEVEL', '100').to_i, period: 1.minute) do |req|
|
throttle('/api/v2/accounts/:account_id/reports/user', limit: reports_api_user_level_limit, period: 1.minute) do |req|
|
||||||
match_data = %r{/api/v2/accounts/(?<account_id>\d+)/reports}.match(req.path)
|
match_data = %r{/api/v2/accounts/(?<account_id>\d+)/reports}.match(req.path)
|
||||||
# Extract user identification (uid for web, api_access_token for API requests)
|
# Extract user identification (uid for web, api_access_token for API requests)
|
||||||
user_uid = req.get_header('HTTP_UID')
|
user_uid = req.get_header('HTTP_UID')
|
||||||
|
|||||||
@@ -134,6 +134,7 @@ en:
|
|||||||
not_supported: 'Reauthorization is not supported for this type of WhatsApp channel.'
|
not_supported: 'Reauthorization is not supported for this type of WhatsApp channel.'
|
||||||
calls:
|
calls:
|
||||||
not_enabled: 'Calling is not enabled for this inbox'
|
not_enabled: 'Calling is not enabled for this inbox'
|
||||||
|
already_ended: 'This call has already ended'
|
||||||
no_recording: 'No recording file provided'
|
no_recording: 'No recording file provided'
|
||||||
no_message: 'Call has no associated message'
|
no_message: 'Call has no associated message'
|
||||||
sdp_offer_required: 'sdp_offer is required'
|
sdp_offer_required: 'sdp_offer is required'
|
||||||
|
|||||||
+3
-2
@@ -66,8 +66,6 @@ Rails.application.routes.draw do
|
|||||||
resources :assistants do
|
resources :assistants do
|
||||||
member do
|
member do
|
||||||
post :playground
|
post :playground
|
||||||
get :stats
|
|
||||||
get :summary
|
|
||||||
end
|
end
|
||||||
collection do
|
collection do
|
||||||
get :tools
|
get :tools
|
||||||
@@ -503,6 +501,7 @@ Rails.application.routes.draw do
|
|||||||
get :conversations
|
get :conversations
|
||||||
get :conversations_summary
|
get :conversations_summary
|
||||||
get :conversation_traffic
|
get :conversation_traffic
|
||||||
|
get :drilldown
|
||||||
get :bot_metrics
|
get :bot_metrics
|
||||||
get :inbox_label_matrix
|
get :inbox_label_matrix
|
||||||
get :first_response_time_distribution
|
get :first_response_time_distribution
|
||||||
@@ -686,6 +685,7 @@ Rails.application.routes.draw do
|
|||||||
resources :accounts, only: [:index, :new, :create, :show, :edit, :update, :destroy] do
|
resources :accounts, only: [:index, :new, :create, :show, :edit, :update, :destroy] do
|
||||||
post :seed, on: :member
|
post :seed, on: :member
|
||||||
post :reset_cache, on: :member
|
post :reset_cache, on: :member
|
||||||
|
resource :email_layout, only: [:edit, :update, :destroy] if ChatwootApp.enterprise?
|
||||||
end
|
end
|
||||||
resources :users, only: [:index, :new, :create, :show, :edit, :update, :destroy] do
|
resources :users, only: [:index, :new, :create, :show, :edit, :update, :destroy] do
|
||||||
delete :avatar, on: :member, action: :destroy_avatar
|
delete :avatar, on: :member, action: :destroy_avatar
|
||||||
@@ -703,6 +703,7 @@ Rails.application.routes.draw do
|
|||||||
resource :settings, only: [:show] do
|
resource :settings, only: [:show] do
|
||||||
get :refresh, on: :collection
|
get :refresh, on: :collection
|
||||||
end
|
end
|
||||||
|
resource :email_layout, only: [:edit, :update, :destroy] if ChatwootApp.enterprise?
|
||||||
|
|
||||||
# resources that doesn't appear in primary navigation in super admin
|
# resources that doesn't appear in primary navigation in super admin
|
||||||
resources :account_users, only: [:new, :create, :show, :destroy]
|
resources :account_users, only: [:new, :create, :show, :destroy]
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
class UpdateEmailTemplatesUniqueIndexForLocaleAndType < ActiveRecord::Migration[7.1]
|
||||||
|
def change
|
||||||
|
remove_index :email_templates, name: 'index_email_templates_on_name_and_account_id'
|
||||||
|
add_index :email_templates,
|
||||||
|
[:name, :account_id, :template_type, :locale],
|
||||||
|
unique: true,
|
||||||
|
name: 'index_email_templates_on_name_account_type_locale'
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
class AddSenderCreatedIndexToMessages < ActiveRecord::Migration[7.1]
|
|
||||||
disable_ddl_transaction!
|
|
||||||
|
|
||||||
# Adds created_at to the (sender_type, sender_id) index so per-assistant
|
|
||||||
# windowed lookups (Captain Overview stats) can range-scan the time slice
|
|
||||||
# instead of reading every lifetime row and filtering at the heap. The new
|
|
||||||
# index is a left-prefix superset of the old one, so the old one is dropped
|
|
||||||
# to keep write amplification on `messages` neutral.
|
|
||||||
def up
|
|
||||||
add_index :messages, [:sender_type, :sender_id, :created_at],
|
|
||||||
name: 'index_messages_on_sender_and_created', algorithm: :concurrently, if_not_exists: true
|
|
||||||
remove_index :messages, name: 'index_messages_on_sender_type_and_sender_id',
|
|
||||||
algorithm: :concurrently, if_exists: true
|
|
||||||
end
|
|
||||||
|
|
||||||
def down
|
|
||||||
add_index :messages, [:sender_type, :sender_id],
|
|
||||||
name: 'index_messages_on_sender_type_and_sender_id', algorithm: :concurrently, if_not_exists: true
|
|
||||||
remove_index :messages, name: 'index_messages_on_sender_and_created',
|
|
||||||
algorithm: :concurrently, if_exists: true
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
class AddActorToReportingEvents < ActiveRecord::Migration[7.1]
|
|
||||||
disable_ddl_transaction!
|
|
||||||
|
|
||||||
def change
|
|
||||||
add_column :reporting_events, :actor_type, :string
|
|
||||||
add_column :reporting_events, :actor_id, :bigint
|
|
||||||
|
|
||||||
add_index :reporting_events,
|
|
||||||
[:account_id, :actor_type, :actor_id, :name, :created_at],
|
|
||||||
name: 'idx_reporting_events_on_account_actor_name_created',
|
|
||||||
algorithm: :concurrently
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
class CreateCaptainConversationFacts < ActiveRecord::Migration[7.1]
|
|
||||||
def change
|
|
||||||
create_captain_conversation_facts_table
|
|
||||||
add_captain_conversation_facts_indexes
|
|
||||||
end
|
|
||||||
|
|
||||||
private
|
|
||||||
|
|
||||||
def create_captain_conversation_facts_table
|
|
||||||
create_table :captain_conversation_facts do |t|
|
|
||||||
t.bigint :account_id, null: false
|
|
||||||
t.bigint :conversation_id, null: false
|
|
||||||
t.bigint :assistant_id, null: false
|
|
||||||
t.bigint :inbox_id, null: false
|
|
||||||
t.datetime :first_captain_message_at
|
|
||||||
t.datetime :last_captain_message_at
|
|
||||||
t.datetime :captain_resolved_at
|
|
||||||
t.datetime :captain_handed_off_at
|
|
||||||
t.datetime :first_human_reply_after_captain_at
|
|
||||||
t.datetime :reopened_after_captain_resolution_at
|
|
||||||
t.bigint :csat_response_id
|
|
||||||
t.integer :csat_rating
|
|
||||||
t.datetime :csat_submitted_at
|
|
||||||
|
|
||||||
t.timestamps
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def add_captain_conversation_facts_indexes
|
|
||||||
add_index :captain_conversation_facts, :account_id
|
|
||||||
add_index :captain_conversation_facts, :conversation_id, unique: true
|
|
||||||
add_index :captain_conversation_facts, [:account_id, :assistant_id, :first_captain_message_at],
|
|
||||||
name: 'idx_captain_facts_on_account_assistant_first_message'
|
|
||||||
add_index :captain_conversation_facts, [:account_id, :captain_resolved_at],
|
|
||||||
name: 'idx_captain_facts_on_account_resolved_at'
|
|
||||||
add_index :captain_conversation_facts, [:account_id, :captain_handed_off_at],
|
|
||||||
name: 'idx_captain_facts_on_account_handed_off_at'
|
|
||||||
add_index :captain_conversation_facts, [:account_id, :csat_submitted_at],
|
|
||||||
name: 'idx_captain_facts_on_account_csat_submitted_at'
|
|
||||||
end
|
|
||||||
end
|
|
||||||
+3
-30
@@ -10,7 +10,7 @@
|
|||||||
#
|
#
|
||||||
# It's strongly recommended that you check this file into your version control system.
|
# It's strongly recommended that you check this file into your version control system.
|
||||||
|
|
||||||
ActiveRecord::Schema[7.1].define(version: 2026_07_01_001000) do
|
ActiveRecord::Schema[7.1].define(version: 2026_06_20_000000) do
|
||||||
# These extensions should be enabled to support this database
|
# These extensions should be enabled to support this database
|
||||||
enable_extension "pg_stat_statements"
|
enable_extension "pg_stat_statements"
|
||||||
enable_extension "pg_trgm"
|
enable_extension "pg_trgm"
|
||||||
@@ -350,30 +350,6 @@ ActiveRecord::Schema[7.1].define(version: 2026_07_01_001000) do
|
|||||||
t.index ["account_id"], name: "index_captain_assistants_on_account_id"
|
t.index ["account_id"], name: "index_captain_assistants_on_account_id"
|
||||||
end
|
end
|
||||||
|
|
||||||
create_table "captain_conversation_facts", force: :cascade do |t|
|
|
||||||
t.bigint "account_id", null: false
|
|
||||||
t.bigint "conversation_id", null: false
|
|
||||||
t.bigint "assistant_id", null: false
|
|
||||||
t.bigint "inbox_id", null: false
|
|
||||||
t.datetime "first_captain_message_at"
|
|
||||||
t.datetime "last_captain_message_at"
|
|
||||||
t.datetime "captain_resolved_at"
|
|
||||||
t.datetime "captain_handed_off_at"
|
|
||||||
t.datetime "first_human_reply_after_captain_at"
|
|
||||||
t.datetime "reopened_after_captain_resolution_at"
|
|
||||||
t.bigint "csat_response_id"
|
|
||||||
t.integer "csat_rating"
|
|
||||||
t.datetime "csat_submitted_at"
|
|
||||||
t.datetime "created_at", null: false
|
|
||||||
t.datetime "updated_at", null: false
|
|
||||||
t.index ["account_id", "assistant_id", "first_captain_message_at"], name: "idx_captain_facts_on_account_assistant_first_message"
|
|
||||||
t.index ["account_id", "captain_handed_off_at"], name: "idx_captain_facts_on_account_handed_off_at"
|
|
||||||
t.index ["account_id", "captain_resolved_at"], name: "idx_captain_facts_on_account_resolved_at"
|
|
||||||
t.index ["account_id", "csat_submitted_at"], name: "idx_captain_facts_on_account_csat_submitted_at"
|
|
||||||
t.index ["account_id"], name: "index_captain_conversation_facts_on_account_id"
|
|
||||||
t.index ["conversation_id"], name: "index_captain_conversation_facts_on_conversation_id", unique: true
|
|
||||||
end
|
|
||||||
|
|
||||||
create_table "captain_custom_tools", force: :cascade do |t|
|
create_table "captain_custom_tools", force: :cascade do |t|
|
||||||
t.bigint "account_id", null: false
|
t.bigint "account_id", null: false
|
||||||
t.string "slug", null: false
|
t.string "slug", null: false
|
||||||
@@ -883,7 +859,7 @@ ActiveRecord::Schema[7.1].define(version: 2026_07_01_001000) do
|
|||||||
t.integer "locale", default: 0, null: false
|
t.integer "locale", default: 0, null: false
|
||||||
t.datetime "created_at", null: false
|
t.datetime "created_at", null: false
|
||||||
t.datetime "updated_at", null: false
|
t.datetime "updated_at", null: false
|
||||||
t.index ["name", "account_id"], name: "index_email_templates_on_name_and_account_id", unique: true
|
t.index ["name", "account_id", "template_type", "locale"], name: "index_email_templates_on_name_account_type_locale", unique: true
|
||||||
end
|
end
|
||||||
|
|
||||||
create_table "folders", force: :cascade do |t|
|
create_table "folders", force: :cascade do |t|
|
||||||
@@ -1058,7 +1034,7 @@ ActiveRecord::Schema[7.1].define(version: 2026_07_01_001000) do
|
|||||||
t.index ["conversation_id"], name: "index_messages_on_conversation_id"
|
t.index ["conversation_id"], name: "index_messages_on_conversation_id"
|
||||||
t.index ["created_at"], name: "index_messages_on_created_at"
|
t.index ["created_at"], name: "index_messages_on_created_at"
|
||||||
t.index ["inbox_id"], name: "index_messages_on_inbox_id"
|
t.index ["inbox_id"], name: "index_messages_on_inbox_id"
|
||||||
t.index ["sender_type", "sender_id", "created_at"], name: "index_messages_on_sender_and_created"
|
t.index ["sender_type", "sender_id"], name: "index_messages_on_sender_type_and_sender_id"
|
||||||
t.index ["source_id"], name: "index_messages_on_source_id"
|
t.index ["source_id"], name: "index_messages_on_source_id"
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -1191,9 +1167,6 @@ ActiveRecord::Schema[7.1].define(version: 2026_07_01_001000) do
|
|||||||
t.float "value_in_business_hours"
|
t.float "value_in_business_hours"
|
||||||
t.datetime "event_start_time", precision: nil
|
t.datetime "event_start_time", precision: nil
|
||||||
t.datetime "event_end_time", precision: nil
|
t.datetime "event_end_time", precision: nil
|
||||||
t.string "actor_type"
|
|
||||||
t.bigint "actor_id"
|
|
||||||
t.index ["account_id", "actor_type", "actor_id", "name", "created_at"], name: "idx_reporting_events_on_account_actor_name_created"
|
|
||||||
t.index ["account_id", "name", "created_at"], name: "reporting_events__account_id__name__created_at"
|
t.index ["account_id", "name", "created_at"], name: "reporting_events__account_id__name__created_at"
|
||||||
t.index ["account_id", "name", "inbox_id", "created_at"], name: "index_reporting_events_for_response_distribution"
|
t.index ["account_id", "name", "inbox_id", "created_at"], name: "index_reporting_events_for_response_distribution"
|
||||||
t.index ["account_id"], name: "index_reporting_events_on_account_id"
|
t.index ["account_id"], name: "index_reporting_events_on_account_id"
|
||||||
|
|||||||
@@ -1,246 +0,0 @@
|
|||||||
# Computes per-assistant overview metrics for the Captain Overview page.
|
|
||||||
# Each metric is returned for the current window and the previous equal-length
|
|
||||||
# window, plus a derived trend.
|
|
||||||
#
|
|
||||||
# Queries are batched to cut round trips: the message-derived counts (handled,
|
|
||||||
# public replies, depth) and the average reply time are each computed for both
|
|
||||||
# windows in a single scan via conditional FILTER aggregation.
|
|
||||||
class Captain::AssistantStatsBuilder
|
|
||||||
RESOLVED_EVENT_NAMES = %w[conversation_captain_inference_resolved conversation_bot_resolved].freeze
|
|
||||||
HANDOFF_EVENT_NAMES = %w[conversation_captain_inference_handoff conversation_bot_handoff].freeze
|
|
||||||
DEFAULT_RANGE = '30'.freeze
|
|
||||||
ALLOWED_RANGES = %w[7 30 90 this_month last_month].freeze
|
|
||||||
|
|
||||||
attr_reader :assistant, :account, :range
|
|
||||||
|
|
||||||
# `range` is either a day count ('7', '30', '90') or a named period
|
|
||||||
# ('this_month', 'last_month'). The previous window mirrors the current one:
|
|
||||||
# the preceding N days for day ranges, or the preceding month for month ranges.
|
|
||||||
# `timezone_offset` is the viewer's UTC offset in hours (as the reports API sends
|
|
||||||
# it), so month/day boundaries anchor to the viewer's day rather than UTC.
|
|
||||||
def initialize(assistant, range = DEFAULT_RANGE, timezone_offset = nil)
|
|
||||||
@assistant = assistant
|
|
||||||
@account = assistant.account
|
|
||||||
@range = ALLOWED_RANGES.include?(range.to_s) ? range.to_s : DEFAULT_RANGE
|
|
||||||
@timezone = ActiveSupport::TimeZone[timezone_offset.to_f] || Time.zone
|
|
||||||
end
|
|
||||||
|
|
||||||
def metrics
|
|
||||||
messages = message_window_metrics
|
|
||||||
reply_times = avg_reply_times
|
|
||||||
current = window_metrics(current_range, messages[:current], reply_times[:current])
|
|
||||||
previous = window_metrics(previous_range, messages[:previous], reply_times[:previous])
|
|
||||||
|
|
||||||
build_metrics(current, previous)
|
|
||||||
end
|
|
||||||
|
|
||||||
# Human-readable description of the period the metrics cover, for grounding the
|
|
||||||
# LLM summary in real dates.
|
|
||||||
def period
|
|
||||||
{ label: period_label, starts_on: current_range.first.to_date, ends_on: current_range.last.to_date }
|
|
||||||
end
|
|
||||||
|
|
||||||
private
|
|
||||||
|
|
||||||
def build_metrics(current, previous)
|
|
||||||
{
|
|
||||||
conversations_handled: pack(current[:handled], previous[:handled], :percent),
|
|
||||||
auto_resolution_rate: pack(current[:auto_resolution], previous[:auto_resolution], :point),
|
|
||||||
handoff_rate: pack(current[:handoff], previous[:handoff], :point),
|
|
||||||
hours_saved: pack(current[:hours_saved], previous[:hours_saved], :percent),
|
|
||||||
reopen_rate: pack(current[:reopen], previous[:reopen], :point),
|
|
||||||
conversation_depth: pack(current[:depth], previous[:depth], :absolute),
|
|
||||||
knowledge: knowledge
|
|
||||||
}
|
|
||||||
end
|
|
||||||
|
|
||||||
def period_label
|
|
||||||
{ 'this_month' => 'this month', 'last_month' => 'last month' }[range.to_s] || "the last #{range.to_i} days"
|
|
||||||
end
|
|
||||||
|
|
||||||
def current_range
|
|
||||||
resolved_ranges[:current]
|
|
||||||
end
|
|
||||||
|
|
||||||
def previous_range
|
|
||||||
resolved_ranges[:previous]
|
|
||||||
end
|
|
||||||
|
|
||||||
def resolved_ranges
|
|
||||||
@resolved_ranges ||= case range.to_s
|
|
||||||
when 'this_month' then this_month_ranges
|
|
||||||
when 'last_month' then last_month_ranges
|
|
||||||
else day_ranges
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# Current time anchored to the viewer's timezone, so calendar boundaries land on
|
|
||||||
# the viewer's day instead of UTC's.
|
|
||||||
def now
|
|
||||||
@now ||= Time.current.in_time_zone(@timezone)
|
|
||||||
end
|
|
||||||
|
|
||||||
def this_month_ranges
|
|
||||||
start = now.beginning_of_month
|
|
||||||
elapsed = now - start
|
|
||||||
previous_start = start - 1.month
|
|
||||||
# Clamp to the previous month's end so a longer current month can't pull the
|
|
||||||
# comparison window into the current month and double-count its rows.
|
|
||||||
previous_end = [previous_start + elapsed, previous_start.end_of_month].min
|
|
||||||
{ current: start..now, previous: previous_start..previous_end }
|
|
||||||
end
|
|
||||||
|
|
||||||
def last_month_ranges
|
|
||||||
start = (now - 1.month).beginning_of_month
|
|
||||||
previous_start = start - 1.month
|
|
||||||
{ current: start..start.end_of_month, previous: previous_start..previous_start.end_of_month }
|
|
||||||
end
|
|
||||||
|
|
||||||
def day_ranges
|
|
||||||
days = range.to_i
|
|
||||||
{ current: (now - days.days)..now, previous: (now - (2 * days).days)..(now - days.days) }
|
|
||||||
end
|
|
||||||
|
|
||||||
# Combines the per-window message counts and reply time with the reporting-event metrics for one window.
|
|
||||||
def window_metrics(range, message_counts, avg_reply)
|
|
||||||
handled = message_counts[:handled]
|
|
||||||
public_count = message_counts[:public_count]
|
|
||||||
depth_conversations = message_counts[:depth_conversations]
|
|
||||||
resolution = resolution_counts(range)
|
|
||||||
|
|
||||||
{
|
|
||||||
handled: handled,
|
|
||||||
auto_resolution: rate(resolution[:resolved], handled),
|
|
||||||
handoff: rate(resolution[:handoff], handled),
|
|
||||||
hours_saved: (public_count * avg_reply / 3600.0).round,
|
|
||||||
reopen: reopen_rate(range),
|
|
||||||
depth: depth_conversations.zero? ? 0 : (public_count.to_f / depth_conversations).round(1)
|
|
||||||
}
|
|
||||||
end
|
|
||||||
|
|
||||||
# One scan over the assistant's messages computes handled, public-reply count,
|
|
||||||
# and depth-conversation count for both windows via conditional aggregation.
|
|
||||||
def message_window_metrics
|
|
||||||
public_clause = "message_type = #{Message.message_types[:outgoing]} AND private = false"
|
|
||||||
cur = window_clause(current_range)
|
|
||||||
prev = window_clause(previous_range)
|
|
||||||
|
|
||||||
row = handled_scope(full_span).reorder(nil).pick(
|
|
||||||
Arel.sql("COUNT(DISTINCT conversation_id) FILTER (WHERE #{cur})"),
|
|
||||||
Arel.sql("COUNT(DISTINCT conversation_id) FILTER (WHERE #{prev})"),
|
|
||||||
Arel.sql("COUNT(*) FILTER (WHERE #{cur} AND #{public_clause})"),
|
|
||||||
Arel.sql("COUNT(*) FILTER (WHERE #{prev} AND #{public_clause})"),
|
|
||||||
Arel.sql("COUNT(DISTINCT conversation_id) FILTER (WHERE #{cur} AND #{public_clause})"),
|
|
||||||
Arel.sql("COUNT(DISTINCT conversation_id) FILTER (WHERE #{prev} AND #{public_clause})")
|
|
||||||
)
|
|
||||||
|
|
||||||
{
|
|
||||||
current: { handled: row[0], public_count: row[2], depth_conversations: row[4] },
|
|
||||||
previous: { handled: row[1], public_count: row[3], depth_conversations: row[5] }
|
|
||||||
}
|
|
||||||
end
|
|
||||||
|
|
||||||
# Average reply time (seconds) for both windows in one scan.
|
|
||||||
def avg_reply_times
|
|
||||||
row = account.reporting_events.where(name: 'reply_time', created_at: full_span).reorder(nil).pick(
|
|
||||||
Arel.sql("AVG(value) FILTER (WHERE #{window_clause(current_range)})"),
|
|
||||||
Arel.sql("AVG(value) FILTER (WHERE #{window_clause(previous_range)})")
|
|
||||||
)
|
|
||||||
{ current: row[0].to_f, previous: row[1].to_f }
|
|
||||||
end
|
|
||||||
|
|
||||||
# Resolved and handed-off conversation counts for one window, in a single scan
|
|
||||||
# of the handled set's reporting events.
|
|
||||||
def resolution_counts(range)
|
|
||||||
row = account.reporting_events
|
|
||||||
.where(name: RESOLVED_EVENT_NAMES + HANDOFF_EVENT_NAMES,
|
|
||||||
created_at: range,
|
|
||||||
conversation_id: handled_scope(range).select(:conversation_id))
|
|
||||||
.reorder(nil)
|
|
||||||
.pick(
|
|
||||||
Arel.sql("COUNT(DISTINCT conversation_id) FILTER (WHERE name IN (#{quoted(RESOLVED_EVENT_NAMES)}))"),
|
|
||||||
Arel.sql("COUNT(DISTINCT conversation_id) FILTER (WHERE name IN (#{quoted(HANDOFF_EVENT_NAMES)}))")
|
|
||||||
)
|
|
||||||
{ resolved: row[0], handoff: row[1] }
|
|
||||||
end
|
|
||||||
|
|
||||||
# Conversations the assistant participated in (authored any message).
|
|
||||||
def handled_scope(range)
|
|
||||||
account.messages.where(sender_type: 'Captain::Assistant', sender_id: assistant.id, created_at: range)
|
|
||||||
end
|
|
||||||
|
|
||||||
# Span covering both windows so a single scan can split them with FILTER.
|
|
||||||
def full_span
|
|
||||||
[current_range.first, previous_range.first].min..current_range.last
|
|
||||||
end
|
|
||||||
|
|
||||||
def window_clause(range)
|
|
||||||
"created_at >= #{quote(range.first)} AND created_at <= #{quote(range.last)}"
|
|
||||||
end
|
|
||||||
|
|
||||||
def quote(value)
|
|
||||||
account.class.connection.quote(value)
|
|
||||||
end
|
|
||||||
|
|
||||||
def quoted(values)
|
|
||||||
values.map { |value| quote(value) }.join(', ')
|
|
||||||
end
|
|
||||||
|
|
||||||
# Of the conversations Captain auto-resolved, the share reopened afterwards. The cohort is
|
|
||||||
# derived from the assistant's handled conversations (not current inbox membership) so a later
|
|
||||||
# inbox reassignment doesn't drop historical resolves, and covers both the evaluated (inference)
|
|
||||||
# and time-based (bot) resolve paths so the denominator matches auto_resolution_rate.
|
|
||||||
def reopen_rate(range)
|
|
||||||
resolved_scope = account.reporting_events.where(name: RESOLVED_EVENT_NAMES, created_at: range,
|
|
||||||
conversation_id: handled_scope(range).select(:conversation_id))
|
|
||||||
# event_end_time on a reopen is when it actually reopened. Join it to the conversation's own
|
|
||||||
# Captain resolves and keep only reopens at/after one of them, so a human resolve/reopen earlier
|
|
||||||
# in the same window isn't mistaken for a reopen-after-Captain-resolve. (Comparing the reopen's
|
|
||||||
# start time instead would misfire: the inference event is dispatched just after the generic
|
|
||||||
# conversation_resolved that seeds event_start_time, so it can land after the reopen's start.)
|
|
||||||
reopened = account.reporting_events
|
|
||||||
.where(name: 'conversation_opened')
|
|
||||||
.where('reporting_events.value > 0')
|
|
||||||
.joins("INNER JOIN (#{resolved_scope.to_sql}) resolves " \
|
|
||||||
'ON resolves.conversation_id = reporting_events.conversation_id ' \
|
|
||||||
'AND reporting_events.event_end_time >= resolves.event_end_time')
|
|
||||||
.distinct.count('reporting_events.conversation_id')
|
|
||||||
rate(reopened, resolved_scope.distinct.count(:conversation_id))
|
|
||||||
end
|
|
||||||
|
|
||||||
# Approved/pending FAQ counts and the document total in a single round trip.
|
|
||||||
def knowledge
|
|
||||||
approved, pending, documents = Captain::AssistantResponse.by_assistant(assistant.id).reorder(nil).pick(
|
|
||||||
Arel.sql("COUNT(*) FILTER (WHERE status = #{Captain::AssistantResponse.statuses['approved']})"),
|
|
||||||
Arel.sql("COUNT(*) FILTER (WHERE status = #{Captain::AssistantResponse.statuses['pending']})"),
|
|
||||||
Arel.sql("(SELECT COUNT(*) FROM captain_documents WHERE assistant_id = #{assistant.id.to_i})")
|
|
||||||
)
|
|
||||||
total = approved + pending
|
|
||||||
|
|
||||||
{
|
|
||||||
approved: approved,
|
|
||||||
pending: pending,
|
|
||||||
documents: documents,
|
|
||||||
coverage: total.zero? ? 0 : (approved.to_f / total * 100).round
|
|
||||||
}
|
|
||||||
end
|
|
||||||
|
|
||||||
def rate(numerator, denominator)
|
|
||||||
return 0 if denominator.zero?
|
|
||||||
|
|
||||||
(numerator.to_f / denominator * 100).round(1)
|
|
||||||
end
|
|
||||||
|
|
||||||
def pack(current, previous, mode)
|
|
||||||
{ current: current, previous: previous, trend: trend(current, previous, mode) }
|
|
||||||
end
|
|
||||||
|
|
||||||
def trend(current, previous, mode)
|
|
||||||
case mode
|
|
||||||
when :percent
|
|
||||||
previous.zero? ? 0 : ((current - previous).to_f / previous * 100).round(1)
|
|
||||||
else # :point and :absolute are both current - previous
|
|
||||||
(current - previous).round(1)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -47,7 +47,7 @@ class Api::V1::Accounts::AppliedSlasController < Api::V1::Accounts::EnterpriseAc
|
|||||||
end
|
end
|
||||||
|
|
||||||
def set_applied_slas
|
def set_applied_slas
|
||||||
initial_query = Current.account.applied_slas.includes(:conversation)
|
initial_query = Current.account.applied_slas.with_sla_applicable_conversation.includes(:conversation)
|
||||||
@applied_slas = apply_filters(initial_query)
|
@applied_slas = apply_filters(initial_query)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ class Api::V1::Accounts::Captain::AssistantsController < Api::V1::Accounts::Base
|
|||||||
before_action :current_account
|
before_action :current_account
|
||||||
before_action -> { check_authorization(Captain::Assistant) }
|
before_action -> { check_authorization(Captain::Assistant) }
|
||||||
|
|
||||||
before_action :set_assistant, only: [:show, :update, :destroy, :playground, :stats, :summary]
|
before_action :set_assistant, only: [:show, :update, :destroy, :playground]
|
||||||
|
|
||||||
def index
|
def index
|
||||||
@assistants = account_assistants.ordered
|
@assistants = account_assistants.ordered
|
||||||
@@ -43,43 +43,8 @@ class Api::V1::Accounts::Captain::AssistantsController < Api::V1::Accounts::Base
|
|||||||
@tools = assistant.available_agent_tools
|
@tools = assistant.available_agent_tools
|
||||||
end
|
end
|
||||||
|
|
||||||
def stats
|
|
||||||
render json: Captain::AssistantStatsBuilder.new(@assistant, params[:range], params[:timezone_offset]).metrics
|
|
||||||
end
|
|
||||||
|
|
||||||
def summary
|
|
||||||
result = cached_or_generated_summary(Captain::AssistantStatsBuilder.new(@assistant, params[:range], params[:timezone_offset]))
|
|
||||||
|
|
||||||
if result[:error]
|
|
||||||
render json: { error: result[:error] }, status: :unprocessable_content
|
|
||||||
else
|
|
||||||
render json: { message: result[:message] }
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
private
|
private
|
||||||
|
|
||||||
def cached_or_generated_summary(builder)
|
|
||||||
cache_key = summary_cache_key(builder.range)
|
|
||||||
cached = Rails.cache.read(cache_key)
|
|
||||||
return cached if cached
|
|
||||||
|
|
||||||
result = Captain::OverviewSummaryService.new(
|
|
||||||
account: Current.account,
|
|
||||||
assistant: @assistant,
|
|
||||||
first_name: Current.user.name.to_s.split.first,
|
|
||||||
stats: builder.metrics,
|
|
||||||
period: builder.period
|
|
||||||
).perform
|
|
||||||
# Don't cache transient LLM/config failures, otherwise every reload returns 422 for the next hour.
|
|
||||||
Rails.cache.write(cache_key, result, expires_in: 1.hour) unless result[:error]
|
|
||||||
result
|
|
||||||
end
|
|
||||||
|
|
||||||
def summary_cache_key(range)
|
|
||||||
"captain_overview_summary/#{@assistant.id}/#{Current.user.id}/#{range}/#{Date.current}"
|
|
||||||
end
|
|
||||||
|
|
||||||
def set_assistant
|
def set_assistant
|
||||||
@assistant = account_assistants.find(params[:id])
|
@assistant = account_assistants.find(params[:id])
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ class Api::V1::Accounts::WhatsappCallsController < Api::V1::Accounts::BaseContro
|
|||||||
Voice::CallErrors::AlreadyAccepted,
|
Voice::CallErrors::AlreadyAccepted,
|
||||||
Voice::CallErrors::CallFailed,
|
Voice::CallErrors::CallFailed,
|
||||||
with: :render_call_error
|
with: :render_call_error
|
||||||
|
rescue_from Voice::CallErrors::CallAlreadyEnded, with: :render_call_ended
|
||||||
rescue_from Voice::CallErrors::NoCallPermission, with: :render_permission_request
|
rescue_from Voice::CallErrors::NoCallPermission, with: :render_permission_request
|
||||||
|
|
||||||
def show; end
|
def show; end
|
||||||
@@ -105,9 +106,14 @@ class Api::V1::Accounts::WhatsappCallsController < Api::V1::Accounts::BaseContro
|
|||||||
|
|
||||||
def create_outbound_call
|
def create_outbound_call
|
||||||
contact_phone = @conversation.contact.phone_number.delete('+')
|
contact_phone = @conversation.contact.phone_number.delete('+')
|
||||||
|
# Claim for the caller only if unassigned at trigger time (before the round-trip); wins over auto-assignment.
|
||||||
|
claim_for_caller = @conversation.assignee_id.nil?
|
||||||
|
|
||||||
result = provider_service.initiate_call(contact_phone, params[:sdp_offer])
|
result = provider_service.initiate_call(contact_phone, params[:sdp_offer])
|
||||||
provider_call_id = result.dig('calls', 0, 'id') || result['call_id']
|
provider_call_id = result.dig('calls', 0, 'id') || result['call_id']
|
||||||
|
|
||||||
|
@conversation.with_lock { @conversation.update!(assignee: Current.user) } if claim_for_caller
|
||||||
|
|
||||||
Current.account.calls.create!(
|
Current.account.calls.create!(
|
||||||
provider: :whatsapp, inbox: @conversation.inbox, conversation: @conversation, contact: @conversation.contact,
|
provider: :whatsapp, inbox: @conversation.inbox, conversation: @conversation, contact: @conversation.contact,
|
||||||
provider_call_id: provider_call_id, direction: :outgoing, status: 'ringing',
|
provider_call_id: provider_call_id, direction: :outgoing, status: 'ringing',
|
||||||
@@ -190,4 +196,9 @@ class Api::V1::Accounts::WhatsappCallsController < Api::V1::Accounts::BaseContro
|
|||||||
def render_call_error(error)
|
def render_call_error(error)
|
||||||
render_could_not_create_error(error.message)
|
render_could_not_create_error(error.message)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
# 409 (not 422) so the FE can tell "already ended" from a generic failure and dismiss the ringing UI.
|
||||||
|
def render_call_ended
|
||||||
|
render json: { error: I18n.t('errors.whatsapp.calls.already_ended') }, status: :conflict
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -0,0 +1,280 @@
|
|||||||
|
class SuperAdmin::EmailLayoutsController < SuperAdmin::EnterpriseBaseController
|
||||||
|
before_action :set_account
|
||||||
|
before_action :set_custom_templates
|
||||||
|
before_action :set_template_selection
|
||||||
|
before_action :set_email_layout
|
||||||
|
before_action :ensure_custom_branding_access!
|
||||||
|
|
||||||
|
def edit
|
||||||
|
@show_template_editor = editor_requested?
|
||||||
|
return unless @show_template_editor
|
||||||
|
|
||||||
|
@layout_body = @email_layout&.body || inherited_template_body
|
||||||
|
set_preview_context
|
||||||
|
end
|
||||||
|
|
||||||
|
def update
|
||||||
|
@layout_body = layout_params[:body].to_s
|
||||||
|
validation_error = validate_layout_body(@layout_body)
|
||||||
|
|
||||||
|
return render_edit_with_alert(validation_error) if validation_error.present?
|
||||||
|
|
||||||
|
return render_edit_with_alert(conflict_error) if conflicting_template_exists?
|
||||||
|
|
||||||
|
@email_layout ||= EmailTemplate.new(name: template_name, template_type: template_type, locale: template_locale, account: @account)
|
||||||
|
@email_layout.body = @layout_body
|
||||||
|
|
||||||
|
if @email_layout.save
|
||||||
|
# rubocop:disable Rails/I18nLocaleTexts
|
||||||
|
redirect_to edit_email_layout_path, notice: 'Email layout updated successfully'
|
||||||
|
# rubocop:enable Rails/I18nLocaleTexts
|
||||||
|
else
|
||||||
|
render_edit_with_alert(@email_layout.errors.full_messages.join(', '))
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def destroy
|
||||||
|
@email_layout&.destroy
|
||||||
|
redirect_to email_layout_overview_path, notice: reset_notice
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def set_account
|
||||||
|
@account = Account.find(params[:account_id]) if params[:account_id].present?
|
||||||
|
end
|
||||||
|
|
||||||
|
def set_custom_templates
|
||||||
|
@custom_templates = EmailTemplate.where(account: @account).order(:template_type, :name, :locale)
|
||||||
|
end
|
||||||
|
|
||||||
|
def set_template_selection
|
||||||
|
@template_type = selected_template_type
|
||||||
|
@template_name = selected_template_name
|
||||||
|
@template_locale = selected_template_locale
|
||||||
|
@template_options = template_options
|
||||||
|
@locale_options = locale_options
|
||||||
|
end
|
||||||
|
|
||||||
|
def set_email_layout
|
||||||
|
@email_layout = EmailTemplate.find_by(name: template_name, template_type: template_type, locale: template_locale, account: @account)
|
||||||
|
end
|
||||||
|
|
||||||
|
attr_reader :template_name, :template_type, :template_locale
|
||||||
|
|
||||||
|
def default_layout_body
|
||||||
|
Rails.root.join('app/views/layouts/mailer/base.liquid').read
|
||||||
|
end
|
||||||
|
|
||||||
|
def default_content_body
|
||||||
|
content_template_path.read
|
||||||
|
end
|
||||||
|
|
||||||
|
def inherited_template_body
|
||||||
|
return global_template_body || default_template_body if @account.present?
|
||||||
|
|
||||||
|
default_template_body
|
||||||
|
end
|
||||||
|
|
||||||
|
def default_template_body
|
||||||
|
return default_layout_body if template_type == 'layout'
|
||||||
|
|
||||||
|
default_content_body
|
||||||
|
end
|
||||||
|
|
||||||
|
def global_template_body
|
||||||
|
EmailTemplate.find_by(name: template_name, template_type: template_type, locale: template_locale, account: nil)&.body
|
||||||
|
end
|
||||||
|
|
||||||
|
def layout_params
|
||||||
|
params.require(:email_layout).permit(:body, :template_type, :template_name, :locale)
|
||||||
|
end
|
||||||
|
|
||||||
|
def validate_layout_body(body)
|
||||||
|
return 'Template body cannot be blank' if body.blank?
|
||||||
|
return 'Layout must include {{ content_for_layout }}' if template_type == 'layout' && !body.match?(/\{\{\s*content_for_layout\s*\}\}/)
|
||||||
|
|
||||||
|
Liquid::Template.parse(body)
|
||||||
|
nil
|
||||||
|
rescue Liquid::SyntaxError => e
|
||||||
|
"Liquid syntax error: #{e.message}"
|
||||||
|
end
|
||||||
|
|
||||||
|
def render_edit_with_alert(message)
|
||||||
|
flash.now[:alert] = message
|
||||||
|
@show_template_editor = true
|
||||||
|
set_preview_context
|
||||||
|
render :edit, status: :unprocessable_entity
|
||||||
|
end
|
||||||
|
|
||||||
|
def set_preview_context
|
||||||
|
@preview_html = render_preview(@layout_body)
|
||||||
|
@supported_variables = supported_variables
|
||||||
|
@template_status = template_status
|
||||||
|
@preview_config = preview_config
|
||||||
|
rescue Liquid::SyntaxError
|
||||||
|
@preview_html = ''
|
||||||
|
@supported_variables = supported_variables
|
||||||
|
@template_status = template_status
|
||||||
|
@preview_config = preview_config
|
||||||
|
end
|
||||||
|
|
||||||
|
def render_preview(body)
|
||||||
|
assigns = {
|
||||||
|
'content_for_layout' => preview_content,
|
||||||
|
'global_config' => GlobalConfig.get('BRAND_NAME', 'BRAND_URL')
|
||||||
|
}
|
||||||
|
assigns['account'] = { 'name' => @account.name } if @account.present?
|
||||||
|
|
||||||
|
rendered_body = Liquid::Template.parse(body).render(assigns)
|
||||||
|
return rendered_body if template_type == 'layout'
|
||||||
|
|
||||||
|
Liquid::Template.parse(default_layout_body).render(assigns.merge('content_for_layout' => rendered_body))
|
||||||
|
end
|
||||||
|
|
||||||
|
def preview_content
|
||||||
|
<<~HTML
|
||||||
|
<tr>
|
||||||
|
<td style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; padding: 0;">
|
||||||
|
<h1 style="font-size: 20px; margin: 0 0 12px;">Sample notification</h1>
|
||||||
|
<p style="margin: 0 0 16px;">This preview shows how notification content renders inside your email layout.</p>
|
||||||
|
<a href="#" style="display: inline-block; background: #1f93ff; color: #fff; padding: 10px 14px; border-radius: 6px; text-decoration: none;">View conversation</a>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
HTML
|
||||||
|
end
|
||||||
|
|
||||||
|
def preview_config
|
||||||
|
brand_config = GlobalConfig.get('BRAND_NAME', 'BRAND_URL')
|
||||||
|
{
|
||||||
|
templateType: template_type,
|
||||||
|
defaultLayout: default_layout_body,
|
||||||
|
previewContent: preview_content,
|
||||||
|
brandName: brand_config['BRAND_NAME'].to_s,
|
||||||
|
brandUrl: brand_config['BRAND_URL'].to_s,
|
||||||
|
accountName: @account&.name.to_s
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
def supported_variables
|
||||||
|
variables = []
|
||||||
|
if template_type == 'layout'
|
||||||
|
variables << {
|
||||||
|
variable: '{{ content_for_layout }}',
|
||||||
|
description: 'Required. Renders the email body inside the layout.'
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
variables + [
|
||||||
|
{
|
||||||
|
variable: "{{ global_config['BRAND_NAME'] }}",
|
||||||
|
description: 'Current brand name from Custom Branding.'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
variable: "{{ global_config['BRAND_URL'] }}",
|
||||||
|
description: 'Current brand URL from Custom Branding.'
|
||||||
|
}
|
||||||
|
].tap do |template_variables|
|
||||||
|
next if @account.blank?
|
||||||
|
|
||||||
|
template_variables << {
|
||||||
|
variable: '{{ account.name }}',
|
||||||
|
description: 'Current account name for account-specific previews.'
|
||||||
|
}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def conflict_error
|
||||||
|
"Cannot save template. '#{template_name}' is already used by another email template for this account, type, and language."
|
||||||
|
end
|
||||||
|
|
||||||
|
def conflicting_template_exists?
|
||||||
|
return false if @email_layout.present?
|
||||||
|
|
||||||
|
EmailTemplate.exists?(name: template_name, template_type: template_type, locale: template_locale, account: @account)
|
||||||
|
end
|
||||||
|
|
||||||
|
def edit_email_layout_path
|
||||||
|
query = { template_type: template_type, template_name: template_name, locale: template_locale }
|
||||||
|
return edit_super_admin_account_email_layout_path(@account, query) if @account.present?
|
||||||
|
|
||||||
|
edit_super_admin_email_layout_path(query)
|
||||||
|
end
|
||||||
|
|
||||||
|
def email_layout_overview_path
|
||||||
|
return edit_super_admin_account_email_layout_path(@account) if @account.present?
|
||||||
|
|
||||||
|
edit_super_admin_email_layout_path
|
||||||
|
end
|
||||||
|
|
||||||
|
def editor_requested?
|
||||||
|
params[:new].present? || params[:template_type].present? || params[:template_name].present? || params[:locale].present?
|
||||||
|
end
|
||||||
|
|
||||||
|
def reset_notice
|
||||||
|
return 'Account email template reset to inherited template' if @account.present?
|
||||||
|
|
||||||
|
'Email template reset to default'
|
||||||
|
end
|
||||||
|
|
||||||
|
def ensure_custom_branding_access!
|
||||||
|
return if ChatwootHub.pricing_plan != 'community'
|
||||||
|
|
||||||
|
invalid_action_perfomed
|
||||||
|
end
|
||||||
|
|
||||||
|
def selected_template_type
|
||||||
|
selected_type = params.dig(:email_layout, :template_type).presence || params[:template_type].presence || 'layout'
|
||||||
|
EmailTemplate.template_types.key?(selected_type) ? selected_type : 'layout'
|
||||||
|
end
|
||||||
|
|
||||||
|
def selected_template_name
|
||||||
|
selected_name = params.dig(:email_layout, :template_name).presence || params[:template_name].presence
|
||||||
|
selected_name = default_template_name if selected_name.blank?
|
||||||
|
available_template_names.include?(selected_name) ? selected_name : default_template_name
|
||||||
|
end
|
||||||
|
|
||||||
|
def selected_template_locale
|
||||||
|
selected_locale = params.dig(:email_layout, :locale).presence || params[:locale].presence || 'en'
|
||||||
|
EmailTemplate.locales.key?(selected_locale) ? selected_locale : 'en'
|
||||||
|
end
|
||||||
|
|
||||||
|
def default_template_name
|
||||||
|
return 'base' if template_type == 'layout'
|
||||||
|
|
||||||
|
content_template_options.first[:name]
|
||||||
|
end
|
||||||
|
|
||||||
|
def template_options
|
||||||
|
return [{ name: 'base', label: 'Base layout' }] if template_type == 'layout'
|
||||||
|
|
||||||
|
content_template_options
|
||||||
|
end
|
||||||
|
|
||||||
|
def available_template_names
|
||||||
|
template_options.pluck(:name)
|
||||||
|
end
|
||||||
|
|
||||||
|
def content_template_options
|
||||||
|
@content_template_options ||= Rails.root.glob('app/views/mailers/**/*.liquid').map do |path|
|
||||||
|
name = path.relative_path_from(Rails.root.join('app/views/mailers')).to_s.delete_suffix('.liquid')
|
||||||
|
{ name: name, label: name.humanize }
|
||||||
|
end.sort_by { |template| template[:label] }
|
||||||
|
end
|
||||||
|
|
||||||
|
def content_template_path
|
||||||
|
Rails.root.join('app/views/mailers', "#{template_name}.liquid")
|
||||||
|
end
|
||||||
|
|
||||||
|
def locale_options
|
||||||
|
EmailTemplate.locales.keys.map { |locale| [locale.upcase, locale] }
|
||||||
|
end
|
||||||
|
|
||||||
|
def template_status
|
||||||
|
return 'Account override configured' if @account.present? && @email_layout.present?
|
||||||
|
return 'Global override configured' if @account.blank? && @email_layout.present?
|
||||||
|
return 'Inherits global template' if @account.present? && global_template_body.present?
|
||||||
|
|
||||||
|
'Inherits default template'
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
module Enterprise::ConversationFinder
|
module Enterprise::ConversationFinder
|
||||||
def conversations_base_query
|
def conversations_base_query
|
||||||
current_account.feature_enabled?('sla') ? super.includes(:applied_sla, :sla_events) : super
|
return super unless current_account.feature_enabled?('sla')
|
||||||
|
|
||||||
|
super.includes(:applied_sla, :sla_events, inbox: :working_hours)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,6 +1,21 @@
|
|||||||
class Onboarding::HelpCenterArticleWriterJob < ApplicationJob
|
class Onboarding::HelpCenterArticleWriterJob < ApplicationJob
|
||||||
queue_as :low
|
queue_as :low
|
||||||
|
|
||||||
|
# Catch-all so no exception type can wedge the generation in "generating".
|
||||||
|
# Declared FIRST because ActiveJob searches rescue handlers bottom-to-top:
|
||||||
|
# this puts StandardError at the bottom of the search order, so the specific
|
||||||
|
# retry_on/discard_on handlers declared below match first for their types.
|
||||||
|
#
|
||||||
|
# Without this, any error that isn't FirecrawlError or ArticleBuildFailed
|
||||||
|
# (e.g. ActiveRecord::RecordInvalid, SSL errors) falls through to ActiveJob's
|
||||||
|
# default retries, exhausts them, and lands in the dead set without ever
|
||||||
|
# calling finalize -> state stays "generating" at total - 1 until the 7-day
|
||||||
|
# Redis TTL expires. on_writer_failure logs the error, so code bugs are still
|
||||||
|
# visible; it just also progresses the state.
|
||||||
|
discard_on StandardError do |job, error|
|
||||||
|
job.send(:on_writer_failure, error)
|
||||||
|
end
|
||||||
|
|
||||||
retry_on Firecrawl::FirecrawlError, wait: :polynomially_longer, attempts: 3 do |job, error|
|
retry_on Firecrawl::FirecrawlError, wait: :polynomially_longer, attempts: 3 do |job, error|
|
||||||
job.send(:on_writer_failure, error)
|
job.send(:on_writer_failure, error)
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ class Sla::ProcessAccountAppliedSlasJob < ApplicationJob
|
|||||||
queue_as :medium
|
queue_as :medium
|
||||||
|
|
||||||
def perform(account)
|
def perform(account)
|
||||||
account.applied_slas.where(sla_status: %w[active active_with_misses]).each do |applied_sla|
|
account.applied_slas.with_sla_applicable_conversation.where(sla_status: %w[active active_with_misses]).each do |applied_sla|
|
||||||
Sla::ProcessAppliedSlaJob.perform_later(applied_sla)
|
Sla::ProcessAppliedSlaJob.perform_later(applied_sla)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -40,10 +40,13 @@ class AppliedSla < ApplicationRecord
|
|||||||
joins(:conversation).where(conversations: { assignee_id: assigned_agent_id }) if assigned_agent_id.present?
|
joins(:conversation).where(conversations: { assignee_id: assigned_agent_id }) if assigned_agent_id.present?
|
||||||
}
|
}
|
||||||
scope :missed, -> { where(sla_status: %i[missed active_with_misses]) }
|
scope :missed, -> { where(sla_status: %i[missed active_with_misses]) }
|
||||||
|
scope :with_sla_applicable_conversation, -> { where(conversation_id: Conversation.with_sla_applicable_contact.select(:id)) }
|
||||||
|
|
||||||
after_update_commit :push_conversation_event
|
after_update_commit :push_conversation_event
|
||||||
|
|
||||||
def push_event_data
|
def push_event_data
|
||||||
|
sla_due_at_values = due_at_values
|
||||||
|
|
||||||
{
|
{
|
||||||
id: id,
|
id: id,
|
||||||
sla_id: sla_policy_id,
|
sla_id: sla_policy_id,
|
||||||
@@ -55,10 +58,65 @@ class AppliedSla < ApplicationRecord
|
|||||||
sla_first_response_time_threshold: sla_policy.first_response_time_threshold,
|
sla_first_response_time_threshold: sla_policy.first_response_time_threshold,
|
||||||
sla_next_response_time_threshold: sla_policy.next_response_time_threshold,
|
sla_next_response_time_threshold: sla_policy.next_response_time_threshold,
|
||||||
sla_only_during_business_hours: sla_policy.only_during_business_hours,
|
sla_only_during_business_hours: sla_policy.only_during_business_hours,
|
||||||
sla_resolution_time_threshold: sla_policy.resolution_time_threshold
|
sla_resolution_time_threshold: sla_policy.resolution_time_threshold,
|
||||||
|
sla_frt_due_at: sla_due_at_values[:frt],
|
||||||
|
sla_nrt_due_at: sla_due_at_values[:nrt],
|
||||||
|
sla_rt_due_at: sla_due_at_values[:rt]
|
||||||
}
|
}
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def due_at_values
|
||||||
|
working_hours_by_day_cache = conversation.inbox.working_hours.index_by(&:day_of_week) if sla_policy.only_during_business_hours?
|
||||||
|
|
||||||
|
{
|
||||||
|
frt: frt_due_at(working_hours_by_day_cache: working_hours_by_day_cache),
|
||||||
|
nrt: nrt_due_at(working_hours_by_day_cache: working_hours_by_day_cache),
|
||||||
|
rt: rt_due_at(working_hours_by_day_cache: working_hours_by_day_cache)
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
def frt_due_at(working_hours_by_day_cache: nil)
|
||||||
|
return nil if sla_policy.first_response_time_threshold.blank?
|
||||||
|
|
||||||
|
calculate_due_at(
|
||||||
|
conversation.created_at,
|
||||||
|
sla_policy.first_response_time_threshold,
|
||||||
|
working_hours_by_day_cache: working_hours_by_day_cache
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
def nrt_due_at(working_hours_by_day_cache: nil)
|
||||||
|
return nil if sla_policy.next_response_time_threshold.blank?
|
||||||
|
return nil if conversation.waiting_since.blank?
|
||||||
|
|
||||||
|
calculate_due_at(
|
||||||
|
conversation.waiting_since,
|
||||||
|
sla_policy.next_response_time_threshold,
|
||||||
|
working_hours_by_day_cache: working_hours_by_day_cache
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
def rt_due_at(working_hours_by_day_cache: nil)
|
||||||
|
return nil if sla_policy.resolution_time_threshold.blank?
|
||||||
|
|
||||||
|
calculate_due_at(
|
||||||
|
conversation.created_at,
|
||||||
|
sla_policy.resolution_time_threshold,
|
||||||
|
working_hours_by_day_cache: working_hours_by_day_cache
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
def calculate_due_at(start_time, threshold_seconds, working_hours_by_day_cache: nil)
|
||||||
|
return (start_time + threshold_seconds.to_i.seconds).to_i unless sla_policy.only_during_business_hours?
|
||||||
|
|
||||||
|
Sla::BusinessHoursService.new(
|
||||||
|
inbox: conversation.inbox,
|
||||||
|
start_time: start_time,
|
||||||
|
threshold_seconds: threshold_seconds,
|
||||||
|
working_hours_by_day_cache: working_hours_by_day_cache
|
||||||
|
).deadline.to_i
|
||||||
|
end
|
||||||
|
|
||||||
private
|
private
|
||||||
|
|
||||||
def push_conversation_event
|
def push_conversation_event
|
||||||
|
|||||||
@@ -35,7 +35,6 @@ class Captain::Assistant < ApplicationRecord
|
|||||||
has_many :messages, as: :sender, dependent: :nullify
|
has_many :messages, as: :sender, dependent: :nullify
|
||||||
has_many :copilot_threads, dependent: :destroy_async
|
has_many :copilot_threads, dependent: :destroy_async
|
||||||
has_many :scenarios, class_name: 'Captain::Scenario', dependent: :destroy_async
|
has_many :scenarios, class_name: 'Captain::Scenario', dependent: :destroy_async
|
||||||
has_many :conversation_facts, class_name: 'Captain::ConversationFact', dependent: :destroy_async
|
|
||||||
|
|
||||||
store_accessor :config, :temperature, :feature_faq, :feature_memory, :feature_contact_attributes, :product_name
|
store_accessor :config, :temperature, :feature_faq, :feature_memory, :feature_contact_attributes, :product_name
|
||||||
|
|
||||||
|
|||||||
@@ -1,41 +0,0 @@
|
|||||||
# == Schema Information
|
|
||||||
#
|
|
||||||
# Table name: captain_conversation_facts
|
|
||||||
#
|
|
||||||
# id :bigint not null, primary key
|
|
||||||
# captain_handed_off_at :datetime
|
|
||||||
# captain_resolved_at :datetime
|
|
||||||
# csat_rating :integer
|
|
||||||
# csat_submitted_at :datetime
|
|
||||||
# first_captain_message_at :datetime
|
|
||||||
# first_human_reply_after_captain_at :datetime
|
|
||||||
# last_captain_message_at :datetime
|
|
||||||
# reopened_after_captain_resolution_at :datetime
|
|
||||||
# created_at :datetime not null
|
|
||||||
# updated_at :datetime not null
|
|
||||||
# account_id :bigint not null
|
|
||||||
# assistant_id :bigint not null
|
|
||||||
# conversation_id :bigint not null
|
|
||||||
# csat_response_id :bigint
|
|
||||||
# inbox_id :bigint not null
|
|
||||||
#
|
|
||||||
# Indexes
|
|
||||||
#
|
|
||||||
# idx_captain_facts_on_account_assistant_first_message (account_id,assistant_id,first_captain_message_at)
|
|
||||||
# idx_captain_facts_on_account_csat_submitted_at (account_id,csat_submitted_at)
|
|
||||||
# idx_captain_facts_on_account_handed_off_at (account_id,captain_handed_off_at)
|
|
||||||
# idx_captain_facts_on_account_resolved_at (account_id,captain_resolved_at)
|
|
||||||
# index_captain_conversation_facts_on_account_id (account_id)
|
|
||||||
# index_captain_conversation_facts_on_conversation_id (conversation_id) UNIQUE
|
|
||||||
#
|
|
||||||
class Captain::ConversationFact < ApplicationRecord
|
|
||||||
self.table_name = 'captain_conversation_facts'
|
|
||||||
|
|
||||||
belongs_to :account
|
|
||||||
belongs_to :conversation
|
|
||||||
belongs_to :assistant, class_name: 'Captain::Assistant'
|
|
||||||
belongs_to :inbox
|
|
||||||
belongs_to :csat_response, class_name: 'CsatSurveyResponse', optional: true
|
|
||||||
|
|
||||||
validates :conversation_id, uniqueness: true
|
|
||||||
end
|
|
||||||
@@ -13,7 +13,6 @@ module Enterprise::Concerns::Account
|
|||||||
has_many :captain_assistant_responses, dependent: :destroy_async, class_name: 'Captain::AssistantResponse'
|
has_many :captain_assistant_responses, dependent: :destroy_async, class_name: 'Captain::AssistantResponse'
|
||||||
has_many :captain_documents, dependent: :destroy_async, class_name: 'Captain::Document'
|
has_many :captain_documents, dependent: :destroy_async, class_name: 'Captain::Document'
|
||||||
has_many :captain_custom_tools, dependent: :destroy_async, class_name: 'Captain::CustomTool'
|
has_many :captain_custom_tools, dependent: :destroy_async, class_name: 'Captain::CustomTool'
|
||||||
has_many :captain_conversation_facts, dependent: :destroy_async, class_name: 'Captain::ConversationFact'
|
|
||||||
|
|
||||||
has_many :copilot_threads, dependent: :destroy_async
|
has_many :copilot_threads, dependent: :destroy_async
|
||||||
has_many :companies, dependent: :destroy_async
|
has_many :companies, dependent: :destroy_async
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ module Enterprise::Concerns::Article
|
|||||||
{ role: 'system', content: article_to_search_terms_prompt },
|
{ role: 'system', content: article_to_search_terms_prompt },
|
||||||
{ role: 'user', content: "title: #{title} \n description: #{description} \n content: #{content}" }
|
{ role: 'user', content: "title: #{title} \n description: #{description} \n content: #{content}" }
|
||||||
]
|
]
|
||||||
headers = { 'Content-Type' => 'application/json', 'Authorization' => "Bearer #{ENV.fetch('OPENAI_API_KEY', nil)}" }
|
headers = { 'Content-Type' => 'application/json', 'Authorization' => "Bearer #{openai_api_key}" }
|
||||||
body = { model: 'gpt-4o', messages: messages, response_format: { type: 'json_object' } }.to_json
|
body = { model: 'gpt-4o', messages: messages, response_format: { type: 'json_object' } }.to_json
|
||||||
Rails.logger.info "Requesting Chat GPT with body: #{body}"
|
Rails.logger.info "Requesting Chat GPT with body: #{body}"
|
||||||
response = HTTParty.post(openai_api_url, headers: headers, body: body)
|
response = HTTParty.post(openai_api_url, headers: headers, body: body)
|
||||||
@@ -77,8 +77,12 @@ module Enterprise::Concerns::Article
|
|||||||
|
|
||||||
private
|
private
|
||||||
|
|
||||||
|
def openai_api_key
|
||||||
|
InstallationConfig.find_by(name: 'CAPTAIN_OPEN_AI_API_KEY')&.value.presence || raise(I18n.t('captain.api_key_missing'))
|
||||||
|
end
|
||||||
|
|
||||||
def openai_api_url
|
def openai_api_url
|
||||||
endpoint = InstallationConfig.find_by(name: 'CAPTAIN_OPEN_AI_ENDPOINT')&.value || 'https://api.openai.com/'
|
endpoint = InstallationConfig.find_by(name: 'CAPTAIN_OPEN_AI_ENDPOINT')&.value.presence || 'https://api.openai.com/'
|
||||||
endpoint = endpoint.chomp('/')
|
endpoint = endpoint.chomp('/')
|
||||||
"#{endpoint}/v1/chat/completions"
|
"#{endpoint}/v1/chat/completions"
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -7,11 +7,16 @@ module Enterprise::Concerns::Conversation
|
|||||||
has_many :sla_events, dependent: :destroy_async
|
has_many :sla_events, dependent: :destroy_async
|
||||||
has_many :calls, dependent: :destroy_async
|
has_many :calls, dependent: :destroy_async
|
||||||
has_many :captain_responses, class_name: 'Captain::AssistantResponse', dependent: :nullify, as: :documentable
|
has_many :captain_responses, class_name: 'Captain::AssistantResponse', dependent: :nullify, as: :documentable
|
||||||
has_one :captain_conversation_fact, class_name: 'Captain::ConversationFact', dependent: :destroy_async
|
scope :with_sla_applicable_contact, -> { left_joins(:contact).where(contacts: { blocked: [false, nil] }) }
|
||||||
|
|
||||||
before_validation :validate_sla_policy, if: -> { sla_policy_id_changed? }
|
before_validation :validate_sla_policy, if: -> { sla_policy_id_changed? }
|
||||||
around_save :ensure_applied_sla_is_created, if: -> { sla_policy_id_changed? }
|
around_save :ensure_applied_sla_is_created, if: -> { sla_policy_id_changed? }
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def sla_applicable?
|
||||||
|
!contact&.blocked?
|
||||||
|
end
|
||||||
|
|
||||||
private
|
private
|
||||||
|
|
||||||
def validate_sla_policy
|
def validate_sla_policy
|
||||||
@@ -21,6 +26,11 @@ module Enterprise::Concerns::Conversation
|
|||||||
return
|
return
|
||||||
end
|
end
|
||||||
|
|
||||||
|
unless sla_applicable?
|
||||||
|
errors.add(:sla_policy, 'cannot be assigned to conversations with blocked contacts')
|
||||||
|
return
|
||||||
|
end
|
||||||
|
|
||||||
if changes[:sla_policy_id].first.present?
|
if changes[:sla_policy_id].first.present?
|
||||||
errors.add(:sla_policy, 'conversation already has a different sla')
|
errors.add(:sla_policy, 'conversation already has a different sla')
|
||||||
return
|
return
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user