Compare commits
70
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
95aab43e3b | ||
|
|
354c2cab6b | ||
|
|
9c68eed676 | ||
|
|
6d38b4d39c | ||
|
|
fd625981e9 | ||
|
|
49c442751d | ||
|
|
13db36609d | ||
|
|
8b4f3e226e | ||
|
|
2ac55c8728 | ||
|
|
9328f8739c | ||
|
|
3e03f8da1e | ||
|
|
280756b483 | ||
|
|
102f19fe41 | ||
|
|
1b6a80d84d | ||
|
|
9c444315a6 | ||
|
|
df7f137657 | ||
|
|
056b5eb89d | ||
|
|
08260f3be7 | ||
|
|
11c65f3b9a | ||
|
|
8fc5c7a5c8 | ||
|
|
7caa4e0bbc | ||
|
|
9c10fe4eb1 | ||
|
|
6b3800e25b | ||
|
|
b560720e08 | ||
|
|
cc87429903 | ||
|
|
98154bbeab | ||
|
|
03a1b1dbc1 | ||
|
|
848e94bcf2 | ||
|
|
56dc580f50 | ||
|
|
35fcd56ba9 | ||
|
|
d57354c8b5 | ||
|
|
8d2ef4ec5e | ||
|
|
bddb561546 | ||
|
|
20227403ce | ||
|
|
0a13dbedfb | ||
|
|
8d554f2b74 | ||
|
|
4854fb7b4b | ||
|
|
66cfb26c77 | ||
|
|
b9536fb8ed | ||
|
|
873d16f54c | ||
|
|
d3c588ff10 | ||
|
|
f6c18f5225 | ||
|
|
0e07a27c74 | ||
|
|
ce8c8e9a11 | ||
|
|
29d0b92f1c | ||
|
|
a5fcecb3f6 | ||
|
|
1e7218d439 | ||
|
|
c8bfbadae2 | ||
|
|
83dda621c5 | ||
|
|
eab859cd04 | ||
|
|
b823764199 | ||
|
|
397ac2e18a | ||
|
|
5f397db19b | ||
|
|
ce178cd3fe | ||
|
|
1f35360ecb | ||
|
|
4a0933aaf6 | ||
|
|
11deffdd5d | ||
|
|
f5ba24a9c5 | ||
|
|
4c25024f74 | ||
|
|
98592b6e62 | ||
|
|
0848c40c0f | ||
|
|
7ec4468af2 | ||
|
|
14d7df5e50 | ||
|
|
26691aa9ed | ||
|
|
210ab45c8e | ||
|
|
f208af126d | ||
|
|
1c5ebcea0c | ||
|
|
50b373c151 | ||
|
|
ffa9e45d70 | ||
|
|
81b4d7abfc |
@@ -77,7 +77,8 @@ jobs:
|
||||
|
||||
- node/install:
|
||||
node-version: '24.13'
|
||||
- node/install-pnpm
|
||||
- node/install-pnpm:
|
||||
version: '10.2.0'
|
||||
- node/install-packages:
|
||||
pkg-manager: pnpm
|
||||
override-ci-command: pnpm i
|
||||
@@ -118,7 +119,8 @@ jobs:
|
||||
- checkout
|
||||
- node/install:
|
||||
node-version: '24.13'
|
||||
- node/install-pnpm
|
||||
- node/install-pnpm:
|
||||
version: '10.2.0'
|
||||
- node/install-packages:
|
||||
pkg-manager: pnpm
|
||||
override-ci-command: pnpm i
|
||||
@@ -149,7 +151,8 @@ jobs:
|
||||
- checkout
|
||||
- node/install:
|
||||
node-version: '24.13'
|
||||
- node/install-pnpm
|
||||
- node/install-pnpm:
|
||||
version: '10.2.0'
|
||||
- node/install-packages:
|
||||
pkg-manager: pnpm
|
||||
override-ci-command: pnpm i
|
||||
|
||||
+1
-1
@@ -1030,7 +1030,7 @@ GEM
|
||||
addressable (>= 2.8.0)
|
||||
crack (>= 0.3.2)
|
||||
hashdiff (>= 0.4.0, < 2.0.0)
|
||||
websocket-driver (0.7.7)
|
||||
websocket-driver (0.8.2)
|
||||
base64
|
||||
websocket-extensions (>= 0.1.0)
|
||||
websocket-extensions (0.1.5)
|
||||
|
||||
@@ -2,6 +2,8 @@ class Api::V1::Accounts::AssignableAgentsController < Api::V1::Accounts::BaseCon
|
||||
before_action :fetch_inboxes
|
||||
|
||||
def index
|
||||
# TODO: Remove this opt-in once mobile clients support AgentBot assignees in this payload.
|
||||
@include_agent_bots = params[:include_agent_bots].present?
|
||||
agent_ids = @inboxes.map do |inbox|
|
||||
authorize inbox, :show?
|
||||
member_ids = inbox.members.pluck(:user_id)
|
||||
@@ -10,6 +12,7 @@ class Api::V1::Accounts::AssignableAgentsController < Api::V1::Accounts::BaseCon
|
||||
agent_ids = agent_ids.inject(:&)
|
||||
agents = Current.account.users.where(id: agent_ids)
|
||||
@assignable_agents = (agents + Current.account.administrators).uniq
|
||||
@agent_bots = @include_agent_bots ? AgentBot.accessible_to(Current.account) : []
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
@@ -6,6 +6,7 @@ class Api::V1::Accounts::CallbacksController < Api::V1::Accounts::BaseController
|
||||
page_access_token = params[:page_access_token]
|
||||
page_id = params[:page_id]
|
||||
inbox_name = params[:inbox_name]
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
facebook_channel = Current.account.facebook_pages.create!(
|
||||
page_id: page_id, user_access_token: user_access_token,
|
||||
@@ -15,6 +16,8 @@ class Api::V1::Accounts::CallbacksController < Api::V1::Accounts::BaseController
|
||||
set_instagram_id(page_access_token, facebook_channel)
|
||||
set_avatar(@facebook_inbox, page_id)
|
||||
end
|
||||
rescue CustomExceptions::Inbox::LimitExceeded => e
|
||||
render_error_response(e)
|
||||
rescue StandardError => e
|
||||
ChatwootExceptionTracker.new(e).capture_exception
|
||||
Rails.logger.error "Error in register_facebook_page: #{e.message}"
|
||||
|
||||
@@ -66,6 +66,7 @@ class Api::V1::Accounts::Captain::PreferencesController < Api::V1::Accounts::Bas
|
||||
config = Llm::Models.feature_config(feature_key)
|
||||
route = Llm::FeatureRouter.resolve(feature: feature_key, account: Current.account)
|
||||
config.merge(
|
||||
default: default_model_for(feature_key),
|
||||
enabled: account_features[feature_key] == true,
|
||||
model: route[:model],
|
||||
selected: route[:model],
|
||||
@@ -74,4 +75,10 @@ class Api::V1::Accounts::Captain::PreferencesController < Api::V1::Accounts::Bas
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
def default_model_for(feature_key)
|
||||
return Llm::FeatureRouter::CAPTAIN_V2_ASSISTANT_MODEL if feature_key == 'assistant' && Current.account.feature_enabled?('captain_integration_v2')
|
||||
|
||||
Llm::Models.default_model_for(feature_key)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -6,6 +6,8 @@ class Api::V1::Accounts::Channels::TwilioChannelsController < Api::V1::Accounts:
|
||||
|
||||
def create
|
||||
process_create
|
||||
rescue CustomExceptions::Inbox::LimitExceeded => e
|
||||
render_error_response(e)
|
||||
rescue StandardError => e
|
||||
render_could_not_create_error(e.message)
|
||||
end
|
||||
|
||||
@@ -1,27 +1,40 @@
|
||||
class Api::V1::Accounts::Conversations::ParticipantsController < Api::V1::Accounts::Conversations::BaseController
|
||||
include Events::Types
|
||||
|
||||
def show
|
||||
@participants = @conversation.conversation_participants
|
||||
end
|
||||
|
||||
def create
|
||||
participant_ids_to_add = participants_to_be_added_ids
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
@participants = participants_to_be_added_ids.map { |user_id| @conversation.conversation_participants.find_or_create_by(user_id: user_id) }
|
||||
@participants = participant_ids_to_add.map { |user_id| @conversation.conversation_participants.find_or_create_by(user_id: user_id) }
|
||||
end
|
||||
notify_unread_count_change if participant_ids_to_add.any?
|
||||
end
|
||||
|
||||
def update
|
||||
participant_ids_to_add = participants_to_be_added_ids
|
||||
participant_ids_to_remove = participants_to_be_removed_ids
|
||||
changed_participant_ids = participant_ids_to_add + participant_ids_to_remove
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
participants_to_be_added_ids.each { |user_id| @conversation.conversation_participants.find_or_create_by(user_id: user_id) }
|
||||
participants_to_be_removed_ids.each { |user_id| @conversation.conversation_participants.find_by(user_id: user_id)&.destroy }
|
||||
participant_ids_to_add.each { |user_id| @conversation.conversation_participants.find_or_create_by(user_id: user_id) }
|
||||
participant_ids_to_remove.each { |user_id| @conversation.conversation_participants.find_by(user_id: user_id)&.destroy }
|
||||
end
|
||||
notify_unread_count_change if changed_participant_ids.any?
|
||||
@participants = @conversation.conversation_participants
|
||||
render action: 'show'
|
||||
end
|
||||
|
||||
def destroy
|
||||
participant_ids_to_remove = current_participant_ids & params[:user_ids]
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
params[:user_ids].map { |user_id| @conversation.conversation_participants.find_by(user_id: user_id)&.destroy }
|
||||
end
|
||||
notify_unread_count_change if participant_ids_to_remove.any?
|
||||
head :ok
|
||||
end
|
||||
|
||||
@@ -38,4 +51,11 @@ class Api::V1::Accounts::Conversations::ParticipantsController < Api::V1::Accoun
|
||||
def current_participant_ids
|
||||
@current_participant_ids ||= @conversation.conversation_participants.pluck(:user_id)
|
||||
end
|
||||
|
||||
def notify_unread_count_change
|
||||
return unless Current.account.feature_enabled?('conversation_unread_counts')
|
||||
return unless Current.account.feature_enabled?('unread_count_for_filters')
|
||||
|
||||
Rails.configuration.dispatcher.dispatch(CONVERSATION_UNREAD_COUNT_CHANGED, Time.zone.now, conversation: @conversation)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -2,12 +2,28 @@ class Api::V1::Accounts::Conversations::UnreadCountsController < Api::V1::Accoun
|
||||
before_action :ensure_unread_counts_enabled
|
||||
|
||||
def index
|
||||
counts = ::Conversations::UnreadCounts::Counter.new(account: Current.account, user: Current.user).perform
|
||||
counts = if filtered_unread_counts_enabled?
|
||||
instrumentation.summarize_request(account_id: Current.account.id) { unread_counts }
|
||||
else
|
||||
unread_counts
|
||||
end
|
||||
render json: { payload: counts }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def unread_counts
|
||||
::Conversations::UnreadCounts::Counter.new(account: Current.account, user: Current.user).perform
|
||||
end
|
||||
|
||||
def filtered_unread_counts_enabled?
|
||||
Current.account.feature_enabled?(::Conversations::UnreadCounts::FilteredCounter::FEATURE_FLAG)
|
||||
end
|
||||
|
||||
def instrumentation
|
||||
::Conversations::UnreadCounts::FilteredCountInstrumentation
|
||||
end
|
||||
|
||||
def ensure_unread_counts_enabled
|
||||
return if Current.account.feature_enabled?('conversation_unread_counts')
|
||||
|
||||
|
||||
@@ -164,6 +164,7 @@ class Api::V1::Accounts::ConversationsController < Api::V1::Accounts::BaseContro
|
||||
# rubocop:enable Rails/SkipsModelValidations
|
||||
|
||||
::Conversations::UnreadCounts::Notifier.new(@conversation).perform
|
||||
::Conversations::UnreadCounts::FilteredCountInvalidator.new(Current.account).conversation_changed!
|
||||
end
|
||||
|
||||
def should_update_last_seen?
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
class Api::V1::Accounts::DashboardAppsController < Api::V1::Accounts::BaseController
|
||||
before_action :check_authorization
|
||||
before_action :fetch_dashboard_apps, except: [:create]
|
||||
before_action :fetch_dashboard_app, only: [:show, :update, :destroy]
|
||||
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
require 'csv'
|
||||
|
||||
class Api::V1::Accounts::DataImportsController < Api::V1::Accounts::BaseController
|
||||
DATA_IMPORT_FEATURE = 'data_import'.freeze
|
||||
|
||||
before_action :ensure_data_import_feature_enabled
|
||||
before_action :set_data_import, only: [:show, :start, :abandon, :error_logs, :skip_logs]
|
||||
before_action :check_authorization
|
||||
|
||||
def index
|
||||
@data_imports = policy_scope(Current.account.data_imports).includes(:initiated_by).order(created_at: :desc)
|
||||
data_import_ids = @data_imports.map(&:id)
|
||||
@import_errors_counts = DataImportError.non_skip_logs.where(data_import_id: data_import_ids).group(:data_import_id).count
|
||||
@skip_logs_counts = DataImportError.skip_logs.where(data_import_id: data_import_ids).group(:data_import_id).count
|
||||
end
|
||||
|
||||
def show
|
||||
render_show
|
||||
end
|
||||
|
||||
def validate_source
|
||||
totals = validate_intercom_source
|
||||
render json: { valid: true, totals: totals }
|
||||
rescue DataImports::Intercom::Client::AuthenticationError
|
||||
render_source_validation_error('We could not validate this Intercom access key. Check the key and its permissions.')
|
||||
rescue DataImports::Intercom::Client::Error
|
||||
render_source_validation_error('Intercom could not be reached. Please try again.')
|
||||
rescue ArgumentError => e
|
||||
render_source_validation_error(e.message)
|
||||
end
|
||||
|
||||
def create
|
||||
@data_import = creation_service.perform
|
||||
unless @data_import
|
||||
render json: { message: 'Another data import is already in progress.' }, status: :unprocessable_entity
|
||||
return
|
||||
end
|
||||
|
||||
DataImports::Intercom::ImportJob.perform_later(@data_import, @data_import.active_intercom_import_run_id)
|
||||
render_show
|
||||
rescue DataImports::Intercom::Client::AuthenticationError
|
||||
render_source_validation_error('We could not validate this Intercom access key. Check the key and its permissions.')
|
||||
rescue DataImports::Intercom::Client::Error
|
||||
render_source_validation_error('Intercom could not be reached. Please try again.')
|
||||
rescue ArgumentError => e
|
||||
render_source_validation_error(e.message)
|
||||
end
|
||||
|
||||
def start
|
||||
restart_service = DataImports::Intercom::RestartService.new(account: Current.account, data_import: @data_import)
|
||||
restart_result = restart_service.perform
|
||||
@data_import = restart_service.data_import
|
||||
if restart_result == :access_token_missing
|
||||
render json: { message: 'The Intercom access key for this import is unavailable.' }, status: :unprocessable_entity
|
||||
return
|
||||
end
|
||||
|
||||
DataImports::Intercom::ImportJob.perform_later(@data_import, @data_import.active_intercom_import_run_id) if restart_result == :enqueue
|
||||
render_show
|
||||
end
|
||||
|
||||
def abandon
|
||||
@data_import.abandon!
|
||||
render_show
|
||||
end
|
||||
|
||||
def skip_logs
|
||||
send_data(
|
||||
skip_logs_csv,
|
||||
filename: "data-import-#{@data_import.id}-skip-logs.csv",
|
||||
type: 'text/csv'
|
||||
)
|
||||
end
|
||||
|
||||
def error_logs
|
||||
send_data(
|
||||
error_logs_csv,
|
||||
filename: "data-import-#{@data_import.id}-error-logs.csv",
|
||||
type: 'text/csv'
|
||||
)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def ensure_data_import_feature_enabled
|
||||
raise Pundit::NotAuthorizedError unless Current.account.feature_enabled?(DATA_IMPORT_FEATURE)
|
||||
end
|
||||
|
||||
def set_data_import
|
||||
@data_import = Current.account.data_imports.find(params[:id])
|
||||
end
|
||||
|
||||
def check_authorization
|
||||
authorize(@data_import || DataImport)
|
||||
end
|
||||
|
||||
def permitted_params
|
||||
params.permit(:name, :source_provider, :access_token, import_types: [])
|
||||
end
|
||||
|
||||
def creation_service
|
||||
DataImports::Intercom::CreationService.new(
|
||||
account: Current.account,
|
||||
initiated_by: Current.user,
|
||||
source_params: permitted_params.to_h
|
||||
)
|
||||
end
|
||||
|
||||
def import_types
|
||||
return DataImports::Intercom::Importer::DEFAULT_IMPORT_TYPES unless permitted_params.key?(:import_types)
|
||||
|
||||
Array(permitted_params[:import_types]).compact_blank
|
||||
end
|
||||
|
||||
def validate_intercom_source
|
||||
raise ArgumentError, 'Unsupported import source.' unless permitted_params[:source_provider] == 'intercom'
|
||||
|
||||
DataImports::Intercom::CredentialsValidator.new(
|
||||
access_token: permitted_params[:access_token],
|
||||
import_types: import_types
|
||||
).perform
|
||||
end
|
||||
|
||||
def render_source_validation_error(message)
|
||||
render json: { valid: false, message: message }, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
def render_show
|
||||
@import_errors_finder = DataImportErrorFinder.new(@data_import)
|
||||
@skip_logs_finder = DataImportSkipLogFinder.new(@data_import, params)
|
||||
render :show
|
||||
end
|
||||
|
||||
def skip_logs_csv
|
||||
logs_csv(@data_import.import_errors.skip_logs)
|
||||
end
|
||||
|
||||
def error_logs_csv
|
||||
logs_csv(@data_import.import_errors.non_skip_logs)
|
||||
end
|
||||
|
||||
def logs_csv(logs)
|
||||
CSV.generate(headers: true) do |csv|
|
||||
csv << %w[created_at kind source_object_type source_object_id error_code message details]
|
||||
|
||||
logs.order(:created_at).find_each do |log|
|
||||
csv << [
|
||||
log.created_at.iso8601,
|
||||
log.details['kind'],
|
||||
log.source_object_type,
|
||||
log.source_object_id,
|
||||
log.error_code,
|
||||
log.message,
|
||||
log.details.to_json
|
||||
]
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -2,7 +2,6 @@ class Api::V1::Accounts::InboxesController < Api::V1::Accounts::BaseController
|
||||
include Api::V1::InboxesHelper
|
||||
before_action :fetch_inbox, except: [:index, :create]
|
||||
before_action :fetch_agent_bot, only: [:set_agent_bot]
|
||||
before_action :validate_limit, only: [:create]
|
||||
# we are already handling the authorization in fetch inbox
|
||||
before_action :check_authorization, except: [:show]
|
||||
|
||||
@@ -125,8 +124,8 @@ class Api::V1::Accounts::InboxesController < Api::V1::Accounts::BaseController
|
||||
end
|
||||
|
||||
def reauthorize_and_update_channel(channel_attributes)
|
||||
@inbox.channel.reauthorized! if @inbox.channel.respond_to?(:reauthorized!)
|
||||
@inbox.channel.update!(permitted_params(channel_attributes)[:channel])
|
||||
@inbox.channel.reauthorized! if @inbox.channel.respond_to?(:reauthorized!)
|
||||
end
|
||||
|
||||
def update_channel_feature_flags
|
||||
|
||||
@@ -6,7 +6,10 @@ class Api::V1::Accounts::Microsoft::AuthorizationsController < Api::V1::Accounts
|
||||
{
|
||||
redirect_uri: "#{base_url}/microsoft/callback",
|
||||
scope: scope,
|
||||
state: state
|
||||
state: state,
|
||||
# Force the Microsoft account picker so an already-signed-in account does not
|
||||
# silently authorize and re-bind to an existing inbox in the new-inbox flow.
|
||||
prompt: 'select_account'
|
||||
}
|
||||
)
|
||||
if redirect_url
|
||||
|
||||
@@ -8,8 +8,10 @@ class Api::V1::Accounts::Whatsapp::AuthorizationsController < Api::V1::Accounts:
|
||||
validate_embedded_signup_params!
|
||||
channel = process_embedded_signup
|
||||
render_success_response(channel.inbox)
|
||||
rescue StandardError => e
|
||||
rescue CustomExceptions::Inbox::LimitExceeded => e
|
||||
render_error_response(e)
|
||||
rescue StandardError => e
|
||||
render_embedded_signup_error(e)
|
||||
end
|
||||
|
||||
private
|
||||
@@ -55,7 +57,7 @@ class Api::V1::Accounts::Whatsapp::AuthorizationsController < Api::V1::Accounts:
|
||||
render json: response
|
||||
end
|
||||
|
||||
def render_error_response(error)
|
||||
def render_embedded_signup_error(error)
|
||||
Rails.logger.error "[WHATSAPP AUTHORIZATION] Embedded signup error: #{error.message}"
|
||||
Rails.logger.error error.backtrace.join("\n")
|
||||
render json: {
|
||||
|
||||
@@ -59,6 +59,10 @@ class Api::V1::Widget::BaseController < ApplicationController
|
||||
permitted_params.dig(:contact, :phone_number)
|
||||
end
|
||||
|
||||
def contact_custom_attributes
|
||||
permitted_params.dig(:contact, :custom_attributes)&.to_h
|
||||
end
|
||||
|
||||
def browser_params
|
||||
{
|
||||
browser_name: browser.name,
|
||||
|
||||
@@ -2,6 +2,7 @@ class Api::V1::Widget::ContactsController < Api::V1::Widget::BaseController
|
||||
include WidgetHelper
|
||||
|
||||
before_action :validate_hmac, only: [:set_user]
|
||||
before_action :validate_hmac_for_identified_update, only: [:update]
|
||||
|
||||
def show; end
|
||||
|
||||
@@ -46,6 +47,16 @@ class Api::V1::Widget::ContactsController < Api::V1::Widget::BaseController
|
||||
@contact.identifier.present? && @contact.identifier != permitted_params[:identifier]
|
||||
end
|
||||
|
||||
# The plain update endpoint is also used for anonymous prechat updates
|
||||
# (name/email/phone/custom_attributes with no identifier), which must keep
|
||||
# working on hmac_mandatory inboxes. Only the identity-binding path, where an
|
||||
# identifier is supplied and the contact can be rebound, requires HMAC.
|
||||
def validate_hmac_for_identified_update
|
||||
return if params[:identifier].blank?
|
||||
|
||||
validate_hmac
|
||||
end
|
||||
|
||||
def validate_hmac
|
||||
return unless should_verify_hmac?
|
||||
|
||||
@@ -62,11 +73,15 @@ class Api::V1::Widget::ContactsController < Api::V1::Widget::BaseController
|
||||
end
|
||||
|
||||
def valid_hmac?
|
||||
params[:identifier_hash] == OpenSSL::HMAC.hexdigest(
|
||||
expected_hash = OpenSSL::HMAC.hexdigest(
|
||||
'sha256',
|
||||
@web_widget.hmac_token,
|
||||
params[:identifier].to_s
|
||||
)
|
||||
identifier_hash = params[:identifier_hash].to_s
|
||||
return false unless identifier_hash.bytesize == expected_hash.bytesize
|
||||
|
||||
ActiveSupport::SecurityUtils.secure_compare(identifier_hash, expected_hash)
|
||||
end
|
||||
|
||||
def permitted_params
|
||||
|
||||
@@ -19,7 +19,7 @@ class Api::V1::Widget::ConversationsController < Api::V1::Widget::BaseController
|
||||
def process_update_contact
|
||||
@contact = ContactIdentifyAction.new(
|
||||
contact: @contact,
|
||||
params: { email: contact_email, phone_number: contact_phone_number, name: contact_name },
|
||||
params: { email: contact_email, phone_number: contact_phone_number, name: contact_name, custom_attributes: contact_custom_attributes },
|
||||
retain_original_contact_name: true,
|
||||
discard_invalid_attrs: true
|
||||
).perform
|
||||
@@ -95,7 +95,7 @@ class Api::V1::Widget::ConversationsController < Api::V1::Widget::BaseController
|
||||
end
|
||||
|
||||
def permitted_params
|
||||
params.permit(:id, :typing_status, :website_token, :email, contact: [:name, :email, :phone_number],
|
||||
params.permit(:id, :typing_status, :website_token, :email, contact: [:name, :email, :phone_number, { custom_attributes: {} }],
|
||||
message: [:content, :referer_url, :timestamp, :echo_id],
|
||||
custom_attributes: {})
|
||||
end
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
module RequestExceptionHandler
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
QUERY_CANCELED_ERROR_MESSAGE_PATTERNS = [
|
||||
'ActiveRecord::QueryCanceled',
|
||||
'PG::QueryCanceled',
|
||||
'canceling statement due to statement timeout'
|
||||
].freeze
|
||||
|
||||
included do
|
||||
rescue_from ActiveRecord::RecordInvalid, with: :render_record_invalid
|
||||
rescue_from CustomExceptions::Inbox::LimitExceeded, with: :render_error_response
|
||||
end
|
||||
|
||||
private
|
||||
@@ -18,6 +25,9 @@ module RequestExceptionHandler
|
||||
rescue ActionController::ParameterMissing => e
|
||||
log_handled_error(e)
|
||||
render_could_not_create_error(e.message)
|
||||
rescue ActiveRecord::QueryCanceled => e
|
||||
log_handled_error(e)
|
||||
render_could_not_create_error(database_query_canceled_message)
|
||||
ensure
|
||||
# to address the thread variable leak issues in Puma/Thin webserver
|
||||
Current.reset
|
||||
@@ -31,8 +41,8 @@ module RequestExceptionHandler
|
||||
render json: { error: message }, status: :not_found
|
||||
end
|
||||
|
||||
def render_could_not_create_error(message)
|
||||
render json: { error: message }, status: :unprocessable_entity
|
||||
def render_could_not_create_error(error)
|
||||
render json: { error: sanitized_error_message(error) }, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
def render_payment_required(message)
|
||||
@@ -59,4 +69,19 @@ module RequestExceptionHandler
|
||||
def log_handled_error(exception)
|
||||
logger.info("Handled error: #{exception.inspect}")
|
||||
end
|
||||
|
||||
def sanitized_error_message(message)
|
||||
return database_query_canceled_message if database_query_canceled_message?(message)
|
||||
|
||||
message
|
||||
end
|
||||
|
||||
def database_query_canceled_message?(message)
|
||||
error_message = message.to_s
|
||||
QUERY_CANCELED_ERROR_MESSAGE_PATTERNS.any? { |pattern| error_message.include?(pattern) }
|
||||
end
|
||||
|
||||
def database_query_canceled_message
|
||||
I18n.t('errors.database.query_canceled')
|
||||
end
|
||||
end
|
||||
|
||||
@@ -11,6 +11,8 @@ class Instagram::CallbacksController < ApplicationController
|
||||
end
|
||||
|
||||
process_successful_authorization
|
||||
rescue CustomExceptions::Inbox::LimitExceeded => e
|
||||
handle_limit_error(e)
|
||||
rescue StandardError => e
|
||||
handle_error(e)
|
||||
end
|
||||
@@ -47,6 +49,14 @@ class Instagram::CallbacksController < ApplicationController
|
||||
redirect_to_error_page(error_info)
|
||||
end
|
||||
|
||||
def handle_limit_error(error)
|
||||
redirect_to_error_page(
|
||||
'error_type' => error.class.name,
|
||||
'code' => Rack::Utils.status_code(error.http_status),
|
||||
'error_message' => error.message
|
||||
)
|
||||
end
|
||||
|
||||
# Extract error details from the exception
|
||||
def extract_error_info(error)
|
||||
if error.is_a?(OAuth2::Error)
|
||||
|
||||
@@ -18,7 +18,8 @@ class Public::Api::V1::Inboxes::ContactsController < Public::Api::V1::InboxesCon
|
||||
contact: @contact_inbox.contact,
|
||||
params: permitted_params.to_h.deep_symbolize_keys.except(:identifier)
|
||||
)
|
||||
render json: contact_identify_action.perform
|
||||
contact_identify_action.perform
|
||||
@contact_inbox.reload
|
||||
end
|
||||
|
||||
private
|
||||
@@ -35,11 +36,15 @@ class Public::Api::V1::Inboxes::ContactsController < Public::Api::V1::InboxesCon
|
||||
end
|
||||
|
||||
def valid_hmac?
|
||||
params[:identifier_hash] == OpenSSL::HMAC.hexdigest(
|
||||
expected_hash = OpenSSL::HMAC.hexdigest(
|
||||
'sha256',
|
||||
@inbox_channel.hmac_token,
|
||||
params[:identifier].to_s
|
||||
)
|
||||
identifier_hash = params[:identifier_hash].to_s
|
||||
return false unless identifier_hash.bytesize == expected_hash.bytesize
|
||||
|
||||
ActiveSupport::SecurityUtils.secure_compare(identifier_hash, expected_hash)
|
||||
end
|
||||
|
||||
def permitted_params
|
||||
|
||||
@@ -6,6 +6,8 @@ class Tiktok::CallbacksController < ApplicationController
|
||||
return handle_ungranted_scopes_error unless all_scopes_granted?
|
||||
|
||||
process_successful_authorization
|
||||
rescue CustomExceptions::Inbox::LimitExceeded => e
|
||||
handle_limit_error(e)
|
||||
rescue StandardError => e
|
||||
handle_error(e)
|
||||
end
|
||||
@@ -36,6 +38,14 @@ class Tiktok::CallbacksController < ApplicationController
|
||||
redirect_to_error_page(error_type: error.class.name, code: 500, error_message: error.message)
|
||||
end
|
||||
|
||||
def handle_limit_error(error)
|
||||
redirect_to_error_page(
|
||||
error_type: error.class.name,
|
||||
code: Rack::Utils.status_code(error.http_status),
|
||||
error_message: error.message
|
||||
)
|
||||
end
|
||||
|
||||
# Handles the case when a user denies permissions or cancels the authorization flow
|
||||
def handle_authorization_error
|
||||
redirect_to_error_page(
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
class DataImportErrorFinder
|
||||
RESULTS_LIMIT = 5
|
||||
|
||||
def initialize(data_import)
|
||||
@data_import = data_import
|
||||
end
|
||||
|
||||
def import_errors
|
||||
@data_import.import_errors.non_skip_logs.order(created_at: :desc).limit(RESULTS_LIMIT)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,35 @@
|
||||
class DataImportSkipLogFinder
|
||||
RESULTS_LIMIT = 5
|
||||
SOURCE_OBJECT_TYPES = %w[contact conversation message].freeze
|
||||
|
||||
attr_reader :selected_source_object_type
|
||||
|
||||
def initialize(data_import, params = {})
|
||||
@data_import = data_import
|
||||
@selected_source_object_type = valid_source_object_type(params[:skip_logs_type])
|
||||
end
|
||||
|
||||
def skip_logs
|
||||
filtered_scope.order(created_at: :desc).limit(RESULTS_LIMIT)
|
||||
end
|
||||
|
||||
def counts_by_type
|
||||
base_scope.group(:source_object_type).count
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def base_scope
|
||||
@base_scope ||= @data_import.import_errors.skip_logs
|
||||
end
|
||||
|
||||
def filtered_scope
|
||||
return base_scope if selected_source_object_type.blank?
|
||||
|
||||
base_scope.where(source_object_type: selected_source_object_type)
|
||||
end
|
||||
|
||||
def valid_source_object_type(source_object_type)
|
||||
source_object_type if SOURCE_OBJECT_TYPES.include?(source_object_type)
|
||||
end
|
||||
end
|
||||
@@ -114,10 +114,4 @@ module Api::V1::InboxesHelper
|
||||
'sms' => Current.account.sms_channels
|
||||
}[permitted_params[:channel][:type]]
|
||||
end
|
||||
|
||||
def validate_limit
|
||||
return unless Current.account.inboxes.count >= Current.account.usage_limits[:inboxes]
|
||||
|
||||
render_payment_required('Account limit exceeded. Upgrade to a higher plan')
|
||||
end
|
||||
end
|
||||
|
||||
@@ -22,4 +22,16 @@ module BillingHelper
|
||||
def agents(account)
|
||||
account.users.count
|
||||
end
|
||||
|
||||
# current_period_end moved to the subscription item in newer Stripe API versions; read both.
|
||||
def subscription_period_end(subscription)
|
||||
subscription['current_period_end'] || subscription['items']['data'].first&.[]('current_period_end')
|
||||
end
|
||||
|
||||
def subscription_ends_on(subscription)
|
||||
period_end = subscription_period_end(subscription)
|
||||
return if period_end.blank?
|
||||
|
||||
Time.zone.at(period_end)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -68,6 +68,8 @@ module Filters::FilterHelper
|
||||
when 'text_case_insensitive'
|
||||
text_case_insensitive_filter(query_hash, filter_operator_value)
|
||||
else
|
||||
return text_cast_filter(query_hash, filter_operator_value) if text_search_on_display_id?(query_hash)
|
||||
|
||||
default_filter(query_hash, filter_operator_value)
|
||||
end
|
||||
end
|
||||
@@ -82,10 +84,18 @@ module Filters::FilterHelper
|
||||
"#{filter_operator_value} #{query_hash[:query_operator]}"
|
||||
end
|
||||
|
||||
def text_cast_filter(query_hash, filter_operator_value)
|
||||
"(#{filter_config[:table_name]}.#{query_hash[:attribute_key]})::text #{filter_operator_value} #{query_hash[:query_operator]}"
|
||||
end
|
||||
|
||||
def default_filter(query_hash, filter_operator_value)
|
||||
"#{filter_config[:table_name]}.#{query_hash[:attribute_key]} #{filter_operator_value} #{query_hash[:query_operator]}"
|
||||
end
|
||||
|
||||
def text_search_on_display_id?(query_hash)
|
||||
query_hash[:attribute_key] == 'display_id' && %w[contains does_not_contain].include?(query_hash[:filter_operator])
|
||||
end
|
||||
|
||||
def validate_single_condition(condition)
|
||||
return if condition['query_operator'].nil?
|
||||
return if condition['query_operator'].empty?
|
||||
|
||||
@@ -6,9 +6,12 @@ class AssignableAgents extends ApiClient {
|
||||
super('assignable_agents', { accountScoped: true });
|
||||
}
|
||||
|
||||
get(inboxIds) {
|
||||
get(inboxIds, { includeAgentBots = false } = {}) {
|
||||
return axios.get(this.url, {
|
||||
params: { inbox_ids: inboxIds },
|
||||
params: {
|
||||
inbox_ids: inboxIds,
|
||||
...(includeAgentBots ? { include_agent_bots: true } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
/* global axios */
|
||||
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 {
|
||||
constructor() {
|
||||
super('captain/assistants', { accountScoped: true });
|
||||
@@ -21,6 +25,32 @@ class CaptainAssistant extends ApiClient {
|
||||
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() },
|
||||
});
|
||||
}
|
||||
|
||||
getDrilldown({ assistantId, metric, range, page, signal }) {
|
||||
const requestConfig = {
|
||||
params: {
|
||||
metric,
|
||||
range,
|
||||
timezone_offset: getTimezoneOffset(),
|
||||
page,
|
||||
},
|
||||
};
|
||||
if (signal) requestConfig.signal = signal;
|
||||
|
||||
return axios.get(`${this.url}/${assistantId}/drilldown`, requestConfig);
|
||||
}
|
||||
}
|
||||
|
||||
export default new CaptainAssistant();
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
/* global axios */
|
||||
|
||||
import ApiClient from './ApiClient';
|
||||
|
||||
class DataImportsAPI extends ApiClient {
|
||||
constructor() {
|
||||
super('data_imports', { accountScoped: true });
|
||||
}
|
||||
|
||||
start(id) {
|
||||
return axios.post(`${this.url}/${id}/start`);
|
||||
}
|
||||
|
||||
abandon(id) {
|
||||
return axios.post(`${this.url}/${id}/abandon`);
|
||||
}
|
||||
|
||||
show(id, params = {}) {
|
||||
return axios.get(`${this.url}/${id}`, { params });
|
||||
}
|
||||
|
||||
validateSource(payload) {
|
||||
return axios.post(`${this.url}/validate_source`, payload);
|
||||
}
|
||||
|
||||
downloadSkipLogs(id) {
|
||||
return axios.get(`${this.url}/${id}/skip_logs.csv`, {
|
||||
responseType: 'blob',
|
||||
});
|
||||
}
|
||||
|
||||
downloadErrorLogs(id) {
|
||||
return axios.get(`${this.url}/${id}/error_logs.csv`, {
|
||||
responseType: 'blob',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default new DataImportsAPI();
|
||||
@@ -14,6 +14,10 @@ class EnterpriseAccountAPI extends ApiClient {
|
||||
return axios.post(`${this.url}subscription`);
|
||||
}
|
||||
|
||||
selectBillingCurrency(currency) {
|
||||
return axios.post(`${this.url}select_billing_currency`, { currency });
|
||||
}
|
||||
|
||||
getLimits() {
|
||||
return axios.get(`${this.url}limits`);
|
||||
}
|
||||
@@ -27,6 +31,11 @@ class EnterpriseAccountAPI extends ApiClient {
|
||||
createTopupCheckout(credits) {
|
||||
return axios.post(`${this.url}topup_checkout`, { credits });
|
||||
}
|
||||
|
||||
// Topup packages for the account's billing currency.
|
||||
getTopupOptions() {
|
||||
return axios.get(`${this.url}topup_options`);
|
||||
}
|
||||
}
|
||||
|
||||
export default new EnterpriseAccountAPI();
|
||||
|
||||
@@ -62,9 +62,10 @@ class ConversationApi extends ApiClient {
|
||||
});
|
||||
}
|
||||
|
||||
assignAgent({ conversationId, agentId }) {
|
||||
assignAgent({ conversationId, agentId, assigneeType }) {
|
||||
return axios.post(`${this.url}/${conversationId}/assignments`, {
|
||||
assignee_id: agentId,
|
||||
assignee_type: assigneeType,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -26,5 +26,15 @@ describe('#AssignableAgentsAPI', () => {
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('#getAssignableAgents with agent bots', () => {
|
||||
assignableAgentsAPI.get([1], { includeAgentBots: true });
|
||||
expect(axiosMock.get).toHaveBeenCalledWith('/api/v1/assignable_agents', {
|
||||
params: {
|
||||
inbox_ids: [1],
|
||||
include_agent_bots: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -90,11 +90,16 @@ describe('#ConversationAPI', () => {
|
||||
});
|
||||
|
||||
it('#assignAgent', () => {
|
||||
conversationAPI.assignAgent({ conversationId: 12, agentId: 34 });
|
||||
conversationAPI.assignAgent({
|
||||
conversationId: 12,
|
||||
agentId: 34,
|
||||
assigneeType: 'AgentBot',
|
||||
});
|
||||
expect(axiosMock.post).toHaveBeenCalledWith(
|
||||
`/api/v1/conversations/12/assignments`,
|
||||
{
|
||||
assignee_id: 34,
|
||||
assignee_type: 'AgentBot',
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
@@ -61,10 +61,10 @@ const triggerAction = () => {
|
||||
<div>
|
||||
<slot />
|
||||
</div>
|
||||
<div>
|
||||
<div class="flex-shrink-0">
|
||||
<button
|
||||
v-if="actionLabel"
|
||||
class="px-3 py-1 w-auto grid place-content-center rounded-lg"
|
||||
class="px-3 py-1 w-auto grid place-content-center rounded-lg whitespace-nowrap"
|
||||
:class="buttonClass"
|
||||
@click="triggerAction"
|
||||
>
|
||||
|
||||
@@ -182,7 +182,8 @@ const handleCreateAssistant = () => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2">
|
||||
<div class="flex items-center gap-2">
|
||||
<slot name="headerActions" />
|
||||
<slot name="search" />
|
||||
<div
|
||||
v-if="!showPaywall && buttonLabel"
|
||||
|
||||
@@ -107,6 +107,7 @@ const onClickCancel = () => {
|
||||
|
||||
<TextArea
|
||||
v-model="state.description"
|
||||
:max-length="500"
|
||||
:label="
|
||||
t('CAPTAIN.ASSISTANTS.SCENARIOS.ADD.NEW.FORM.DESCRIPTION.LABEL')
|
||||
"
|
||||
|
||||
@@ -66,6 +66,10 @@ const props = defineProps({
|
||||
type: Number,
|
||||
default: null,
|
||||
},
|
||||
responsesCount: {
|
||||
type: Number,
|
||||
default: 0,
|
||||
},
|
||||
isSelected: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
@@ -112,10 +116,10 @@ const showSyncStatus = computed(() => !isPdf.value);
|
||||
const menuItems = computed(() => {
|
||||
const allOptions = [
|
||||
{
|
||||
label: t('CAPTAIN.DOCUMENTS.OPTIONS.VIEW_RELATED_RESPONSES'),
|
||||
value: 'viewRelatedQuestions',
|
||||
action: 'viewRelatedQuestions',
|
||||
icon: 'i-ph-tree-view-duotone',
|
||||
label: t('CAPTAIN.DOCUMENTS.OPTIONS.VIEW_DETAILS'),
|
||||
value: 'viewDetails',
|
||||
action: 'viewDetails',
|
||||
icon: 'i-lucide-eye',
|
||||
},
|
||||
];
|
||||
|
||||
@@ -143,6 +147,9 @@ const menuItems = computed(() => {
|
||||
});
|
||||
|
||||
const createdAtLabel = computed(() => dynamicTime(props.createdAt));
|
||||
const responsesCountLabel = computed(() =>
|
||||
t('CAPTAIN.DOCUMENTS.FAQ_COUNT', { n: props.responsesCount })
|
||||
);
|
||||
|
||||
const displayLink = computed(() =>
|
||||
isPdf.value
|
||||
@@ -158,6 +165,10 @@ const handleAction = ({ action, value }) => {
|
||||
emit('action', { action, value, id: props.id });
|
||||
};
|
||||
|
||||
const handleViewDetails = () => {
|
||||
emit('action', { action: 'viewDetails', id: props.id });
|
||||
};
|
||||
|
||||
const handleRetry = () => {
|
||||
emit('action', { action: 'sync', id: props.id });
|
||||
};
|
||||
@@ -177,9 +188,13 @@ const handleRetry = () => {
|
||||
<Checkbox v-model="modelValue" />
|
||||
</div>
|
||||
<div class="flex gap-1 justify-between w-full">
|
||||
<span class="text-base text-n-slate-12 line-clamp-1">
|
||||
<button
|
||||
type="button"
|
||||
class="p-0 text-base text-left bg-transparent border-0 outline-transparent text-n-slate-12 line-clamp-1 underline-offset-2 hover:underline focus-visible:underline"
|
||||
@click="handleViewDetails"
|
||||
>
|
||||
{{ name }}
|
||||
</span>
|
||||
</button>
|
||||
<div v-if="showMenu" class="flex gap-2 items-center">
|
||||
<div
|
||||
v-on-clickaway="() => toggleDropdown(false)"
|
||||
@@ -228,6 +243,9 @@ const handleRetry = () => {
|
||||
<Icon :icon="linkIcon" class="shrink-0" />
|
||||
<span class="truncate">{{ displayLink }}</span>
|
||||
</span>
|
||||
<span class="text-sm shrink-0 text-n-slate-11">
|
||||
{{ responsesCountLabel }}
|
||||
</span>
|
||||
<DocumentSyncStatus
|
||||
v-if="showSyncStatus"
|
||||
:status="syncStatus"
|
||||
|
||||
@@ -213,6 +213,7 @@ const renderInstruction = instruction => () =>
|
||||
|
||||
<TextArea
|
||||
v-model="state.description"
|
||||
:max-length="500"
|
||||
:label="
|
||||
t('CAPTAIN.ASSISTANTS.SCENARIOS.ADD.NEW.FORM.DESCRIPTION.LABEL')
|
||||
"
|
||||
|
||||
+1
@@ -122,6 +122,7 @@ watch(
|
||||
|
||||
<Editor
|
||||
v-model="state.description"
|
||||
:max-length="500"
|
||||
:label="t('CAPTAIN.ASSISTANTS.FORM.DESCRIPTION.LABEL')"
|
||||
:placeholder="t('CAPTAIN.ASSISTANTS.FORM.DESCRIPTION.PLACEHOLDER')"
|
||||
:message="formErrors.description"
|
||||
|
||||
+1
@@ -117,6 +117,7 @@ watch(
|
||||
|
||||
<Editor
|
||||
v-model="state.description"
|
||||
:max-length="500"
|
||||
:label="t('CAPTAIN.ASSISTANTS.FORM.DESCRIPTION.LABEL')"
|
||||
:placeholder="t('CAPTAIN.ASSISTANTS.FORM.DESCRIPTION.PLACEHOLDER')"
|
||||
:message="formErrors.description"
|
||||
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
import { flushPromises, shallowMount } from '@vue/test-utils';
|
||||
import DocumentDetails from './DocumentDetails.vue';
|
||||
|
||||
const { dispatch, getterValues } = vi.hoisted(() => ({
|
||||
dispatch: vi.fn(),
|
||||
getterValues: {
|
||||
'captainResponses/getUIFlags': { value: { fetchingList: false } },
|
||||
'captainResponses/getRecords': { value: [] },
|
||||
'captainResponses/getMeta': { value: { totalCount: 26, page: 1 } },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('dashboard/composables/store', () => ({
|
||||
useStore: () => ({ dispatch }),
|
||||
useMapGetter: key => getterValues[key],
|
||||
}));
|
||||
|
||||
vi.mock('dashboard/composables', () => ({ useAlert: vi.fn() }));
|
||||
|
||||
vi.mock('vue-i18n', () => ({
|
||||
useI18n: () => ({ t: key => key }),
|
||||
}));
|
||||
|
||||
const captainDocument = {
|
||||
id: 42,
|
||||
name: 'FAQ source',
|
||||
external_link: 'https://example.com/docs',
|
||||
assistant: { id: 7 },
|
||||
content: 'Document content',
|
||||
pdf_document: false,
|
||||
};
|
||||
|
||||
const DialogStub = {
|
||||
name: 'Dialog',
|
||||
template: '<div><slot /></div>',
|
||||
};
|
||||
|
||||
const TabBarStub = {
|
||||
name: 'TabBar',
|
||||
template:
|
||||
'<button data-test="faq-tab" @click="$emit(\'tabChanged\', { key: \'faqs\' })" />',
|
||||
};
|
||||
|
||||
const PaginationFooterStub = {
|
||||
name: 'PaginationFooter',
|
||||
template:
|
||||
'<button data-test="next-page" @click="$emit(\'update:currentPage\', 2)" />',
|
||||
};
|
||||
|
||||
describe('DocumentDetails', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
dispatch.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
it('requests another FAQ page when the document has more than 25 FAQs', async () => {
|
||||
const wrapper = shallowMount(DocumentDetails, {
|
||||
props: { captainDocument },
|
||||
global: {
|
||||
directives: { dompurifyHtml: {} },
|
||||
stubs: {
|
||||
Dialog: DialogStub,
|
||||
TabBar: TabBarStub,
|
||||
PaginationFooter: PaginationFooterStub,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await flushPromises();
|
||||
|
||||
expect(dispatch).toHaveBeenCalledWith('captainResponses/get', {
|
||||
page: 1,
|
||||
assistantId: 7,
|
||||
documentId: 42,
|
||||
});
|
||||
|
||||
await wrapper.get('[data-test="faq-tab"]').trigger('click');
|
||||
await wrapper.get('[data-test="next-page"]').trigger('click');
|
||||
|
||||
expect(dispatch).toHaveBeenLastCalledWith('captainResponses/get', {
|
||||
page: 2,
|
||||
assistantId: 7,
|
||||
documentId: 42,
|
||||
});
|
||||
});
|
||||
});
|
||||
+374
@@ -0,0 +1,374 @@
|
||||
<script setup>
|
||||
import { ref, computed, onMounted } from 'vue';
|
||||
import { useStore, useMapGetter } from 'dashboard/composables/store';
|
||||
import { useAlert } from 'dashboard/composables';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { messageTimestamp } from 'shared/helpers/timeHelper';
|
||||
import { copyTextToClipboard } from 'shared/helpers/clipboard';
|
||||
import MessageFormatter from 'shared/helpers/MessageFormatter';
|
||||
import {
|
||||
isSafeHttpLink,
|
||||
formatDocumentLink,
|
||||
getDocumentDisplayPath,
|
||||
} from 'shared/helpers/documentHelper';
|
||||
import Spinner from 'dashboard/components-next/spinner/Spinner.vue';
|
||||
import Dialog from 'dashboard/components-next/dialog/Dialog.vue';
|
||||
import Icon from 'dashboard/components-next/icon/Icon.vue';
|
||||
import Button from 'dashboard/components-next/button/Button.vue';
|
||||
import TabBar from 'dashboard/components-next/tabbar/TabBar.vue';
|
||||
import PaginationFooter from 'dashboard/components-next/pagination/PaginationFooter.vue';
|
||||
import ResponseCard from '../../assistant/ResponseCard.vue';
|
||||
|
||||
const props = defineProps({
|
||||
captainDocument: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
});
|
||||
const emit = defineEmits(['close']);
|
||||
const TAB_KEYS = {
|
||||
CONTENT: 'content',
|
||||
FAQS: 'faqs',
|
||||
};
|
||||
const RESPONSES_PER_PAGE = 25;
|
||||
const { t } = useI18n();
|
||||
const store = useStore();
|
||||
const dialogRef = ref(null);
|
||||
const documentDetails = computed(() => props.captainDocument);
|
||||
const showRawContent = ref(false);
|
||||
const activeTabIndex = ref(0);
|
||||
|
||||
const uiFlags = useMapGetter('captainResponses/getUIFlags');
|
||||
const responses = useMapGetter('captainResponses/getRecords');
|
||||
const meta = useMapGetter('captainResponses/getMeta');
|
||||
const isFetching = computed(() => uiFlags.value.fetchingList);
|
||||
const totalCount = computed(() => meta.value.totalCount || 0);
|
||||
const currentPage = computed(() => meta.value.page || 1);
|
||||
const showPaginationFooter = computed(
|
||||
() => totalCount.value > RESPONSES_PER_PAGE
|
||||
);
|
||||
const documentContent = computed(() => documentDetails.value?.content?.trim());
|
||||
const documentContentLength = computed(
|
||||
() => documentContent.value?.length || 0
|
||||
);
|
||||
const isPdf = computed(() => documentDetails.value?.pdf_document);
|
||||
const displayUrl = computed(() => documentDetails.value?.display_url);
|
||||
const externalLink = computed(() => documentDetails.value?.external_link);
|
||||
const sourceHref = computed(() => displayUrl.value || externalLink.value);
|
||||
const hasSafeLink = computed(() => isSafeHttpLink(sourceHref.value));
|
||||
const displayLink = computed(() => {
|
||||
if (isPdf.value) return formatDocumentLink(externalLink.value);
|
||||
return getDocumentDisplayPath(displayUrl.value || externalLink.value);
|
||||
});
|
||||
const contentTabLabel = computed(() =>
|
||||
isPdf.value
|
||||
? t('CAPTAIN.DOCUMENTS.DETAILS.PDF_TAB')
|
||||
: t('CAPTAIN.DOCUMENTS.DETAILS.CONTENT_TAB')
|
||||
);
|
||||
const tabs = computed(() => [
|
||||
{ key: TAB_KEYS.CONTENT, label: contentTabLabel.value },
|
||||
{
|
||||
key: TAB_KEYS.FAQS,
|
||||
label: t('CAPTAIN.DOCUMENTS.RELATED_RESPONSES.TITLE'),
|
||||
count: totalCount.value,
|
||||
},
|
||||
]);
|
||||
const activeTabKey = computed(() => tabs.value[activeTabIndex.value]?.key);
|
||||
const isUnreadableContent = computed(() => {
|
||||
if (!documentContent.value) return false;
|
||||
|
||||
const content = documentContent.value;
|
||||
const sample = content.slice(0, 2000);
|
||||
const characters = Array.from(sample);
|
||||
const nonPrintableCharacters = characters.filter(character => {
|
||||
const charCode = character.charCodeAt(0);
|
||||
return (
|
||||
(charCode <= 31 && ![9, 10, 13].includes(charCode)) ||
|
||||
(charCode >= 127 && charCode <= 159)
|
||||
);
|
||||
});
|
||||
const nonPrintableRatio =
|
||||
nonPrintableCharacters.length / Math.max(characters.length, 1);
|
||||
const replacementCharacterRatio =
|
||||
characters.filter(character => character === '\uFFFD').length /
|
||||
Math.max(characters.length, 1);
|
||||
const hasPdfObjectMarkers =
|
||||
content.includes(' obj') &&
|
||||
content.includes(' endobj') &&
|
||||
content.includes(' stream');
|
||||
|
||||
return (
|
||||
content.startsWith('%PDF') ||
|
||||
hasPdfObjectMarkers ||
|
||||
nonPrintableRatio > 0.02 ||
|
||||
replacementCharacterRatio > 0.05
|
||||
);
|
||||
});
|
||||
const formattedDocumentContent = computed(() => {
|
||||
if (!documentContent.value || isUnreadableContent.value) return '';
|
||||
|
||||
const formatter = new MessageFormatter(documentContent.value);
|
||||
formatter.disableImageRendering();
|
||||
return formatter.formattedMessage;
|
||||
});
|
||||
const updatedAtLabel = computed(() => {
|
||||
if (!documentDetails.value?.updated_at) return null;
|
||||
return messageTimestamp(
|
||||
documentDetails.value.updated_at,
|
||||
'MMM d, yyyy h:mm a'
|
||||
);
|
||||
});
|
||||
const syncedAtLabel = computed(() => {
|
||||
if (!documentDetails.value?.last_synced_at) return null;
|
||||
return messageTimestamp(
|
||||
documentDetails.value.last_synced_at,
|
||||
'MMM d, yyyy h:mm a'
|
||||
);
|
||||
});
|
||||
|
||||
const handleClose = () => {
|
||||
emit('close');
|
||||
};
|
||||
|
||||
const handleCopyContent = async () => {
|
||||
try {
|
||||
await copyTextToClipboard(documentContent.value);
|
||||
useAlert(t('CAPTAIN.DOCUMENTS.DETAILS.COPY_SUCCESS'));
|
||||
} catch {
|
||||
useAlert(t('CAPTAIN.DOCUMENTS.DETAILS.COPY_ERROR'));
|
||||
}
|
||||
};
|
||||
|
||||
const handleTabChanged = tab => {
|
||||
activeTabIndex.value = tabs.value.findIndex(item => item.key === tab.key);
|
||||
};
|
||||
|
||||
const fetchResponses = (page = 1) => {
|
||||
return store.dispatch('captainResponses/get', {
|
||||
page,
|
||||
assistantId: props.captainDocument.assistant.id,
|
||||
documentId: props.captainDocument.id,
|
||||
});
|
||||
};
|
||||
|
||||
const handlePageChange = page => {
|
||||
fetchResponses(page);
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
fetchResponses();
|
||||
});
|
||||
defineExpose({ dialogRef });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog
|
||||
ref="dialogRef"
|
||||
type="edit"
|
||||
:title="documentDetails.name || documentDetails.external_link"
|
||||
:description="t('CAPTAIN.DOCUMENTS.DETAILS.DESCRIPTION')"
|
||||
:show-cancel-button="false"
|
||||
:show-confirm-button="false"
|
||||
overflow-y-auto
|
||||
width="3xl"
|
||||
@close="handleClose"
|
||||
>
|
||||
<div
|
||||
v-if="isFetching"
|
||||
class="flex items-center justify-center py-10 text-n-slate-11"
|
||||
>
|
||||
<Spinner />
|
||||
</div>
|
||||
<div v-else class="flex flex-col gap-6 min-h-48">
|
||||
<section class="flex flex-col gap-3">
|
||||
<div class="grid grid-cols-1 gap-3 sm:grid-cols-3">
|
||||
<div class="flex flex-col gap-1">
|
||||
<span class="text-xs font-medium uppercase text-n-slate-10">
|
||||
{{ t('CAPTAIN.DOCUMENTS.DETAILS.SOURCE') }}
|
||||
</span>
|
||||
<a
|
||||
v-if="hasSafeLink"
|
||||
:href="sourceHref"
|
||||
:title="sourceHref"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="inline-flex items-center min-w-0 gap-1 text-sm text-n-slate-12 hover:underline"
|
||||
>
|
||||
<Icon icon="i-lucide-external-link" class="size-3 shrink-0" />
|
||||
<span class="truncate">{{ displayLink }}</span>
|
||||
</a>
|
||||
<span v-else class="text-sm truncate text-n-slate-12">
|
||||
{{ displayLink }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex flex-col gap-1">
|
||||
<span class="text-xs font-medium uppercase text-n-slate-10">
|
||||
{{ t('CAPTAIN.DOCUMENTS.DETAILS.GENERATED_FAQS') }}
|
||||
</span>
|
||||
<span class="text-sm text-n-slate-12">
|
||||
{{ totalCount }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex flex-col gap-1">
|
||||
<span class="text-xs font-medium uppercase text-n-slate-10">
|
||||
{{ t('CAPTAIN.DOCUMENTS.DETAILS.LAST_UPDATED') }}
|
||||
</span>
|
||||
<span class="text-sm text-n-slate-12">
|
||||
{{
|
||||
syncedAtLabel ||
|
||||
updatedAtLabel ||
|
||||
t('CAPTAIN.DOCUMENTS.DETAILS.NOT_AVAILABLE')
|
||||
}}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<TabBar
|
||||
:tabs="tabs"
|
||||
:initial-active-tab="activeTabIndex"
|
||||
@tab-changed="handleTabChanged"
|
||||
/>
|
||||
|
||||
<div class="h-[32rem] overflow-y-auto">
|
||||
<section
|
||||
v-if="activeTabKey === TAB_KEYS.CONTENT"
|
||||
class="flex flex-col gap-3"
|
||||
>
|
||||
<div class="flex flex-wrap items-start justify-between gap-3">
|
||||
<div class="flex flex-col gap-1">
|
||||
<h4 class="text-sm font-medium text-n-slate-12">
|
||||
{{
|
||||
isPdf
|
||||
? t('CAPTAIN.DOCUMENTS.DETAILS.PDF_TITLE')
|
||||
: t('CAPTAIN.DOCUMENTS.DETAILS.CONTENT_TITLE')
|
||||
}}
|
||||
</h4>
|
||||
<span
|
||||
v-if="documentContent && !isPdf"
|
||||
class="text-xs text-n-slate-10"
|
||||
>
|
||||
{{
|
||||
t('CAPTAIN.DOCUMENTS.DETAILS.CHARACTER_COUNT', {
|
||||
count: documentContentLength.toLocaleString(),
|
||||
})
|
||||
}}
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="documentContent && !isPdf"
|
||||
class="flex flex-wrap items-center justify-end gap-4"
|
||||
>
|
||||
<Button
|
||||
:label="
|
||||
showRawContent
|
||||
? t('CAPTAIN.DOCUMENTS.DETAILS.VIEW_PREVIEW')
|
||||
: t('CAPTAIN.DOCUMENTS.DETAILS.VIEW_RAW')
|
||||
"
|
||||
sm
|
||||
slate
|
||||
link
|
||||
@click="showRawContent = !showRawContent"
|
||||
/>
|
||||
<Button
|
||||
:label="t('CAPTAIN.DOCUMENTS.DETAILS.COPY_CONTENT')"
|
||||
icon="i-lucide-copy"
|
||||
sm
|
||||
slate
|
||||
link
|
||||
@click="handleCopyContent"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-if="isPdf"
|
||||
class="rounded-lg border border-n-weak bg-n-alpha-1 p-4 text-sm text-n-slate-11"
|
||||
>
|
||||
<p class="mb-3">
|
||||
{{ t('CAPTAIN.DOCUMENTS.DETAILS.PDF_DESCRIPTION') }}
|
||||
</p>
|
||||
<a
|
||||
v-if="hasSafeLink"
|
||||
:href="sourceHref"
|
||||
:title="sourceHref"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="inline-flex items-center gap-1 font-medium text-n-blue-11 hover:underline"
|
||||
>
|
||||
<Icon icon="i-ph-file-pdf" class="size-4" />
|
||||
{{ displayLink }}
|
||||
<Icon icon="i-lucide-external-link" class="size-3" />
|
||||
</a>
|
||||
<span v-else class="inline-flex items-center gap-1 text-n-slate-12">
|
||||
<Icon icon="i-ph-file-pdf" class="size-4" />
|
||||
{{ displayLink }}
|
||||
</span>
|
||||
</div>
|
||||
<template v-else-if="documentContent">
|
||||
<div
|
||||
v-if="isUnreadableContent && !showRawContent"
|
||||
class="rounded-lg border border-dashed border-n-weak p-4 text-sm text-n-slate-11"
|
||||
>
|
||||
{{ t('CAPTAIN.DOCUMENTS.DETAILS.UNREADABLE_CONTENT') }}
|
||||
</div>
|
||||
<div
|
||||
v-else
|
||||
class="h-[26rem] overflow-y-auto rounded-lg border border-n-weak bg-n-alpha-1 p-4"
|
||||
>
|
||||
<pre
|
||||
v-if="showRawContent || isUnreadableContent"
|
||||
class="m-0 whitespace-pre-wrap break-words text-xs leading-5 text-n-slate-12"
|
||||
><code>{{ documentContent }}</code></pre>
|
||||
<div
|
||||
v-else
|
||||
v-dompurify-html="formattedDocumentContent"
|
||||
class="prose prose-sm max-w-none break-words text-n-slate-12 prose-p:my-2 prose-headings:mb-2 prose-headings:mt-4 prose-a:text-n-blue-11 prose-ul:my-2 prose-ol:my-2 prose-li:my-1 prose-img:hidden"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
<div
|
||||
v-else
|
||||
class="rounded-lg border border-dashed border-n-weak p-4 text-sm text-n-slate-11"
|
||||
>
|
||||
{{ t('CAPTAIN.DOCUMENTS.DETAILS.EMPTY_CONTENT') }}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section
|
||||
v-if="activeTabKey === TAB_KEYS.FAQS"
|
||||
class="flex flex-col gap-3"
|
||||
>
|
||||
<div v-if="responses.length" class="flex flex-col gap-3">
|
||||
<ResponseCard
|
||||
v-for="response in responses"
|
||||
:id="response.id"
|
||||
:key="response.id"
|
||||
:question="response.question"
|
||||
:status="response.status"
|
||||
:answer="response.answer"
|
||||
:assistant="response.assistant"
|
||||
:created-at="response.created_at"
|
||||
:updated-at="response.updated_at"
|
||||
compact
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
v-else
|
||||
class="rounded-lg border border-dashed border-n-weak p-4 text-sm text-n-slate-11"
|
||||
>
|
||||
{{ t('CAPTAIN.DOCUMENTS.RELATED_RESPONSES.EMPTY') }}
|
||||
</div>
|
||||
<footer v-if="showPaginationFooter" class="sticky bottom-0 z-10">
|
||||
<PaginationFooter
|
||||
:current-page="currentPage"
|
||||
:total-items="totalCount"
|
||||
:items-per-page="RESPONSES_PER_PAGE"
|
||||
class="!px-0"
|
||||
@update:current-page="handlePageChange"
|
||||
/>
|
||||
</footer>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
</template>
|
||||
-71
@@ -1,71 +0,0 @@
|
||||
<script setup>
|
||||
import { ref, computed, onMounted } from 'vue';
|
||||
import { useStore, useMapGetter } from 'dashboard/composables/store';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import Spinner from 'dashboard/components-next/spinner/Spinner.vue';
|
||||
import Dialog from 'dashboard/components-next/dialog/Dialog.vue';
|
||||
import ResponseCard from '../../assistant/ResponseCard.vue';
|
||||
const props = defineProps({
|
||||
captainDocument: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
});
|
||||
const emit = defineEmits(['close']);
|
||||
const { t } = useI18n();
|
||||
const store = useStore();
|
||||
const dialogRef = ref(null);
|
||||
|
||||
const uiFlags = useMapGetter('captainResponses/getUIFlags');
|
||||
const responses = useMapGetter('captainResponses/getRecords');
|
||||
const meta = useMapGetter('captainResponses/getMeta');
|
||||
const isFetching = computed(() => uiFlags.value.fetchingList);
|
||||
const totalCount = computed(() => meta.value.totalCount || 0);
|
||||
|
||||
const handleClose = () => {
|
||||
emit('close');
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
store.dispatch('captainResponses/get', {
|
||||
assistantId: props.captainDocument.assistant.id,
|
||||
documentId: props.captainDocument.id,
|
||||
});
|
||||
});
|
||||
defineExpose({ dialogRef });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog
|
||||
ref="dialogRef"
|
||||
type="edit"
|
||||
:title="`${t('CAPTAIN.DOCUMENTS.RELATED_RESPONSES.TITLE')} (${totalCount})`"
|
||||
:description="t('CAPTAIN.DOCUMENTS.RELATED_RESPONSES.DESCRIPTION')"
|
||||
:show-cancel-button="false"
|
||||
:show-confirm-button="false"
|
||||
overflow-y-auto
|
||||
width="3xl"
|
||||
@close="handleClose"
|
||||
>
|
||||
<div
|
||||
v-if="isFetching"
|
||||
class="flex items-center justify-center py-10 text-n-slate-11"
|
||||
>
|
||||
<Spinner />
|
||||
</div>
|
||||
<div v-else class="flex flex-col gap-3 min-h-48">
|
||||
<ResponseCard
|
||||
v-for="response in responses"
|
||||
:id="response.id"
|
||||
:key="response.id"
|
||||
:question="response.question"
|
||||
:status="response.status"
|
||||
:answer="response.answer"
|
||||
:assistant="response.assistant"
|
||||
:created-at="response.created_at"
|
||||
:updated-at="response.updated_at"
|
||||
compact
|
||||
/>
|
||||
</div>
|
||||
</Dialog>
|
||||
</template>
|
||||
+234
@@ -0,0 +1,234 @@
|
||||
<script setup>
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useEventListener } from '@vueuse/core';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import CaptainAssistant from 'dashboard/api/captain/assistant';
|
||||
import { useReportDrilldown } from 'dashboard/routes/dashboard/settings/reports/composables/useReportDrilldown';
|
||||
import ReportDrilldownCard from 'dashboard/routes/dashboard/settings/reports/components/ReportDrilldownCard.vue';
|
||||
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';
|
||||
|
||||
const props = defineProps({
|
||||
open: { type: Boolean, default: false },
|
||||
assistantId: { type: [String, Number], default: null },
|
||||
metric: { type: String, default: '' },
|
||||
metricName: { type: String, default: '' },
|
||||
metricValue: { type: String, default: '' },
|
||||
range: { type: String, default: '' },
|
||||
});
|
||||
|
||||
const emit = defineEmits(['close']);
|
||||
|
||||
const { t } = useI18n();
|
||||
const drawerRef = ref(null);
|
||||
const {
|
||||
records,
|
||||
meta,
|
||||
isFetching,
|
||||
isFetchingMore,
|
||||
hasError,
|
||||
hasRecords,
|
||||
hasMore,
|
||||
open: openDrilldown,
|
||||
close,
|
||||
loadMore,
|
||||
} = useReportDrilldown(params => CaptainAssistant.getDrilldown(params));
|
||||
|
||||
let previousActiveElement = null;
|
||||
|
||||
const isOpen = computed(() => props.open);
|
||||
const title = computed(() => props.metricName || '');
|
||||
|
||||
const subtitle = computed(() => {
|
||||
if (!meta.value.conversation_count) return '';
|
||||
|
||||
return t('CAPTAIN.OVERVIEW.DRILLDOWN.RESULT_COUNT_CONVERSATION', {
|
||||
count: meta.value.conversation_count,
|
||||
});
|
||||
});
|
||||
|
||||
const recordKey = record => `${record.conversation?.id}-${record.occurred_at}`;
|
||||
|
||||
const restoreFocus = () => {
|
||||
if (previousActiveElement?.isConnected) {
|
||||
previousActiveElement.focus();
|
||||
}
|
||||
previousActiveElement = null;
|
||||
};
|
||||
|
||||
const closeDrawer = () => {
|
||||
close();
|
||||
emit('close');
|
||||
restoreFocus();
|
||||
};
|
||||
|
||||
const rememberActiveElement = () => {
|
||||
if (previousActiveElement) return;
|
||||
|
||||
previousActiveElement =
|
||||
document.activeElement instanceof HTMLElement
|
||||
? document.activeElement
|
||||
: null;
|
||||
};
|
||||
|
||||
const focusDrawer = () => {
|
||||
nextTick(() => drawerRef.value?.focus());
|
||||
};
|
||||
|
||||
const fetchDrilldown = () => {
|
||||
if (!props.metric || !props.assistantId) return;
|
||||
|
||||
openDrilldown({
|
||||
assistantId: props.assistantId,
|
||||
metric: props.metric,
|
||||
range: props.range,
|
||||
});
|
||||
};
|
||||
|
||||
const onKeydown = event => {
|
||||
if (!isOpen.value) return;
|
||||
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
closeDrawer();
|
||||
}
|
||||
};
|
||||
|
||||
useEventListener(document, 'keydown', onKeydown);
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
isDrawerOpen => {
|
||||
if (!isDrawerOpen) {
|
||||
close();
|
||||
restoreFocus();
|
||||
return;
|
||||
}
|
||||
|
||||
rememberActiveElement();
|
||||
fetchDrilldown();
|
||||
focusDrawer();
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
|
||||
watch(
|
||||
() => [props.metric, props.range],
|
||||
() => {
|
||||
if (props.open) fetchDrilldown();
|
||||
}
|
||||
);
|
||||
|
||||
// The drawer's headline value is a snapshot of the previous assistant's card,
|
||||
// so switching assistants (e.g. browser Back/Forward) closes it instead of
|
||||
// refetching records that would no longer match the header.
|
||||
watch(
|
||||
() => props.assistantId,
|
||||
() => {
|
||||
if (props.open) closeDrawer();
|
||||
}
|
||||
);
|
||||
|
||||
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="metricValue"
|
||||
class="mt-1 text-xl font-semibold text-n-slate-12"
|
||||
>
|
||||
{{ metricValue }}
|
||||
</p>
|
||||
<div
|
||||
class="text-sm text-n-slate-11"
|
||||
:class="{
|
||||
'mt-2': metricValue,
|
||||
'mt-1': !metricValue,
|
||||
}"
|
||||
>
|
||||
{{ subtitle }}
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
ghost
|
||||
slate
|
||||
size="sm"
|
||||
icon="i-ph-x"
|
||||
:aria-label="$t('CAPTAIN.OVERVIEW.DRILLDOWN.CLOSE')"
|
||||
@click="closeDrawer"
|
||||
/>
|
||||
</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('CAPTAIN.OVERVIEW.DRILLDOWN.ERROR') }}
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else-if="!hasRecords"
|
||||
class="flex h-40 items-center justify-center text-sm text-n-slate-10"
|
||||
>
|
||||
{{ $t('CAPTAIN.OVERVIEW.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('CAPTAIN.OVERVIEW.DRILLDOWN.LOAD_MORE')"
|
||||
:is-loading="isFetchingMore"
|
||||
@click="loadMore"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
</Transition>
|
||||
</TeleportWithDirection>
|
||||
</template>
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
<script setup>
|
||||
import { computed, ref, watch } 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);
|
||||
|
||||
// Re-read the stored flag whenever the assistant changes, otherwise the banner
|
||||
// would keep the first assistant's dismissed state after switching.
|
||||
const dismissed = ref(false);
|
||||
|
||||
watch(
|
||||
[accountId, assistantId],
|
||||
([account, assistant]) => {
|
||||
dismissed.value = LocalStorage.getFlag(DISMISS_STORE, account, assistant);
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
|
||||
// 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>
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
<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
@@ -0,0 +1,87 @@
|
||||
<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>
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
<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 },
|
||||
clickable: { type: Boolean, default: false },
|
||||
});
|
||||
|
||||
const emit = defineEmits(['click']);
|
||||
|
||||
const trendClass = computed(() => {
|
||||
if (props.trendGood === null) return 'text-n-slate-11';
|
||||
return props.trendGood ? 'text-n-teal-11' : 'text-n-ruby-11';
|
||||
});
|
||||
|
||||
const onActivate = () => {
|
||||
if (props.clickable) emit('click');
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="flex flex-col gap-3 p-5 group bg-n-solid-1"
|
||||
:class="
|
||||
clickable
|
||||
? 'cursor-pointer transition-colors hover:bg-n-slate-2/50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-n-brand'
|
||||
: ''
|
||||
"
|
||||
:role="clickable ? 'button' : undefined"
|
||||
:tabindex="clickable ? 0 : undefined"
|
||||
@click="onActivate"
|
||||
@keydown.enter.self.prevent="onActivate"
|
||||
@keydown.space.self.prevent="onActivate"
|
||||
>
|
||||
<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
@@ -0,0 +1,81 @@
|
||||
<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>
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
<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-sections="menuSections"
|
||||
class="mt-1 ltr:right-0 rtl:left-0 top-full"
|
||||
@action="handleAction($event)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
<script setup>
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useRoute } from 'vue-router';
|
||||
import CaptainAssistant from 'dashboard/api/captain/assistant';
|
||||
import MessageFormatter from 'shared/helpers/MessageFormatter.js';
|
||||
|
||||
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 (see prose-strong styling below).
|
||||
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 });
|
||||
|
||||
// Render through the shared markdown formatter (html disabled, so it is safe)
|
||||
// used everywhere else for Captain output, instead of a bespoke parser. It
|
||||
// handles paragraphs, line breaks, links, lists and emphasis consistently.
|
||||
const formattedSummary = computed(
|
||||
() => new MessageFormatter(welcomeMarkdown.value).formattedMessage
|
||||
);
|
||||
</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>
|
||||
<div
|
||||
v-else
|
||||
v-dompurify-html="formattedSummary"
|
||||
class="max-w-none prose prose-p:text-lg prose-p:leading-relaxed prose-p:mt-0 prose-p:mb-3 last:prose-p:mb-0 prose-strong:font-bold prose-strong:tabular-nums prose-strong:text-n-brand text-n-slate-12"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
+1
-1
@@ -65,7 +65,7 @@ const handleAssistantChange = async assistant => {
|
||||
|
||||
const currentRouteName = route.name;
|
||||
const targetRouteName =
|
||||
currentRouteName || 'captain_assistants_responses_index';
|
||||
currentRouteName || 'captain_assistants_overview_index';
|
||||
|
||||
await fetchDataForRoute(targetRouteName, assistant.id);
|
||||
|
||||
|
||||
@@ -75,6 +75,23 @@ const hasConversationUnreadCounts = computed(() => {
|
||||
);
|
||||
});
|
||||
|
||||
const hasFilteredUnreadCounts = computed(() => {
|
||||
return (
|
||||
hasConversationUnreadCounts.value &&
|
||||
isFeatureEnabledonAccount.value(
|
||||
accountId.value,
|
||||
FEATURE_FLAGS.UNREAD_COUNT_FOR_FILTERS
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
const hasDataImport = computed(() => {
|
||||
return isFeatureEnabledonAccount.value(
|
||||
accountId.value,
|
||||
FEATURE_FLAGS.DATA_IMPORT
|
||||
);
|
||||
});
|
||||
|
||||
const fetchConversationUnreadCounts = ([currentAccountId, isEnabled]) => {
|
||||
if (!currentAccountId) return;
|
||||
|
||||
@@ -199,6 +216,18 @@ const getLabelUnreadCount = useMapGetter(
|
||||
const getTeamUnreadCount = useMapGetter(
|
||||
'conversationUnreadCounts/getTeamUnreadCount'
|
||||
);
|
||||
const mentionsUnreadCount = useMapGetter(
|
||||
'conversationUnreadCounts/getMentionsUnreadCount'
|
||||
);
|
||||
const participatingUnreadCount = useMapGetter(
|
||||
'conversationUnreadCounts/getParticipatingUnreadCount'
|
||||
);
|
||||
const unattendedUnreadCount = useMapGetter(
|
||||
'conversationUnreadCounts/getUnattendedUnreadCount'
|
||||
);
|
||||
const getFolderUnreadCount = useMapGetter(
|
||||
'conversationUnreadCounts/getFolderUnreadCount'
|
||||
);
|
||||
const teams = useMapGetter('teams/getMyTeams');
|
||||
const contactCustomViews = useMapGetter('customViews/getContactCustomViews');
|
||||
const conversationCustomViews = useMapGetter(
|
||||
@@ -226,14 +255,22 @@ watch([accountId, currentUserId], fetchSidebarSortPreferences, {
|
||||
immediate: true,
|
||||
});
|
||||
|
||||
const hasUnreadCountsForSection = section => {
|
||||
if (section === SIDEBAR_SORT_SECTIONS.FOLDERS) {
|
||||
return hasFilteredUnreadCounts.value;
|
||||
}
|
||||
|
||||
return hasConversationUnreadCounts.value;
|
||||
};
|
||||
|
||||
const getSortOptionsForSection = section =>
|
||||
getSidebarSortOptions(section, {
|
||||
hasUnreadCounts: hasConversationUnreadCounts.value,
|
||||
hasUnreadCounts: hasUnreadCountsForSection(section),
|
||||
});
|
||||
|
||||
const getSortForSection = section =>
|
||||
resolveSidebarSort(section, getSidebarSectionSort.value(section), {
|
||||
hasUnreadCounts: hasConversationUnreadCounts.value,
|
||||
hasUnreadCounts: hasUnreadCountsForSection(section),
|
||||
});
|
||||
|
||||
const updateSortPreference = (section, sortBy) => {
|
||||
@@ -253,6 +290,7 @@ const sortedFolders = computed(() =>
|
||||
sortSidebarItems(conversationCustomViews.value, {
|
||||
sortBy: getSortForSection(SIDEBAR_SORT_SECTIONS.FOLDERS),
|
||||
labelKey: view => view.name,
|
||||
unreadCountKey: view => getFolderUnreadCount.value(view.id),
|
||||
})
|
||||
);
|
||||
|
||||
@@ -342,6 +380,9 @@ const menuItems = computed(() => {
|
||||
name: 'Mentions',
|
||||
label: t('SIDEBAR.MENTIONED_CONVERSATIONS'),
|
||||
icon: 'i-lucide-at-sign',
|
||||
badgeCount: hasFilteredUnreadCounts.value
|
||||
? mentionsUnreadCount.value
|
||||
: 0,
|
||||
activeOn: ['conversation_through_mentions'],
|
||||
to: accountScopedRoute('conversation_mentions'),
|
||||
},
|
||||
@@ -349,6 +390,9 @@ const menuItems = computed(() => {
|
||||
name: 'Participating',
|
||||
label: t('SIDEBAR.PARTICIPATING_CONVERSATIONS'),
|
||||
icon: 'i-lucide-user-round-check',
|
||||
badgeCount: hasFilteredUnreadCounts.value
|
||||
? participatingUnreadCount.value
|
||||
: 0,
|
||||
activeOn: ['conversation_through_participating'],
|
||||
to: accountScopedRoute('conversation_participating'),
|
||||
},
|
||||
@@ -357,6 +401,9 @@ const menuItems = computed(() => {
|
||||
activeOn: ['conversation_through_unattended'],
|
||||
label: t('SIDEBAR.UNATTENDED_CONVERSATIONS'),
|
||||
icon: 'i-lucide-clock-alert',
|
||||
badgeCount: hasFilteredUnreadCounts.value
|
||||
? unattendedUnreadCount.value
|
||||
: 0,
|
||||
to: accountScopedRoute('conversation_unattended'),
|
||||
},
|
||||
{
|
||||
@@ -370,6 +417,9 @@ const menuItems = computed(() => {
|
||||
children: sortedFolders.value.map(view => ({
|
||||
name: `${view.name}-${view.id}`,
|
||||
label: view.name,
|
||||
badgeCount: hasFilteredUnreadCounts.value
|
||||
? getFolderUnreadCount.value(view.id)
|
||||
: 0,
|
||||
to: accountScopedRoute('folder_conversations', { id: view.id }),
|
||||
})),
|
||||
},
|
||||
@@ -440,6 +490,14 @@ const menuItems = computed(() => {
|
||||
label: t('SIDEBAR.CAPTAIN'),
|
||||
activeOn: ['captain_assistants_create_index'],
|
||||
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',
|
||||
label: t('SIDEBAR.CAPTAIN_RESPONSES'),
|
||||
@@ -805,6 +863,16 @@ const menuItems = computed(() => {
|
||||
icon: 'i-lucide-blocks',
|
||||
to: accountScopedRoute('settings_applications'),
|
||||
},
|
||||
...(hasDataImport.value
|
||||
? [
|
||||
{
|
||||
name: 'Settings Data',
|
||||
label: t('SIDEBAR.DATA'),
|
||||
icon: 'i-lucide-database',
|
||||
to: accountScopedRoute('settings_data_imports'),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{
|
||||
name: 'Settings Audit Logs',
|
||||
label: t('SIDEBAR.AUDIT_LOGS'),
|
||||
|
||||
@@ -44,6 +44,12 @@ const showChatSupport = computed(() => {
|
||||
);
|
||||
});
|
||||
|
||||
const toggleChatSupport = () => {
|
||||
if (window.$chatwoot) {
|
||||
window.$chatwoot.toggle();
|
||||
}
|
||||
};
|
||||
|
||||
const menuItems = computed(() => {
|
||||
return [
|
||||
{
|
||||
@@ -51,9 +57,7 @@ const menuItems = computed(() => {
|
||||
showOnCustomBrandedInstance: false,
|
||||
label: t('SIDEBAR_ITEMS.CONTACT_SUPPORT'),
|
||||
icon: 'i-lucide-life-buoy',
|
||||
click: () => {
|
||||
window.$chatwoot.toggle();
|
||||
},
|
||||
click: toggleChatSupport,
|
||||
},
|
||||
{
|
||||
show: true,
|
||||
|
||||
@@ -7,7 +7,7 @@ import Button from 'dashboard/components-next/button/Button.vue';
|
||||
const { modalType, closeOnBackdropClick, onClose } = defineProps({
|
||||
closeOnBackdropClick: { type: Boolean, default: true },
|
||||
showCloseButton: { type: Boolean, default: true },
|
||||
onClose: { type: Function, required: true },
|
||||
onClose: { type: Function, default: null },
|
||||
fullWidth: { type: Boolean, default: false },
|
||||
modalType: { type: String, default: 'centered' },
|
||||
size: { type: String, default: '' },
|
||||
@@ -35,7 +35,7 @@ const handleMouseDown = () => {
|
||||
const close = () => {
|
||||
show.value = false;
|
||||
emit('close');
|
||||
onClose();
|
||||
onClose?.();
|
||||
};
|
||||
|
||||
const onMouseUp = () => {
|
||||
|
||||
@@ -52,18 +52,10 @@ const isActive = computed(() => {
|
||||
return props.enabledFeatures.channel_tiktok && hasTiktokConfigured.value;
|
||||
}
|
||||
|
||||
if (key === 'voice') {
|
||||
if (key === 'voice' || key === 'whatsapp_call') {
|
||||
return props.enabledFeatures.channel_voice;
|
||||
}
|
||||
|
||||
if (key === 'whatsapp_call') {
|
||||
return (
|
||||
props.enabledFeatures.channel_voice &&
|
||||
!!window.chatwootConfig?.whatsappAppId &&
|
||||
window.chatwootConfig.whatsappAppId !== 'none'
|
||||
);
|
||||
}
|
||||
|
||||
return [
|
||||
'website',
|
||||
'twilio',
|
||||
|
||||
@@ -62,6 +62,7 @@ import {
|
||||
calculateMenuPosition,
|
||||
getEffectiveChannelType,
|
||||
stripUnsupportedFormatting,
|
||||
createVariableInputRule,
|
||||
} from 'dashboard/helper/editorHelper';
|
||||
import {
|
||||
hasPressedEnterAndNotCmdOrShift,
|
||||
@@ -306,6 +307,10 @@ const plugins = computed(() => {
|
||||
searchTerm: variableSearchTerm,
|
||||
isAllowed: () => !props.isPrivate,
|
||||
}),
|
||||
createVariableInputRule({
|
||||
isPrivate: () => props.isPrivate,
|
||||
getVariables: () => props.variables,
|
||||
}),
|
||||
createSuggestionPlugin({
|
||||
trigger: ':',
|
||||
minChars: 2,
|
||||
|
||||
@@ -62,7 +62,10 @@ export default {
|
||||
immediate: true,
|
||||
handler(inboxId) {
|
||||
if (inboxId) {
|
||||
this.$store.dispatch('inboxAssignableAgents/fetch', [inboxId]);
|
||||
this.$store.dispatch('inboxAssignableAgents/fetch', {
|
||||
inboxIds: [inboxId],
|
||||
includeAgentBots: true,
|
||||
});
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { getLastMessage } from 'dashboard/helper/conversationHelper';
|
||||
import Avatar from 'next/avatar/Avatar.vue';
|
||||
import Icon from 'dashboard/components-next/icon/Icon.vue';
|
||||
import MessagePreview from './MessagePreview.vue';
|
||||
import InboxName from '../InboxName.vue';
|
||||
import TimeAgo from 'dashboard/components/ui/TimeAgo.vue';
|
||||
@@ -57,6 +58,10 @@ const showMetaSection = computed(() => {
|
||||
);
|
||||
});
|
||||
|
||||
const isAgentBotAssignee = computed(
|
||||
() => props.chat?.meta?.assignee_type === 'AgentBot'
|
||||
);
|
||||
|
||||
const hasSlaPolicyId = computed(
|
||||
() => props.chat?.applied_sla?.id && !props.currentContact?.blocked
|
||||
);
|
||||
@@ -159,10 +164,15 @@ watch(
|
||||
>
|
||||
<span
|
||||
v-if="showAssignee && assignee.name"
|
||||
class="text-n-slate-11 text-xs font-medium leading-3 py-0.5 px-0 inline-flex items-center truncate"
|
||||
class="text-n-slate-11 text-xs font-medium leading-3 py-0.5 px-0 inline-flex items-center gap-px truncate"
|
||||
>
|
||||
<fluent-icon icon="person" size="12" class="text-n-slate-11" />
|
||||
{{ assignee.name }}
|
||||
<Icon
|
||||
:icon="
|
||||
isAgentBotAssignee ? 'i-lucide-bot' : 'i-lucide-user-round'
|
||||
"
|
||||
class="size-3 text-n-slate-11 flex-shrink-0"
|
||||
/>
|
||||
<span class="truncate">{{ assignee.name }}</span>
|
||||
</span>
|
||||
<CardPriorityIcon
|
||||
:priority="chat.priority"
|
||||
|
||||
@@ -123,7 +123,13 @@ export default {
|
||||
$t('EMAIL_TRANSCRIPT.FORM.SEND_TO_CONTACT')
|
||||
}}</label>
|
||||
</div>
|
||||
<div v-if="currentChat.meta.assignee" class="flex items-center gap-2">
|
||||
<div
|
||||
v-if="
|
||||
currentChat.meta.assignee &&
|
||||
currentChat.meta.assignee_type !== 'AgentBot'
|
||||
"
|
||||
class="flex items-center gap-2"
|
||||
>
|
||||
<input
|
||||
id="assignee"
|
||||
v-model="selectedType"
|
||||
|
||||
@@ -33,7 +33,9 @@ import {
|
||||
// constants
|
||||
import { BUS_EVENTS } from 'shared/constants/busEvents';
|
||||
import { REPLY_POLICY } from 'shared/constants/links';
|
||||
import wootConstants from 'dashboard/constants/globals';
|
||||
import wootConstants, {
|
||||
META_RESTRICTION_STATUS_URL,
|
||||
} from 'dashboard/constants/globals';
|
||||
import { LOCAL_STORAGE_KEYS } from 'dashboard/constants/localStorage';
|
||||
import { INBOX_TYPES } from 'dashboard/helper/inbox';
|
||||
|
||||
@@ -93,6 +95,7 @@ export default {
|
||||
currentUserId: 'getCurrentUserID',
|
||||
listLoadingStatus: 'getAllMessagesLoaded',
|
||||
currentAccountId: 'getCurrentAccountId',
|
||||
isOnChatwootCloud: 'globalConfig/isOnChatwootCloud',
|
||||
}),
|
||||
isOpen() {
|
||||
return this.currentChat?.status === wootConstants.STATUS_TYPE.OPEN;
|
||||
@@ -170,6 +173,12 @@ export default {
|
||||
instagramInbox
|
||||
);
|
||||
},
|
||||
isInstagramRestrictionBannerVisible() {
|
||||
return this.isOnChatwootCloud && this.isAnInstagramChannel;
|
||||
},
|
||||
instagramRestrictionStatusUrl() {
|
||||
return META_RESTRICTION_STATUS_URL;
|
||||
},
|
||||
|
||||
replyWindowBannerMessage() {
|
||||
if (this.isAWhatsAppChannel) {
|
||||
@@ -455,7 +464,15 @@ export default {
|
||||
>
|
||||
<div ref="topBannerRef">
|
||||
<Banner
|
||||
v-if="!currentChat.can_reply"
|
||||
v-if="isInstagramRestrictionBannerVisible"
|
||||
color-scheme="warning"
|
||||
class="mx-2 mt-2 overflow-hidden rounded-lg"
|
||||
:banner-message="$t('CONVERSATION.INSTAGRAM_RESTRICTION_BANNER')"
|
||||
:href-link="instagramRestrictionStatusUrl"
|
||||
:href-link-text="$t('CONVERSATION.INSTAGRAM_RESTRICTION_STATUS_LINK')"
|
||||
/>
|
||||
<Banner
|
||||
v-else-if="!currentChat.can_reply"
|
||||
color-scheme="alert"
|
||||
class="mx-2 mt-2 overflow-hidden rounded-lg"
|
||||
:banner-message="replyWindowBannerMessage"
|
||||
|
||||
@@ -48,6 +48,8 @@ import {
|
||||
appendSignature,
|
||||
removeSignature,
|
||||
getEffectiveChannelType,
|
||||
getAgentVariables,
|
||||
getContactVariables,
|
||||
} from 'dashboard/helper/editorHelper';
|
||||
import { useCopilotReply } from 'dashboard/composables/useCopilotReply';
|
||||
import { useKbd } from 'dashboard/composables/utils/useKbd';
|
||||
@@ -393,7 +395,13 @@ export default {
|
||||
contact: this.currentContact,
|
||||
inbox: this.inbox,
|
||||
});
|
||||
return variables;
|
||||
// Match the backend drops: names are Ruby-capitalized and
|
||||
// {{agent.*}} is the message sender, not the assignee.
|
||||
return {
|
||||
...variables,
|
||||
...getContactVariables(this.currentContact),
|
||||
...getAgentVariables(this.currentUser),
|
||||
};
|
||||
},
|
||||
connectedPortalSlug() {
|
||||
const { help_center: portal = {} } = this.inbox;
|
||||
|
||||
@@ -33,10 +33,19 @@ defineProps({
|
||||
v-if="variant === 'agent'"
|
||||
:name="option.label"
|
||||
:src="option.thumbnail"
|
||||
:icon-name="option.iconName"
|
||||
:status="option.status === 'online' ? option.status : null"
|
||||
:size="20"
|
||||
class="flex-shrink-0"
|
||||
/>
|
||||
>
|
||||
<template v-if="option.iconName && option.thumbnail" #badge>
|
||||
<div
|
||||
class="absolute z-20 flex items-center justify-center rounded-full outline outline-1 outline-n-weak bg-n-solid-1 -bottom-0.5 ltr:-right-0.5 rtl:-left-0.5 size-3"
|
||||
>
|
||||
<Icon icon="i-lucide-bot" class="text-n-slate-11 size-2" />
|
||||
</div>
|
||||
</template>
|
||||
</Avatar>
|
||||
<p class="menu-label truncate min-w-0 flex-1">
|
||||
{{ option.label }}
|
||||
</p>
|
||||
|
||||
@@ -26,11 +26,12 @@ const mockNoneAgent = {
|
||||
};
|
||||
|
||||
const mockUseMapGetter = (overrides = {}) => {
|
||||
const getAssignableAgents = vi.fn(() => allAgentsData);
|
||||
const defaultGetters = {
|
||||
getCurrentUser: ref(allAgentsData[0]),
|
||||
getSelectedChat: ref({ inbox_id: 1, meta: { assignee: true } }),
|
||||
getCurrentAccountId: ref(1),
|
||||
'inboxAssignableAgents/getAssignableAgents': ref(() => allAgentsData),
|
||||
'inboxAssignableAgents/getAssignableAgents': ref(getAssignableAgents),
|
||||
};
|
||||
|
||||
const mergedGetters = { ...defaultGetters, ...overrides };
|
||||
@@ -53,6 +54,24 @@ describe('useAgentsList', () => {
|
||||
const { agentsList, assignableAgents } = useAgentsList();
|
||||
|
||||
expect(assignableAgents.value).toEqual(allAgentsData);
|
||||
expect(
|
||||
useMapGetter('inboxAssignableAgents/getAssignableAgents').value
|
||||
).toHaveBeenCalledWith(1, { includeAgentBots: false });
|
||||
expect(agentsList.value[0]).toEqual(mockNoneAgent);
|
||||
expect(agentsList.value.length).toBe(
|
||||
formattedAgentsData.slice(1).length + 1
|
||||
);
|
||||
});
|
||||
|
||||
it('requests agent bots when explicitly included', () => {
|
||||
const { agentsList, assignableAgents } = useAgentsList(true, {
|
||||
includeAgentBots: true,
|
||||
});
|
||||
|
||||
expect(assignableAgents.value).toEqual(allAgentsData);
|
||||
expect(
|
||||
useMapGetter('inboxAssignableAgents/getAssignableAgents').value
|
||||
).toHaveBeenCalledWith(1, { includeAgentBots: true });
|
||||
expect(agentsList.value[0]).toEqual(mockNoneAgent);
|
||||
expect(agentsList.value.length).toBe(
|
||||
formattedAgentsData.slice(1).length + 1
|
||||
|
||||
@@ -10,9 +10,14 @@ import {
|
||||
* A composable function that provides a list of agents for assignment.
|
||||
*
|
||||
* @param {boolean} [includeNoneAgent=true] - Whether to include a 'None' agent option.
|
||||
* @param {Object} [options] - Options for the assignable agents list.
|
||||
* @param {boolean} [options.includeAgentBots=false] - Whether to include AgentBot assignees. Only pass this from surfaces that thread `assignee_type` through the assignment request.
|
||||
* @returns {Object} An object containing the agents list and assignable agents.
|
||||
*/
|
||||
export function useAgentsList(includeNoneAgent = true) {
|
||||
export function useAgentsList(
|
||||
includeNoneAgent = true,
|
||||
{ includeAgentBots = false } = {}
|
||||
) {
|
||||
const { t } = useI18n();
|
||||
const currentUser = useMapGetter('getCurrentUser');
|
||||
const currentChat = useMapGetter('getSelectedChat');
|
||||
@@ -39,7 +44,9 @@ export function useAgentsList(includeNoneAgent = true) {
|
||||
* @type {import('vue').ComputedRef<Array>}
|
||||
*/
|
||||
const assignableAgents = computed(() => {
|
||||
return inboxId.value ? assignable.value(inboxId.value) : [];
|
||||
return inboxId.value
|
||||
? assignable.value(inboxId.value, { includeAgentBots })
|
||||
: [];
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
// Single source of truth for billing currencies on the frontend.
|
||||
// Adding a currency = one entry in BILLING_CURRENCY_CONFIG, add the code to
|
||||
// SUPPORTED_BILLING_CURRENCIES, and add its label key under
|
||||
// BILLING_SETTINGS.CURRENCY.OPTIONS in the locale files.
|
||||
|
||||
export const DEFAULT_BILLING_CURRENCY = 'usd';
|
||||
|
||||
// Order here drives the order of the currency toggle in the UI.
|
||||
export const SUPPORTED_BILLING_CURRENCIES = ['usd', 'brl'];
|
||||
|
||||
export const BILLING_CURRENCY_CONFIG = {
|
||||
usd: {
|
||||
code: 'usd',
|
||||
intlLocale: 'en-US',
|
||||
i18nLabelKey: 'BILLING_SETTINGS.CURRENCY.OPTIONS.USD',
|
||||
},
|
||||
brl: {
|
||||
code: 'brl',
|
||||
intlLocale: 'pt-BR',
|
||||
i18nLabelKey: 'BILLING_SETTINGS.CURRENCY.OPTIONS.BRL',
|
||||
},
|
||||
};
|
||||
|
||||
export const getCurrencyConfig = code =>
|
||||
BILLING_CURRENCY_CONFIG[(code || DEFAULT_BILLING_CURRENCY).toLowerCase()] ||
|
||||
BILLING_CURRENCY_CONFIG[DEFAULT_BILLING_CURRENCY];
|
||||
|
||||
export const formatCurrencyAmount = (amount, code, options = {}) => {
|
||||
const { intlLocale, code: currencyCode } = getCurrencyConfig(code);
|
||||
return new Intl.NumberFormat(intlLocale, {
|
||||
style: 'currency',
|
||||
currency: currencyCode.toUpperCase(),
|
||||
...options,
|
||||
}).format(amount);
|
||||
};
|
||||
@@ -78,3 +78,5 @@ export default {
|
||||
},
|
||||
};
|
||||
export const DEFAULT_REDIRECT_URL = '/app/';
|
||||
export const META_RESTRICTION_STATUS_URL =
|
||||
'https://status.chatwoot.com/incident/948346';
|
||||
|
||||
@@ -7,9 +7,11 @@ export const FEATURE_FLAGS = {
|
||||
AUTOMATIONS: 'automations',
|
||||
CAMPAIGNS: 'campaigns',
|
||||
WHATSAPP_CAMPAIGNS: 'whatsapp_campaign',
|
||||
WHATSAPP_MANUAL_TRANSFER: 'whatsapp_manual_transfer',
|
||||
CANNED_RESPONSES: 'canned_responses',
|
||||
CRM: 'crm',
|
||||
CUSTOM_ATTRIBUTES: 'custom_attributes',
|
||||
DATA_IMPORT: 'data_import',
|
||||
INBOX_MANAGEMENT: 'inbox_management',
|
||||
INTEGRATIONS: 'integrations',
|
||||
LABELS: 'labels',
|
||||
@@ -47,6 +49,7 @@ export const FEATURE_FLAGS = {
|
||||
ADVANCED_SEARCH: 'advanced_search',
|
||||
CONVERSATION_REQUIRED_ATTRIBUTES: 'conversation_required_attributes',
|
||||
CONVERSATION_UNREAD_COUNTS: 'conversation_unread_counts',
|
||||
UNREAD_COUNT_FOR_FILTERS: 'unread_count_for_filters',
|
||||
};
|
||||
|
||||
export const PREMIUM_FEATURES = [
|
||||
|
||||
@@ -17,6 +17,13 @@ import { FEATURE_FLAGS } from 'dashboard/featureFlags';
|
||||
|
||||
const { isImpersonating } = useImpersonation();
|
||||
const UNREAD_COUNTS_REFETCH_THROTTLE_MS = 5000;
|
||||
const FILTERED_UNREAD_COUNTS_REFRESH_RETRY_MS = 30000;
|
||||
const FILTERED_UNREAD_COUNTS_REFRESH_RETRY_JITTER_MS = 15000;
|
||||
const MENTION_UNREAD_COUNTS_REFETCH_DELAY_MS =
|
||||
UNREAD_COUNTS_REFETCH_THROTTLE_MS;
|
||||
const getFilteredUnreadCountsRefreshRetryDelay = () =>
|
||||
FILTERED_UNREAD_COUNTS_REFRESH_RETRY_MS +
|
||||
Math.random() * FILTERED_UNREAD_COUNTS_REFRESH_RETRY_JITTER_MS;
|
||||
|
||||
class ActionCableConnector extends BaseActionCableConnector {
|
||||
constructor(app, pubsubToken) {
|
||||
@@ -25,6 +32,9 @@ class ActionCableConnector extends BaseActionCableConnector {
|
||||
this.CancelTyping = [];
|
||||
this.lastUnreadCountsFetchAt = null;
|
||||
this.unreadCountsFetchTimer = null;
|
||||
this.mentionUnreadCountsFetchTimer = null;
|
||||
this.mentionUnreadCountsRetryTimer = null;
|
||||
this.filteredUnreadCountsRetryTimer = null;
|
||||
this.events = {
|
||||
'message.created': this.onMessageCreated,
|
||||
'message.updated': this.onMessageUpdated,
|
||||
@@ -140,7 +150,12 @@ class ActionCableConnector extends BaseActionCableConnector {
|
||||
};
|
||||
|
||||
onConversationUnreadCountChanged = () => {
|
||||
this.refreshConversationUnreadCountsWithFilteredRetry();
|
||||
};
|
||||
|
||||
refreshConversationUnreadCountsWithFilteredRetry = () => {
|
||||
this.throttledFetchConversationUnreadCounts();
|
||||
this.scheduleFilteredUnreadCountsRetry();
|
||||
};
|
||||
|
||||
throttledFetchConversationUnreadCounts = () => {
|
||||
@@ -171,6 +186,51 @@ class ActionCableConnector extends BaseActionCableConnector {
|
||||
this.unreadCountsFetchTimer = null;
|
||||
};
|
||||
|
||||
scheduleMentionUnreadCountsFetch = () => {
|
||||
if (!this.isFilteredUnreadCountsEnabled()) return;
|
||||
|
||||
// Mention invalidation runs through the async dispatcher, and stale snapshots
|
||||
// can be served until the filtered-count backend refresh window opens.
|
||||
this.scheduleUnreadCountsFetchAfter(
|
||||
'mentionUnreadCountsFetchTimer',
|
||||
MENTION_UNREAD_COUNTS_REFETCH_DELAY_MS
|
||||
);
|
||||
this.scheduleUnreadCountsFetchAfter(
|
||||
'mentionUnreadCountsRetryTimer',
|
||||
getFilteredUnreadCountsRefreshRetryDelay(),
|
||||
{ reset: true }
|
||||
);
|
||||
};
|
||||
|
||||
scheduleFilteredUnreadCountsRetry = () => {
|
||||
if (!this.isFilteredUnreadCountsEnabled()) return;
|
||||
|
||||
// Filtered snapshots can intentionally stay stale until the backend
|
||||
// refresh window opens.
|
||||
this.scheduleUnreadCountsFetchAfter(
|
||||
'filteredUnreadCountsRetryTimer',
|
||||
getFilteredUnreadCountsRefreshRetryDelay(),
|
||||
{ reset: true }
|
||||
);
|
||||
};
|
||||
|
||||
scheduleUnreadCountsFetchAfter = (
|
||||
timerName,
|
||||
delay,
|
||||
{ reset = false } = {}
|
||||
) => {
|
||||
if (this[timerName]) {
|
||||
if (!reset) return;
|
||||
|
||||
clearTimeout(this[timerName]);
|
||||
}
|
||||
|
||||
this[timerName] = setTimeout(() => {
|
||||
this[timerName] = null;
|
||||
this.throttledFetchConversationUnreadCounts();
|
||||
}, delay);
|
||||
};
|
||||
|
||||
fetchConversationUnreadCounts = () => {
|
||||
if (!this.isConversationUnreadCountsEnabled()) return;
|
||||
|
||||
@@ -189,6 +249,17 @@ class ActionCableConnector extends BaseActionCableConnector {
|
||||
);
|
||||
};
|
||||
|
||||
isFilteredUnreadCountsEnabled = () => {
|
||||
const accountId = this.app.$store.getters.getCurrentAccountId;
|
||||
const isFeatureEnabled =
|
||||
this.app.$store.getters['accounts/isFeatureEnabledonAccount'];
|
||||
|
||||
return (
|
||||
isFeatureEnabled?.(accountId, FEATURE_FLAGS.CONVERSATION_UNREAD_COUNTS) &&
|
||||
isFeatureEnabled?.(accountId, FEATURE_FLAGS.UNREAD_COUNT_FOR_FILTERS)
|
||||
);
|
||||
};
|
||||
|
||||
onTypingOn = ({ conversation, user }) => {
|
||||
const conversationId = conversation.id;
|
||||
|
||||
@@ -212,6 +283,7 @@ class ActionCableConnector extends BaseActionCableConnector {
|
||||
|
||||
onConversationMentioned = data => {
|
||||
this.app.$store.dispatch('addMentions', data);
|
||||
this.scheduleMentionUnreadCountsFetch();
|
||||
};
|
||||
|
||||
clearTimer = conversationId => {
|
||||
@@ -273,6 +345,12 @@ class ActionCableConnector extends BaseActionCableConnector {
|
||||
this.app.$store.dispatch('labels/revalidate', { newKey: keys.label });
|
||||
this.app.$store.dispatch('inboxes/revalidate', { newKey: keys.inbox });
|
||||
this.app.$store.dispatch('teams/revalidate', { newKey: keys.team });
|
||||
|
||||
if (this.isFilteredUnreadCountsEnabled()) {
|
||||
// Inbox/team/label visibility changes can change the accessible set used
|
||||
// by filtered unread counts even when no conversation row changes.
|
||||
this.refreshConversationUnreadCountsWithFilteredRetry();
|
||||
}
|
||||
};
|
||||
|
||||
onVoiceCallIncoming = data => {
|
||||
|
||||
@@ -38,7 +38,7 @@ export const getAgentsByUpdatedPresence = (
|
||||
currentAccountId
|
||||
) => {
|
||||
const agentsWithDynamicPresenceUpdate = agents.map(item =>
|
||||
item.id === currentUser.id
|
||||
item.id === currentUser.id && (item.assignee_type || 'User') === 'User'
|
||||
? {
|
||||
...item,
|
||||
availability_status: currentUser.accounts.find(
|
||||
|
||||
@@ -9,6 +9,7 @@ import * as Sentry from '@sentry/vue';
|
||||
import camelcaseKeys from 'camelcase-keys';
|
||||
import { FORMATTING, MARKDOWN_PATTERNS } from 'dashboard/constants/editor';
|
||||
import { INBOX_TYPES, TWILIO_CHANNEL_MEDIUM } from 'dashboard/helper/inbox';
|
||||
import { InputRule, inputRules } from 'prosemirror-inputrules';
|
||||
|
||||
/**
|
||||
* Extract text from markdown, and remove all images, code blocks, links, headers, bold, italic, lists etc.
|
||||
@@ -428,6 +429,55 @@ export function stripUnsupportedFormatting(content, schema) {
|
||||
* - emoji
|
||||
*/
|
||||
|
||||
// Liquid delimiters ({{ }} / {% %}) the backend evaluates on send.
|
||||
const LIQUID_SYNTAX = /\{\{|\{%/;
|
||||
|
||||
// Value when set (and not itself Liquid), else the {{placeholder}} for the backend.
|
||||
export const resolveVariableText = (key, variables) => {
|
||||
const value = String(variables?.[key] ?? '');
|
||||
return value && !LIQUID_SYNTAX.test(value) ? value : `{{${key}}}`;
|
||||
};
|
||||
|
||||
// Name variables normalized like the backend drops (UserDrop/ContactDrop):
|
||||
// name split on whitespace, each word Ruby-capitalized (rest downcased).
|
||||
const getNameVariables = (prefix, name) => {
|
||||
const names = (name || '')
|
||||
.split(/\s+/)
|
||||
.filter(Boolean)
|
||||
.map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase());
|
||||
return {
|
||||
[`${prefix}.name`]: names.join(' '),
|
||||
[`${prefix}.first_name`]: names[0] || '',
|
||||
[`${prefix}.last_name`]: names.length > 1 ? names[names.length - 1] : '',
|
||||
};
|
||||
};
|
||||
|
||||
// {{agent.*}} values for the message sender.
|
||||
export const getAgentVariables = user => ({
|
||||
...getNameVariables('agent', user.name),
|
||||
'agent.email': user.email,
|
||||
});
|
||||
|
||||
// {{contact.*}} name values.
|
||||
export const getContactVariables = contact =>
|
||||
getNameVariables('contact', contact?.name);
|
||||
|
||||
// Resolves a manually typed {{variable}} to its value on the closing braces.
|
||||
// Leaves the placeholder when there's no value, the value is Liquid, or it's a private note.
|
||||
export const createVariableInputRule = ({ isPrivate, getVariables }) => {
|
||||
const rule = new InputRule(
|
||||
/\{\{([^{}]+)\}\}$/,
|
||||
(editorState, match, from, to) => {
|
||||
if (isPrivate()) return null;
|
||||
const [, key] = match;
|
||||
const text = resolveVariableText(key, getVariables());
|
||||
if (text === `{{${key}}}`) return null;
|
||||
return editorState.tr.insertText(text, from, to);
|
||||
}
|
||||
);
|
||||
return inputRules({ rules: [rule] });
|
||||
};
|
||||
|
||||
/**
|
||||
* Centralized node creation function that handles the creation of different types of nodes based on the specified type.
|
||||
* @param {Object} editorView - The editor view instance.
|
||||
@@ -462,7 +512,7 @@ const createNode = (editorView, nodeType, content) => {
|
||||
);
|
||||
}
|
||||
case 'variable':
|
||||
return state.schema.text(`{{${content}}}`);
|
||||
return state.schema.text(content);
|
||||
case 'emoji':
|
||||
return state.schema.text(content);
|
||||
case 'tool': {
|
||||
@@ -497,8 +547,12 @@ const nodeCreators = {
|
||||
to,
|
||||
};
|
||||
},
|
||||
variable: (editorView, content, from, to) => ({
|
||||
node: createNode(editorView, 'variable', content),
|
||||
variable: (editorView, content, from, to, variables) => ({
|
||||
node: createNode(
|
||||
editorView,
|
||||
'variable',
|
||||
resolveVariableText(content, variables)
|
||||
),
|
||||
from,
|
||||
to,
|
||||
}),
|
||||
|
||||
@@ -19,6 +19,7 @@ const FEATURE_HELP_URLS = {
|
||||
webhook: 'https://chwt.app/hc/webhooks',
|
||||
billing: 'https://chwt.app/pricing',
|
||||
saml: 'https://chwt.app/hc/saml',
|
||||
captain: 'https://chwt.app/captain-docs',
|
||||
captain_billing: 'https://chwt.app/hc/captain_billing',
|
||||
};
|
||||
|
||||
|
||||
@@ -20,6 +20,8 @@ export const SIDEBAR_SORT_OPTIONS_BY_SECTION = Object.freeze({
|
||||
SIDEBAR_SORT_KEYS.CREATED_ASC,
|
||||
SIDEBAR_SORT_KEYS.ALPHABETICAL_ASC,
|
||||
SIDEBAR_SORT_KEYS.ALPHABETICAL_DESC,
|
||||
SIDEBAR_SORT_KEYS.UNREAD_COUNT_DESC,
|
||||
SIDEBAR_SORT_KEYS.UNREAD_COUNT_ASC,
|
||||
],
|
||||
[SIDEBAR_SORT_SECTIONS.TEAMS]: [
|
||||
SIDEBAR_SORT_KEYS.CREATED_DESC,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, it, beforeEach, afterEach, expect, vi } from 'vitest';
|
||||
import ActionCableConnector from '../actionCable';
|
||||
import { FEATURE_FLAGS } from 'dashboard/featureFlags';
|
||||
|
||||
vi.mock('shared/helpers/mitt', () => ({
|
||||
emitter: {
|
||||
@@ -17,6 +18,9 @@ global.chatwootConfig = {
|
||||
websocketURL: 'wss://test.chatwoot.com',
|
||||
};
|
||||
|
||||
const mockRetryJitter = value =>
|
||||
vi.spyOn(Math, 'random').mockReturnValue(value);
|
||||
|
||||
describe('ActionCableConnector - Copilot Tests', () => {
|
||||
let store;
|
||||
let actionCable;
|
||||
@@ -39,6 +43,8 @@ describe('ActionCableConnector - Copilot Tests', () => {
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.clearAllTimers();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
describe('copilot event handlers', () => {
|
||||
@@ -81,12 +87,223 @@ describe('ActionCableConnector - Copilot Tests', () => {
|
||||
});
|
||||
|
||||
it('should refetch unread counts when unread count changes', () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));
|
||||
mockRetryJitter(0.5);
|
||||
|
||||
actionCable.onReceived({
|
||||
event: 'conversation.unread_count_changed',
|
||||
data: { account_id: 1 },
|
||||
});
|
||||
|
||||
expect(mockDispatch).toHaveBeenCalledWith('conversationUnreadCounts/get');
|
||||
|
||||
vi.advanceTimersByTime(37499);
|
||||
expect(mockDispatch).toHaveBeenCalledTimes(1);
|
||||
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(mockDispatch).toHaveBeenCalledTimes(2);
|
||||
expect(mockDispatch).toHaveBeenLastCalledWith(
|
||||
'conversationUnreadCounts/get'
|
||||
);
|
||||
});
|
||||
|
||||
it('does not retry unread count changes when filtered counts are disabled', () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));
|
||||
store.$store.getters[
|
||||
'accounts/isFeatureEnabledonAccount'
|
||||
].mockImplementation(
|
||||
(_, featureFlag) =>
|
||||
featureFlag === FEATURE_FLAGS.CONVERSATION_UNREAD_COUNTS
|
||||
);
|
||||
|
||||
actionCable.onReceived({
|
||||
event: 'conversation.unread_count_changed',
|
||||
data: { account_id: 1 },
|
||||
});
|
||||
|
||||
expect(mockDispatch).toHaveBeenCalledTimes(1);
|
||||
|
||||
vi.advanceTimersByTime(45000);
|
||||
expect(mockDispatch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('delays unread count refetch when a conversation is mentioned', () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));
|
||||
|
||||
const conversation = { id: 1, account_id: 1 };
|
||||
|
||||
actionCable.onReceived({
|
||||
event: 'conversation.mentioned',
|
||||
data: conversation,
|
||||
});
|
||||
|
||||
expect(mockDispatch).toHaveBeenCalledWith('addMentions', conversation);
|
||||
expect(mockDispatch).not.toHaveBeenCalledWith(
|
||||
'conversationUnreadCounts/get'
|
||||
);
|
||||
|
||||
vi.advanceTimersByTime(4999);
|
||||
expect(mockDispatch).not.toHaveBeenCalledWith(
|
||||
'conversationUnreadCounts/get'
|
||||
);
|
||||
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(mockDispatch).toHaveBeenCalledWith('conversationUnreadCounts/get');
|
||||
});
|
||||
|
||||
it('does not schedule mention unread count fetches when filtered counts are disabled', () => {
|
||||
vi.useFakeTimers();
|
||||
store.$store.getters[
|
||||
'accounts/isFeatureEnabledonAccount'
|
||||
].mockImplementation(
|
||||
(_, featureFlag) =>
|
||||
featureFlag === FEATURE_FLAGS.CONVERSATION_UNREAD_COUNTS
|
||||
);
|
||||
|
||||
const conversation = { id: 1, account_id: 1 };
|
||||
|
||||
actionCable.onReceived({
|
||||
event: 'conversation.mentioned',
|
||||
data: conversation,
|
||||
});
|
||||
|
||||
expect(mockDispatch).toHaveBeenCalledWith('addMentions', conversation);
|
||||
|
||||
vi.advanceTimersByTime(45000);
|
||||
expect(mockDispatch).not.toHaveBeenCalledWith(
|
||||
'conversationUnreadCounts/get'
|
||||
);
|
||||
});
|
||||
|
||||
it('retries mentioned unread counts after the backend refresh window', () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));
|
||||
mockRetryJitter(0.5);
|
||||
|
||||
actionCable.onReceived({
|
||||
event: 'conversation.mentioned',
|
||||
data: { id: 1, account_id: 1 },
|
||||
});
|
||||
|
||||
const unreadCountFetches = () =>
|
||||
mockDispatch.mock.calls.filter(
|
||||
([action]) => action === 'conversationUnreadCounts/get'
|
||||
);
|
||||
|
||||
vi.advanceTimersByTime(5000);
|
||||
expect(unreadCountFetches()).toHaveLength(1);
|
||||
|
||||
vi.advanceTimersByTime(32499);
|
||||
expect(unreadCountFetches()).toHaveLength(1);
|
||||
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(unreadCountFetches()).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('reschedules mentioned unread count retries for later invalidations', () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));
|
||||
mockRetryJitter(0);
|
||||
|
||||
const unreadCountFetches = () =>
|
||||
mockDispatch.mock.calls.filter(
|
||||
([action]) => action === 'conversationUnreadCounts/get'
|
||||
);
|
||||
|
||||
actionCable.onReceived({
|
||||
event: 'conversation.mentioned',
|
||||
data: { id: 1, account_id: 1 },
|
||||
});
|
||||
|
||||
vi.advanceTimersByTime(5000);
|
||||
expect(unreadCountFetches()).toHaveLength(1);
|
||||
|
||||
vi.advanceTimersByTime(10000);
|
||||
actionCable.onReceived({
|
||||
event: 'conversation.mentioned',
|
||||
data: { id: 1, account_id: 1 },
|
||||
});
|
||||
|
||||
vi.advanceTimersByTime(5000);
|
||||
expect(unreadCountFetches()).toHaveLength(2);
|
||||
|
||||
vi.advanceTimersByTime(10000);
|
||||
expect(unreadCountFetches()).toHaveLength(2);
|
||||
|
||||
vi.advanceTimersByTime(15000);
|
||||
expect(unreadCountFetches()).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('refetches filtered unread counts after account cache invalidation', () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));
|
||||
mockRetryJitter(0.5);
|
||||
|
||||
const cacheKeys = {
|
||||
label: 'label-key',
|
||||
inbox: 'inbox-key',
|
||||
team: 'team-key',
|
||||
};
|
||||
const unreadCountFetches = () =>
|
||||
mockDispatch.mock.calls.filter(
|
||||
([action]) => action === 'conversationUnreadCounts/get'
|
||||
);
|
||||
|
||||
actionCable.onReceived({
|
||||
event: 'account.cache_invalidated',
|
||||
data: { account_id: 1, cache_keys: cacheKeys },
|
||||
});
|
||||
|
||||
expect(mockDispatch).toHaveBeenCalledWith('labels/revalidate', {
|
||||
newKey: cacheKeys.label,
|
||||
});
|
||||
expect(mockDispatch).toHaveBeenCalledWith('inboxes/revalidate', {
|
||||
newKey: cacheKeys.inbox,
|
||||
});
|
||||
expect(mockDispatch).toHaveBeenCalledWith('teams/revalidate', {
|
||||
newKey: cacheKeys.team,
|
||||
});
|
||||
expect(unreadCountFetches()).toHaveLength(1);
|
||||
|
||||
vi.advanceTimersByTime(37499);
|
||||
expect(unreadCountFetches()).toHaveLength(1);
|
||||
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(unreadCountFetches()).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('does not refetch unread counts after cache invalidation when filtered counts are disabled', () => {
|
||||
vi.useFakeTimers();
|
||||
store.$store.getters[
|
||||
'accounts/isFeatureEnabledonAccount'
|
||||
].mockImplementation(
|
||||
(_, featureFlag) =>
|
||||
featureFlag === FEATURE_FLAGS.CONVERSATION_UNREAD_COUNTS
|
||||
);
|
||||
|
||||
actionCable.onReceived({
|
||||
event: 'account.cache_invalidated',
|
||||
data: {
|
||||
account_id: 1,
|
||||
cache_keys: {
|
||||
label: 'label-key',
|
||||
inbox: 'inbox-key',
|
||||
team: 'team-key',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(mockDispatch).not.toHaveBeenCalledWith(
|
||||
'conversationUnreadCounts/get'
|
||||
);
|
||||
|
||||
vi.advanceTimersByTime(45000);
|
||||
expect(mockDispatch).not.toHaveBeenCalledWith(
|
||||
'conversationUnreadCounts/get'
|
||||
);
|
||||
});
|
||||
|
||||
it('does not refetch unread counts when unread count feature is disabled', () => {
|
||||
|
||||
@@ -94,16 +94,56 @@ describe('getContentNode', () => {
|
||||
});
|
||||
|
||||
describe('getVariableNode', () => {
|
||||
it('should create a variable node', () => {
|
||||
const content = 'name';
|
||||
const from = 0;
|
||||
const to = 10;
|
||||
getContentNode(editorView, 'variable', content, {
|
||||
from,
|
||||
to,
|
||||
});
|
||||
it('should render the resolved value directly when the variable has a value', () => {
|
||||
getContentNode(
|
||||
editorView,
|
||||
'variable',
|
||||
'contact.name',
|
||||
{ from: 0, to: 10 },
|
||||
{ 'contact.name': 'John' }
|
||||
);
|
||||
|
||||
expect(editorView.state.schema.text).toHaveBeenCalledWith('{{name}}');
|
||||
expect(editorView.state.schema.text).toHaveBeenCalledWith('John');
|
||||
});
|
||||
|
||||
it('should resolve camelCase custom attributes and non-string values', () => {
|
||||
getContentNode(
|
||||
editorView,
|
||||
'variable',
|
||||
'contact.custom_attribute.cloudCustomer',
|
||||
{ from: 0, to: 10 },
|
||||
{ 'contact.custom_attribute.cloudCustomer': true }
|
||||
);
|
||||
|
||||
expect(editorView.state.schema.text).toHaveBeenCalledWith('true');
|
||||
});
|
||||
|
||||
it('should keep the placeholder when the variable has no value', () => {
|
||||
getContentNode(
|
||||
editorView,
|
||||
'variable',
|
||||
'contact.email',
|
||||
{ from: 0, to: 10 },
|
||||
{}
|
||||
);
|
||||
|
||||
expect(editorView.state.schema.text).toHaveBeenCalledWith(
|
||||
'{{contact.email}}'
|
||||
);
|
||||
});
|
||||
|
||||
it('should keep the placeholder when the value contains Liquid syntax', () => {
|
||||
getContentNode(
|
||||
editorView,
|
||||
'variable',
|
||||
'contact.name',
|
||||
{ from: 0, to: 10 },
|
||||
{ 'contact.name': '{{agent.email}}' }
|
||||
);
|
||||
|
||||
expect(editorView.state.schema.text).toHaveBeenCalledWith(
|
||||
'{{contact.name}}'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -11,9 +11,12 @@ import {
|
||||
calculateMenuPosition,
|
||||
cleanSignature,
|
||||
collapseSelection,
|
||||
createVariableInputRule,
|
||||
extractTextFromMarkdown,
|
||||
findNodeToInsertImage,
|
||||
findSignatureInBody,
|
||||
getAgentVariables,
|
||||
getContactVariables,
|
||||
getContentNode,
|
||||
getFormattingForEditor,
|
||||
getMenuAnchor,
|
||||
@@ -1228,3 +1231,149 @@ describe('Menu positioning helpers', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAgentVariables', () => {
|
||||
it('builds agent variables from the user', () => {
|
||||
expect(
|
||||
getAgentVariables({ name: 'John Doe', email: 'john@example.com' })
|
||||
).toEqual({
|
||||
'agent.name': 'John Doe',
|
||||
'agent.first_name': 'John',
|
||||
'agent.last_name': 'Doe',
|
||||
'agent.email': 'john@example.com',
|
||||
});
|
||||
});
|
||||
|
||||
it('normalizes casing like the backend UserDrop (Ruby capitalize)', () => {
|
||||
const variables = getAgentVariables({ name: 'JANE doE' });
|
||||
|
||||
expect(variables['agent.name']).toBe('Jane Doe');
|
||||
expect(variables['agent.first_name']).toBe('Jane');
|
||||
expect(variables['agent.last_name']).toBe('Doe');
|
||||
});
|
||||
|
||||
it('ignores extra whitespace between words', () => {
|
||||
expect(getAgentVariables({ name: ' john doe ' })['agent.name']).toBe(
|
||||
'John Doe'
|
||||
);
|
||||
});
|
||||
|
||||
it('leaves last_name empty for single-word names', () => {
|
||||
const variables = getAgentVariables({ name: 'john' });
|
||||
|
||||
expect(variables['agent.first_name']).toBe('John');
|
||||
expect(variables['agent.last_name']).toBe('');
|
||||
});
|
||||
|
||||
it('handles a missing name', () => {
|
||||
const variables = getAgentVariables({ email: 'john@example.com' });
|
||||
|
||||
expect(variables['agent.name']).toBe('');
|
||||
expect(variables['agent.first_name']).toBe('');
|
||||
expect(variables['agent.last_name']).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getContactVariables', () => {
|
||||
it('normalizes casing like the backend ContactDrop (Ruby capitalize)', () => {
|
||||
expect(getContactVariables({ name: 'JANE doE' })).toEqual({
|
||||
'contact.name': 'Jane Doe',
|
||||
'contact.first_name': 'Jane',
|
||||
'contact.last_name': 'Doe',
|
||||
});
|
||||
});
|
||||
|
||||
it('leaves last_name empty for single-word names', () => {
|
||||
const variables = getContactVariables({ name: 'john' });
|
||||
|
||||
expect(variables['contact.first_name']).toBe('John');
|
||||
expect(variables['contact.last_name']).toBe('');
|
||||
});
|
||||
|
||||
it('handles a missing contact', () => {
|
||||
expect(getContactVariables(undefined)['contact.name']).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('createVariableInputRule', () => {
|
||||
// Editor holding `{{key}` so we can simulate typing the final `}`.
|
||||
const buildView = (typed, { isPrivate = false, variables = {} } = {}) => {
|
||||
const plugin = createVariableInputRule({
|
||||
isPrivate: () => isPrivate,
|
||||
getVariables: () => variables,
|
||||
});
|
||||
const state = EditorState.create({
|
||||
schema,
|
||||
doc: schema.node('doc', null, [
|
||||
schema.node('paragraph', null, [schema.text(typed)]),
|
||||
]),
|
||||
plugins: [plugin],
|
||||
});
|
||||
return new EditorView(document.body, { state });
|
||||
};
|
||||
|
||||
// Types the closing `}`; when the rule declines, insert it like the browser would.
|
||||
const typeClosingBrace = view => {
|
||||
const end = view.state.doc.content.size - 1;
|
||||
const handled = view.someProp('handleTextInput', fn =>
|
||||
fn(view, end, end, '}')
|
||||
);
|
||||
if (!handled) {
|
||||
view.dispatch(view.state.tr.insertText('}', end, end));
|
||||
}
|
||||
};
|
||||
|
||||
it('resolves a manually typed {{variable}} to its value on the closing brace', () => {
|
||||
const view = buildView('{{contact.name}', {
|
||||
variables: { 'contact.name': 'John' },
|
||||
});
|
||||
|
||||
typeClosingBrace(view);
|
||||
|
||||
expect(view.state.doc.textContent).toBe('John');
|
||||
view.destroy();
|
||||
});
|
||||
|
||||
it('resolves boolean/non-string values', () => {
|
||||
const view = buildView('{{contact.custom_attribute.cloudCustomer}', {
|
||||
variables: { 'contact.custom_attribute.cloudCustomer': true },
|
||||
});
|
||||
|
||||
typeClosingBrace(view);
|
||||
|
||||
expect(view.state.doc.textContent).toBe('true');
|
||||
view.destroy();
|
||||
});
|
||||
|
||||
it('keeps the placeholder when the variable has no value', () => {
|
||||
const view = buildView('{{contact.email}', { variables: {} });
|
||||
|
||||
typeClosingBrace(view);
|
||||
|
||||
expect(view.state.doc.textContent).toBe('{{contact.email}}');
|
||||
view.destroy();
|
||||
});
|
||||
|
||||
it('keeps the placeholder when the value itself contains Liquid syntax', () => {
|
||||
const view = buildView('{{contact.name}', {
|
||||
variables: { 'contact.name': '{{agent.email}}' },
|
||||
});
|
||||
|
||||
typeClosingBrace(view);
|
||||
|
||||
expect(view.state.doc.textContent).toBe('{{contact.name}}');
|
||||
view.destroy();
|
||||
});
|
||||
|
||||
it('does not resolve inside a private note', () => {
|
||||
const view = buildView('{{contact.name}', {
|
||||
isPrivate: true,
|
||||
variables: { 'contact.name': 'John' },
|
||||
});
|
||||
|
||||
typeClosingBrace(view);
|
||||
|
||||
expect(view.state.doc.textContent).toBe('{{contact.name}}');
|
||||
view.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -148,7 +148,7 @@ describe('#normalizeSidebarSortPreferences', () => {
|
||||
|
||||
it('falls back to defaults for unsupported preferences', () => {
|
||||
const preferences = normalizeSidebarSortPreferences({
|
||||
[SIDEBAR_SORT_SECTIONS.FOLDERS]: SIDEBAR_SORT_KEYS.UNREAD_COUNT_DESC,
|
||||
[SIDEBAR_SORT_SECTIONS.FOLDERS]: 'unsupported_sort',
|
||||
});
|
||||
|
||||
expect(preferences).toEqual(DEFAULT_SIDEBAR_SORT_PREFERENCES);
|
||||
@@ -171,6 +171,15 @@ describe('#getSidebarSortOptions', () => {
|
||||
expect(options).toContain(SIDEBAR_SORT_KEYS.UNREAD_COUNT_ASC);
|
||||
});
|
||||
|
||||
it('keeps folder unread count options when filtered unread counts are enabled', () => {
|
||||
const options = getSidebarSortOptions(SIDEBAR_SORT_SECTIONS.FOLDERS, {
|
||||
hasUnreadCounts: true,
|
||||
});
|
||||
|
||||
expect(options).toContain(SIDEBAR_SORT_KEYS.UNREAD_COUNT_DESC);
|
||||
expect(options).toContain(SIDEBAR_SORT_KEYS.UNREAD_COUNT_ASC);
|
||||
});
|
||||
|
||||
it('removes unread count options when unread counts are disabled', () => {
|
||||
const options = getSidebarSortOptions(SIDEBAR_SORT_SECTIONS.TEAMS, {
|
||||
hasUnreadCounts: false,
|
||||
@@ -180,6 +189,16 @@ describe('#getSidebarSortOptions', () => {
|
||||
expect(options).not.toContain(SIDEBAR_SORT_KEYS.UNREAD_COUNT_ASC);
|
||||
expect(options).toContain(SIDEBAR_SORT_KEYS.ALPHABETICAL_ASC);
|
||||
});
|
||||
|
||||
it('removes folder unread count options when filtered unread counts are disabled', () => {
|
||||
const options = getSidebarSortOptions(SIDEBAR_SORT_SECTIONS.FOLDERS, {
|
||||
hasUnreadCounts: false,
|
||||
});
|
||||
|
||||
expect(options).not.toContain(SIDEBAR_SORT_KEYS.UNREAD_COUNT_DESC);
|
||||
expect(options).not.toContain(SIDEBAR_SORT_KEYS.UNREAD_COUNT_ASC);
|
||||
expect(options).toContain(SIDEBAR_SORT_KEYS.ALPHABETICAL_ASC);
|
||||
});
|
||||
});
|
||||
|
||||
describe('#resolveSidebarSort', () => {
|
||||
@@ -202,4 +221,14 @@ describe('#resolveSidebarSort', () => {
|
||||
|
||||
expect(sortBy).toBe(SIDEBAR_SORT_KEYS.ALPHABETICAL_ASC);
|
||||
});
|
||||
|
||||
it('falls back to alphabetical sort for folders when filtered unread counts are disabled', () => {
|
||||
const sortBy = resolveSidebarSort(
|
||||
SIDEBAR_SORT_SECTIONS.FOLDERS,
|
||||
SIDEBAR_SORT_KEYS.UNREAD_COUNT_DESC,
|
||||
{ hasUnreadCounts: false }
|
||||
);
|
||||
|
||||
expect(sortBy).toBe(SIDEBAR_SORT_KEYS.ALPHABETICAL_ASC);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -44,6 +44,8 @@
|
||||
"TWILIO_WHATSAPP_CAN_REPLY": "You can only reply to this conversation using a template message due to",
|
||||
"TWILIO_WHATSAPP_24_HOURS_WINDOW": "24 hour message window restriction",
|
||||
"OLD_INSTAGRAM_INBOX_REPLY_BANNER": "This Instagram account was migrated to the new Instagram channel inbox. All new messages will show up there. You won’t be able to send messages from this conversation anymore.",
|
||||
"INSTAGRAM_RESTRICTION_BANNER": "Instagram is currently restricted. Some messages or actions may be delayed or unavailable while we restore full support.",
|
||||
"INSTAGRAM_RESTRICTION_STATUS_LINK": "View status update",
|
||||
"REPLYING_TO": "You are replying to:",
|
||||
"REMOVE_SELECTION": "Remove Selection",
|
||||
"DOWNLOAD": "Download",
|
||||
|
||||
@@ -58,7 +58,10 @@
|
||||
"ERROR_MESSAGE": "There was an error connecting to Instagram, please try again",
|
||||
"ERROR_AUTH": "There was an error connecting to Instagram, please try again",
|
||||
"NEW_INBOX_SUGGESTION": "This Instagram account was previously linked to a different inbox and has now been migrated here. All new messages will appear here. The old inbox will no longer be able to send or receive messages for this account.",
|
||||
"DUPLICATE_INBOX_BANNER": "This Instagram account was migrated to the new Instagram channel inbox. You won’t be able to send/receive Instagram messages from this inbox anymore."
|
||||
"DUPLICATE_INBOX_BANNER": "This Instagram account was migrated to the new Instagram channel inbox. You won’t be able to send/receive Instagram messages from this inbox anymore.",
|
||||
"RESTRICTED_WARNING": "Instagram inbox creation is temporarily unavailable due to current Instagram platform restrictions. We’ll restore support as soon as possible.",
|
||||
"SETTINGS_RESTRICTED_WARNING": "Instagram is currently restricted. Some messages or actions may be delayed or unavailable while we restore full support.",
|
||||
"STATUS_LINK": "View status update"
|
||||
},
|
||||
"TIKTOK": {
|
||||
"CONTINUE_WITH_TIKTOK": "Continue with TikTok",
|
||||
@@ -320,6 +323,8 @@
|
||||
"SUCCESS_FALLBACK": "WhatsApp Business Account has been successfully configured",
|
||||
"MANUAL_FALLBACK": "If your number is already connected to the WhatsApp Business Platform (API), or if you’re a tech provider onboarding your own number, please use the {link} flow",
|
||||
"MANUAL_LINK_TEXT": "manual setup flow",
|
||||
"RESTRICTED_WARNING": "WhatsApp embedded signup is temporarily unavailable due to current Meta platform restrictions. We’ll restore support as soon as possible.",
|
||||
"STATUS_LINK": "View status update",
|
||||
"CALLING_ENABLE_FAILED": "Your WhatsApp inbox is ready, but voice calling couldn't be turned on — this number isn't enrolled in the WhatsApp Business Calling API yet. Reach out to Meta or your WhatsApp Business Solution Provider to onboard it, then turn calling on from the inbox's Calls settings."
|
||||
},
|
||||
"API": {
|
||||
@@ -815,6 +820,15 @@
|
||||
"WHATSAPP_EMBEDDED_SIGNUP_SUBHEADER": "This inbox is connected through WhatsApp embedded signup.",
|
||||
"WHATSAPP_EMBEDDED_SIGNUP_DESCRIPTION": "You can reconfigure this inbox to update your WhatsApp Business settings.",
|
||||
"WHATSAPP_RECONFIGURE_BUTTON": "Reconfigure",
|
||||
"WHATSAPP_MANUAL_TRANSFER_TITLE": "Switch to Manual Setup",
|
||||
"WHATSAPP_MANUAL_TRANSFER_SUBHEADER": "This inbox was connected through WhatsApp embedded signup, which is no longer supported. Enter the WhatsApp Cloud API credentials from your own Meta app to switch this inbox to a manual setup. Configure the webhook in your Meta app using the verification token above before switching.",
|
||||
"WHATSAPP_MANUAL_TRANSFER_PHONE_NUMBER_ID_LABEL": "Phone Number ID",
|
||||
"WHATSAPP_MANUAL_TRANSFER_BUSINESS_ACCOUNT_ID_LABEL": "Business Account ID",
|
||||
"WHATSAPP_MANUAL_TRANSFER_API_KEY_LABEL": "API Key",
|
||||
"WHATSAPP_MANUAL_TRANSFER_API_KEY_PLACEHOLDER": "Enter a permanent access token from your Meta app",
|
||||
"WHATSAPP_MANUAL_TRANSFER_BUTTON": "Switch to Manual Setup",
|
||||
"WHATSAPP_MANUAL_TRANSFER_SUCCESS": "Inbox switched to manual setup successfully.",
|
||||
"WHATSAPP_MANUAL_TRANSFER_ERROR": "Could not switch to manual setup. Please verify the credentials and try again.",
|
||||
"WHATSAPP_CONNECT_TITLE": "Connect to WhatsApp Business",
|
||||
"WHATSAPP_CONNECT_SUBHEADER": "Upgrade to WhatsApp embedded signup for easier management.",
|
||||
"WHATSAPP_CONNECT_DESCRIPTION": "Connect this inbox to WhatsApp Business for enhanced features and easier management.",
|
||||
@@ -832,6 +846,70 @@
|
||||
"WHATSAPP_TEMPLATES_SYNC_SUBHEADER": "Manually sync message templates from WhatsApp to update your available templates.",
|
||||
"WHATSAPP_TEMPLATES_SYNC_BUTTON": "Sync Templates",
|
||||
"WHATSAPP_TEMPLATES_SYNC_SUCCESS": "Templates sync initiated successfully. It may take a couple of minutes to update.",
|
||||
"WHATSAPP_MANUAL_MIGRATION": {
|
||||
"BANNER": {
|
||||
"TITLE": "WhatsApp setup action required",
|
||||
"DESCRIPTION": "Meta restrictions are affecting WhatsApp setup and management features. Reconnect this inbox manually to keep your WhatsApp configuration up to date.",
|
||||
"START": "Start manual migration",
|
||||
"GUIDE": "View guide"
|
||||
},
|
||||
"DIALOG": {
|
||||
"EYEBROW": "WhatsApp manual migration",
|
||||
"TITLE": "Reconnect WhatsApp inbox",
|
||||
"CLOSE": "Close",
|
||||
"ACTION_REQUIRED_TITLE": "Action required for this WhatsApp inbox",
|
||||
"ACTION_REQUIRED_DESCRIPTION": "Meta restrictions are affecting setup and management features. This guided flow updates the WhatsApp API connection without creating a new inbox.",
|
||||
"GUIDE_LINK": "Open the manual setup guide",
|
||||
"PRESERVED_TITLE": "Preserved",
|
||||
"PRESERVED_DESCRIPTION": "Conversations, contacts, collaborators, routing, business hours, and inbox settings.",
|
||||
"UPDATED_TITLE": "Updated",
|
||||
"UPDATED_DESCRIPTION": "WABA ID, phone number ID, access token, and webhook configuration.",
|
||||
"WABA_ID": "WABA ID",
|
||||
"WABA_PLACEHOLDER": "Enter WABA ID",
|
||||
"WABA_HELP": "The WhatsApp Business Account that owns this phone number.",
|
||||
"PHONE_NUMBER_ID": "Phone Number ID",
|
||||
"PHONE_NUMBER_PLACEHOLDER": "Enter Phone Number ID",
|
||||
"PHONE_NUMBER_HELP": "Meta's unique ID for the WhatsApp number connected to this inbox.",
|
||||
"DISPLAY_PHONE_NUMBER": "Display phone number",
|
||||
"DISPLAY_PHONE_NUMBER_PLACEHOLDER": "Enter display phone number",
|
||||
"DISPLAY_PHONE_NUMBER_HELP": "The customer-facing WhatsApp number. This cannot be changed during migration.",
|
||||
"ACCESS_TOKEN": "Permanent access token or system user token",
|
||||
"ACCESS_TOKEN_PLACEHOLDER": "Paste access token",
|
||||
"TOKEN_HELP_PREFIX": "The token must include",
|
||||
"TOKEN_HELP_MIDDLE": "Add",
|
||||
"TOKEN_HELP_SUFFIX": "for template sync and template management.",
|
||||
"MESSAGING_PERMISSION": "whatsapp_business_messaging.",
|
||||
"MANAGEMENT_PERMISSION": "whatsapp_business_management",
|
||||
"REVIEW_TITLE": "Review before reconnecting",
|
||||
"INBOX": "Inbox",
|
||||
"PHONE_NUMBER": "Phone number",
|
||||
"NOT_ENTERED": "Not entered",
|
||||
"VERIFY_NOTICE": "Chatwoot will verify these credentials with Meta before applying any changes. If verification fails, the current configuration is left untouched.",
|
||||
"BACK": "Back",
|
||||
"CANCEL": "Cancel",
|
||||
"CONTINUE": "Continue",
|
||||
"REVIEW_MIGRATION": "Review migration",
|
||||
"RECONNECT": "Reconnect WhatsApp inbox"
|
||||
},
|
||||
"STEPS": {
|
||||
"BEFORE_YOU_START": {
|
||||
"TITLE": "Before you start",
|
||||
"DESCRIPTION": "This reconnects the WhatsApp API details for this inbox. Conversations, collaborators, routing, business hours, CSAT, and bot settings will be preserved."
|
||||
},
|
||||
"BUSINESS_DETAILS": {
|
||||
"TITLE": "Business details",
|
||||
"DESCRIPTION": "Enter the WhatsApp assets from the customer Meta Business account."
|
||||
},
|
||||
"ACCESS_TOKEN": {
|
||||
"TITLE": "Access token",
|
||||
"DESCRIPTION": "Paste a permanent access token or system user token with WhatsApp permissions."
|
||||
},
|
||||
"REVIEW_MIGRATION": {
|
||||
"TITLE": "Review migration",
|
||||
"DESCRIPTION": "Confirm the connection details before reconnecting this inbox. Chatwoot will verify the token, WABA, and phone number with Meta before applying changes."
|
||||
}
|
||||
}
|
||||
},
|
||||
"WHATSAPP_CALLING_ENABLED": {
|
||||
"LABEL": "Enable voice calling",
|
||||
"DESCRIPTION": "Allow agents to start and receive WhatsApp voice calls on this inbox. Available only on embedded-signup WhatsApp Cloud channels with calling permission granted by Meta."
|
||||
|
||||
@@ -392,6 +392,82 @@
|
||||
"CAPTAIN": {
|
||||
"NAME": "Captain",
|
||||
"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": "Time saved",
|
||||
"HINT": "Estimate: Captain replies times ~2 minutes of assumed agent effort per reply. 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."
|
||||
}
|
||||
},
|
||||
"DRILLDOWN": {
|
||||
"CLOSE": "Close details",
|
||||
"EMPTY": "No records found for this metric.",
|
||||
"ERROR": "Could not load records. Please try again.",
|
||||
"LOAD_MORE": "Load more",
|
||||
"RESULT_COUNT_CONVERSATION": "{count} conversation | {count} conversations"
|
||||
},
|
||||
"KNOWLEDGE": {
|
||||
"TITLE": "Knowledge coverage",
|
||||
"COVERAGE": "{pct}% approved",
|
||||
"APPROVED": "Approved FAQs",
|
||||
"PENDING": "Pending FAQs",
|
||||
"DOCUMENTS": "Documents"
|
||||
},
|
||||
"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"
|
||||
}
|
||||
}
|
||||
},
|
||||
"ASSISTANT_SWITCHER": {
|
||||
"ASSISTANTS": "Assistants",
|
||||
"SWITCH_ASSISTANT": "Switch between assistants",
|
||||
@@ -735,6 +811,7 @@
|
||||
"DOCUMENTS": {
|
||||
"HEADER": "Documents",
|
||||
"ADD_NEW": "Create a new document",
|
||||
"FAQ_COUNT": "{n} FAQ | {n} FAQs",
|
||||
"SELECTED": "{count} selected",
|
||||
"SELECT_ALL": "Select all ({count})",
|
||||
"UNSELECT_ALL": "Unselect all ({count})",
|
||||
@@ -794,7 +871,27 @@
|
||||
},
|
||||
"RELATED_RESPONSES": {
|
||||
"TITLE": "Related FAQs",
|
||||
"DESCRIPTION": "These FAQs are generated directly from the document."
|
||||
"EMPTY": "No FAQs have been generated from this document yet."
|
||||
},
|
||||
"DETAILS": {
|
||||
"DESCRIPTION": "Review the crawled content and the FAQs generated from this source.",
|
||||
"SOURCE": "Source",
|
||||
"GENERATED_FAQS": "Generated FAQs",
|
||||
"LAST_UPDATED": "Last updated",
|
||||
"NOT_AVAILABLE": "Not available",
|
||||
"CONTENT_TAB": "Crawled content",
|
||||
"PDF_TAB": "PDF details",
|
||||
"CONTENT_TITLE": "Crawled content",
|
||||
"PDF_TITLE": "PDF file",
|
||||
"PDF_DESCRIPTION": "Review the original PDF source.",
|
||||
"CHARACTER_COUNT": "{count} characters extracted",
|
||||
"COPY_CONTENT": "Copy",
|
||||
"COPY_SUCCESS": "Crawled content copied to clipboard",
|
||||
"COPY_ERROR": "Could not copy crawled content",
|
||||
"VIEW_RAW": "View raw",
|
||||
"VIEW_PREVIEW": "View preview",
|
||||
"UNREADABLE_CONTENT": "Readable content could not be extracted from this document. You can view the raw extracted content.",
|
||||
"EMPTY_CONTENT": "No crawled content is available for this document yet."
|
||||
},
|
||||
"FORM_DESCRIPTION": "Enter the URL of the document to add it as a knowledge source and choose the assistant to associate it with.",
|
||||
"CREATE": {
|
||||
@@ -835,7 +932,7 @@
|
||||
},
|
||||
|
||||
"OPTIONS": {
|
||||
"VIEW_RELATED_RESPONSES": "View Related Responses",
|
||||
"VIEW_DETAILS": "View details",
|
||||
"SYNC_NOW": "Refresh now",
|
||||
"RETRY_SYNC": "Retry refresh",
|
||||
"DELETE_DOCUMENT": "Delete Document"
|
||||
|
||||
@@ -263,7 +263,7 @@
|
||||
"EMAIL_VERIFICATION_SENT": "Verification email has been sent. Please check your inbox.",
|
||||
"ACCOUNT_SUSPENDED": {
|
||||
"TITLE": "Account Suspended",
|
||||
"MESSAGE": "Your account is suspended. Please reach out to the support team for more information."
|
||||
"MESSAGE": "Your account has been suspended due to activity that may violate our policies. If you believe this is a mistake, please contact our support team."
|
||||
},
|
||||
"NO_ACCOUNTS": {
|
||||
"TITLE": "No account found",
|
||||
@@ -324,6 +324,7 @@
|
||||
"ALL_COMPANIES": "All Companies",
|
||||
"CAPTAIN": "Captain",
|
||||
"CAPTAIN_ASSISTANTS": "Assistants",
|
||||
"CAPTAIN_OVERVIEW": "Overview",
|
||||
"CAPTAIN_DOCUMENTS": "Documents",
|
||||
"CAPTAIN_RESPONSES": "FAQs",
|
||||
"CAPTAIN_TOOLS": "Tools",
|
||||
@@ -339,6 +340,7 @@
|
||||
"NOTIFICATIONS": "Notifications",
|
||||
"CANNED_RESPONSES": "Canned Responses",
|
||||
"INTEGRATIONS": "Integrations",
|
||||
"DATA": "Data",
|
||||
"PROFILE_SETTINGS": "Profile Settings",
|
||||
"ACCOUNT_SETTINGS": "Account Settings",
|
||||
"APPLICATIONS": "Applications",
|
||||
@@ -410,6 +412,104 @@
|
||||
"CAPTAIN_AI": "Captain",
|
||||
"CONVERSATION_WORKFLOW": "Conversation Workflow"
|
||||
},
|
||||
"DATA_IMPORTS": {
|
||||
"HEADER": "Data",
|
||||
"DESCRIPTION": "Bring your existing contacts and past conversations into this account from another support tool. Each import runs in the background, so you can keep working while it finishes, track its progress, and review anything that was skipped along the way.",
|
||||
"LOADING": "Fetching imports",
|
||||
"DEFAULT_IMPORT_NAME": "Intercom import",
|
||||
"TABS": {
|
||||
"IMPORT": "Import",
|
||||
"EXPORT": "Export"
|
||||
},
|
||||
"TYPES": {
|
||||
"CONTACTS": "Contacts",
|
||||
"CONVERSATIONS": "Conversations",
|
||||
"MESSAGES": "Messages"
|
||||
},
|
||||
"DRAWER": {
|
||||
"TITLE": "New import",
|
||||
"SOURCE": "Source",
|
||||
"NAME": "Import name",
|
||||
"NAME_PLACEHOLDER": "July Intercom migration",
|
||||
"ACCESS_KEY": "Intercom access key",
|
||||
"ACCESS_KEY_PLACEHOLDER": "Paste your Intercom access key",
|
||||
"DATA_TYPES": "Data to import",
|
||||
"VALIDATING": "Validating access key...",
|
||||
"VALID_KEY": "Access key validated.",
|
||||
"INVALID_KEY": "Could not validate this access key.",
|
||||
"ACTIVE_IMPORT": "Wait for the active import to finish before starting another one.",
|
||||
"CANCEL": "Cancel",
|
||||
"IMPORT": "Import"
|
||||
},
|
||||
"EXPORT": {
|
||||
"TITLE": "Exports are on the way",
|
||||
"DESCRIPTION": "Export your contacts and conversations out of this account. This workflow is coming soon.",
|
||||
"COMING_SOON": "Coming soon"
|
||||
},
|
||||
"TABLE": {
|
||||
"TITLE": "Recent imports",
|
||||
"EMPTY": "No imports yet",
|
||||
"EMPTY_DESCRIPTION": "Start an import to bring your existing customer history into this account.",
|
||||
"NEW_IMPORT": "Import",
|
||||
"COUNT": "{count} imports",
|
||||
"UNNAMED": "Untitled import",
|
||||
"IMPORTED_COUNT": "{count} imported",
|
||||
"VIEW": "View import",
|
||||
"NAME": "Name",
|
||||
"TYPE": "Type",
|
||||
"STATUS": "Status",
|
||||
"IMPORTED": "Imported",
|
||||
"CREATED": "Created",
|
||||
"ABANDON": "Abandon"
|
||||
},
|
||||
"DETAIL": {
|
||||
"BACK": "Back to imports",
|
||||
"ERRORS": "Errors",
|
||||
"SKIP_LOGS": "Skip logs",
|
||||
"SOURCE": "Source",
|
||||
"IMPORT_TYPES": "Import types",
|
||||
"CREATED": "Created",
|
||||
"DURATION": "Duration",
|
||||
"INITIATED_BY": "Started by",
|
||||
"PROGRESS": "Import progress",
|
||||
"PROGRESS_WITH_TOTAL": "{imported} of {total} imported",
|
||||
"PROGRESS_WITHOUT_TOTAL": "{imported} imported",
|
||||
"PROGRESS_OF_TOTAL": "of {total} imported",
|
||||
"PROGRESS_IMPORTED": "imported",
|
||||
"LAST_UPDATED_TOOLTIP": "Last updated {time}",
|
||||
"NO_SKIP_LOGS": "No skipped or failed records recorded.",
|
||||
"DOWNLOAD_SKIP_LOGS": "Download CSV",
|
||||
"DOWNLOAD_ERROR_LOGS": "Download CSV",
|
||||
"ALL_SKIP_LOGS": "All",
|
||||
"KIND": "Kind",
|
||||
"NO_ERRORS": "No errors recorded.",
|
||||
"ERROR_CODE": "Code",
|
||||
"SOURCE_OBJECT": "Source object",
|
||||
"MESSAGE": "Message"
|
||||
},
|
||||
"MONITOR": {
|
||||
"LIVE": "Live updates every {seconds}s",
|
||||
"LAST_UPDATED": "Last updated {time}",
|
||||
"REFRESH": "Refresh",
|
||||
"REFRESHING": "Refreshing",
|
||||
"STAGES": {
|
||||
"unknown": "Waiting for update",
|
||||
"queued": "Queued",
|
||||
"contacts": "Importing contacts",
|
||||
"conversations": "Importing conversations",
|
||||
"finalizing": "Finalizing import",
|
||||
"completed": "Completed",
|
||||
"completed_with_errors": "Completed with errors",
|
||||
"failed": "Failed",
|
||||
"abandoned": "Abandoned"
|
||||
}
|
||||
},
|
||||
"ALERTS": {
|
||||
"IMPORT_STARTED": "Intercom import has started.",
|
||||
"IMPORT_ABANDONED": "Intercom import has been abandoned.",
|
||||
"IMPORT_FAILED": "Could not start the Intercom import."
|
||||
}
|
||||
},
|
||||
"CAPTAIN_SETTINGS": {
|
||||
"TITLE": "Captain Settings",
|
||||
"DESCRIPTION": "Configure your AI models and features for Captain. Captain follows a credit based billing, you will be charged credits for every action Captain takes based on the model selected.",
|
||||
@@ -467,7 +567,18 @@
|
||||
"TITLE": "Current Plan",
|
||||
"PLAN_NOTE": "You are currently subscribed to the **{plan}** plan with **{quantity}** licenses",
|
||||
"SEAT_COUNT": "Number of seats",
|
||||
"RENEWS_ON": "Renews on"
|
||||
"RENEWS_ON": "Renews on",
|
||||
"CURRENCY": "Currency"
|
||||
},
|
||||
"CURRENCY": {
|
||||
"SELECT": {
|
||||
"TITLE": "Choose your billing currency",
|
||||
"DESCRIPTION": "Select the currency you'd like to be billed in. This can't be changed once your subscription is created."
|
||||
},
|
||||
"OPTIONS": {
|
||||
"USD": "US Dollar (USD)",
|
||||
"BRL": "Brazilian Real (BRL)"
|
||||
}
|
||||
},
|
||||
"VIEW_PRICING": "View Pricing",
|
||||
"MANAGE_SUBSCRIPTION": {
|
||||
@@ -503,6 +614,7 @@
|
||||
"PURCHASE": "Purchase Credits",
|
||||
"LOADING": "Loading options...",
|
||||
"FETCH_ERROR": "Failed to load credit options. Please try again.",
|
||||
"RETRY": "Retry",
|
||||
"PURCHASE_ERROR": "Failed to process purchase. Please try again.",
|
||||
"PURCHASE_SUCCESS": "Successfully added {credits} credits to your account",
|
||||
"CONFIRM": {
|
||||
@@ -529,7 +641,7 @@
|
||||
"SSO_URL": {
|
||||
"LABEL": "SSO URL",
|
||||
"HELP": "The URL where SAML authentication requests will be sent",
|
||||
"PLACEHOLDER": "https://your-idp.com/saml/sso"
|
||||
"PLACEHOLDER": "https://sso.example.com/saml/sso"
|
||||
},
|
||||
"CERTIFICATE": {
|
||||
"LABEL": "Signing certificate in PEM format",
|
||||
@@ -549,7 +661,7 @@
|
||||
"IDP_ENTITY_ID": {
|
||||
"LABEL": "Identity Provider Entity ID",
|
||||
"HELP": "Unique identifier for your identity provider (usually found in IdP configuration)",
|
||||
"PLACEHOLDER": "https://your-idp.com/saml"
|
||||
"PLACEHOLDER": "https://sso.example.com/saml"
|
||||
},
|
||||
"UPDATE_BUTTON": "Update SAML Settings",
|
||||
"API": {
|
||||
|
||||
@@ -501,7 +501,7 @@
|
||||
"SSO_URL": {
|
||||
"LABEL": "SSO URL",
|
||||
"HELP": "A URL para onde as solicitações de autenticação SAML serão enviadas",
|
||||
"PLACEHOLDER": "https://your-idp.com/saml/sso"
|
||||
"PLACEHOLDER": "https://sso.example.com/saml/sso"
|
||||
},
|
||||
"CERTIFICATE": {
|
||||
"LABEL": "Certificado de assinatura no formato PEM",
|
||||
@@ -521,7 +521,7 @@
|
||||
"IDP_ENTITY_ID": {
|
||||
"LABEL": "ID da Entidade do Provedor de Identidade",
|
||||
"HELP": "Identificador exclusivo do seu provedor de identidade (geralmente encontrado na configuração do IdP)",
|
||||
"PLACEHOLDER": "https://seu-idp.com/saml"
|
||||
"PLACEHOLDER": "https://sso.example.com/saml"
|
||||
},
|
||||
"UPDATE_BUTTON": "Atualizar configurações de SAML",
|
||||
"API": {
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
<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 { usePolicy } from 'dashboard/composables/usePolicy';
|
||||
import CaptainAssistant from 'dashboard/api/captain/assistant';
|
||||
|
||||
import PageLayout from 'dashboard/components-next/captain/PageLayout.vue';
|
||||
import CaptainPaywall from 'dashboard/components-next/captain/pageComponents/Paywall.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 AssistantDrilldownDrawer from 'dashboard/components-next/captain/pageComponents/overview/AssistantDrilldownDrawer.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();
|
||||
// Drilldown is admin-only; the backend policy enforces the same restriction.
|
||||
const { checkPermissions } = usePolicy();
|
||||
const canDrilldown = computed(() => checkPermissions(['administrator']));
|
||||
|
||||
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: '' };
|
||||
|
||||
// Hours-saved is reported in hours, but large values read better as days. Past
|
||||
// 100h we switch the unit so the card stays legible.
|
||||
const formatDuration = hours =>
|
||||
hours >= 100 ? `${Math.round(hours / 24)}d` : `${hours}h`;
|
||||
|
||||
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',
|
||||
metric: 'conversations_handled',
|
||||
label: t('CAPTAIN.OVERVIEW.METRICS.HANDLED.LABEL'),
|
||||
hint: t('CAPTAIN.OVERVIEW.METRICS.HANDLED.HINT'),
|
||||
...metricFor('conversations_handled', v => v.toLocaleString(), 'up'),
|
||||
},
|
||||
{
|
||||
key: 'autoResolution',
|
||||
metric: 'auto_resolution_rate',
|
||||
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',
|
||||
metric: 'handoff_rate',
|
||||
label: t('CAPTAIN.OVERVIEW.METRICS.HANDOFF.LABEL'),
|
||||
hint: t('CAPTAIN.OVERVIEW.METRICS.HANDOFF.HINT'),
|
||||
...metricFor('handoff_rate', v => `${v}%`, 'down', 'point'),
|
||||
},
|
||||
{
|
||||
key: 'reopen',
|
||||
metric: 'reopen_rate',
|
||||
label: t('CAPTAIN.OVERVIEW.METRICS.REOPEN.LABEL'),
|
||||
hint: t('CAPTAIN.OVERVIEW.METRICS.REOPEN.HINT'),
|
||||
...metricFor('reopen_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', formatDuration, 'up'),
|
||||
},
|
||||
{
|
||||
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'
|
||||
),
|
||||
},
|
||||
]);
|
||||
|
||||
const drilldown = ref({ metric: '', label: '', value: '' });
|
||||
const isDrilldownOpen = ref(false);
|
||||
|
||||
const openDrilldown = metric => {
|
||||
drilldown.value = {
|
||||
metric: metric.metric,
|
||||
label: metric.label,
|
||||
value: metric.value,
|
||||
};
|
||||
isDrilldownOpen.value = true;
|
||||
};
|
||||
|
||||
const closeDrilldown = () => {
|
||||
isDrilldownOpen.value = false;
|
||||
};
|
||||
</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 #paywall>
|
||||
<CaptainPaywall />
|
||||
</template>
|
||||
<template #body>
|
||||
<div class="flex flex-col gap-6 pb-8">
|
||||
<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"
|
||||
:clickable="canDrilldown && Boolean(metric.metric)"
|
||||
@click="openDrilldown(metric)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<KnowledgeCard :knowledge="stats?.knowledge" />
|
||||
|
||||
<QuickLinks />
|
||||
</div>
|
||||
|
||||
<AssistantDrilldownDrawer
|
||||
v-if="canDrilldown"
|
||||
:open="isDrilldownOpen"
|
||||
:assistant-id="assistantId"
|
||||
:metric="drilldown.metric"
|
||||
:metric-name="drilldown.label"
|
||||
:metric-value="drilldown.value"
|
||||
:range="selectedRange"
|
||||
@close="closeDrilldown"
|
||||
/>
|
||||
</template>
|
||||
</PageLayout>
|
||||
</template>
|
||||
@@ -6,6 +6,7 @@ import CaptainPageRouteView from './pages/CaptainPageRouteView.vue';
|
||||
import AssistantsIndexPage from './pages/AssistantsIndexPage.vue';
|
||||
import AssistantEmptyStateIndex from './assistants/Index.vue';
|
||||
|
||||
import AssistantOverviewIndex from './assistants/overview/Index.vue';
|
||||
import AssistantSettingsIndex from './assistants/settings/Settings.vue';
|
||||
import AssistantInboxesIndex from './assistants/inboxes/Index.vue';
|
||||
import AssistantPlaygroundIndex from './assistants/playground/Index.vue';
|
||||
@@ -36,6 +37,12 @@ const metaV2 = {
|
||||
};
|
||||
|
||||
const assistantRoutes = [
|
||||
{
|
||||
path: frontendURL('accounts/:accountId/captain/:assistantId/overview'),
|
||||
component: AssistantOverviewIndex,
|
||||
name: 'captain_assistants_overview_index',
|
||||
meta,
|
||||
},
|
||||
{
|
||||
path: frontendURL('accounts/:accountId/captain/:assistantId/faqs'),
|
||||
component: ResponsesIndex,
|
||||
@@ -129,7 +136,7 @@ export const routes = [
|
||||
return {
|
||||
name: 'captain_assistants_index',
|
||||
params: {
|
||||
navigationPath: 'captain_assistants_responses_index',
|
||||
navigationPath: 'captain_assistants_overview_index',
|
||||
...to.params,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -17,7 +17,7 @@ import Input from 'dashboard/components-next/input/Input.vue';
|
||||
import Policy from 'dashboard/components/policy.vue';
|
||||
import PageLayout from 'dashboard/components-next/captain/PageLayout.vue';
|
||||
import CaptainPaywall from 'dashboard/components-next/captain/pageComponents/Paywall.vue';
|
||||
import RelatedResponses from 'dashboard/components-next/captain/pageComponents/document/RelatedResponses.vue';
|
||||
import DocumentDetails from 'dashboard/components-next/captain/pageComponents/document/DocumentDetails.vue';
|
||||
import CreateDocumentDialog from 'dashboard/components-next/captain/pageComponents/document/CreateDocumentDialog.vue';
|
||||
import DocumentPageEmptyState from 'dashboard/components-next/captain/pageComponents/emptyStates/DocumentPageEmptyState.vue';
|
||||
import FeatureSpotlightPopover from 'dashboard/components-next/feature-spotlight/FeatureSpotlightPopover.vue';
|
||||
@@ -51,22 +51,22 @@ const handleDelete = () => {
|
||||
deleteDocumentDialog.value.dialogRef.open();
|
||||
};
|
||||
|
||||
const showRelatedResponses = ref(false);
|
||||
const showDocumentDetails = ref(false);
|
||||
const showCreateDialog = ref(false);
|
||||
const createDocumentDialog = ref(null);
|
||||
const relationQuestionDialog = ref(null);
|
||||
const documentDetailsDialog = ref(null);
|
||||
|
||||
const handleShowRelatedDocument = () => {
|
||||
showRelatedResponses.value = true;
|
||||
nextTick(() => relationQuestionDialog.value.dialogRef.open());
|
||||
const handleShowDocumentDetails = () => {
|
||||
showDocumentDetails.value = true;
|
||||
nextTick(() => documentDetailsDialog.value.dialogRef.open());
|
||||
};
|
||||
const handleCreateDocument = () => {
|
||||
showCreateDialog.value = true;
|
||||
nextTick(() => createDocumentDialog.value.dialogRef.open());
|
||||
};
|
||||
|
||||
const handleRelatedResponseClose = () => {
|
||||
showRelatedResponses.value = false;
|
||||
const handleDocumentDetailsClose = () => {
|
||||
showDocumentDetails.value = false;
|
||||
};
|
||||
|
||||
const handleCreateDialogClose = () => {
|
||||
@@ -235,8 +235,8 @@ const handleAction = ({ action, id }) => {
|
||||
nextTick(() => {
|
||||
if (action === 'delete') {
|
||||
handleDelete();
|
||||
} else if (action === 'viewRelatedQuestions') {
|
||||
handleShowRelatedDocument();
|
||||
} else if (action === 'viewDetails') {
|
||||
handleShowDocumentDetails();
|
||||
} else if (action === 'sync') {
|
||||
handleSync(id);
|
||||
}
|
||||
@@ -416,6 +416,7 @@ onUnmounted(() => {
|
||||
:last-sync-error-code="doc.last_sync_error_code"
|
||||
:sync-in-progress="doc.sync_in_progress"
|
||||
:sync-stale-after-hours="syncIntervalHours"
|
||||
:responses-count="doc.responses_count"
|
||||
:is-selected="canManageDocuments && bulkSelectedIds.has(doc.id)"
|
||||
:selectable="canManageDocuments"
|
||||
:show-selection-control="shouldShowSelectionControl(doc.id)"
|
||||
@@ -427,11 +428,11 @@ onUnmounted(() => {
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<RelatedResponses
|
||||
v-if="showRelatedResponses"
|
||||
ref="relationQuestionDialog"
|
||||
<DocumentDetails
|
||||
v-if="showDocumentDetails"
|
||||
ref="documentDetailsDialog"
|
||||
:captain-document="selectedDocument"
|
||||
@close="handleRelatedResponseClose"
|
||||
@close="handleDocumentDetailsClose"
|
||||
/>
|
||||
<CreateDocumentDialog
|
||||
v-if="showCreateDialog"
|
||||
|
||||
@@ -53,6 +53,7 @@ const routeToLastActiveAssistant = () => {
|
||||
|
||||
const { navigationPath } = route.params;
|
||||
const isAValidRoute = [
|
||||
'captain_assistants_overview_index', // Overview page
|
||||
'captain_assistants_responses_index', // Faq page
|
||||
'captain_assistants_documents_index', // Document page
|
||||
'captain_assistants_scenarios_index', // Scenario page
|
||||
@@ -64,7 +65,7 @@ const routeToLastActiveAssistant = () => {
|
||||
|
||||
const navigateTo = isAValidRoute
|
||||
? navigationPath
|
||||
: 'captain_assistants_responses_index';
|
||||
: 'captain_assistants_overview_index';
|
||||
|
||||
return routeToView(navigateTo, {
|
||||
accountId: route.params.accountId,
|
||||
|
||||
@@ -25,7 +25,7 @@ export default {
|
||||
},
|
||||
},
|
||||
setup() {
|
||||
const { agentsList } = useAgentsList();
|
||||
const { agentsList } = useAgentsList(true, { includeAgentBots: true });
|
||||
return {
|
||||
agentsList,
|
||||
};
|
||||
@@ -81,18 +81,27 @@ export default {
|
||||
},
|
||||
assignedAgent: {
|
||||
get() {
|
||||
return this.currentChat.meta.assignee;
|
||||
const assignee = this.currentChat.meta.assignee;
|
||||
return (
|
||||
assignee && {
|
||||
...assignee,
|
||||
assignee_type: this.currentChat.meta.assignee_type || 'User',
|
||||
}
|
||||
);
|
||||
},
|
||||
set(agent) {
|
||||
const agentId = agent ? agent.id : null;
|
||||
const assigneeType = agent ? agent.assignee_type || 'User' : null;
|
||||
this.$store.dispatch('setCurrentChatAssignee', {
|
||||
conversationId: this.currentChat.id,
|
||||
assignee: agent,
|
||||
assigneeType,
|
||||
});
|
||||
this.$store
|
||||
.dispatch('assignAgent', {
|
||||
conversationId: this.currentChat.id,
|
||||
agentId,
|
||||
assigneeType,
|
||||
})
|
||||
.then(() => {
|
||||
useAlert(this.$t('CONVERSATION.CHANGE_AGENT'));
|
||||
@@ -152,7 +161,10 @@ export default {
|
||||
if (!this.assignedAgent) {
|
||||
return true;
|
||||
}
|
||||
if (this.assignedAgent.id !== this.currentUser.id) {
|
||||
if (
|
||||
this.assignedAgent.id !== this.currentUser.id ||
|
||||
(this.assignedAgent.assignee_type || 'User') !== 'User'
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
@@ -183,7 +195,11 @@ export default {
|
||||
this.assignedAgent = selfAssign;
|
||||
},
|
||||
onClickAssignAgent(selectedItem) {
|
||||
if (this.assignedAgent && this.assignedAgent.id === selectedItem.id) {
|
||||
if (
|
||||
this.assignedAgent?.id === selectedItem.id &&
|
||||
(this.assignedAgent?.assignee_type || 'User') ===
|
||||
(selectedItem.assignee_type || 'User')
|
||||
) {
|
||||
this.assignedAgent = null;
|
||||
} else {
|
||||
this.assignedAgent = selectedItem;
|
||||
|
||||
+4
-1
@@ -7,17 +7,20 @@ import { useMapGetter } from 'dashboard/composables/store';
|
||||
// Mirrors the availability checks in ChannelItem.vue.
|
||||
export function useChannelConfig() {
|
||||
const globalConfig = useMapGetter('globalConfig/get');
|
||||
const isOnChatwootCloud = useMapGetter('globalConfig/isOnChatwootCloud');
|
||||
const installationConfig = window.chatwootConfig || {};
|
||||
|
||||
const CHANNEL_CONFIGURED = {
|
||||
// WhatsApp is onboarded only via Meta embedded signup, which needs both the
|
||||
// app id (not the 'none' sentinel) and the signup configuration id.
|
||||
whatsapp: () =>
|
||||
!isOnChatwootCloud.value &&
|
||||
Boolean(installationConfig.whatsappAppId) &&
|
||||
installationConfig.whatsappAppId !== 'none' &&
|
||||
Boolean(installationConfig.whatsappConfigurationId),
|
||||
facebook: () => Boolean(installationConfig.fbAppId),
|
||||
instagram: () => Boolean(installationConfig.instagramAppId),
|
||||
instagram: () =>
|
||||
!isOnChatwootCloud.value && Boolean(installationConfig.instagramAppId),
|
||||
tiktok: () => Boolean(installationConfig.tiktokAppId),
|
||||
gmail: () => Boolean(installationConfig.googleOAuthClientId),
|
||||
outlook: () => Boolean(globalConfig.value.azureAppId),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useAlert } from 'dashboard/composables';
|
||||
import { useStore } from 'dashboard/composables/store';
|
||||
import { useAccount } from 'dashboard/composables/useAccount';
|
||||
import { useWhatsappEmbeddedSignup } from 'dashboard/composables/useWhatsappEmbeddedSignup';
|
||||
import { parseAPIErrorResponse } from 'dashboard/store/utils/api';
|
||||
import googleClient from 'dashboard/api/channel/googleClient';
|
||||
@@ -23,11 +24,17 @@ export function useChannelConnect() {
|
||||
const { t } = useI18n();
|
||||
const store = useStore();
|
||||
const { runEmbeddedSignup } = useWhatsappEmbeddedSignup();
|
||||
const { isOnChatwootCloud } = useAccount();
|
||||
|
||||
const connectViaOAuth = async provider => {
|
||||
const client = OAUTH_CLIENTS[provider];
|
||||
if (!client) return;
|
||||
|
||||
if (provider === 'instagram' && isOnChatwootCloud.value) {
|
||||
useAlert(t('INBOX_MGMT.ADD.INSTAGRAM.RESTRICTED_WARNING'));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const {
|
||||
data: { url },
|
||||
|
||||
+28
-1
@@ -11,9 +11,20 @@ vi.mock('vue-router');
|
||||
// resolves the current account is exercised here too. The real ./constants are
|
||||
// used, so assertions validate against the actual channel identity (label keys,
|
||||
// channel_type, social ordering) derived from CHANNEL_LIST.
|
||||
const mountComposable = ({ brandInfo, inboxes = [] } = {}) => {
|
||||
const mountComposable = ({
|
||||
brandInfo,
|
||||
inboxes = [],
|
||||
isOnChatwootCloud = false,
|
||||
} = {}) => {
|
||||
const store = createStore({
|
||||
modules: {
|
||||
globalConfig: {
|
||||
namespaced: true,
|
||||
getters: {
|
||||
get: () => ({}),
|
||||
isOnChatwootCloud: () => isOnChatwootCloud,
|
||||
},
|
||||
},
|
||||
accounts: {
|
||||
namespaced: true,
|
||||
getters: {
|
||||
@@ -195,6 +206,22 @@ describe('useDetectedChannels', () => {
|
||||
'line',
|
||||
]);
|
||||
});
|
||||
|
||||
it('hides Instagram from onboarding on Chatwoot Cloud', () => {
|
||||
const { displayedChannels } = mountComposable({
|
||||
isOnChatwootCloud: true,
|
||||
brandInfo: {
|
||||
socials: [
|
||||
{ type: 'instagram', url: 'https://instagram.com/acme' },
|
||||
{ type: 'tiktok', url: 'https://tiktok.com/@acme' },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(displayedChannels.value.map(channel => channel.type)).toEqual([
|
||||
'tiktok',
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('remainingChannels', () => {
|
||||
|
||||
@@ -15,6 +15,8 @@ import PurchaseCreditsModal from './components/PurchaseCreditsModal.vue';
|
||||
import BaseSettingsHeader from '../components/BaseSettingsHeader.vue';
|
||||
import SettingsLayout from '../SettingsLayout.vue';
|
||||
import ButtonV4 from 'next/button/Button.vue';
|
||||
import { getCurrencyConfig } from 'dashboard/constants/billing';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
const router = useRouter();
|
||||
const { currentAccount, isOnChatwootCloud } = useAccount();
|
||||
@@ -29,6 +31,7 @@ const {
|
||||
|
||||
const uiFlags = useMapGetter('accounts/getUIFlags');
|
||||
const store = useStore();
|
||||
const { t } = useI18n();
|
||||
|
||||
const BILLING_REFRESH_ATTEMPTED = 'billing_refresh_attempted';
|
||||
|
||||
@@ -36,6 +39,10 @@ const BILLING_REFRESH_ATTEMPTED = 'billing_refresh_attempted';
|
||||
const isWaitingForBilling = ref(false);
|
||||
const purchaseCreditsModalRef = ref(null);
|
||||
|
||||
// Currency selection shown to new accounts whose locale supports a non-USD currency.
|
||||
const currencySelectionRequired = ref(false);
|
||||
const currencyOptions = ref([]);
|
||||
|
||||
const customAttributes = computed(() => {
|
||||
return currentAccount.value.custom_attributes || {};
|
||||
});
|
||||
@@ -61,6 +68,13 @@ const subscribedQuantity = computed(() => {
|
||||
return customAttributes.value.subscribed_quantity;
|
||||
});
|
||||
|
||||
const billingCurrency = computed(() => {
|
||||
if (!customAttributes.value.billing_currency) return '';
|
||||
return t(
|
||||
getCurrencyConfig(customAttributes.value.billing_currency).i18nLabelKey
|
||||
);
|
||||
});
|
||||
|
||||
const subscriptionRenewsOn = computed(() => {
|
||||
if (!customAttributes.value.subscription_ends_on) return '';
|
||||
const endDate = new Date(customAttributes.value.subscription_ends_on);
|
||||
@@ -78,7 +92,9 @@ const hasABillingPlan = computed(() => {
|
||||
|
||||
const fetchAccountDetails = async () => {
|
||||
if (!hasABillingPlan.value) {
|
||||
await store.dispatch('accounts/subscription');
|
||||
const data = await store.dispatch('accounts/subscription');
|
||||
currencySelectionRequired.value = !!data?.currency_selection_required;
|
||||
currencyOptions.value = data?.currency_options || [];
|
||||
}
|
||||
// Always fetch limits for billing page to show credit usage
|
||||
fetchLimits();
|
||||
@@ -97,6 +113,9 @@ const handleBillingPageLogic = async () => {
|
||||
// If cloud user, fetch account details first
|
||||
await fetchAccountDetails();
|
||||
|
||||
// Waiting on the user to pick a billing currency — don't auto-refresh.
|
||||
if (currencySelectionRequired.value) return;
|
||||
|
||||
// If still no billing plan after fetch
|
||||
if (!hasABillingPlan.value) {
|
||||
// If we haven't attempted refresh yet, do it once
|
||||
@@ -118,6 +137,13 @@ const handleBillingPageLogic = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
const onSelectCurrency = async code => {
|
||||
await store.dispatch('accounts/selectBillingCurrency', code);
|
||||
currencySelectionRequired.value = false;
|
||||
// Currency stored and customer creation kicked off — resume the standard wait flow.
|
||||
await handleBillingPageLogic();
|
||||
};
|
||||
|
||||
const onClickBillingPortal = () => {
|
||||
store.dispatch('accounts/checkout');
|
||||
};
|
||||
@@ -148,7 +174,9 @@ onMounted(handleBillingPageLogic);
|
||||
? $t('BILLING_SETTINGS.NO_BILLING_USER')
|
||||
: $t('ATTRIBUTES_MGMT.LOADING')
|
||||
"
|
||||
:no-records-found="!hasABillingPlan && !isWaitingForBilling"
|
||||
:no-records-found="
|
||||
!hasABillingPlan && !isWaitingForBilling && !currencySelectionRequired
|
||||
"
|
||||
:no-records-message="$t('BILLING_SETTINGS.NO_BILLING_USER')"
|
||||
>
|
||||
<template #header>
|
||||
@@ -160,7 +188,30 @@ onMounted(handleBillingPageLogic);
|
||||
/>
|
||||
</template>
|
||||
<template #body>
|
||||
<section class="grid gap-4">
|
||||
<section v-if="currencySelectionRequired" class="grid gap-4">
|
||||
<BillingCard
|
||||
:title="$t('BILLING_SETTINGS.CURRENCY.SELECT.TITLE')"
|
||||
:description="$t('BILLING_SETTINGS.CURRENCY.SELECT.DESCRIPTION')"
|
||||
>
|
||||
<template #action>
|
||||
<div class="flex gap-2">
|
||||
<ButtonV4
|
||||
v-for="code in currencyOptions"
|
||||
:key="code"
|
||||
sm
|
||||
solid
|
||||
blue
|
||||
:is-loading="uiFlags.isCheckoutInProcess"
|
||||
:disabled="uiFlags.isCheckoutInProcess"
|
||||
@click="onSelectCurrency(code)"
|
||||
>
|
||||
{{ $t(getCurrencyConfig(code).i18nLabelKey) }}
|
||||
</ButtonV4>
|
||||
</div>
|
||||
</template>
|
||||
</BillingCard>
|
||||
</section>
|
||||
<section v-else class="grid gap-4">
|
||||
<BillingCard
|
||||
:title="$t('BILLING_SETTINGS.MANAGE_SUBSCRIPTION.TITLE')"
|
||||
:description="$t('BILLING_SETTINGS.MANAGE_SUBSCRIPTION.DESCRIPTION')"
|
||||
@@ -188,6 +239,11 @@ onMounted(handleBillingPageLogic);
|
||||
:label="$t('BILLING_SETTINGS.CURRENT_PLAN.RENEWS_ON')"
|
||||
:value="subscriptionRenewsOn"
|
||||
/>
|
||||
<DetailItem
|
||||
v-if="billingCurrency"
|
||||
:label="$t('BILLING_SETTINGS.CURRENT_PLAN.CURRENCY')"
|
||||
:value="billingCurrency"
|
||||
/>
|
||||
</div>
|
||||
</BillingCard>
|
||||
<BillingCard
|
||||
|
||||
+3
-5
@@ -1,4 +1,6 @@
|
||||
<script setup>
|
||||
import { formatCurrencyAmount } from 'dashboard/constants/billing';
|
||||
|
||||
defineProps({
|
||||
credits: {
|
||||
type: Number,
|
||||
@@ -33,11 +35,7 @@ const formatCredits = credits => {
|
||||
};
|
||||
|
||||
const formatAmount = (amount, currency) => {
|
||||
return new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency: currency.toUpperCase(),
|
||||
minimumFractionDigits: 0,
|
||||
}).format(amount);
|
||||
return formatCurrencyAmount(amount, currency, { minimumFractionDigits: 0 });
|
||||
};
|
||||
</script>
|
||||
|
||||
|
||||
+91
-43
@@ -4,20 +4,18 @@ import { useI18n } from 'vue-i18n';
|
||||
import { useAlert } from 'dashboard/composables';
|
||||
import Dialog from 'dashboard/components-next/dialog/Dialog.vue';
|
||||
import Button from 'dashboard/components-next/button/Button.vue';
|
||||
import Spinner from 'dashboard/components-next/spinner/Spinner.vue';
|
||||
import CreditPackageCard from './CreditPackageCard.vue';
|
||||
import EnterpriseAccountAPI from 'dashboard/api/enterprise/account';
|
||||
import {
|
||||
formatCurrencyAmount,
|
||||
DEFAULT_BILLING_CURRENCY,
|
||||
} from 'dashboard/constants/billing';
|
||||
|
||||
const emit = defineEmits(['close', 'success']);
|
||||
const emit = defineEmits(['success']);
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const TOPUP_OPTIONS = [
|
||||
{ credits: 1000, amount: 20.0, currency: 'usd' },
|
||||
{ credits: 2500, amount: 50.0, currency: 'usd' },
|
||||
{ credits: 6000, amount: 100.0, currency: 'usd' },
|
||||
{ credits: 12000, amount: 200.0, currency: 'usd' },
|
||||
];
|
||||
|
||||
const POPULAR_CREDITS_AMOUNT = 6000;
|
||||
const STEP_SELECT = 'select';
|
||||
const STEP_CONFIRM = 'confirm';
|
||||
@@ -27,16 +25,20 @@ const selectedCredits = ref(null);
|
||||
const isLoading = ref(false);
|
||||
const currentStep = ref(STEP_SELECT);
|
||||
|
||||
// Topup packages come from the backend for the account's billing currency.
|
||||
const topupOptions = ref([]);
|
||||
const optionsCurrency = ref(DEFAULT_BILLING_CURRENCY);
|
||||
const isFetchingOptions = ref(false);
|
||||
const fetchError = ref(false);
|
||||
|
||||
const selectedOption = computed(() => {
|
||||
return TOPUP_OPTIONS.find(o => o.credits === selectedCredits.value);
|
||||
return topupOptions.value.find(o => o.credits === selectedCredits.value);
|
||||
});
|
||||
|
||||
const formattedAmount = computed(() => {
|
||||
if (!selectedOption.value) return '';
|
||||
return new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency: selectedOption.value.currency.toUpperCase(),
|
||||
}).format(selectedOption.value.amount);
|
||||
const { amount, currency } = selectedOption.value;
|
||||
return formatCurrencyAmount(amount, currency || optionsCurrency.value);
|
||||
});
|
||||
|
||||
const formattedCredits = computed(() => {
|
||||
@@ -64,24 +66,44 @@ const handlePackageSelect = credits => {
|
||||
selectedCredits.value = credits;
|
||||
};
|
||||
|
||||
const open = () => {
|
||||
const popularOption = TOPUP_OPTIONS.find(
|
||||
const selectDefaultOption = () => {
|
||||
const popularOption = topupOptions.value.find(
|
||||
o => o.credits === POPULAR_CREDITS_AMOUNT
|
||||
);
|
||||
selectedCredits.value = popularOption?.credits || TOPUP_OPTIONS[0]?.credits;
|
||||
selectedCredits.value =
|
||||
popularOption?.credits || topupOptions.value[0]?.credits || null;
|
||||
};
|
||||
|
||||
const fetchOptions = async () => {
|
||||
isFetchingOptions.value = true;
|
||||
fetchError.value = false;
|
||||
try {
|
||||
const { data } = await EnterpriseAccountAPI.getTopupOptions();
|
||||
topupOptions.value = data.options ?? [];
|
||||
optionsCurrency.value = (
|
||||
data.currency || DEFAULT_BILLING_CURRENCY
|
||||
).toLowerCase();
|
||||
selectDefaultOption();
|
||||
} catch {
|
||||
fetchError.value = true;
|
||||
topupOptions.value = [];
|
||||
} finally {
|
||||
isFetchingOptions.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const open = () => {
|
||||
currentStep.value = STEP_SELECT;
|
||||
isLoading.value = false;
|
||||
selectedCredits.value = null;
|
||||
dialogRef.value?.open();
|
||||
fetchOptions();
|
||||
};
|
||||
|
||||
const close = () => {
|
||||
dialogRef.value?.close();
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
emit('close');
|
||||
};
|
||||
|
||||
const goToConfirmStep = () => {
|
||||
if (!selectedOption.value) return;
|
||||
currentStep.value = STEP_CONFIRM;
|
||||
@@ -127,32 +149,58 @@ defineExpose({ open, close });
|
||||
:width="dialogWidth"
|
||||
:show-confirm-button="false"
|
||||
:show-cancel-button="false"
|
||||
@close="handleClose"
|
||||
>
|
||||
<!-- Step 1: Select Credits Package -->
|
||||
<template v-if="currentStep === 'select'">
|
||||
<div class="grid grid-cols-2 gap-4">
|
||||
<CreditPackageCard
|
||||
v-for="option in TOPUP_OPTIONS"
|
||||
:key="option.credits"
|
||||
name="credit-package"
|
||||
:credits="option.credits"
|
||||
:amount="option.amount"
|
||||
:currency="option.currency"
|
||||
:is-popular="option.credits === POPULAR_CREDITS_AMOUNT"
|
||||
:is-selected="selectedCredits === option.credits"
|
||||
@select="handlePackageSelect(option.credits)"
|
||||
<template v-if="currentStep === STEP_SELECT">
|
||||
<div
|
||||
v-if="isFetchingOptions"
|
||||
class="flex items-center justify-center gap-2 py-10"
|
||||
>
|
||||
<Spinner />
|
||||
<span class="text-sm text-n-slate-11">{{
|
||||
$t('BILLING_SETTINGS.TOPUP.LOADING')
|
||||
}}</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else-if="fetchError"
|
||||
class="flex flex-col items-center justify-center gap-3 py-10"
|
||||
>
|
||||
<p class="text-sm text-n-slate-11">
|
||||
{{ $t('BILLING_SETTINGS.TOPUP.FETCH_ERROR') }}
|
||||
</p>
|
||||
<Button
|
||||
variant="faded"
|
||||
color="slate"
|
||||
:label="$t('BILLING_SETTINGS.TOPUP.RETRY')"
|
||||
@click="fetchOptions"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="p-4 mt-6 rounded-lg bg-n-solid-2 border border-n-weak">
|
||||
<p class="text-sm text-n-slate-11">
|
||||
<span class="font-semibold text-n-slate-12">{{
|
||||
$t('BILLING_SETTINGS.TOPUP.NOTE_TITLE')
|
||||
}}</span>
|
||||
{{ $t('BILLING_SETTINGS.TOPUP.NOTE_DESCRIPTION') }}
|
||||
</p>
|
||||
</div>
|
||||
<template v-else>
|
||||
<div class="grid grid-cols-2 gap-4">
|
||||
<CreditPackageCard
|
||||
v-for="option in topupOptions"
|
||||
:key="option.credits"
|
||||
name="credit-package"
|
||||
:credits="option.credits"
|
||||
:amount="option.amount"
|
||||
:currency="option.currency"
|
||||
:is-popular="option.credits === POPULAR_CREDITS_AMOUNT"
|
||||
:is-selected="selectedCredits === option.credits"
|
||||
@select="handlePackageSelect(option.credits)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="p-4 mt-6 rounded-lg bg-n-solid-2 border border-n-weak">
|
||||
<p class="text-sm text-n-slate-11">
|
||||
<span class="font-semibold text-n-slate-12">{{
|
||||
$t('BILLING_SETTINGS.TOPUP.NOTE_TITLE')
|
||||
}}</span>
|
||||
{{ $t('BILLING_SETTINGS.TOPUP.NOTE_DESCRIPTION') }}
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
<!-- Step 2: Confirm Purchase -->
|
||||
@@ -178,7 +226,7 @@ defineExpose({ open, close });
|
||||
<template #footer>
|
||||
<!-- Step 1 Footer -->
|
||||
<div
|
||||
v-if="currentStep === 'select'"
|
||||
v-if="currentStep === STEP_SELECT"
|
||||
class="flex items-center justify-between w-full gap-3"
|
||||
>
|
||||
<Button
|
||||
@@ -192,7 +240,7 @@ defineExpose({ open, close });
|
||||
color="blue"
|
||||
:label="$t('BILLING_SETTINGS.TOPUP.PURCHASE')"
|
||||
class="w-full"
|
||||
:disabled="!selectedCredits"
|
||||
:disabled="!selectedCredits || isFetchingOptions || fetchError"
|
||||
@click="goToConfirmStep"
|
||||
/>
|
||||
</div>
|
||||
|
||||
+5
-3
@@ -52,9 +52,11 @@ const helpURL = getHelpUrlForFeature(props.featureName);
|
||||
v-if="title"
|
||||
class="flex items-center justify-between w-full gap-4 min-h-8 mb-2"
|
||||
>
|
||||
<h1 class="text-heading-1 text-n-slate-12">
|
||||
{{ title }}
|
||||
</h1>
|
||||
<slot name="title">
|
||||
<h1 class="text-heading-1 text-n-slate-12">
|
||||
{{ title }}
|
||||
</h1>
|
||||
</slot>
|
||||
</div>
|
||||
<div
|
||||
v-if="description || $slots.description || linkText || helpURL"
|
||||
|
||||
@@ -0,0 +1,378 @@
|
||||
<script setup>
|
||||
import {
|
||||
computed,
|
||||
onActivated,
|
||||
onBeforeUnmount,
|
||||
onDeactivated,
|
||||
ref,
|
||||
} from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useStoreGetters } from 'dashboard/composables/store';
|
||||
|
||||
import Button from 'dashboard/components-next/button/Button.vue';
|
||||
import Icon from 'dashboard/components-next/icon/Icon.vue';
|
||||
import TabBar from 'dashboard/components-next/tabbar/TabBar.vue';
|
||||
import SettingsLayout from '../SettingsLayout.vue';
|
||||
import BaseSettingsHeader from '../components/BaseSettingsHeader.vue';
|
||||
import DataImportsAPI from 'dashboard/api/dataImports';
|
||||
import NewImportDialog from './NewImportDialog.vue';
|
||||
import { importSourceFor } from './importSources';
|
||||
import {
|
||||
POLL_INTERVAL_MS,
|
||||
formatDate,
|
||||
formatStatus,
|
||||
importedCount,
|
||||
isActiveImport,
|
||||
isActiveIntercomImport,
|
||||
statusDotClass,
|
||||
} from './importStatus';
|
||||
|
||||
const { t } = useI18n();
|
||||
const getters = useStoreGetters();
|
||||
const router = useRouter();
|
||||
|
||||
const dataImports = ref([]);
|
||||
const isLoading = ref(true);
|
||||
const isRefreshing = ref(false);
|
||||
const isPolling = ref(false);
|
||||
const showImportDrawer = ref(false);
|
||||
const activeTab = ref('import');
|
||||
let pollTimer;
|
||||
let isPageActive = false;
|
||||
|
||||
const accountId = getters.getCurrentAccountId;
|
||||
|
||||
const tabs = computed(() => [
|
||||
{ key: 'import', label: t('DATA_IMPORTS.TABS.IMPORT') },
|
||||
{ key: 'export', label: t('DATA_IMPORTS.TABS.EXPORT') },
|
||||
]);
|
||||
|
||||
const activeTabIndex = computed(() =>
|
||||
tabs.value.findIndex(tab => tab.key === activeTab.value)
|
||||
);
|
||||
|
||||
const hasActiveImport = computed(() => dataImports.value.some(isActiveImport));
|
||||
const hasActiveIntercomImport = computed(() =>
|
||||
dataImports.value.some(isActiveIntercomImport)
|
||||
);
|
||||
|
||||
const dataImportRoute = dataImport => ({
|
||||
name: 'settings_data_import_show',
|
||||
params: { accountId: accountId.value, dataImportId: dataImport.id },
|
||||
});
|
||||
|
||||
const importTypesFor = dataImport =>
|
||||
dataImport.import_types?.length
|
||||
? dataImport.import_types
|
||||
: [dataImport.data_type];
|
||||
|
||||
const importTypeLabel = dataImport =>
|
||||
importTypesFor(dataImport)
|
||||
.map(type => {
|
||||
if (type === 'contacts') return t('DATA_IMPORTS.TYPES.CONTACTS');
|
||||
if (type === 'conversations') {
|
||||
return t('DATA_IMPORTS.TYPES.CONVERSATIONS');
|
||||
}
|
||||
return type;
|
||||
})
|
||||
.join(', ');
|
||||
|
||||
const fetchImports = async () => {
|
||||
const response = await DataImportsAPI.get();
|
||||
dataImports.value = response.data.payload || [];
|
||||
};
|
||||
|
||||
const stopPolling = () => {
|
||||
if (!pollTimer) return;
|
||||
|
||||
window.clearInterval(pollTimer);
|
||||
pollTimer = null;
|
||||
};
|
||||
|
||||
const refreshImportsInBackground = async () => {
|
||||
if (
|
||||
!isPageActive ||
|
||||
isPolling.value ||
|
||||
!hasActiveImport.value ||
|
||||
document.hidden
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
isPolling.value = true;
|
||||
try {
|
||||
await fetchImports();
|
||||
} finally {
|
||||
isPolling.value = false;
|
||||
if (!hasActiveImport.value) stopPolling();
|
||||
}
|
||||
};
|
||||
|
||||
const startPolling = () => {
|
||||
stopPolling();
|
||||
if (!isPageActive || !hasActiveImport.value) return;
|
||||
|
||||
pollTimer = window.setInterval(refreshImportsInBackground, POLL_INTERVAL_MS);
|
||||
};
|
||||
|
||||
const refresh = async ({ showLoader = true } = {}) => {
|
||||
if (showLoader) isLoading.value = true;
|
||||
else isRefreshing.value = true;
|
||||
|
||||
try {
|
||||
await fetchImports();
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
isRefreshing.value = false;
|
||||
if (isPageActive) {
|
||||
if (hasActiveImport.value && !pollTimer) startPolling();
|
||||
if (!hasActiveImport.value) stopPolling();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const openImport = dataImport => {
|
||||
router.push(dataImportRoute(dataImport));
|
||||
};
|
||||
|
||||
const openImportDrawer = () => {
|
||||
if (!hasActiveIntercomImport.value) showImportDrawer.value = true;
|
||||
};
|
||||
|
||||
const onImportCreated = dataImportId => {
|
||||
showImportDrawer.value = false;
|
||||
router.push({
|
||||
name: 'settings_data_import_show',
|
||||
params: { accountId: accountId.value, dataImportId },
|
||||
});
|
||||
};
|
||||
|
||||
const onTabChanged = tab => {
|
||||
activeTab.value = tab.key;
|
||||
};
|
||||
|
||||
const handleVisibilityChange = () => {
|
||||
if (isPageActive && !document.hidden && hasActiveImport.value) {
|
||||
refreshImportsInBackground();
|
||||
}
|
||||
};
|
||||
|
||||
onActivated(async () => {
|
||||
isPageActive = true;
|
||||
await refresh();
|
||||
if (!isPageActive) return;
|
||||
|
||||
startPolling();
|
||||
document.addEventListener('visibilitychange', handleVisibilityChange);
|
||||
});
|
||||
|
||||
onDeactivated(() => {
|
||||
isPageActive = false;
|
||||
stopPolling();
|
||||
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
isPageActive = false;
|
||||
stopPolling();
|
||||
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<SettingsLayout
|
||||
:is-loading="isLoading"
|
||||
:loading-message="$t('DATA_IMPORTS.LOADING')"
|
||||
>
|
||||
<template #header>
|
||||
<BaseSettingsHeader
|
||||
:title="$t('DATA_IMPORTS.HEADER')"
|
||||
:description="$t('DATA_IMPORTS.DESCRIPTION')"
|
||||
>
|
||||
<template #tabs>
|
||||
<TabBar
|
||||
:tabs="tabs"
|
||||
:initial-active-tab="activeTabIndex"
|
||||
@tab-changed="onTabChanged"
|
||||
/>
|
||||
</template>
|
||||
<template v-if="activeTab === 'import' && dataImports.length" #count>
|
||||
<span class="text-body-main text-n-slate-11">
|
||||
{{ $t('DATA_IMPORTS.TABLE.COUNT', { count: dataImports.length }) }}
|
||||
</span>
|
||||
</template>
|
||||
<template v-if="activeTab === 'import'" #actions>
|
||||
<span
|
||||
v-if="hasActiveImport"
|
||||
class="hidden items-center gap-1.5 text-body-main text-n-slate-11 sm:inline-flex"
|
||||
>
|
||||
<span class="size-2 rounded-full bg-n-teal-9 animate-pulse" />
|
||||
{{
|
||||
$t('DATA_IMPORTS.MONITOR.LIVE', {
|
||||
seconds: POLL_INTERVAL_MS / 1000,
|
||||
})
|
||||
}}
|
||||
</span>
|
||||
<Button
|
||||
ghost
|
||||
slate
|
||||
size="sm"
|
||||
icon="i-lucide-refresh-cw"
|
||||
:is-loading="isRefreshing"
|
||||
:aria-label="$t('DATA_IMPORTS.MONITOR.REFRESH')"
|
||||
:title="$t('DATA_IMPORTS.MONITOR.REFRESH')"
|
||||
@click="refresh({ showLoader: false })"
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
:label="$t('DATA_IMPORTS.TABLE.NEW_IMPORT')"
|
||||
:disabled="hasActiveIntercomImport"
|
||||
:title="
|
||||
hasActiveIntercomImport
|
||||
? $t('DATA_IMPORTS.DRAWER.ACTIVE_IMPORT')
|
||||
: undefined
|
||||
"
|
||||
@click="openImportDrawer"
|
||||
/>
|
||||
</template>
|
||||
</BaseSettingsHeader>
|
||||
</template>
|
||||
|
||||
<template #body>
|
||||
<div
|
||||
v-if="activeTab === 'export'"
|
||||
class="flex min-h-80 flex-col items-center justify-center gap-4 rounded-xl border border-n-weak bg-n-solid-1 px-6 py-16 text-center"
|
||||
>
|
||||
<span
|
||||
class="flex size-12 items-center justify-center rounded-full bg-n-alpha-2"
|
||||
>
|
||||
<Icon icon="i-lucide-upload" class="size-5 text-n-slate-11" />
|
||||
</span>
|
||||
<div class="flex flex-col gap-1">
|
||||
<h3 class="text-heading-2 text-n-slate-12">
|
||||
{{ $t('DATA_IMPORTS.EXPORT.TITLE') }}
|
||||
</h3>
|
||||
<p class="max-w-sm text-body-main text-n-slate-11">
|
||||
{{ $t('DATA_IMPORTS.EXPORT.DESCRIPTION') }}
|
||||
</p>
|
||||
</div>
|
||||
<span
|
||||
class="inline-flex items-center gap-1.5 rounded-md bg-n-alpha-2 px-2 py-1 text-label-small text-n-slate-11"
|
||||
>
|
||||
<Icon icon="i-lucide-clock" class="size-3.5" />
|
||||
{{ $t('DATA_IMPORTS.EXPORT.COMING_SOON') }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else-if="!dataImports.length"
|
||||
class="flex min-h-80 flex-col items-center justify-center gap-4 rounded-xl border border-n-weak bg-n-solid-1 px-6 py-16 text-center"
|
||||
>
|
||||
<span
|
||||
class="flex size-12 items-center justify-center rounded-full bg-n-alpha-2"
|
||||
>
|
||||
<Icon icon="i-lucide-database" class="size-5 text-n-slate-11" />
|
||||
</span>
|
||||
<div class="flex flex-col gap-1">
|
||||
<h3 class="text-heading-2 text-n-slate-12">
|
||||
{{ $t('DATA_IMPORTS.TABLE.EMPTY') }}
|
||||
</h3>
|
||||
<p class="max-w-sm text-body-main text-n-slate-11">
|
||||
{{ $t('DATA_IMPORTS.TABLE.EMPTY_DESCRIPTION') }}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
icon="i-lucide-download"
|
||||
:label="$t('DATA_IMPORTS.TABLE.NEW_IMPORT')"
|
||||
@click="openImportDrawer"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div v-else class="divide-y divide-n-weak border-t border-n-weak">
|
||||
<div
|
||||
v-for="dataImport in dataImports"
|
||||
:key="dataImport.id"
|
||||
class="group flex cursor-pointer items-center justify-between gap-4 py-4"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
@click="openImport(dataImport)"
|
||||
@keydown.enter="openImport(dataImport)"
|
||||
@keydown.space.prevent="openImport(dataImport)"
|
||||
>
|
||||
<div class="flex min-w-0 items-center gap-3">
|
||||
<img
|
||||
v-if="importSourceFor(dataImport).icon"
|
||||
v-tooltip.top="importSourceFor(dataImport).label"
|
||||
:src="importSourceFor(dataImport).icon"
|
||||
alt=""
|
||||
class="size-10 justify-center bg-n-alpha-3 rounded-xl shrink-0 object-contain border border-n-strong"
|
||||
/>
|
||||
<span
|
||||
v-else
|
||||
v-tooltip.top="importSourceFor(dataImport).label"
|
||||
class="size-10 justify-center bg-n-alpha-3 rounded-xl ring ring-n-solid-1 border border-n-strong shadow-sm grid place-items-center"
|
||||
>
|
||||
<Icon
|
||||
:icon="importSourceFor(dataImport).iconClass"
|
||||
class="size-4"
|
||||
/>
|
||||
</span>
|
||||
<div class="flex min-w-0 flex-col gap-1">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="truncate text-heading-3 text-n-slate-12">
|
||||
{{ dataImport.name || $t('DATA_IMPORTS.TABLE.UNNAMED') }}
|
||||
</span>
|
||||
<span class="flex shrink-0 items-center gap-1.5">
|
||||
<span
|
||||
class="size-2 rounded-full"
|
||||
:class="[
|
||||
statusDotClass(dataImport.status),
|
||||
{ 'animate-pulse': isActiveImport(dataImport) },
|
||||
]"
|
||||
/>
|
||||
<span
|
||||
class="whitespace-nowrap capitalize text-body-main text-n-slate-11"
|
||||
>
|
||||
{{ formatStatus(dataImport.status) }}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
class="flex flex-wrap items-center gap-2 text-body-main text-n-slate-11"
|
||||
>
|
||||
<span>{{ importTypeLabel(dataImport) }}</span>
|
||||
<div class="h-3 w-px rounded-lg bg-n-strong" />
|
||||
<span class="tabular-nums">
|
||||
{{
|
||||
$t('DATA_IMPORTS.TABLE.IMPORTED_COUNT', {
|
||||
count: importedCount(dataImport),
|
||||
})
|
||||
}}
|
||||
</span>
|
||||
<div class="h-3 w-px rounded-lg bg-n-strong" />
|
||||
<span>{{ formatDate(dataImport.created_at) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
v-tooltip.top="$t('DATA_IMPORTS.TABLE.VIEW')"
|
||||
icon="i-lucide-eye"
|
||||
slate
|
||||
sm
|
||||
class="shrink-0"
|
||||
@click.stop="openImport(dataImport)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</SettingsLayout>
|
||||
|
||||
<NewImportDialog
|
||||
:show="showImportDrawer"
|
||||
:has-active-import="hasActiveIntercomImport"
|
||||
@close="showImportDrawer = false"
|
||||
@created="onImportCreated"
|
||||
/>
|
||||
</template>
|
||||
@@ -0,0 +1,210 @@
|
||||
<script setup>
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useAlert } from 'dashboard/composables';
|
||||
|
||||
import Dialog from 'dashboard/components-next/dialog/Dialog.vue';
|
||||
import Checkbox from 'dashboard/components-next/checkbox/Checkbox.vue';
|
||||
import Input from 'dashboard/components-next/input/Input.vue';
|
||||
import Select from 'dashboard/components-next/select/Select.vue';
|
||||
import DataImportsAPI from 'dashboard/api/dataImports';
|
||||
import { IMPORT_SOURCES } from './importSources';
|
||||
|
||||
const props = defineProps({
|
||||
show: { type: Boolean, default: false },
|
||||
hasActiveImport: { type: Boolean, default: false },
|
||||
});
|
||||
|
||||
const emit = defineEmits(['close', 'created']);
|
||||
|
||||
const { t } = useI18n();
|
||||
const dialogRef = ref(null);
|
||||
const sourceProvider = ref('intercom');
|
||||
const importName = ref(t('DATA_IMPORTS.DEFAULT_IMPORT_NAME'));
|
||||
const accessToken = ref('');
|
||||
const selectedImportTypes = ref(['contacts', 'conversations']);
|
||||
const validationState = ref('idle');
|
||||
const validationMessage = ref('');
|
||||
const isCreating = ref(false);
|
||||
let validationRequestId = 0;
|
||||
|
||||
const closeDrawer = () => emit('close');
|
||||
|
||||
const sourceOptions = computed(() =>
|
||||
IMPORT_SOURCES.map(({ value, label }) => ({ value, label }))
|
||||
);
|
||||
|
||||
const tokenMessageType = computed(() => {
|
||||
if (validationState.value === 'valid') return 'success';
|
||||
if (validationState.value === 'invalid') return 'error';
|
||||
return 'info';
|
||||
});
|
||||
|
||||
const canCreate = computed(
|
||||
() =>
|
||||
validationState.value === 'valid' &&
|
||||
selectedImportTypes.value.length > 0 &&
|
||||
!props.hasActiveImport &&
|
||||
!isCreating.value
|
||||
);
|
||||
|
||||
const validationPayload = () => ({
|
||||
source_provider: sourceProvider.value,
|
||||
access_token: accessToken.value.trim(),
|
||||
import_types: selectedImportTypes.value,
|
||||
});
|
||||
|
||||
const invalidateValidation = () => {
|
||||
validationRequestId += 1;
|
||||
validationState.value = 'idle';
|
||||
validationMessage.value = '';
|
||||
};
|
||||
|
||||
const validateSource = async () => {
|
||||
if (!accessToken.value.trim() || !selectedImportTypes.value.length) {
|
||||
invalidateValidation();
|
||||
return;
|
||||
}
|
||||
|
||||
validationRequestId += 1;
|
||||
const requestId = validationRequestId;
|
||||
validationState.value = 'validating';
|
||||
validationMessage.value = t('DATA_IMPORTS.DRAWER.VALIDATING');
|
||||
try {
|
||||
await DataImportsAPI.validateSource(validationPayload());
|
||||
if (requestId !== validationRequestId) return;
|
||||
|
||||
validationState.value = 'valid';
|
||||
validationMessage.value = t('DATA_IMPORTS.DRAWER.VALID_KEY');
|
||||
} catch (error) {
|
||||
if (requestId !== validationRequestId) return;
|
||||
|
||||
validationState.value = 'invalid';
|
||||
validationMessage.value =
|
||||
error?.response?.data?.message || t('DATA_IMPORTS.DRAWER.INVALID_KEY');
|
||||
}
|
||||
};
|
||||
|
||||
const toggleImportType = type => {
|
||||
selectedImportTypes.value = selectedImportTypes.value.includes(type)
|
||||
? selectedImportTypes.value.filter(item => item !== type)
|
||||
: [...selectedImportTypes.value, type];
|
||||
};
|
||||
|
||||
const createImport = async () => {
|
||||
if (!canCreate.value) return;
|
||||
|
||||
isCreating.value = true;
|
||||
try {
|
||||
const response = await DataImportsAPI.create({
|
||||
...validationPayload(),
|
||||
name: importName.value.trim() || t('DATA_IMPORTS.DEFAULT_IMPORT_NAME'),
|
||||
});
|
||||
useAlert(t('DATA_IMPORTS.ALERTS.IMPORT_STARTED'));
|
||||
emit('created', response.data.id);
|
||||
} catch (error) {
|
||||
useAlert(
|
||||
error?.response?.data?.message || t('DATA_IMPORTS.ALERTS.IMPORT_FAILED')
|
||||
);
|
||||
} finally {
|
||||
isCreating.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
watch(accessToken, invalidateValidation);
|
||||
|
||||
watch(selectedImportTypes, () => {
|
||||
invalidateValidation();
|
||||
if (accessToken.value.trim() && selectedImportTypes.value.length) {
|
||||
validateSource();
|
||||
}
|
||||
});
|
||||
|
||||
watch(
|
||||
() => props.show,
|
||||
show => {
|
||||
if (show) {
|
||||
dialogRef.value?.open();
|
||||
return;
|
||||
}
|
||||
|
||||
dialogRef.value?.close();
|
||||
accessToken.value = '';
|
||||
validationState.value = 'idle';
|
||||
validationMessage.value = '';
|
||||
}
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog
|
||||
ref="dialogRef"
|
||||
:title="$t('DATA_IMPORTS.DRAWER.TITLE')"
|
||||
:confirm-button-label="$t('DATA_IMPORTS.DRAWER.IMPORT')"
|
||||
:cancel-button-label="$t('DATA_IMPORTS.DRAWER.CANCEL')"
|
||||
:disable-confirm-button="!canCreate"
|
||||
:is-loading="isCreating || validationState === 'validating'"
|
||||
width="md"
|
||||
@confirm="createImport"
|
||||
@close="closeDrawer"
|
||||
>
|
||||
<div class="flex flex-col gap-4">
|
||||
<label class="flex flex-col gap-1.5 text-heading-3 text-n-slate-12">
|
||||
{{ $t('DATA_IMPORTS.DRAWER.SOURCE') }}
|
||||
<Select
|
||||
v-model="sourceProvider"
|
||||
class="!w-full [&>select]:w-full"
|
||||
:options="sourceOptions"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<Input
|
||||
v-model="importName"
|
||||
:label="$t('DATA_IMPORTS.DRAWER.NAME')"
|
||||
:placeholder="$t('DATA_IMPORTS.DRAWER.NAME_PLACEHOLDER')"
|
||||
/>
|
||||
|
||||
<Input
|
||||
v-model="accessToken"
|
||||
type="password"
|
||||
autocomplete="off"
|
||||
:label="$t('DATA_IMPORTS.DRAWER.ACCESS_KEY')"
|
||||
:placeholder="$t('DATA_IMPORTS.DRAWER.ACCESS_KEY_PLACEHOLDER')"
|
||||
:message="validationMessage"
|
||||
:message-type="tokenMessageType"
|
||||
@blur="validateSource"
|
||||
/>
|
||||
|
||||
<fieldset class="flex flex-col gap-2.5">
|
||||
<legend class="mb-1.5 text-heading-3 text-n-slate-12">
|
||||
{{ $t('DATA_IMPORTS.DRAWER.DATA_TYPES') }}
|
||||
</legend>
|
||||
<label
|
||||
class="inline-flex cursor-pointer items-center gap-2 text-body-main text-n-slate-12"
|
||||
>
|
||||
<Checkbox
|
||||
:model-value="selectedImportTypes.includes('contacts')"
|
||||
@change="toggleImportType('contacts')"
|
||||
/>
|
||||
{{ $t('DATA_IMPORTS.TYPES.CONTACTS') }}
|
||||
</label>
|
||||
<label
|
||||
class="inline-flex cursor-pointer items-center gap-2 text-body-main text-n-slate-12"
|
||||
>
|
||||
<Checkbox
|
||||
:model-value="selectedImportTypes.includes('conversations')"
|
||||
@change="toggleImportType('conversations')"
|
||||
/>
|
||||
{{ $t('DATA_IMPORTS.TYPES.CONVERSATIONS') }}
|
||||
</label>
|
||||
</fieldset>
|
||||
|
||||
<p
|
||||
v-if="hasActiveImport"
|
||||
class="rounded-lg bg-n-amber-2 px-3 py-2 text-body-main text-n-amber-11"
|
||||
>
|
||||
{{ $t('DATA_IMPORTS.DRAWER.ACTIVE_IMPORT') }}
|
||||
</p>
|
||||
</div>
|
||||
</Dialog>
|
||||
</template>
|
||||
@@ -0,0 +1,238 @@
|
||||
<script setup>
|
||||
import {
|
||||
computed,
|
||||
onActivated,
|
||||
onBeforeUnmount,
|
||||
onDeactivated,
|
||||
ref,
|
||||
} from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useRoute } from 'vue-router';
|
||||
import { useAlert } from 'dashboard/composables';
|
||||
|
||||
import DataImportsAPI from 'dashboard/api/dataImports';
|
||||
import { POLL_INTERVAL_MS, isActiveImport } from './importStatus';
|
||||
import SettingsLayout from '../SettingsLayout.vue';
|
||||
import ImportDetailHeader from './components/ImportDetailHeader.vue';
|
||||
import ImportSummaryTiles from './components/ImportSummaryTiles.vue';
|
||||
import ImportProgress from './components/ImportProgress.vue';
|
||||
import ImportErrorsSection from './components/ImportErrorsSection.vue';
|
||||
import ImportSkipLogsSection from './components/ImportSkipLogsSection.vue';
|
||||
|
||||
const { t } = useI18n();
|
||||
const route = useRoute();
|
||||
|
||||
const dataImport = ref(null);
|
||||
const isLoading = ref(true);
|
||||
const isRefreshing = ref(false);
|
||||
const isPolling = ref(false);
|
||||
const isAbandoning = ref(false);
|
||||
const isDownloadingErrorLogs = ref(false);
|
||||
const isDownloadingSkipLogs = ref(false);
|
||||
const isChangingSkipLogsType = ref(false);
|
||||
const selectedSkipLogsType = ref('');
|
||||
const errorsOpen = ref(true);
|
||||
const skipLogsOpen = ref(true);
|
||||
let pollTimer;
|
||||
let isPageActive = false;
|
||||
|
||||
const hasActiveImport = computed(() => isActiveImport(dataImport.value));
|
||||
|
||||
const stopPolling = () => {
|
||||
if (!pollTimer) return;
|
||||
|
||||
window.clearInterval(pollTimer);
|
||||
pollTimer = null;
|
||||
};
|
||||
|
||||
const fetchImport = async ({
|
||||
showLoader = false,
|
||||
manual = false,
|
||||
requestedSkipLogsType = selectedSkipLogsType.value,
|
||||
} = {}) => {
|
||||
if (showLoader) {
|
||||
isLoading.value = true;
|
||||
} else if (manual) {
|
||||
isRefreshing.value = true;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await DataImportsAPI.show(route.params.dataImportId, {
|
||||
skip_logs_type: requestedSkipLogsType || undefined,
|
||||
});
|
||||
dataImport.value = response.data;
|
||||
selectedSkipLogsType.value =
|
||||
response.data.skip_logs_filters?.selected_source_object_type ||
|
||||
requestedSkipLogsType ||
|
||||
'';
|
||||
} finally {
|
||||
if (showLoader) isLoading.value = false;
|
||||
if (manual) isRefreshing.value = false;
|
||||
if (!hasActiveImport.value) stopPolling();
|
||||
}
|
||||
};
|
||||
|
||||
const changeSkipLogsType = async type => {
|
||||
if (type === selectedSkipLogsType.value || isChangingSkipLogsType.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
selectedSkipLogsType.value = type;
|
||||
isChangingSkipLogsType.value = true;
|
||||
try {
|
||||
await fetchImport({ requestedSkipLogsType: type });
|
||||
} finally {
|
||||
isChangingSkipLogsType.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const refreshImportInBackground = async () => {
|
||||
if (
|
||||
!isPageActive ||
|
||||
isPolling.value ||
|
||||
!hasActiveImport.value ||
|
||||
document.hidden
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
isPolling.value = true;
|
||||
try {
|
||||
await fetchImport();
|
||||
} finally {
|
||||
isPolling.value = false;
|
||||
if (!hasActiveImport.value) stopPolling();
|
||||
}
|
||||
};
|
||||
|
||||
const abandonImport = async () => {
|
||||
isAbandoning.value = true;
|
||||
try {
|
||||
const response = await DataImportsAPI.abandon(dataImport.value.id);
|
||||
dataImport.value = response.data;
|
||||
stopPolling();
|
||||
useAlert(t('DATA_IMPORTS.ALERTS.IMPORT_ABANDONED'));
|
||||
} finally {
|
||||
isAbandoning.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const downloadCsv = (response, filename) => {
|
||||
const url = window.URL.createObjectURL(
|
||||
new Blob([response.data], { type: 'text/csv' })
|
||||
);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = filename;
|
||||
link.click();
|
||||
window.URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
const downloadErrorLogs = async () => {
|
||||
isDownloadingErrorLogs.value = true;
|
||||
try {
|
||||
const response = await DataImportsAPI.downloadErrorLogs(
|
||||
dataImport.value.id
|
||||
);
|
||||
downloadCsv(response, `data-import-${dataImport.value.id}-error-logs.csv`);
|
||||
} finally {
|
||||
isDownloadingErrorLogs.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const downloadSkipLogs = async () => {
|
||||
isDownloadingSkipLogs.value = true;
|
||||
try {
|
||||
const response = await DataImportsAPI.downloadSkipLogs(dataImport.value.id);
|
||||
downloadCsv(response, `data-import-${dataImport.value.id}-skip-logs.csv`);
|
||||
} finally {
|
||||
isDownloadingSkipLogs.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const startPolling = () => {
|
||||
stopPolling();
|
||||
if (!isPageActive || !hasActiveImport.value) return;
|
||||
|
||||
pollTimer = window.setInterval(refreshImportInBackground, POLL_INTERVAL_MS);
|
||||
};
|
||||
|
||||
const handleVisibilityChange = () => {
|
||||
if (isPageActive && !document.hidden && hasActiveImport.value) {
|
||||
refreshImportInBackground();
|
||||
}
|
||||
};
|
||||
|
||||
onActivated(async () => {
|
||||
isPageActive = true;
|
||||
await fetchImport({ showLoader: true });
|
||||
if (!isPageActive) return;
|
||||
|
||||
// Collapse empty sections by default; expand the ones with records.
|
||||
errorsOpen.value = Boolean(dataImport.value?.import_errors_count);
|
||||
skipLogsOpen.value = Boolean(dataImport.value?.skip_logs_count);
|
||||
startPolling();
|
||||
document.addEventListener('visibilitychange', handleVisibilityChange);
|
||||
});
|
||||
|
||||
onDeactivated(() => {
|
||||
isPageActive = false;
|
||||
stopPolling();
|
||||
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
isPageActive = false;
|
||||
stopPolling();
|
||||
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<SettingsLayout
|
||||
:is-loading="isLoading"
|
||||
:loading-message="$t('DATA_IMPORTS.LOADING')"
|
||||
>
|
||||
<template #header>
|
||||
<ImportDetailHeader
|
||||
:data-import="dataImport"
|
||||
:is-refreshing="isRefreshing"
|
||||
:is-abandoning="isAbandoning"
|
||||
:is-polling="isPolling"
|
||||
@refresh="fetchImport({ manual: true })"
|
||||
@abandon="abandonImport"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<template #body>
|
||||
<div v-if="dataImport" class="flex flex-col gap-3">
|
||||
<ImportSummaryTiles :data-import="dataImport" />
|
||||
|
||||
<ImportProgress
|
||||
v-if="dataImport.import_types?.length"
|
||||
:data-import="dataImport"
|
||||
:title="$t('DATA_IMPORTS.DETAIL.PROGRESS')"
|
||||
/>
|
||||
|
||||
<ImportErrorsSection
|
||||
:data-import="dataImport"
|
||||
:is-open="errorsOpen"
|
||||
:is-downloading="isDownloadingErrorLogs"
|
||||
@toggle="errorsOpen = !errorsOpen"
|
||||
@download="downloadErrorLogs"
|
||||
/>
|
||||
|
||||
<ImportSkipLogsSection
|
||||
:data-import="dataImport"
|
||||
:is-open="skipLogsOpen"
|
||||
:is-downloading="isDownloadingSkipLogs"
|
||||
:selected-type="selectedSkipLogsType"
|
||||
:is-changing-type="isChangingSkipLogsType"
|
||||
@toggle="skipLogsOpen = !skipLogsOpen"
|
||||
@download="downloadSkipLogs"
|
||||
@change-type="changeSkipLogsType"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</SettingsLayout>
|
||||
</template>
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
<script setup>
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
import Button from 'dashboard/components-next/button/Button.vue';
|
||||
import BaseSettingsHeader from '../../components/BaseSettingsHeader.vue';
|
||||
import {
|
||||
POLL_INTERVAL_MS,
|
||||
importStageKey,
|
||||
isAbandonableImport,
|
||||
isActiveImport,
|
||||
statusDotClass as getStatusDotClass,
|
||||
} from '../importStatus';
|
||||
|
||||
const props = defineProps({
|
||||
dataImport: {
|
||||
type: Object,
|
||||
default: null,
|
||||
},
|
||||
isRefreshing: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
isAbandoning: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
isPolling: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
});
|
||||
|
||||
defineEmits(['refresh', 'abandon']);
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const pollIntervalSeconds = POLL_INTERVAL_MS / 1000;
|
||||
|
||||
const title = computed(
|
||||
() => props.dataImport?.name || t('DATA_IMPORTS.TABLE.UNNAMED')
|
||||
);
|
||||
|
||||
const stageLabels = computed(() => ({
|
||||
unknown: t('DATA_IMPORTS.MONITOR.STAGES.unknown'),
|
||||
queued: t('DATA_IMPORTS.MONITOR.STAGES.queued'),
|
||||
contacts: t('DATA_IMPORTS.MONITOR.STAGES.contacts'),
|
||||
conversations: t('DATA_IMPORTS.MONITOR.STAGES.conversations'),
|
||||
finalizing: t('DATA_IMPORTS.MONITOR.STAGES.finalizing'),
|
||||
completed: t('DATA_IMPORTS.MONITOR.STAGES.completed'),
|
||||
completed_with_errors: t('DATA_IMPORTS.MONITOR.STAGES.completed_with_errors'),
|
||||
failed: t('DATA_IMPORTS.MONITOR.STAGES.failed'),
|
||||
abandoned: t('DATA_IMPORTS.MONITOR.STAGES.abandoned'),
|
||||
}));
|
||||
|
||||
const monitorTitle = computed(
|
||||
() =>
|
||||
stageLabels.value[importStageKey(props.dataImport)] ||
|
||||
stageLabels.value.unknown
|
||||
);
|
||||
|
||||
const statusDotClass = computed(() =>
|
||||
getStatusDotClass(props.dataImport?.status)
|
||||
);
|
||||
|
||||
const hasActiveImport = computed(() => isActiveImport(props.dataImport));
|
||||
|
||||
const canAbandonImport = computed(() => isAbandonableImport(props.dataImport));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<BaseSettingsHeader
|
||||
:title="title"
|
||||
:back-button-label="$t('DATA_IMPORTS.DETAIL.BACK')"
|
||||
>
|
||||
<template #title>
|
||||
<div class="flex w-full items-center justify-between gap-4">
|
||||
<h1 class="min-w-0 truncate text-heading-1 text-n-slate-12">
|
||||
{{ title }}
|
||||
</h1>
|
||||
<div class="flex shrink-0 items-center gap-2">
|
||||
<Button
|
||||
v-if="hasActiveImport"
|
||||
outline
|
||||
slate
|
||||
size="sm"
|
||||
icon="i-lucide-refresh-cw"
|
||||
:is-loading="isRefreshing"
|
||||
:aria-label="$t('DATA_IMPORTS.MONITOR.REFRESH')"
|
||||
:title="$t('DATA_IMPORTS.MONITOR.REFRESH')"
|
||||
@click="$emit('refresh')"
|
||||
/>
|
||||
<Button
|
||||
v-if="canAbandonImport"
|
||||
ruby
|
||||
size="sm"
|
||||
:is-loading="isAbandoning"
|
||||
:label="$t('DATA_IMPORTS.TABLE.ABANDON')"
|
||||
@click="$emit('abandon')"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<template #description>
|
||||
<span class="inline-flex items-center gap-1.5 align-middle">
|
||||
<span
|
||||
class="size-2 rounded-full"
|
||||
:class="[statusDotClass, { 'animate-pulse': hasActiveImport }]"
|
||||
/>
|
||||
{{ monitorTitle }}
|
||||
</span>
|
||||
<template v-if="hasActiveImport">
|
||||
<span
|
||||
class="mx-2 inline-block h-3 w-px rounded-lg bg-n-strong align-middle"
|
||||
/>
|
||||
<span class="text-n-teal-11">
|
||||
{{
|
||||
isPolling
|
||||
? $t('DATA_IMPORTS.MONITOR.REFRESHING')
|
||||
: $t('DATA_IMPORTS.MONITOR.LIVE', {
|
||||
seconds: pollIntervalSeconds,
|
||||
})
|
||||
}}
|
||||
</span>
|
||||
</template>
|
||||
</template>
|
||||
</BaseSettingsHeader>
|
||||
</template>
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
<script setup>
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
import { BaseTableRow, BaseTableCell } from 'dashboard/components-next/table';
|
||||
import ImportLogSection from './ImportLogSection.vue';
|
||||
import { formatDate, sourceObjectLabel } from '../importStatus';
|
||||
|
||||
const props = defineProps({
|
||||
dataImport: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
isOpen: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
isDownloading: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
});
|
||||
|
||||
defineEmits(['toggle', 'download']);
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const errors = computed(() => props.dataImport?.import_errors || []);
|
||||
|
||||
const headers = computed(() => [
|
||||
t('DATA_IMPORTS.DETAIL.ERROR_CODE'),
|
||||
t('DATA_IMPORTS.DETAIL.SOURCE_OBJECT'),
|
||||
t('DATA_IMPORTS.DETAIL.MESSAGE'),
|
||||
t('DATA_IMPORTS.DETAIL.CREATED'),
|
||||
]);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ImportLogSection
|
||||
:title="$t('DATA_IMPORTS.DETAIL.ERRORS')"
|
||||
:count="dataImport.import_errors_count"
|
||||
:is-open="isOpen"
|
||||
:is-downloading="isDownloading"
|
||||
:download-label="$t('DATA_IMPORTS.DETAIL.DOWNLOAD_ERROR_LOGS')"
|
||||
:headers="headers"
|
||||
:items="errors"
|
||||
:empty-message="$t('DATA_IMPORTS.DETAIL.NO_ERRORS')"
|
||||
@toggle="$emit('toggle')"
|
||||
@download="$emit('download')"
|
||||
>
|
||||
<template #row="{ items }">
|
||||
<BaseTableRow v-for="error in items" :key="error.id" :item="error">
|
||||
<template #default>
|
||||
<BaseTableCell>
|
||||
<span class="text-body-main text-n-slate-12">
|
||||
{{ error.error_code }}
|
||||
</span>
|
||||
</BaseTableCell>
|
||||
<BaseTableCell>
|
||||
<span class="text-body-main text-n-slate-12">
|
||||
{{ sourceObjectLabel(error) }}
|
||||
</span>
|
||||
</BaseTableCell>
|
||||
<BaseTableCell>
|
||||
<span class="text-body-main text-n-slate-11">
|
||||
{{ error.message || '-' }}
|
||||
</span>
|
||||
</BaseTableCell>
|
||||
<BaseTableCell>
|
||||
<span class="whitespace-nowrap text-body-main text-n-slate-11">
|
||||
{{ formatDate(error.created_at) }}
|
||||
</span>
|
||||
</BaseTableCell>
|
||||
</template>
|
||||
</BaseTableRow>
|
||||
</template>
|
||||
</ImportLogSection>
|
||||
</template>
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
<script setup>
|
||||
import Button from 'dashboard/components-next/button/Button.vue';
|
||||
import Icon from 'dashboard/components-next/icon/Icon.vue';
|
||||
import { BaseTable } from 'dashboard/components-next/table';
|
||||
|
||||
defineProps({
|
||||
title: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
count: {
|
||||
type: Number,
|
||||
default: 0,
|
||||
},
|
||||
isOpen: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
isDownloading: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
downloadLabel: {
|
||||
type: String,
|
||||
default: '',
|
||||
},
|
||||
headers: {
|
||||
type: Array,
|
||||
default: () => [],
|
||||
},
|
||||
items: {
|
||||
type: Array,
|
||||
default: () => [],
|
||||
},
|
||||
emptyMessage: {
|
||||
type: String,
|
||||
default: '',
|
||||
},
|
||||
});
|
||||
|
||||
defineEmits(['toggle', 'download']);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="overflow-hidden rounded-xl border border-n-weak bg-n-solid-1">
|
||||
<div class="flex items-center justify-between gap-3 px-4 py-3">
|
||||
<button
|
||||
type="button"
|
||||
class="flex min-w-0 items-center gap-2 !p-0"
|
||||
:aria-expanded="isOpen"
|
||||
@click="$emit('toggle')"
|
||||
>
|
||||
<h2 class="text-heading-3 text-n-slate-12">{{ title }}</h2>
|
||||
<span
|
||||
v-if="count"
|
||||
class="rounded-md bg-n-alpha-2 px-1.5 text-label-small tabular-nums text-n-slate-11"
|
||||
>
|
||||
{{ count }}
|
||||
</span>
|
||||
<Icon
|
||||
icon="i-lucide-chevron-down"
|
||||
class="size-4 shrink-0 text-n-slate-10 transition-transform duration-200"
|
||||
:class="{ '-rotate-90 rtl:rotate-90': !isOpen }"
|
||||
/>
|
||||
</button>
|
||||
<Button
|
||||
ghost
|
||||
slate
|
||||
xs
|
||||
icon="i-lucide-download"
|
||||
:is-loading="isDownloading"
|
||||
:disabled="!count"
|
||||
:label="downloadLabel"
|
||||
@click="$emit('download')"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
class="grid transition-[grid-template-rows] duration-300 ease-in-out"
|
||||
:class="isOpen ? 'grid-rows-[1fr]' : 'grid-rows-[0fr]'"
|
||||
>
|
||||
<div class="min-h-0 overflow-hidden">
|
||||
<div class="border-t border-n-weak">
|
||||
<slot name="filters" />
|
||||
<p
|
||||
v-if="!items.length"
|
||||
class="px-4 py-8 text-center text-body-main text-n-slate-11"
|
||||
>
|
||||
{{ emptyMessage }}
|
||||
</p>
|
||||
<div v-else class="overflow-x-auto">
|
||||
<BaseTable
|
||||
class="[&_td:first-child]:ps-4 [&_th:first-child]:ps-4 [&_th]:text-n-slate-11 [&_thead]:border-t-0"
|
||||
:headers="headers"
|
||||
:items="items"
|
||||
>
|
||||
<template #row="{ items: rows }">
|
||||
<slot name="row" :items="rows" />
|
||||
</template>
|
||||
</BaseTable>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user