Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3cbc19b3f2 | ||
|
|
65dedba3ab | ||
|
|
7e760732a2 | ||
|
|
51c7e3ff0f | ||
|
|
3b1e3683da | ||
|
|
8a983c10b4 | ||
|
|
1265cb0ff9 | ||
|
|
11b22b2804 | ||
|
|
cc5a76f24a | ||
|
|
f6d11d2fa8 | ||
|
|
e05f024581 | ||
|
|
d791e51f5d | ||
|
|
014167fd62 |
+1
-8
@@ -7,7 +7,6 @@ plugins:
|
||||
require:
|
||||
- ./rubocop/use_from_email.rb
|
||||
- ./rubocop/custom_cop_location.rb
|
||||
- ./rubocop/attachment_download.rb
|
||||
- ./rubocop/one_class_per_file.rb
|
||||
|
||||
Layout/LineLength:
|
||||
@@ -42,12 +41,6 @@ Style/SymbolArray:
|
||||
Style/OpenStructUse:
|
||||
Enabled: false
|
||||
|
||||
Chatwoot/AttachmentDownload:
|
||||
Enabled: true
|
||||
Exclude:
|
||||
- 'spec/**/*'
|
||||
- 'test/**/*'
|
||||
|
||||
Style/OptionalBooleanParameter:
|
||||
Exclude:
|
||||
- 'app/services/email_templates/db_resolver_service.rb'
|
||||
@@ -95,7 +88,7 @@ Metrics/ModuleLength:
|
||||
Rails/HelperInstanceVariable:
|
||||
Exclude:
|
||||
- enterprise/app/helpers/captain/chat_helper.rb
|
||||
- enterprise/app/helpers/captain/chat_response_helper.rb
|
||||
- 'enterprise/app/helpers/captain/tool_execution_helper.rb'
|
||||
Rails/ApplicationController:
|
||||
Exclude:
|
||||
- 'app/controllers/api/v1/widget/messages_controller.rb'
|
||||
|
||||
@@ -162,7 +162,7 @@ gem 'working_hours'
|
||||
gem 'pg_search'
|
||||
|
||||
# Subscriptions, Billing
|
||||
gem 'stripe', '~> 18.0'
|
||||
gem 'stripe'
|
||||
|
||||
## - helper gems --##
|
||||
## to populate db with sample data
|
||||
@@ -191,10 +191,9 @@ gem 'reverse_markdown'
|
||||
|
||||
gem 'iso-639'
|
||||
gem 'ruby-openai'
|
||||
gem 'ai-agents', '>= 0.7.0'
|
||||
gem 'ai-agents', '>= 0.4.3'
|
||||
|
||||
# TODO: Move this gem as a dependency of ai-agents
|
||||
gem 'ruby_llm', '>= 1.8.2'
|
||||
gem 'ruby_llm-schema'
|
||||
|
||||
# OpenTelemetry for LLM observability
|
||||
@@ -215,7 +214,7 @@ group :production do
|
||||
end
|
||||
|
||||
group :development do
|
||||
gem 'annotaterb'
|
||||
gem 'annotate'
|
||||
gem 'bullet'
|
||||
gem 'letter_opener'
|
||||
gem 'scss_lint', require: false
|
||||
|
||||
+11
-12
@@ -126,11 +126,11 @@ GEM
|
||||
jbuilder (~> 2)
|
||||
rails (>= 4.2, < 7.2)
|
||||
selectize-rails (~> 0.6)
|
||||
ai-agents (0.7.0)
|
||||
ruby_llm (~> 1.8.2)
|
||||
annotaterb (4.20.0)
|
||||
activerecord (>= 6.0.0)
|
||||
activesupport (>= 6.0.0)
|
||||
ai-agents (0.4.3)
|
||||
ruby_llm (~> 1.3)
|
||||
annotate (3.2.0)
|
||||
activerecord (>= 3.2, < 8.0)
|
||||
rake (>= 10.4, < 14.0)
|
||||
ast (2.4.3)
|
||||
attr_extras (7.1.0)
|
||||
audited (5.4.1)
|
||||
@@ -819,7 +819,7 @@ GEM
|
||||
ruby2ruby (2.5.0)
|
||||
ruby_parser (~> 3.1)
|
||||
sexp_processor (~> 4.6)
|
||||
ruby_llm (1.8.2)
|
||||
ruby_llm (1.5.1)
|
||||
base64
|
||||
event_stream_parser (~> 1)
|
||||
faraday (>= 1.10.0)
|
||||
@@ -828,7 +828,7 @@ GEM
|
||||
faraday-retry (>= 1)
|
||||
marcel (~> 1.0)
|
||||
zeitwerk (~> 2)
|
||||
ruby_llm-schema (0.2.5)
|
||||
ruby_llm-schema (0.1.0)
|
||||
ruby_parser (3.20.0)
|
||||
sexp_processor (~> 4.16)
|
||||
sass (3.7.4)
|
||||
@@ -928,7 +928,7 @@ GEM
|
||||
squasher (0.7.2)
|
||||
stackprof (0.2.25)
|
||||
statsd-ruby (1.5.0)
|
||||
stripe (18.0.1)
|
||||
stripe (8.5.0)
|
||||
telephone_number (1.4.20)
|
||||
test-prof (1.2.1)
|
||||
thor (1.4.0)
|
||||
@@ -1017,8 +1017,8 @@ DEPENDENCIES
|
||||
administrate (>= 0.20.1)
|
||||
administrate-field-active_storage (>= 1.0.3)
|
||||
administrate-field-belongs_to_search (>= 0.9.0)
|
||||
ai-agents (>= 0.7.0)
|
||||
annotaterb
|
||||
ai-agents (>= 0.4.3)
|
||||
annotate
|
||||
attr_extras
|
||||
audited (~> 5.4, >= 5.4.1)
|
||||
aws-actionmailbox-ses (~> 0)
|
||||
@@ -1119,7 +1119,6 @@ DEPENDENCIES
|
||||
rubocop-rails
|
||||
rubocop-rspec
|
||||
ruby-openai
|
||||
ruby_llm (>= 1.8.2)
|
||||
ruby_llm-schema
|
||||
scout_apm
|
||||
scss_lint
|
||||
@@ -1140,7 +1139,7 @@ DEPENDENCIES
|
||||
spring-watcher-listen
|
||||
squasher
|
||||
stackprof
|
||||
stripe (~> 18.0)
|
||||
stripe
|
||||
telephone_number
|
||||
test-prof
|
||||
tidewave
|
||||
|
||||
@@ -9,8 +9,6 @@ class Messages::Messenger::MessageBuilder
|
||||
attachment_obj.save!
|
||||
attach_file(attachment_obj, attachment_params(attachment)[:remote_file_url]) if attachment_params(attachment)[:remote_file_url]
|
||||
fetch_story_link(attachment_obj) if attachment_obj.file_type == 'story_mention'
|
||||
fetch_ig_story_link(attachment_obj) if attachment_obj.file_type == 'ig_story'
|
||||
fetch_ig_post_link(attachment_obj) if attachment_obj.file_type == 'ig_post'
|
||||
update_attachment_file_type(attachment_obj)
|
||||
end
|
||||
|
||||
@@ -29,7 +27,7 @@ class Messages::Messenger::MessageBuilder
|
||||
file_type = attachment['type'].to_sym
|
||||
params = { file_type: file_type, account_id: @message.account_id }
|
||||
|
||||
if [:image, :file, :audio, :video, :share, :story_mention, :ig_reel, :ig_post, :ig_story].include? file_type
|
||||
if [:image, :file, :audio, :video, :share, :story_mention, :ig_reel].include? file_type
|
||||
params.merge!(file_type_params(attachment))
|
||||
elsif file_type == :location
|
||||
params.merge!(location_params(attachment))
|
||||
@@ -41,17 +39,9 @@ class Messages::Messenger::MessageBuilder
|
||||
end
|
||||
|
||||
def file_type_params(attachment)
|
||||
# Handle different URL field names for different attachment types
|
||||
url = case attachment['type'].to_sym
|
||||
when :ig_story
|
||||
attachment['payload']['story_media_url']
|
||||
else
|
||||
attachment['payload']['url']
|
||||
end
|
||||
|
||||
{
|
||||
external_url: url,
|
||||
remote_file_url: url
|
||||
external_url: attachment['payload']['url'],
|
||||
remote_file_url: attachment['payload']['url']
|
||||
}
|
||||
end
|
||||
|
||||
@@ -78,21 +68,6 @@ class Messages::Messenger::MessageBuilder
|
||||
message.save!
|
||||
end
|
||||
|
||||
def fetch_ig_story_link(attachment)
|
||||
message = attachment.message
|
||||
# For ig_story, we don't have the same API call as story_mention, so we'll set it up similarly but with generic content
|
||||
message.content_attributes[:image_type] = 'ig_story'
|
||||
message.content = I18n.t('conversations.messages.instagram_shared_story_content')
|
||||
message.save!
|
||||
end
|
||||
|
||||
def fetch_ig_post_link(attachment)
|
||||
message = attachment.message
|
||||
message.content_attributes[:image_type] = 'ig_post'
|
||||
message.content = I18n.t('conversations.messages.instagram_shared_post_content')
|
||||
message.save!
|
||||
end
|
||||
|
||||
# This is a placeholder method to be overridden by child classes
|
||||
def get_story_object_from_source_id(_source_id)
|
||||
{}
|
||||
@@ -101,6 +76,6 @@ class Messages::Messenger::MessageBuilder
|
||||
private
|
||||
|
||||
def unsupported_file_type?(attachment_type)
|
||||
[:template, :unsupported_type, :ephemeral].include? attachment_type.to_sym
|
||||
[:template, :unsupported_type].include? attachment_type.to_sym
|
||||
end
|
||||
end
|
||||
|
||||
@@ -92,7 +92,14 @@ class Api::V1::AccountsController < Api::BaseController
|
||||
end
|
||||
|
||||
def settings_params
|
||||
params.permit(:auto_resolve_after, :auto_resolve_message, :auto_resolve_ignore_waiting, :audio_transcriptions, :auto_resolve_label)
|
||||
params.permit(
|
||||
:auto_resolve_after,
|
||||
:auto_resolve_message,
|
||||
:auto_resolve_ignore_waiting,
|
||||
:audio_transcriptions,
|
||||
:auto_resolve_label,
|
||||
conversation_required_attributes: []
|
||||
)
|
||||
end
|
||||
|
||||
def check_signup_enabled
|
||||
|
||||
@@ -23,10 +23,6 @@ class EnterpriseAccountAPI extends ApiClient {
|
||||
action_type: action,
|
||||
});
|
||||
}
|
||||
|
||||
createTopupCheckout(credits) {
|
||||
return axios.post(`${this.url}topup_checkout`, { credits });
|
||||
}
|
||||
}
|
||||
|
||||
export default new EnterpriseAccountAPI();
|
||||
|
||||
@@ -11,8 +11,6 @@ describe('#enterpriseAccountAPI', () => {
|
||||
expect(accountAPI).toHaveProperty('delete');
|
||||
expect(accountAPI).toHaveProperty('checkout');
|
||||
expect(accountAPI).toHaveProperty('toggleDeletion');
|
||||
expect(accountAPI).toHaveProperty('createTopupCheckout');
|
||||
expect(accountAPI).toHaveProperty('getLimits');
|
||||
});
|
||||
|
||||
describe('API calls', () => {
|
||||
@@ -61,29 +59,5 @@ describe('#enterpriseAccountAPI', () => {
|
||||
{ action_type: 'undelete' }
|
||||
);
|
||||
});
|
||||
|
||||
it('#createTopupCheckout with credits', () => {
|
||||
accountAPI.createTopupCheckout(1000);
|
||||
expect(axiosMock.post).toHaveBeenCalledWith(
|
||||
'/enterprise/api/v1/topup_checkout',
|
||||
{ credits: 1000 }
|
||||
);
|
||||
});
|
||||
|
||||
it('#createTopupCheckout with different credit amounts', () => {
|
||||
const creditAmounts = [1000, 2500, 6000, 12000];
|
||||
creditAmounts.forEach(credits => {
|
||||
accountAPI.createTopupCheckout(credits);
|
||||
expect(axiosMock.post).toHaveBeenCalledWith(
|
||||
'/enterprise/api/v1/topup_checkout',
|
||||
{ credits }
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('#getLimits', () => {
|
||||
accountAPI.getLimits();
|
||||
expect(axiosMock.get).toHaveBeenCalledWith('/enterprise/api/v1/limits');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
<template>
|
||||
<div class="flex justify-between items-center px-4 py-4 w-full">
|
||||
<div
|
||||
class="flex justify-center items-center py-6 w-full custom-dashed-border"
|
||||
>
|
||||
<span class="text-sm text-n-slate-11">
|
||||
{{ $t('CONVERSATION_WORKFLOW.REQUIRED_ATTRIBUTES.NO_ATTRIBUTES') }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,42 @@
|
||||
<script setup>
|
||||
import { computed } from 'vue';
|
||||
import Icon from 'dashboard/components-next/icon/Icon.vue';
|
||||
|
||||
const props = defineProps({
|
||||
type: { type: String, default: 'resolution' },
|
||||
});
|
||||
|
||||
const colorClass = computed(() => {
|
||||
const colorMap = {
|
||||
'pre-chat': 'blue',
|
||||
resolution: 'teal',
|
||||
};
|
||||
const color = colorMap[props.type] || colorMap.resolution;
|
||||
return `text-n-${color}-11`;
|
||||
});
|
||||
|
||||
const iconName = computed(() => {
|
||||
const iconMap = {
|
||||
'pre-chat': 'i-lucide-message-circle',
|
||||
resolution: 'i-lucide-circle-check-big',
|
||||
};
|
||||
return iconMap[props.type] || iconMap.resolution;
|
||||
});
|
||||
|
||||
const displayLabel = computed(() => {
|
||||
const labelMap = {
|
||||
'pre-chat': 'Pre-chat',
|
||||
resolution: 'Resolution',
|
||||
};
|
||||
return labelMap[props.type] || labelMap.resolution;
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="flex gap-1 justify-center items-center px-1.5 py-1 rounded-md shadow outline-1 outline outline-n-container bg-n-solid-2"
|
||||
>
|
||||
<Icon :icon="iconName" class="size-4" :class="colorClass" />
|
||||
<span class="text-xs" :class="colorClass">{{ displayLabel }}</span>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,80 @@
|
||||
<script setup>
|
||||
import Button from 'dashboard/components-next/button/Button.vue';
|
||||
import Icon from 'dashboard/components-next/icon/Icon.vue';
|
||||
import AttributeBadge from 'dashboard/components-next/ConversationWorkflow/AttributeBadge.vue';
|
||||
import { computed } from 'vue';
|
||||
|
||||
const props = defineProps({
|
||||
attribute: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
badges: {
|
||||
type: Array,
|
||||
default: () => [],
|
||||
},
|
||||
});
|
||||
|
||||
const emit = defineEmits(['edit', 'delete']);
|
||||
|
||||
const iconByType = {
|
||||
text: 'i-lucide-align-justify',
|
||||
checkbox: 'i-lucide-circle-check-big',
|
||||
list: 'i-lucide-list',
|
||||
date: 'i-lucide-calendar',
|
||||
link: 'i-lucide-link',
|
||||
number: 'i-lucide-hash',
|
||||
};
|
||||
|
||||
const attributeIcon = computed(() => {
|
||||
const typeKey = props.attribute.type?.toLowerCase();
|
||||
return iconByType[typeKey] || 'i-lucide-align-justify';
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="flex flex-col gap-2 p-4 bg-white rounded-2xl border border-n-weak dark:bg-n-solid-1"
|
||||
>
|
||||
<div class="flex flex-wrap gap-2 justify-between items-center">
|
||||
<div class="flex flex-wrap gap-2 items-center min-w-0">
|
||||
<h4 class="text-sm font-medium truncate text-n-slate-12">
|
||||
{{ attribute.label }}
|
||||
</h4>
|
||||
<div class="flex gap-2 items-center text-sm text-n-slate-11">
|
||||
<Icon :icon="attributeIcon" class="size-4" />
|
||||
<span class="text-sm text-n-slate-11">{{ attribute.type }}</span>
|
||||
<div class="w-px h-3 bg-n-weak" />
|
||||
<Icon icon="i-lucide-key-round" class="size-4" />
|
||||
<span class="line-clamp-1">{{ attribute.value }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex gap-2 items-center">
|
||||
<AttributeBadge
|
||||
v-for="badge in badges"
|
||||
:key="badge.label"
|
||||
:type="badge.type"
|
||||
/>
|
||||
<div class="w-px h-3 bg-n-strong" />
|
||||
<Button
|
||||
icon="i-lucide-pencil-line"
|
||||
size="sm"
|
||||
color="slate"
|
||||
ghost
|
||||
@click="emit('edit', attribute)"
|
||||
/>
|
||||
<div class="w-px h-3 bg-n-strong" />
|
||||
<Button
|
||||
icon="i-lucide-trash"
|
||||
size="sm"
|
||||
color="slate"
|
||||
ghost
|
||||
@click="emit('delete', attribute)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<p class="mb-0 text-sm text-n-slate-11">
|
||||
{{ attribute.attribute_description || attribute.description || '' }}
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
<script setup>
|
||||
import { computed } from 'vue';
|
||||
import Button from 'dashboard/components-next/button/Button.vue';
|
||||
import Icon from 'dashboard/components-next/icon/Icon.vue';
|
||||
|
||||
const props = defineProps({
|
||||
attribute: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
});
|
||||
|
||||
const emit = defineEmits(['delete']);
|
||||
|
||||
const iconByType = {
|
||||
text: 'i-lucide-align-justify',
|
||||
checkbox: 'i-lucide-circle-check-big',
|
||||
list: 'i-lucide-list',
|
||||
date: 'i-lucide-calendar',
|
||||
link: 'i-lucide-link',
|
||||
number: 'i-lucide-hash',
|
||||
};
|
||||
|
||||
const attributeIcon = computed(() => {
|
||||
const typeKey = props.attribute.type?.toLowerCase();
|
||||
return iconByType[typeKey] || 'i-lucide-align-justify';
|
||||
});
|
||||
|
||||
const handleDelete = () => {
|
||||
emit('delete', props.attribute);
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex justify-between items-center px-4 py-3 w-full">
|
||||
<div class="flex gap-3 items-center">
|
||||
<h5 class="text-sm font-medium text-n-slate-12 line-clamp-1">
|
||||
{{ attribute.label }}
|
||||
</h5>
|
||||
<div class="w-px h-2.5 bg-n-slate-5" />
|
||||
<div class="flex gap-1.5 items-center">
|
||||
<Icon :icon="attributeIcon" class="size-4 text-n-slate-11" />
|
||||
<span class="text-sm text-n-slate-11">{{ attribute.type }}</span>
|
||||
</div>
|
||||
<div class="w-px h-2.5 bg-n-slate-5" />
|
||||
<div class="flex gap-1.5 items-center">
|
||||
<Icon icon="i-lucide-key-round" class="size-4 text-n-slate-11" />
|
||||
<span class="text-sm text-n-slate-11">{{ attribute.value }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex gap-2 items-center">
|
||||
<Button icon="i-lucide-trash" sm slate ghost @click.stop="handleDelete" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
<script setup>
|
||||
import { ref, computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useMapGetter } from 'dashboard/composables/store';
|
||||
import { useAccount } from 'dashboard/composables/useAccount';
|
||||
import { useAlert } from 'dashboard/composables';
|
||||
import Button from 'dashboard/components-next/button/Button.vue';
|
||||
import CardLayout from 'dashboard/components-next/CardLayout.vue';
|
||||
import DropdownMenu from 'dashboard/components-next/dropdown-menu/DropdownMenu.vue';
|
||||
import ConversationRequiredAttributeItem from 'dashboard/components-next/ConversationWorkflow/ConversationRequiredAttributeItem.vue';
|
||||
import ConversationRequiredEmpty from 'dashboard/components-next/Conversation/ConversationRequiredEmpty.vue';
|
||||
|
||||
defineProps({
|
||||
title: { type: String, default: '' },
|
||||
description: { type: String, default: '' },
|
||||
});
|
||||
|
||||
const emit = defineEmits(['click']);
|
||||
const { t } = useI18n();
|
||||
const { currentAccount, updateAccount } = useAccount();
|
||||
const showDropdown = ref(false);
|
||||
const isSaving = ref(false);
|
||||
const conversationAttributes = useMapGetter(
|
||||
'attributes/getConversationAttributes'
|
||||
);
|
||||
|
||||
const handleClick = () => {
|
||||
emit('click');
|
||||
};
|
||||
|
||||
const selectedAttributeKeys = computed(
|
||||
() => currentAccount.value?.settings?.conversation_required_attributes || []
|
||||
);
|
||||
|
||||
const allAttributeOptions = computed(() =>
|
||||
(conversationAttributes.value || []).map(attribute => ({
|
||||
...attribute,
|
||||
action: 'add',
|
||||
value: attribute.attributeKey,
|
||||
label: attribute.attributeDisplayName,
|
||||
type: attribute.attributeDisplayType,
|
||||
}))
|
||||
);
|
||||
|
||||
const attributeOptions = computed(() =>
|
||||
allAttributeOptions.value.filter(
|
||||
attribute => !selectedAttributeKeys.value.includes(attribute.value)
|
||||
)
|
||||
);
|
||||
|
||||
const conversationRequiredAttributes = computed(() =>
|
||||
selectedAttributeKeys.value
|
||||
.map(key =>
|
||||
allAttributeOptions.value.find(attribute => attribute.value === key)
|
||||
)
|
||||
.filter(Boolean)
|
||||
);
|
||||
|
||||
const handleAddAttributesClick = event => {
|
||||
event.stopPropagation();
|
||||
showDropdown.value = !showDropdown.value;
|
||||
};
|
||||
|
||||
const saveRequiredAttributes = async keys => {
|
||||
try {
|
||||
isSaving.value = true;
|
||||
await updateAccount(
|
||||
{ conversation_required_attributes: keys },
|
||||
{ silent: true }
|
||||
);
|
||||
useAlert(t('CONVERSATION_WORKFLOW.REQUIRED_ATTRIBUTES.SAVE.SUCCESS'));
|
||||
} catch (error) {
|
||||
useAlert(t('CONVERSATION_WORKFLOW.REQUIRED_ATTRIBUTES.SAVE.ERROR'));
|
||||
} finally {
|
||||
isSaving.value = false;
|
||||
showDropdown.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const handleAttributeAction = ({ value }) => {
|
||||
if (!value || isSaving.value) return;
|
||||
const updatedKeys = Array.from(
|
||||
new Set([...selectedAttributeKeys.value, value])
|
||||
);
|
||||
saveRequiredAttributes(updatedKeys);
|
||||
};
|
||||
|
||||
const closeDropdown = () => {
|
||||
showDropdown.value = false;
|
||||
};
|
||||
|
||||
const handleDelete = attribute => {
|
||||
if (isSaving.value) return;
|
||||
const updatedKeys = selectedAttributeKeys.value.filter(
|
||||
key => key !== attribute.value
|
||||
);
|
||||
saveRequiredAttributes(updatedKeys);
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<CardLayout
|
||||
class="[&>div]:px-0 [&>div]:py-0 [&>div]:gap-0 [&>div]:divide-y [&>div]:divide-n-weak"
|
||||
@click="handleClick"
|
||||
>
|
||||
<div class="flex flex-col gap-2 items-start px-5 py-4">
|
||||
<div class="flex justify-between items-center w-full">
|
||||
<h3 class="text-base font-medium text-n-slate-12">{{ title }}</h3>
|
||||
<div v-on-clickaway="closeDropdown" class="relative">
|
||||
<Button
|
||||
icon="i-lucide-circle-plus"
|
||||
:label="$t('CONVERSATION_WORKFLOW.REQUIRED_ATTRIBUTES.ADD.TITLE')"
|
||||
:is-loading="isSaving"
|
||||
:disabled="isSaving || attributeOptions.length === 0"
|
||||
@click="handleAddAttributesClick"
|
||||
/>
|
||||
<DropdownMenu
|
||||
v-if="showDropdown"
|
||||
:menu-items="attributeOptions"
|
||||
show-search
|
||||
:search-placeholder="
|
||||
$t(
|
||||
'CONVERSATION_WORKFLOW.REQUIRED_ATTRIBUTES.ADD.SEARCH_PLACEHOLDER'
|
||||
)
|
||||
"
|
||||
class="top-full mt-1 w-52 ltr:right-0 rtl:left-0"
|
||||
@action="handleAttributeAction"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<p class="mb-0 text-sm text-n-slate-11">{{ description }}</p>
|
||||
</div>
|
||||
|
||||
<ConversationRequiredEmpty
|
||||
v-if="conversationRequiredAttributes.length === 0"
|
||||
/>
|
||||
|
||||
<ConversationRequiredAttributeItem
|
||||
v-for="attribute in conversationRequiredAttributes"
|
||||
:key="attribute.value"
|
||||
:attribute="attribute"
|
||||
@delete="handleDelete"
|
||||
/>
|
||||
</CardLayout>
|
||||
</template>
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
<script setup>
|
||||
import { ref, computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import Dialog from 'dashboard/components-next/dialog/Dialog.vue';
|
||||
import TextArea from 'next/textarea/TextArea.vue';
|
||||
import ComboBox from 'dashboard/components-next/combobox/ComboBox.vue';
|
||||
import Input from 'dashboard/components-next/input/Input.vue';
|
||||
import ChoiceToggle from 'dashboard/components-next/input/ChoiceToggle.vue';
|
||||
|
||||
const emit = defineEmits(['submit']);
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const dialogRef = ref(null);
|
||||
const visibleAttributes = ref([]);
|
||||
const formValues = ref({});
|
||||
|
||||
const close = () => {
|
||||
dialogRef.value?.close();
|
||||
};
|
||||
|
||||
const getPlaceholder = type => {
|
||||
const placeholders = {
|
||||
text: t(
|
||||
'CONVERSATION_WORKFLOW.REQUIRED_ATTRIBUTES.MODAL.PLACEHOLDERS.TEXT'
|
||||
),
|
||||
number: t(
|
||||
'CONVERSATION_WORKFLOW.REQUIRED_ATTRIBUTES.MODAL.PLACEHOLDERS.NUMBER'
|
||||
),
|
||||
link: t(
|
||||
'CONVERSATION_WORKFLOW.REQUIRED_ATTRIBUTES.MODAL.PLACEHOLDERS.LINK'
|
||||
),
|
||||
date: t(
|
||||
'CONVERSATION_WORKFLOW.REQUIRED_ATTRIBUTES.MODAL.PLACEHOLDERS.DATE'
|
||||
),
|
||||
list: t(
|
||||
'CONVERSATION_WORKFLOW.REQUIRED_ATTRIBUTES.MODAL.PLACEHOLDERS.LIST'
|
||||
),
|
||||
};
|
||||
|
||||
return placeholders[type] || '';
|
||||
};
|
||||
|
||||
const isFormComplete = computed(() =>
|
||||
visibleAttributes.value.every(attribute => {
|
||||
const value = formValues.value?.[attribute.value];
|
||||
return value !== undefined && value !== null && String(value).trim() !== '';
|
||||
})
|
||||
);
|
||||
|
||||
const open = (attributes = [], initialValues = {}) => {
|
||||
visibleAttributes.value = attributes;
|
||||
formValues.value = attributes.reduce((acc, attribute) => {
|
||||
const presetValue = initialValues[attribute.value];
|
||||
acc[attribute.value] =
|
||||
presetValue !== undefined && presetValue !== null ? presetValue : '';
|
||||
return acc;
|
||||
}, {});
|
||||
dialogRef.value?.open();
|
||||
};
|
||||
|
||||
const handleConfirm = () => {
|
||||
emit('submit', { ...formValues.value });
|
||||
};
|
||||
|
||||
defineExpose({ open, close });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog
|
||||
ref="dialogRef"
|
||||
width="lg"
|
||||
:title="t('CONVERSATION_WORKFLOW.REQUIRED_ATTRIBUTES.MODAL.TITLE')"
|
||||
:description="
|
||||
t('CONVERSATION_WORKFLOW.REQUIRED_ATTRIBUTES.MODAL.DESCRIPTION')
|
||||
"
|
||||
:confirm-button-label="
|
||||
t('CONVERSATION_WORKFLOW.REQUIRED_ATTRIBUTES.MODAL.ACTIONS.RESOLVE')
|
||||
"
|
||||
:cancel-button-label="
|
||||
t('CONVERSATION_WORKFLOW.REQUIRED_ATTRIBUTES.MODAL.ACTIONS.CANCEL')
|
||||
"
|
||||
:show-confirm-button="isFormComplete"
|
||||
@confirm="handleConfirm"
|
||||
>
|
||||
<div class="flex flex-col gap-4">
|
||||
<div
|
||||
v-for="attribute in visibleAttributes"
|
||||
:key="attribute.value"
|
||||
class="flex flex-col gap-2"
|
||||
>
|
||||
<div class="flex justify-between items-center">
|
||||
<label class="text-sm font-medium text-n-slate-12">
|
||||
{{ attribute.label }}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<template v-if="attribute.type === 'text'">
|
||||
<TextArea
|
||||
v-model="formValues[attribute.value]"
|
||||
class="w-full"
|
||||
:placeholder="getPlaceholder('text')"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<template v-else-if="attribute.type === 'number'">
|
||||
<Input
|
||||
v-model="formValues[attribute.value]"
|
||||
type="number"
|
||||
size="md"
|
||||
:placeholder="getPlaceholder('number')"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<template v-else-if="attribute.type === 'link'">
|
||||
<Input
|
||||
v-model="formValues[attribute.value]"
|
||||
type="url"
|
||||
size="md"
|
||||
:placeholder="getPlaceholder('link')"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<template v-else-if="attribute.type === 'date'">
|
||||
<Input
|
||||
v-model="formValues[attribute.value]"
|
||||
type="date"
|
||||
size="md"
|
||||
:placeholder="getPlaceholder('date')"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<template v-else-if="attribute.type === 'list'">
|
||||
<ComboBox
|
||||
v-model="formValues[attribute.value]"
|
||||
:options="
|
||||
(
|
||||
attribute.attribute_values ||
|
||||
attribute.attributeValues ||
|
||||
[]
|
||||
).map(option => ({
|
||||
value: option,
|
||||
label: option,
|
||||
}))
|
||||
"
|
||||
:placeholder="getPlaceholder('list')"
|
||||
class="w-full"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<template v-else-if="attribute.type === 'checkbox'">
|
||||
<ChoiceToggle
|
||||
v-model="formValues[attribute.value]"
|
||||
:yes-label="
|
||||
t('CONVERSATION_WORKFLOW.REQUIRED_ATTRIBUTES.MODAL.CHECKBOX.YES')
|
||||
"
|
||||
:no-label="
|
||||
t('CONVERSATION_WORKFLOW.REQUIRED_ATTRIBUTES.MODAL.CHECKBOX.NO')
|
||||
"
|
||||
/>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
</template>
|
||||
@@ -19,6 +19,7 @@ const props = defineProps({
|
||||
},
|
||||
enableVariables: { type: Boolean, default: false },
|
||||
enableCannedResponses: { type: Boolean, default: true },
|
||||
enabledMenuOptions: { type: Array, default: () => [] },
|
||||
enableCaptainTools: { type: Boolean, default: false },
|
||||
signature: { type: String, default: '' },
|
||||
allowSignature: { type: Boolean, default: false },
|
||||
@@ -101,6 +102,7 @@ watch(
|
||||
:disabled="disabled"
|
||||
:enable-variables="enableVariables"
|
||||
:enable-canned-responses="enableCannedResponses"
|
||||
:enabled-menu-options="enabledMenuOptions"
|
||||
:enable-captain-tools="enableCaptainTools"
|
||||
:signature="signature"
|
||||
:allow-signature="allowSignature"
|
||||
@@ -137,6 +139,19 @@ watch(
|
||||
.editor-wrapper {
|
||||
::v-deep {
|
||||
.ProseMirror-menubar-wrapper {
|
||||
@apply gap-2 !important;
|
||||
|
||||
.ProseMirror-menubar {
|
||||
@apply bg-transparent dark:bg-transparent w-fit left-1 pt-0 h-5 !top-0 !relative !important;
|
||||
|
||||
.ProseMirror-menuitem {
|
||||
@apply h-5 !important;
|
||||
}
|
||||
|
||||
.ProseMirror-icon {
|
||||
@apply p-1 w-3 h-3 text-n-slate-12 dark:text-n-slate-12 !important;
|
||||
}
|
||||
}
|
||||
.ProseMirror.ProseMirror-woot-style {
|
||||
p {
|
||||
@apply first:mt-0 !important;
|
||||
|
||||
+1
-1
@@ -172,7 +172,7 @@ const previewArticle = () => {
|
||||
@apply mr-0;
|
||||
|
||||
.ProseMirror-icon {
|
||||
@apply p-0 mt-0 !mr-0;
|
||||
@apply p-0 mt-1 !mr-0;
|
||||
|
||||
svg {
|
||||
width: 20px !important;
|
||||
|
||||
+12
-14
@@ -7,7 +7,7 @@ import { vOnClickOutside } from '@vueuse/components';
|
||||
import { ALLOWED_FILE_TYPES } from 'shared/constants/messages';
|
||||
import { useKeyboardEvents } from 'dashboard/composables/useKeyboardEvents';
|
||||
import FileUpload from 'vue-upload-component';
|
||||
import { INBOX_TYPES } from 'dashboard/helper/inbox';
|
||||
import { extractTextFromMarkdown } from 'dashboard/helper/editorHelper';
|
||||
|
||||
import Button from 'dashboard/components-next/button/Button.vue';
|
||||
import WhatsAppOptions from './WhatsAppOptions.vue';
|
||||
@@ -50,6 +50,12 @@ const EmojiInput = defineAsyncComponent(
|
||||
() => import('shared/components/emoji/EmojiInput.vue')
|
||||
);
|
||||
|
||||
const signatureToApply = computed(() =>
|
||||
props.isEmailOrWebWidgetInbox
|
||||
? props.messageSignature
|
||||
: extractTextFromMarkdown(props.messageSignature)
|
||||
);
|
||||
|
||||
const {
|
||||
fetchSignatureFlagFromUISettings,
|
||||
setSignatureFlagForInbox,
|
||||
@@ -74,20 +80,12 @@ const isRegularMessageMode = computed(() => {
|
||||
return !props.isWhatsappInbox && !props.isTwilioWhatsAppInbox;
|
||||
});
|
||||
|
||||
const isVoiceInbox = computed(() => props.channelType === INBOX_TYPES.VOICE);
|
||||
|
||||
const shouldShowSignatureButton = computed(() => {
|
||||
return (
|
||||
props.hasSelectedInbox && isRegularMessageMode.value && !isVoiceInbox.value
|
||||
);
|
||||
});
|
||||
|
||||
const setSignature = () => {
|
||||
if (props.messageSignature) {
|
||||
if (signatureToApply.value) {
|
||||
if (sendWithSignature.value) {
|
||||
emit('addSignature', props.messageSignature);
|
||||
emit('addSignature', signatureToApply.value);
|
||||
} else {
|
||||
emit('removeSignature', props.messageSignature);
|
||||
emit('removeSignature', signatureToApply.value);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -103,7 +101,7 @@ watch(
|
||||
() => props.hasSelectedInbox,
|
||||
newValue => {
|
||||
nextTick(() => {
|
||||
if (newValue && !isVoiceInbox.value) setSignature();
|
||||
if (newValue && props.isEmailOrWebWidgetInbox) setSignature();
|
||||
});
|
||||
},
|
||||
{ immediate: true }
|
||||
@@ -222,7 +220,7 @@ useKeyboardEvents(keyboardEvents);
|
||||
/>
|
||||
</FileUpload>
|
||||
<Button
|
||||
v-if="shouldShowSignatureButton"
|
||||
v-if="hasSelectedInbox && isRegularMessageMode"
|
||||
icon="i-lucide-signature"
|
||||
color="slate"
|
||||
size="sm"
|
||||
|
||||
+1
-1
@@ -39,7 +39,7 @@ const removeAttachment = id => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-4 p-4 max-h-48 overflow-y-auto">
|
||||
<div class="flex flex-col gap-4 p-4">
|
||||
<div
|
||||
v-if="filteredImageAttachments.length > 0"
|
||||
class="flex flex-wrap gap-3"
|
||||
|
||||
+7
-7
@@ -6,6 +6,7 @@ import { INBOX_TYPES } from 'dashboard/helper/inbox';
|
||||
import {
|
||||
appendSignature,
|
||||
removeSignature,
|
||||
extractTextFromMarkdown,
|
||||
} from 'dashboard/helper/editorHelper';
|
||||
import {
|
||||
buildContactableInboxesList,
|
||||
@@ -201,8 +202,11 @@ const handleInboxAction = ({ value, action, ...rest }) => {
|
||||
const removeSignatureFromMessage = () => {
|
||||
// Always remove the signature from message content when inbox/contact is removed
|
||||
// to ensure no leftover signature content remains
|
||||
if (props.messageSignature) {
|
||||
state.message = removeSignature(state.message, props.messageSignature);
|
||||
const signatureToRemove = inboxTypes.value.isEmailOrWebWidget
|
||||
? props.messageSignature
|
||||
: extractTextFromMarkdown(props.messageSignature);
|
||||
if (signatureToRemove) {
|
||||
state.message = removeSignature(state.message, signatureToRemove);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -224,11 +228,7 @@ const onClickInsertEmoji = emoji => {
|
||||
};
|
||||
|
||||
const handleAddSignature = signature => {
|
||||
state.message = appendSignature(
|
||||
state.message,
|
||||
signature,
|
||||
inboxChannelType.value
|
||||
);
|
||||
state.message = appendSignature(state.message, signature);
|
||||
};
|
||||
|
||||
const handleRemoveSignature = signature => {
|
||||
|
||||
+8
-3
@@ -1,8 +1,9 @@
|
||||
<script setup>
|
||||
import { ref, watch, nextTick } from 'vue';
|
||||
import { ref, watch, computed, nextTick } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import {
|
||||
appendSignature,
|
||||
extractTextFromMarkdown,
|
||||
removeSignature,
|
||||
} from 'dashboard/helper/editorHelper';
|
||||
|
||||
@@ -32,13 +33,17 @@ const state = ref({
|
||||
mentionSearchKey: '',
|
||||
});
|
||||
|
||||
const plainTextSignature = computed(() =>
|
||||
extractTextFromMarkdown(props.messageSignature)
|
||||
);
|
||||
|
||||
watch(
|
||||
modelValue,
|
||||
newValue => {
|
||||
if (props.isEmailOrWebWidgetInbox) return;
|
||||
|
||||
const bodyWithoutSignature = newValue
|
||||
? removeSignature(newValue, props.messageSignature)
|
||||
? removeSignature(newValue, plainTextSignature.value)
|
||||
: '';
|
||||
|
||||
// Check if message starts with slash
|
||||
@@ -62,7 +67,7 @@ const hideMention = () => {
|
||||
const replaceText = async message => {
|
||||
// Only append signature on replace if sendWithSignature is true
|
||||
const finalMessage = props.sendWithSignature
|
||||
? appendSignature(message, props.messageSignature, props.channelType)
|
||||
? appendSignature(message, plainTextSignature.value)
|
||||
: message;
|
||||
|
||||
await nextTick();
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
<script setup>
|
||||
import { computed } from 'vue';
|
||||
|
||||
const props = defineProps({
|
||||
modelValue: {
|
||||
type: [String, Number],
|
||||
default: '',
|
||||
},
|
||||
yesLabel: {
|
||||
type: String,
|
||||
default: 'Yes',
|
||||
},
|
||||
noLabel: {
|
||||
type: String,
|
||||
default: 'No',
|
||||
},
|
||||
});
|
||||
|
||||
const emit = defineEmits(['update:modelValue']);
|
||||
|
||||
const options = computed(() => [
|
||||
{ label: props.yesLabel, value: 'yes' },
|
||||
{ label: props.noLabel, value: 'no' },
|
||||
]);
|
||||
|
||||
const handleSelect = value => {
|
||||
emit('update:modelValue', value);
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="flex gap-4 items-center px-4 py-2.5 w-full bg-white rounded-lg divide-x transition-colors outline outline-1 outline-n-weak dark:bg-n-solid-1 hover:outline-n-slate-6 focus-within:outline-n-brand divide-n-weak"
|
||||
>
|
||||
<div
|
||||
v-for="option in options"
|
||||
:key="option.value"
|
||||
class="flex flex-1 gap-2 justify-center items-center"
|
||||
>
|
||||
<label class="inline-flex gap-2 items-center text-base cursor-pointer">
|
||||
<input
|
||||
type="radio"
|
||||
:value="option.value"
|
||||
:checked="modelValue === option.value"
|
||||
class="size-4 accent-n-blue-9 text-n-blue-9"
|
||||
@change="handleSelect(option.value)"
|
||||
/>
|
||||
<span class="text-sm text-n-slate-12">{{ option.label }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -299,12 +299,7 @@ const componentToRender = computed(() => {
|
||||
return DyteBubble;
|
||||
}
|
||||
|
||||
const instagramSharedTypes = [
|
||||
ATTACHMENT_TYPES.STORY_MENTION,
|
||||
ATTACHMENT_TYPES.IG_STORY,
|
||||
ATTACHMENT_TYPES.IG_POST,
|
||||
];
|
||||
if (instagramSharedTypes.includes(props.contentAttributes.imageType)) {
|
||||
if (props.contentAttributes.imageType === 'story_mention') {
|
||||
return InstagramStoryBubble;
|
||||
}
|
||||
|
||||
@@ -481,7 +476,7 @@ provideMessageContext({
|
||||
<div
|
||||
v-if="shouldRenderMessage"
|
||||
:id="`message${props.id}`"
|
||||
class="flex mb-2 w-full message-bubble-container"
|
||||
class="flex w-full message-bubble-container mb-2"
|
||||
:data-message-id="props.id"
|
||||
:class="[
|
||||
flexOrientationClass,
|
||||
|
||||
@@ -49,8 +49,6 @@ export const ATTACHMENT_TYPES = {
|
||||
STORY_MENTION: 'story_mention',
|
||||
CONTACT: 'contact',
|
||||
IG_REEL: 'ig_reel',
|
||||
IG_POST: 'ig_post',
|
||||
IG_STORY: 'ig_story',
|
||||
};
|
||||
|
||||
export const CONTENT_TYPES = {
|
||||
|
||||
@@ -520,7 +520,7 @@ const menuItems = computed(() => {
|
||||
{
|
||||
name: 'Settings Automation',
|
||||
label: t('SIDEBAR.AUTOMATION'),
|
||||
icon: 'i-lucide-workflow',
|
||||
icon: 'i-lucide-repeat',
|
||||
to: accountScopedRoute('automation_list'),
|
||||
},
|
||||
{
|
||||
@@ -565,6 +565,12 @@ const menuItems = computed(() => {
|
||||
icon: 'i-lucide-clock-alert',
|
||||
to: accountScopedRoute('sla_list'),
|
||||
},
|
||||
{
|
||||
name: ' Conversation Workflow',
|
||||
label: t('SIDEBAR.CONVERSATION_WORKFLOW'),
|
||||
icon: 'i-lucide-workflow',
|
||||
to: accountScopedRoute('conversation_workflow_index'),
|
||||
},
|
||||
{
|
||||
name: 'Settings Security',
|
||||
label: t('SIDEBAR.SECURITY'),
|
||||
@@ -646,7 +652,7 @@ const menuItems = computed(() => {
|
||||
</ul>
|
||||
</nav>
|
||||
<section
|
||||
class="flex flex-col flex-shrink-0 relative gap-1 justify-between items-center"
|
||||
class="flex relative flex-col flex-shrink-0 gap-1 justify-between items-center"
|
||||
>
|
||||
<div
|
||||
class="pointer-events-none absolute inset-x-0 -top-[31px] h-8 bg-gradient-to-t from-n-solid-2 to-transparent"
|
||||
|
||||
@@ -20,7 +20,7 @@ const props = defineProps({
|
||||
},
|
||||
});
|
||||
|
||||
const emit = defineEmits(['tabChanged']);
|
||||
const emit = defineEmits(['change', 'tabChanged']);
|
||||
|
||||
const activeTab = computed(() => props.initialActiveTab);
|
||||
|
||||
@@ -51,6 +51,7 @@ onMounted(() => {
|
||||
});
|
||||
|
||||
const selectTab = index => {
|
||||
emit('change', index);
|
||||
emit('tabChanged', props.tabs[index]);
|
||||
};
|
||||
|
||||
|
||||
@@ -3,9 +3,14 @@ import { ref, computed } from 'vue';
|
||||
import { useAlert } from 'dashboard/composables';
|
||||
import { useToggle } from '@vueuse/core';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useStore, useStoreGetters } from 'dashboard/composables/store';
|
||||
import {
|
||||
useStore,
|
||||
useStoreGetters,
|
||||
useMapGetter,
|
||||
} from 'dashboard/composables/store';
|
||||
import { useEmitter } from 'dashboard/composables/emitter';
|
||||
import { useKeyboardEvents } from 'dashboard/composables/useKeyboardEvents';
|
||||
import { useAccount } from 'dashboard/composables/useAccount';
|
||||
|
||||
import WootDropdownItem from 'shared/components/ui/dropdown/DropdownItem.vue';
|
||||
import WootDropdownMenu from 'shared/components/ui/dropdown/DropdownMenu.vue';
|
||||
@@ -17,13 +22,19 @@ import {
|
||||
|
||||
import ButtonGroup from 'dashboard/components-next/buttonGroup/ButtonGroup.vue';
|
||||
import Button from 'dashboard/components-next/button/Button.vue';
|
||||
import ConversationResolveAttributesModal from 'dashboard/components-next/ConversationWorkflow/ConversationResolveAttributesModal.vue';
|
||||
|
||||
const store = useStore();
|
||||
const getters = useStoreGetters();
|
||||
const { t } = useI18n();
|
||||
const { currentAccount } = useAccount();
|
||||
const conversationAttributes = useMapGetter(
|
||||
'attributes/getConversationAttributes'
|
||||
);
|
||||
|
||||
const arrowDownButtonRef = ref(null);
|
||||
const isLoading = ref(false);
|
||||
const resolveAttributesModalRef = ref(null);
|
||||
|
||||
const [showActionsDropdown, toggleDropdown] = useToggle();
|
||||
const closeDropdown = () => toggleDropdown(false);
|
||||
@@ -52,31 +63,103 @@ const showOpenButton = computed(() => {
|
||||
return isPending.value || isSnoozed.value;
|
||||
});
|
||||
|
||||
const getConversationParams = () => {
|
||||
const allConversations = document.querySelectorAll(
|
||||
'.conversations-list .conversation'
|
||||
);
|
||||
|
||||
const activeConversation = document.querySelector(
|
||||
'div.conversations-list div.conversation.active'
|
||||
);
|
||||
const activeConversationIndex = [...allConversations].indexOf(
|
||||
activeConversation
|
||||
);
|
||||
const lastConversationIndex = allConversations.length - 1;
|
||||
|
||||
return {
|
||||
all: allConversations,
|
||||
activeIndex: activeConversationIndex,
|
||||
lastIndex: lastConversationIndex,
|
||||
};
|
||||
};
|
||||
|
||||
const openSnoozeModal = () => {
|
||||
const ninja = document.querySelector('ninja-keys');
|
||||
ninja.open({ parent: 'snooze_conversation' });
|
||||
};
|
||||
|
||||
const requiredAttributeKeys = computed(
|
||||
() => currentAccount.value?.settings?.conversation_required_attributes || []
|
||||
);
|
||||
|
||||
const requiredAttributes = computed(() =>
|
||||
requiredAttributeKeys.value.map(key => {
|
||||
const definition = conversationAttributes.value?.find(
|
||||
attribute => attribute.attributeKey === key
|
||||
);
|
||||
if (!definition) {
|
||||
return {
|
||||
value: key,
|
||||
label: key,
|
||||
type: 'text',
|
||||
attribute_values: [],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
...definition,
|
||||
value: definition.attributeKey,
|
||||
label: definition.attributeDisplayName,
|
||||
type: definition.attributeDisplayType,
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
const getMissingRequiredAttributes = () => {
|
||||
if (!currentChat.value?.id) return [];
|
||||
const existingValues = currentChat.value.custom_attributes || {};
|
||||
return requiredAttributes.value.filter(attribute => {
|
||||
const value = existingValues?.[attribute.value];
|
||||
return value === undefined || value === null || String(value) === '';
|
||||
});
|
||||
};
|
||||
|
||||
const toggleStatusInternal = async (status, snoozedUntil = null) => {
|
||||
closeDropdown();
|
||||
isLoading.value = true;
|
||||
try {
|
||||
await store.dispatch('toggleStatus', {
|
||||
conversationId: currentChat.value.id,
|
||||
status,
|
||||
snoozedUntil,
|
||||
});
|
||||
useAlert(t('CONVERSATION.CHANGE_STATUS'));
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const resolveWithAttributes = async customAttributes => {
|
||||
if (!currentChat.value?.id) return;
|
||||
try {
|
||||
isLoading.value = true;
|
||||
if (requiredAttributeKeys.value.length) {
|
||||
await store.dispatch('updateCustomAttributes', {
|
||||
conversationId: currentChat.value.id,
|
||||
customAttributes,
|
||||
});
|
||||
}
|
||||
await toggleStatusInternal(wootConstants.STATUS_TYPE.RESOLVED);
|
||||
} catch (error) {
|
||||
useAlert(t('CONVERSATION_WORKFLOW.REQUIRED_ATTRIBUTES.SAVE.ERROR'));
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const openResolveModal = () => {
|
||||
closeDropdown();
|
||||
if (!currentChat.value?.id) return;
|
||||
const missing = getMissingRequiredAttributes();
|
||||
if (!missing.length) {
|
||||
resolveWithAttributes(currentChat.value.custom_attributes || {});
|
||||
return;
|
||||
}
|
||||
resolveAttributesModalRef.value?.open(
|
||||
missing,
|
||||
currentChat.value.custom_attributes || {}
|
||||
);
|
||||
};
|
||||
|
||||
const handleModalSubmit = async values => {
|
||||
if (!currentChat.value?.id) return;
|
||||
resolveAttributesModalRef.value?.close();
|
||||
await resolveWithAttributes({
|
||||
...(currentChat.value.custom_attributes || {}),
|
||||
...values,
|
||||
});
|
||||
};
|
||||
|
||||
const toggleStatus = (status, snoozedUntil) => {
|
||||
closeDropdown();
|
||||
isLoading.value = true;
|
||||
@@ -97,7 +180,7 @@ const onCmdOpenConversation = () => {
|
||||
};
|
||||
|
||||
const onCmdResolveConversation = () => {
|
||||
toggleStatus(wootConstants.STATUS_TYPE.RESOLVED);
|
||||
openResolveModal();
|
||||
};
|
||||
|
||||
const keyboardEvents = {
|
||||
@@ -106,21 +189,11 @@ const keyboardEvents = {
|
||||
allowOnFocusedInput: true,
|
||||
},
|
||||
'Alt+KeyE': {
|
||||
action: async () => {
|
||||
await toggleStatus(wootConstants.STATUS_TYPE.RESOLVED);
|
||||
},
|
||||
action: () => openResolveModal(),
|
||||
},
|
||||
'$mod+Alt+KeyE': {
|
||||
action: async event => {
|
||||
const { all, activeIndex, lastIndex } = getConversationParams();
|
||||
await toggleStatus(wootConstants.STATUS_TYPE.RESOLVED);
|
||||
|
||||
if (activeIndex < lastIndex) {
|
||||
all[activeIndex + 1].click();
|
||||
} else if (all.length > 1) {
|
||||
all[0].click();
|
||||
document.querySelector('.conversations-list').scrollTop = 0;
|
||||
}
|
||||
action: event => {
|
||||
openResolveModal();
|
||||
event.preventDefault();
|
||||
},
|
||||
},
|
||||
@@ -133,9 +206,13 @@ useEmitter(CMD_RESOLVE_CONVERSATION, onCmdResolveConversation);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="relative flex items-center justify-end resolve-actions">
|
||||
<div class="flex relative justify-end items-center resolve-actions">
|
||||
<ConversationResolveAttributesModal
|
||||
ref="resolveAttributesModalRef"
|
||||
@submit="handleModalSubmit"
|
||||
/>
|
||||
<ButtonGroup
|
||||
class="rounded-lg shadow outline-1 outline flex-shrink-0"
|
||||
class="flex-shrink-0 rounded-lg shadow outline-1 outline"
|
||||
:class="!showOpenButton ? 'outline-n-container' : 'outline-transparent'"
|
||||
>
|
||||
<Button
|
||||
|
||||
@@ -26,11 +26,13 @@ import { useAlert } from 'dashboard/composables';
|
||||
|
||||
import { BUS_EVENTS } from 'shared/constants/busEvents';
|
||||
import { CONVERSATION_EVENTS } from 'dashboard/helper/AnalyticsHelper/events';
|
||||
import { MESSAGE_EDITOR_IMAGE_RESIZES } from 'dashboard/constants/editor';
|
||||
import {
|
||||
MESSAGE_EDITOR_MENU_OPTIONS,
|
||||
MESSAGE_EDITOR_IMAGE_RESIZES,
|
||||
} from 'dashboard/constants/editor';
|
||||
|
||||
import {
|
||||
messageSchema,
|
||||
buildMessageSchema,
|
||||
buildEditor,
|
||||
EditorView,
|
||||
MessageMarkdownTransformer,
|
||||
@@ -51,9 +53,6 @@ import {
|
||||
removeSignature as removeSignatureHelper,
|
||||
scrollCursorIntoView,
|
||||
setURLWithQueryAndSize,
|
||||
getFormattingForEditor,
|
||||
getSelectionCoords,
|
||||
calculateMenuPosition,
|
||||
} from 'dashboard/helper/editorHelper';
|
||||
import {
|
||||
hasPressedEnterAndNotCmdOrShift,
|
||||
@@ -76,6 +75,7 @@ const props = defineProps({
|
||||
enableCannedResponses: { type: Boolean, default: true },
|
||||
enableCaptainTools: { type: Boolean, default: false },
|
||||
variables: { type: Object, default: () => ({}) },
|
||||
enabledMenuOptions: { type: Array, default: () => [] },
|
||||
signature: { type: String, default: '' },
|
||||
// allowSignature is a kill switch, ensuring no signature methods
|
||||
// are triggered except when this flag is true
|
||||
@@ -103,34 +103,22 @@ const { t } = useI18n();
|
||||
|
||||
const TYPING_INDICATOR_IDLE_TIME = 4000;
|
||||
const MAXIMUM_FILE_UPLOAD_SIZE = 4; // in MB
|
||||
const DEFAULT_FORMATTING = 'Context::Default';
|
||||
|
||||
const editorSchema = computed(() => {
|
||||
if (!props.channelType) return messageSchema;
|
||||
|
||||
const formatType = props.isPrivate ? DEFAULT_FORMATTING : props.channelType;
|
||||
const formatting = getFormattingForEditor(formatType);
|
||||
return buildMessageSchema(formatting.marks, formatting.nodes);
|
||||
});
|
||||
|
||||
const editorMenuOptions = computed(() => {
|
||||
const formatType = props.isPrivate
|
||||
? DEFAULT_FORMATTING
|
||||
: props.channelType || DEFAULT_FORMATTING;
|
||||
const formatting = getFormattingForEditor(formatType);
|
||||
return formatting.menu;
|
||||
});
|
||||
|
||||
const createState = (content, placeholder, plugins = [], methods = {}) => {
|
||||
const schema = editorSchema.value;
|
||||
const createState = (
|
||||
content,
|
||||
placeholder,
|
||||
plugins = [],
|
||||
methods = {},
|
||||
enabledMenuOptions = []
|
||||
) => {
|
||||
return EditorState.create({
|
||||
doc: new MessageMarkdownTransformer(schema).parse(content),
|
||||
doc: new MessageMarkdownTransformer(messageSchema).parse(content),
|
||||
plugins: buildEditor({
|
||||
schema,
|
||||
schema: messageSchema,
|
||||
placeholder,
|
||||
methods,
|
||||
plugins,
|
||||
enabledMenuOptions: editorMenuOptions.value,
|
||||
enabledMenuOptions,
|
||||
}),
|
||||
});
|
||||
};
|
||||
@@ -165,8 +153,6 @@ const range = ref(null);
|
||||
const isImageNodeSelected = ref(false);
|
||||
const toolbarPosition = ref({ top: 0, left: 0 });
|
||||
const selectedImageNode = ref(null);
|
||||
const isTextSelected = ref(false); // Tracks text selection and prevents unnecessary re-renders on mouse selection
|
||||
const showSelectionMenu = ref(false);
|
||||
const sizes = MESSAGE_EDITOR_IMAGE_RESIZES;
|
||||
|
||||
// element ref
|
||||
@@ -188,6 +174,12 @@ const shouldShowCannedResponses = computed(() => {
|
||||
);
|
||||
});
|
||||
|
||||
const editorMenuOptions = computed(() => {
|
||||
return props.enabledMenuOptions.length
|
||||
? props.enabledMenuOptions
|
||||
: MESSAGE_EDITOR_MENU_OPTIONS;
|
||||
});
|
||||
|
||||
function createSuggestionPlugin({
|
||||
trigger,
|
||||
minChars = 0,
|
||||
@@ -370,7 +362,7 @@ function addSignature() {
|
||||
// see if the content is empty, if it is before appending the signature
|
||||
// we need to add a paragraph node and move the cursor at the start of the editor
|
||||
const contentWasEmpty = isBodyEmpty(content);
|
||||
content = appendSignature(content, props.signature, props.channelType);
|
||||
content = appendSignature(content, props.signature);
|
||||
// need to reload first, ensuring that the editorView is updated
|
||||
reloadState(content);
|
||||
|
||||
@@ -408,38 +400,6 @@ function setToolbarPosition() {
|
||||
};
|
||||
}
|
||||
|
||||
function setMenubarPosition({ selection } = {}) {
|
||||
const wrapper = editorRoot.value;
|
||||
if (!selection || !wrapper) return;
|
||||
|
||||
const rect = wrapper.getBoundingClientRect();
|
||||
const isRtl = getComputedStyle(wrapper).direction === 'rtl';
|
||||
|
||||
// Calculate coords and final position
|
||||
const coords = getSelectionCoords(editorView, selection, rect);
|
||||
const { left, top, width } = calculateMenuPosition(coords, rect, isRtl);
|
||||
|
||||
wrapper.style.setProperty('--selection-left', `${left}px`);
|
||||
wrapper.style.setProperty(
|
||||
'--selection-right',
|
||||
`${rect.width - left - width}px`
|
||||
);
|
||||
wrapper.style.setProperty('--selection-top', `${top}px`);
|
||||
}
|
||||
|
||||
function checkSelection(editorState) {
|
||||
showSelectionMenu.value = false;
|
||||
const hasSelection = editorState.selection.from !== editorState.selection.to;
|
||||
if (hasSelection === isTextSelected.value) return;
|
||||
|
||||
isTextSelected.value = hasSelection;
|
||||
const wrapper = editorRoot.value;
|
||||
if (!wrapper) return;
|
||||
|
||||
wrapper.classList.toggle('has-selection', hasSelection);
|
||||
if (hasSelection) setMenubarPosition(editorState);
|
||||
}
|
||||
|
||||
function setURLWithQueryAndImageSize(size) {
|
||||
if (!props.showImageResizeToolbar) {
|
||||
return;
|
||||
@@ -569,9 +529,7 @@ async function insertNodeIntoEditor(node, from = 0, to = 0) {
|
||||
|
||||
function insertContentIntoEditor(content, defaultFrom = 0) {
|
||||
const from = defaultFrom || editorView.state.selection.from || 0;
|
||||
// Use the editor's current schema to ensure compatibility with buildMessageSchema
|
||||
const currentSchema = editorView.state.schema;
|
||||
let node = new MessageMarkdownTransformer(currentSchema).parse(content);
|
||||
let node = new MessageMarkdownTransformer(messageSchema).parse(content);
|
||||
|
||||
insertNodeIntoEditor(node, from, undefined);
|
||||
}
|
||||
@@ -638,7 +596,6 @@ function createEditorView() {
|
||||
if (tx.docChanged) {
|
||||
emitOnChange();
|
||||
}
|
||||
checkSelection(state);
|
||||
},
|
||||
handleDOMEvents: {
|
||||
keyup: () => {
|
||||
@@ -804,33 +761,15 @@ useEmitter(BUS_EVENTS.INSERT_INTO_RICH_EDITOR, insertContentIntoEditor);
|
||||
@import '@chatwoot/prosemirror-schema/src/styles/base.scss';
|
||||
|
||||
.ProseMirror-menubar-wrapper {
|
||||
@apply flex flex-col gap-3;
|
||||
@apply flex flex-col;
|
||||
|
||||
.ProseMirror-menubar {
|
||||
min-height: 1.25rem !important;
|
||||
@apply items-center gap-4 flex pb-0 bg-transparent text-n-slate-11 relative ltr:-left-[3px] rtl:-right-[3px];
|
||||
@apply -ml-2.5 pb-0 bg-transparent text-n-slate-11;
|
||||
|
||||
.ProseMirror-menu-active {
|
||||
@apply bg-n-slate-5 dark:bg-n-solid-3 !important;
|
||||
@apply bg-n-slate-5 dark:bg-n-solid-3;
|
||||
}
|
||||
|
||||
.ProseMirror-menuitem {
|
||||
@apply mr-0 size-4 flex items-center justify-center;
|
||||
|
||||
.ProseMirror-icon {
|
||||
@apply size-4 flex items-center justify-center flex-shrink-0;
|
||||
|
||||
svg {
|
||||
@apply size-full;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.ProseMirror-menubar:not(:has(*)) {
|
||||
max-height: none !important;
|
||||
min-height: 0 !important;
|
||||
padding: 0 !important;
|
||||
}
|
||||
|
||||
> .ProseMirror {
|
||||
@@ -921,53 +860,4 @@ useEmitter(BUS_EVENTS.INSERT_INTO_RICH_EDITOR, insertContentIntoEditor);
|
||||
.editor-warning__message {
|
||||
@apply text-n-ruby-9 dark:text-n-ruby-9 font-normal text-sm pt-1 pb-0 px-0;
|
||||
}
|
||||
|
||||
// Float editor menu
|
||||
.popover-prosemirror-menu {
|
||||
position: relative;
|
||||
|
||||
.ProseMirror p:last-child {
|
||||
margin-bottom: 10px !important;
|
||||
}
|
||||
|
||||
.ProseMirror-menubar {
|
||||
display: none; // Hide by default
|
||||
}
|
||||
|
||||
&.has-selection {
|
||||
// Hide menu completely when it has no items
|
||||
.ProseMirror-menubar:not(:has(*)) {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.ProseMirror-menubar {
|
||||
@apply rounded-lg !px-3 !py-1.5 z-50 bg-n-background items-center gap-4 ml-0 mb-0 shadow-md outline outline-1 outline-n-weak;
|
||||
display: flex;
|
||||
width: fit-content !important;
|
||||
position: absolute !important;
|
||||
|
||||
// Default/LTR: position from left
|
||||
top: var(--selection-top);
|
||||
left: var(--selection-left);
|
||||
|
||||
// RTL: position from right instead
|
||||
[dir='rtl'] & {
|
||||
left: auto;
|
||||
right: var(--selection-right);
|
||||
}
|
||||
|
||||
.ProseMirror-menuitem {
|
||||
@apply mr-0 size-4 flex items-center;
|
||||
|
||||
.ProseMirror-icon {
|
||||
@apply p-0.5 flex-shrink-0;
|
||||
}
|
||||
}
|
||||
|
||||
.ProseMirror-menu-active {
|
||||
@apply bg-n-slate-3;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -78,6 +78,10 @@ export default {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
showEditorToggle: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
isOnPrivateNote: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
@@ -126,6 +130,7 @@ export default {
|
||||
emits: [
|
||||
'replaceText',
|
||||
'toggleInsertArticle',
|
||||
'toggleEditor',
|
||||
'selectWhatsappTemplate',
|
||||
'selectContentTemplate',
|
||||
'toggleQuotedReply',
|
||||
@@ -320,8 +325,18 @@ export default {
|
||||
sm
|
||||
@click="toggleAudioRecorder"
|
||||
/>
|
||||
<NextButton
|
||||
v-if="showEditorToggle"
|
||||
v-tooltip.top-end="$t('CONVERSATION.REPLYBOX.TIP_FORMAT_ICON')"
|
||||
icon="i-ph-quotes"
|
||||
slate
|
||||
faded
|
||||
sm
|
||||
@click="$emit('toggleEditor')"
|
||||
/>
|
||||
<NextButton
|
||||
v-if="showAudioPlayStopButton"
|
||||
v-tooltip.top-end="$t('CONVERSATION.REPLYBOX.TIP_FORMAT_ICON')"
|
||||
:icon="audioRecorderPlayStopIcon"
|
||||
slate
|
||||
faded
|
||||
|
||||
@@ -7,7 +7,9 @@ import { useTrack } from 'dashboard/composables';
|
||||
import keyboardEventListenerMixins from 'shared/mixins/keyboardEventListenerMixins';
|
||||
import { FEATURE_FLAGS } from 'dashboard/featureFlags';
|
||||
|
||||
import CannedResponse from './CannedResponse.vue';
|
||||
import ReplyToMessage from './ReplyToMessage.vue';
|
||||
import ResizableTextArea from 'shared/components/ResizableTextArea.vue';
|
||||
import AttachmentPreview from 'dashboard/components/widgets/AttachmentsPreview.vue';
|
||||
import ReplyTopPanel from 'dashboard/components/widgets/WootWriter/ReplyTopPanel.vue';
|
||||
import ReplyEmailHead from './ReplyEmailHead.vue';
|
||||
@@ -43,6 +45,8 @@ import fileUploadMixin from 'dashboard/mixins/fileUploadMixin';
|
||||
import {
|
||||
appendSignature,
|
||||
removeSignature,
|
||||
replaceSignature,
|
||||
extractTextFromMarkdown,
|
||||
} from 'dashboard/helper/editorHelper';
|
||||
|
||||
import { LOCAL_STORAGE_KEYS } from 'dashboard/constants/localStorage';
|
||||
@@ -57,6 +61,7 @@ export default {
|
||||
ArticleSearchPopover,
|
||||
AttachmentPreview,
|
||||
AudioRecorder,
|
||||
CannedResponse,
|
||||
ReplyBoxBanner,
|
||||
EmojiInput,
|
||||
MessageSignatureMissingAlert,
|
||||
@@ -64,6 +69,7 @@ export default {
|
||||
ReplyEmailHead,
|
||||
ReplyToMessage,
|
||||
ReplyTopPanel,
|
||||
ResizableTextArea,
|
||||
ContentTemplates,
|
||||
WhatsappTemplates,
|
||||
WootMessageEditor,
|
||||
@@ -80,6 +86,7 @@ export default {
|
||||
setup() {
|
||||
const {
|
||||
uiSettings,
|
||||
updateUISettings,
|
||||
isEditorHotKeyEnabled,
|
||||
fetchSignatureFlagFromUISettings,
|
||||
setQuotedReplyFlagForInbox,
|
||||
@@ -90,6 +97,7 @@ export default {
|
||||
|
||||
return {
|
||||
uiSettings,
|
||||
updateUISettings,
|
||||
isEditorHotKeyEnabled,
|
||||
fetchSignatureFlagFromUISettings,
|
||||
setQuotedReplyFlagForInbox,
|
||||
@@ -107,7 +115,10 @@ export default {
|
||||
isRecordingAudio: false,
|
||||
recordingAudioState: '',
|
||||
recordingAudioDurationText: '',
|
||||
isUploading: false,
|
||||
replyType: REPLY_EDITOR_MODES.REPLY,
|
||||
mentionSearchKey: '',
|
||||
hasSlashCommand: false,
|
||||
bccEmails: '',
|
||||
ccEmails: '',
|
||||
toEmails: '',
|
||||
@@ -148,6 +159,20 @@ export default {
|
||||
!this.is360DialogWhatsAppChannel
|
||||
);
|
||||
},
|
||||
showRichContentEditor() {
|
||||
if (this.isOnPrivateNote || this.isRichEditorEnabled) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (this.isAPIInbox) {
|
||||
const {
|
||||
display_rich_content_editor: displayRichContentEditor = false,
|
||||
} = this.uiSettings;
|
||||
return displayRichContentEditor;
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
showWhatsappTemplates() {
|
||||
// We support templates for API channels if someone updates templates manually via API
|
||||
// That's why we don't explicitly check for channel type here
|
||||
@@ -275,6 +300,9 @@ export default {
|
||||
hasAttachments() {
|
||||
return this.attachedFiles.length;
|
||||
},
|
||||
isRichEditorEnabled() {
|
||||
return this.isAWebWidgetInbox || this.isAnEmailChannel;
|
||||
},
|
||||
showAudioRecorder() {
|
||||
return !this.isOnPrivateNote && this.showFileUpload;
|
||||
},
|
||||
@@ -314,11 +342,21 @@ export default {
|
||||
return !this.isPrivate && this.sendWithSignature;
|
||||
},
|
||||
isSignatureAvailable() {
|
||||
return !!this.messageSignature;
|
||||
return !!this.signatureToApply;
|
||||
},
|
||||
sendWithSignature() {
|
||||
return this.fetchSignatureFlagFromUISettings(this.channelType);
|
||||
},
|
||||
editorMessageKey() {
|
||||
const { editor_message_key: isEnabled } = this.uiSettings;
|
||||
return isEnabled;
|
||||
},
|
||||
commandPlusEnterToSendEnabled() {
|
||||
return this.editorMessageKey === 'cmd_enter';
|
||||
},
|
||||
enterToSendEnabled() {
|
||||
return this.editorMessageKey === 'enter';
|
||||
},
|
||||
conversationId() {
|
||||
return this.currentChat.id;
|
||||
},
|
||||
@@ -345,6 +383,12 @@ export default {
|
||||
});
|
||||
return variables;
|
||||
},
|
||||
// ensure that the signature is plain text depending on `showRichContentEditor`
|
||||
signatureToApply() {
|
||||
return this.showRichContentEditor
|
||||
? this.messageSignature
|
||||
: extractTextFromMarkdown(this.messageSignature);
|
||||
},
|
||||
connectedPortalSlug() {
|
||||
const { help_center: portal = {} } = this.inbox;
|
||||
const { slug = '' } = portal;
|
||||
@@ -437,7 +481,25 @@ export default {
|
||||
this.resetRecorderAndClearAttachments();
|
||||
}
|
||||
},
|
||||
message() {
|
||||
message(updatedMessage) {
|
||||
// Check if the message starts with a slash.
|
||||
const bodyWithoutSignature = removeSignature(
|
||||
updatedMessage,
|
||||
this.signatureToApply
|
||||
);
|
||||
const startsWithSlash = bodyWithoutSignature.startsWith('/');
|
||||
|
||||
// Determine if the user is potentially typing a slash command.
|
||||
// This is true if the message starts with a slash and the rich content editor is not active.
|
||||
this.hasSlashCommand = startsWithSlash && !this.showRichContentEditor;
|
||||
this.showMentions = this.hasSlashCommand;
|
||||
|
||||
// If a slash command is active, extract the command text after the slash.
|
||||
// If not, reset the mentionSearchKey.
|
||||
this.mentionSearchKey = this.hasSlashCommand
|
||||
? bodyWithoutSignature.substring(1)
|
||||
: '';
|
||||
|
||||
// Autosave the current message draft.
|
||||
this.doAutoSaveDraft();
|
||||
},
|
||||
@@ -450,7 +512,7 @@ export default {
|
||||
mounted() {
|
||||
this.getFromDraft();
|
||||
// Don't use the keyboard listener mixin here as the events here are supposed to be
|
||||
// working even if the editor is focussed.
|
||||
// working even if input/textarea is focussed.
|
||||
document.addEventListener('paste', this.onPaste);
|
||||
document.addEventListener('keydown', this.handleKeyEvents);
|
||||
this.setCCAndToEmailsFromLastChat();
|
||||
@@ -487,17 +549,45 @@ export default {
|
||||
methods: {
|
||||
handleInsert(article) {
|
||||
const { url, title } = article;
|
||||
// Removing empty lines from the title
|
||||
const lines = title.split('\n');
|
||||
const nonEmptyLines = lines.filter(line => line.trim() !== '');
|
||||
const filteredMarkdown = nonEmptyLines.join(' ');
|
||||
emitter.emit(
|
||||
BUS_EVENTS.INSERT_INTO_RICH_EDITOR,
|
||||
`[${filteredMarkdown}](${url})`
|
||||
);
|
||||
if (this.isRichEditorEnabled) {
|
||||
// Removing empty lines from the title
|
||||
const lines = title.split('\n');
|
||||
const nonEmptyLines = lines.filter(line => line.trim() !== '');
|
||||
const filteredMarkdown = nonEmptyLines.join(' ');
|
||||
emitter.emit(
|
||||
BUS_EVENTS.INSERT_INTO_RICH_EDITOR,
|
||||
`[${filteredMarkdown}](${url})`
|
||||
);
|
||||
} else {
|
||||
this.addIntoEditor(
|
||||
`${this.$t('CONVERSATION.REPLYBOX.INSERT_READ_MORE')} ${url}`
|
||||
);
|
||||
}
|
||||
|
||||
useTrack(CONVERSATION_EVENTS.INSERT_ARTICLE_LINK);
|
||||
},
|
||||
toggleRichContentEditor() {
|
||||
this.updateUISettings({
|
||||
display_rich_content_editor: !this.showRichContentEditor,
|
||||
});
|
||||
|
||||
const plainTextSignature = extractTextFromMarkdown(this.messageSignature);
|
||||
|
||||
if (!this.showRichContentEditor && this.messageSignature) {
|
||||
// remove the old signature -> extract text from markdown -> attach new signature
|
||||
let message = removeSignature(this.message, this.messageSignature);
|
||||
message = extractTextFromMarkdown(message);
|
||||
message = appendSignature(message, plainTextSignature);
|
||||
|
||||
this.message = message;
|
||||
} else {
|
||||
this.message = replaceSignature(
|
||||
this.message,
|
||||
plainTextSignature,
|
||||
this.messageSignature
|
||||
);
|
||||
}
|
||||
},
|
||||
toggleQuotedReply() {
|
||||
if (!this.isAnEmailChannel) {
|
||||
return;
|
||||
@@ -565,8 +655,8 @@ export default {
|
||||
}
|
||||
|
||||
return this.sendWithSignature
|
||||
? appendSignature(message, this.messageSignature, this.channelType)
|
||||
: removeSignature(message, this.messageSignature);
|
||||
? appendSignature(message, this.signatureToApply)
|
||||
: removeSignature(message, this.signatureToApply);
|
||||
},
|
||||
removeFromDraft() {
|
||||
if (this.conversationIdByRoute) {
|
||||
@@ -582,6 +672,7 @@ export default {
|
||||
Escape: {
|
||||
action: () => {
|
||||
this.hideEmojiPicker();
|
||||
this.hideMentions();
|
||||
},
|
||||
allowOnFocusedInput: true,
|
||||
},
|
||||
@@ -624,6 +715,9 @@ export default {
|
||||
},
|
||||
onPaste(e) {
|
||||
const data = e.clipboardData.files;
|
||||
if (!this.showRichContentEditor && data.length !== 0) {
|
||||
this.$refs.messageInput.$el.blur();
|
||||
}
|
||||
if (!data.length || !data[0]) {
|
||||
return;
|
||||
}
|
||||
@@ -757,11 +851,7 @@ export default {
|
||||
// if signature is enabled, append it to the message
|
||||
// appendSignature ensures that the signature is not duplicated
|
||||
// so we don't need to check if the signature is already present
|
||||
message = appendSignature(
|
||||
message,
|
||||
this.messageSignature,
|
||||
this.channelType
|
||||
);
|
||||
message = appendSignature(message, this.signatureToApply);
|
||||
}
|
||||
|
||||
const updatedMessage = replaceVariablesInMessage({
|
||||
@@ -785,26 +875,40 @@ export default {
|
||||
});
|
||||
if (canReply || this.isAWhatsAppChannel || this.isAPIInbox)
|
||||
this.replyType = mode;
|
||||
if (this.isRecordingAudio) {
|
||||
this.toggleAudioRecorder();
|
||||
if (this.showRichContentEditor) {
|
||||
if (this.isRecordingAudio) {
|
||||
this.toggleAudioRecorder();
|
||||
}
|
||||
return;
|
||||
}
|
||||
this.$nextTick(() => this.$refs.messageInput.focus());
|
||||
},
|
||||
clearEditorSelection() {
|
||||
this.updateEditorSelectionWith = '';
|
||||
},
|
||||
insertIntoTextEditor(text, selectionStart, selectionEnd) {
|
||||
const { message } = this;
|
||||
const newMessage =
|
||||
message.slice(0, selectionStart) +
|
||||
text +
|
||||
message.slice(selectionEnd, message.length);
|
||||
this.message = newMessage;
|
||||
},
|
||||
addIntoEditor(content) {
|
||||
this.updateEditorSelectionWith = content;
|
||||
this.onFocus();
|
||||
if (this.showRichContentEditor) {
|
||||
this.updateEditorSelectionWith = content;
|
||||
this.onFocus();
|
||||
}
|
||||
if (!this.showRichContentEditor) {
|
||||
const { selectionStart, selectionEnd } = this.$refs.messageInput.$el;
|
||||
this.insertIntoTextEditor(content, selectionStart, selectionEnd);
|
||||
}
|
||||
},
|
||||
clearMessage() {
|
||||
this.message = '';
|
||||
if (this.sendWithSignature && !this.isPrivate) {
|
||||
// if signature is enabled, append it to the message
|
||||
this.message = appendSignature(
|
||||
this.message,
|
||||
this.messageSignature,
|
||||
this.channelType
|
||||
);
|
||||
this.message = appendSignature(this.message, this.signatureToApply);
|
||||
}
|
||||
this.attachedFiles = [];
|
||||
this.isRecordingAudio = false;
|
||||
@@ -822,15 +926,19 @@ export default {
|
||||
},
|
||||
toggleAudioRecorder() {
|
||||
this.isRecordingAudio = !this.isRecordingAudio;
|
||||
this.isRecorderAudioStopped = !this.isRecordingAudio;
|
||||
if (!this.isRecordingAudio) {
|
||||
this.resetAudioRecorderInput();
|
||||
}
|
||||
},
|
||||
toggleAudioRecorderPlayPause() {
|
||||
if (!this.$refs.audioRecorderInput) return;
|
||||
if (!this.recordingAudioState) {
|
||||
if (!this.isRecordingAudio) {
|
||||
return;
|
||||
}
|
||||
if (!this.isRecorderAudioStopped) {
|
||||
this.isRecorderAudioStopped = true;
|
||||
this.$refs.audioRecorderInput.stopRecording();
|
||||
} else {
|
||||
} else if (this.isRecorderAudioStopped) {
|
||||
this.$refs.audioRecorderInput.playPause();
|
||||
}
|
||||
},
|
||||
@@ -839,6 +947,9 @@ export default {
|
||||
this.toggleEmojiPicker();
|
||||
}
|
||||
},
|
||||
hideMentions() {
|
||||
this.showMentions = false;
|
||||
},
|
||||
onTypingOn() {
|
||||
this.toggleTyping('on');
|
||||
},
|
||||
@@ -1085,6 +1196,13 @@ export default {
|
||||
:message="inReplyTo"
|
||||
@dismiss="resetReplyToMessage"
|
||||
/>
|
||||
<CannedResponse
|
||||
v-if="showMentions && hasSlashCommand"
|
||||
v-on-clickaway="hideMentions"
|
||||
class="normal-editor__canned-box"
|
||||
:search-key="mentionSearchKey"
|
||||
@replace="replaceText"
|
||||
/>
|
||||
<EmojiInput
|
||||
v-if="showEmojiPicker"
|
||||
v-on-clickaway="hideEmojiPicker"
|
||||
@@ -1108,17 +1226,33 @@ export default {
|
||||
@play="recordingAudioState = 'playing'"
|
||||
@pause="recordingAudioState = 'paused'"
|
||||
/>
|
||||
<ResizableTextArea
|
||||
v-else-if="!showRichContentEditor"
|
||||
ref="messageInput"
|
||||
v-model="message"
|
||||
class="rounded-none input"
|
||||
:placeholder="messagePlaceHolder"
|
||||
:min-height="4"
|
||||
:signature="signatureToApply"
|
||||
allow-signature
|
||||
:send-with-signature="sendWithSignature"
|
||||
@typing-off="onTypingOff"
|
||||
@typing-on="onTypingOn"
|
||||
@focus="onFocus"
|
||||
@blur="onBlur"
|
||||
/>
|
||||
<WootMessageEditor
|
||||
v-else
|
||||
v-model="message"
|
||||
:editor-id="editorStateId"
|
||||
class="input popover-prosemirror-menu"
|
||||
class="input"
|
||||
:is-private="isOnPrivateNote"
|
||||
:placeholder="messagePlaceHolder"
|
||||
:update-selection-with="updateEditorSelectionWith"
|
||||
:min-height="4"
|
||||
enable-variables
|
||||
:variables="messageVariables"
|
||||
:signature="messageSignature"
|
||||
:signature="signatureToApply"
|
||||
allow-signature
|
||||
:channel-type="channelType"
|
||||
@typing-off="onTypingOff"
|
||||
@@ -1168,6 +1302,7 @@ export default {
|
||||
:recording-audio-state="recordingAudioState"
|
||||
:send-button-text="replyButtonLabel"
|
||||
:show-audio-recorder="showAudioRecorder"
|
||||
:show-editor-toggle="isAPIInbox && !isOnPrivateNote"
|
||||
:show-emoji-picker="showEmojiPicker"
|
||||
:show-file-upload="showFileUpload"
|
||||
:show-quoted-reply-toggle="shouldShowQuotedReplyToggle"
|
||||
@@ -1180,6 +1315,7 @@ export default {
|
||||
:new-conversation-modal-active="newConversationModalActive"
|
||||
@select-whatsapp-template="openWhatsappTemplateModal"
|
||||
@select-content-template="openContentTemplateModal"
|
||||
@toggle-editor="toggleRichContentEditor"
|
||||
@replace-text="replaceText"
|
||||
@toggle-insert-article="toggleInsertArticle"
|
||||
@toggle-quoted-reply="toggleQuotedReply"
|
||||
@@ -1233,6 +1369,10 @@ export default {
|
||||
|
||||
.reply-box__top {
|
||||
@apply relative py-0 px-4 -mt-px;
|
||||
|
||||
textarea {
|
||||
@apply shadow-none outline-none border-transparent bg-transparent m-0 max-h-60 min-h-[3rem] pt-4 pb-0 px-0 resize-none;
|
||||
}
|
||||
}
|
||||
|
||||
.emoji-dialog {
|
||||
@@ -1252,4 +1392,9 @@ export default {
|
||||
@apply ltr:left-1 rtl:right-1 -bottom-2;
|
||||
}
|
||||
}
|
||||
|
||||
.normal-editor__canned-box {
|
||||
width: calc(100% - 2 * 1rem);
|
||||
left: 1rem;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,18 +1,43 @@
|
||||
import { ref, unref } from 'vue';
|
||||
import { computed, ref, unref } from 'vue';
|
||||
import { useStore } from 'vuex';
|
||||
import { useAlert } from 'dashboard/composables';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useMapGetter } from 'dashboard/composables/store.js';
|
||||
import { useAccount } from 'dashboard/composables/useAccount';
|
||||
|
||||
export function useBulkActions() {
|
||||
const store = useStore();
|
||||
const { t } = useI18n();
|
||||
const { currentAccount } = useAccount();
|
||||
|
||||
const selectedConversations = useMapGetter(
|
||||
'bulkActions/getSelectedConversationIds'
|
||||
);
|
||||
const allConversations = useMapGetter('getAllConversations');
|
||||
const selectedInboxes = ref([]);
|
||||
|
||||
const requiredAttributeKeys = computed(
|
||||
() => currentAccount.value?.settings?.conversation_required_attributes || []
|
||||
);
|
||||
|
||||
const conversationsById = computed(() =>
|
||||
(allConversations.value || []).reduce((acc, conversation) => {
|
||||
acc[conversation.id] = conversation;
|
||||
return acc;
|
||||
}, {})
|
||||
);
|
||||
|
||||
const hasAllRequiredValues = conversation => {
|
||||
if (!conversation) return false;
|
||||
const attrs = conversation.custom_attributes || {};
|
||||
return requiredAttributeKeys.value.every(key => {
|
||||
const value = attrs?.[key];
|
||||
return (
|
||||
value !== undefined && value !== null && String(value).trim() !== ''
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
function selectConversation(conversationId, inboxId) {
|
||||
store.dispatch('bulkActions/setSelectedConversationIds', conversationId);
|
||||
selectedInboxes.value = [...selectedInboxes.value, inboxId];
|
||||
@@ -116,17 +141,58 @@ export function useBulkActions() {
|
||||
}
|
||||
|
||||
async function onUpdateConversations(status, snoozedUntil) {
|
||||
const selectedIds = selectedConversations.value;
|
||||
const requiresCheck =
|
||||
status === 'resolved' && requiredAttributeKeys.value.length > 0;
|
||||
|
||||
const resolveCandidates = requiresCheck
|
||||
? selectedIds.reduce(
|
||||
(result, id) => {
|
||||
const conversation = conversationsById.value[id];
|
||||
if (hasAllRequiredValues(conversation)) {
|
||||
result.resolvable.push(id);
|
||||
} else {
|
||||
result.blocked.push(id);
|
||||
}
|
||||
return result;
|
||||
},
|
||||
{ resolvable: [], blocked: [] }
|
||||
)
|
||||
: { resolvable: selectedIds, blocked: [] };
|
||||
|
||||
if (!resolveCandidates.resolvable.length) {
|
||||
if (requiresCheck) {
|
||||
useAlert(t('BULK_ACTION.UPDATE.REQUIRED_ATTRIBUTES_MISSING'));
|
||||
} else {
|
||||
useAlert(t('BULK_ACTION.UPDATE.UPDATE_FAILED'));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await store.dispatch('bulkActions/process', {
|
||||
type: 'Conversation',
|
||||
ids: selectedConversations.value,
|
||||
ids: resolveCandidates.resolvable,
|
||||
fields: {
|
||||
status,
|
||||
},
|
||||
snoozed_until: snoozedUntil,
|
||||
});
|
||||
|
||||
// Update selection to keep only blocked conversations, if any.
|
||||
store.dispatch('bulkActions/clearSelectedConversationIds');
|
||||
useAlert(t('BULK_ACTION.UPDATE.UPDATE_SUCCESFUL'));
|
||||
selectedInboxes.value = [];
|
||||
if (resolveCandidates.blocked.length) {
|
||||
store.dispatch('bulkActions/setSelectedConversationIds', [
|
||||
...resolveCandidates.blocked,
|
||||
]);
|
||||
selectedInboxes.value = resolveCandidates.blocked
|
||||
.map(id => conversationsById.value[id]?.inbox_id)
|
||||
.filter(Boolean);
|
||||
useAlert(t('BULK_ACTION.UPDATE.REQUIRED_ATTRIBUTES_MISSING'));
|
||||
} else {
|
||||
useAlert(t('BULK_ACTION.UPDATE.UPDATE_SUCCESFUL'));
|
||||
}
|
||||
} catch (err) {
|
||||
useAlert(t('BULK_ACTION.UPDATE.UPDATE_FAILED'));
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { computed } from 'vue';
|
||||
import { useMapGetter, useStore } from 'dashboard/composables/store.js';
|
||||
import { useStore } from 'dashboard/composables/store.js';
|
||||
import { useAccount } from 'dashboard/composables/useAccount';
|
||||
import { useConfig } from 'dashboard/composables/useConfig';
|
||||
import { useCamelCase } from 'dashboard/composables/useTransformKeys';
|
||||
@@ -9,7 +9,6 @@ export function useCaptain() {
|
||||
const store = useStore();
|
||||
const { isCloudFeatureEnabled, currentAccount } = useAccount();
|
||||
const { isEnterprise } = useConfig();
|
||||
const uiFlags = useMapGetter('accounts/getUIFlags');
|
||||
|
||||
const captainEnabled = computed(() => {
|
||||
return isCloudFeatureEnabled(FEATURE_FLAGS.CAPTAIN);
|
||||
@@ -35,8 +34,6 @@ export function useCaptain() {
|
||||
return null;
|
||||
});
|
||||
|
||||
const isFetchingLimits = computed(() => uiFlags.value.isFetchingLimits);
|
||||
|
||||
const fetchLimits = () => {
|
||||
if (isEnterprise) {
|
||||
store.dispatch('accounts/limits');
|
||||
@@ -49,6 +46,5 @@ export function useCaptain() {
|
||||
documentLimits,
|
||||
responseLimits,
|
||||
fetchLimits,
|
||||
isFetchingLimits,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,143 +1,23 @@
|
||||
// Formatting rules for different contexts (channels and special contexts)
|
||||
// marks: inline formatting (strong, em, code, link, strike)
|
||||
// nodes: block structures (bulletList, orderedList, codeBlock, blockquote)
|
||||
export const FORMATTING = {
|
||||
// Channel formatting
|
||||
'Channel::Email': {
|
||||
marks: ['strong', 'em', 'code', 'link'],
|
||||
nodes: ['bulletList', 'orderedList', 'codeBlock', 'blockquote', 'image'],
|
||||
menu: [
|
||||
'strong',
|
||||
'em',
|
||||
'code',
|
||||
'link',
|
||||
'bulletList',
|
||||
'orderedList',
|
||||
'undo',
|
||||
'redo',
|
||||
],
|
||||
},
|
||||
'Channel::WebWidget': {
|
||||
marks: ['strong', 'em', 'code', 'link', 'strike'],
|
||||
nodes: ['bulletList', 'orderedList', 'codeBlock', 'blockquote', 'image'],
|
||||
menu: [
|
||||
'strong',
|
||||
'em',
|
||||
'code',
|
||||
'link',
|
||||
'strike',
|
||||
'bulletList',
|
||||
'orderedList',
|
||||
'undo',
|
||||
'redo',
|
||||
],
|
||||
},
|
||||
'Channel::Api': {
|
||||
marks: ['strong', 'em'],
|
||||
nodes: [],
|
||||
menu: ['strong', 'em', 'undo', 'redo'],
|
||||
},
|
||||
'Channel::FacebookPage': {
|
||||
marks: ['strong', 'em', 'code', 'strike'],
|
||||
nodes: ['bulletList', 'orderedList', 'codeBlock'],
|
||||
menu: [
|
||||
'strong',
|
||||
'em',
|
||||
'code',
|
||||
'strike',
|
||||
'bulletList',
|
||||
'orderedList',
|
||||
'undo',
|
||||
'redo',
|
||||
],
|
||||
},
|
||||
'Channel::TwitterProfile': {
|
||||
marks: [],
|
||||
nodes: [],
|
||||
menu: [],
|
||||
},
|
||||
'Channel::TwilioSms': {
|
||||
marks: [],
|
||||
nodes: [],
|
||||
menu: [],
|
||||
},
|
||||
'Channel::Sms': {
|
||||
marks: [],
|
||||
nodes: [],
|
||||
menu: [],
|
||||
},
|
||||
'Channel::Whatsapp': {
|
||||
marks: ['strong', 'em', 'code', 'strike'],
|
||||
nodes: ['bulletList', 'orderedList', 'codeBlock'],
|
||||
menu: [
|
||||
'strong',
|
||||
'em',
|
||||
'code',
|
||||
'strike',
|
||||
'bulletList',
|
||||
'orderedList',
|
||||
'undo',
|
||||
'redo',
|
||||
],
|
||||
},
|
||||
'Channel::Line': {
|
||||
marks: ['strong', 'em', 'code', 'strike'],
|
||||
nodes: ['codeBlock'],
|
||||
menu: ['strong', 'em', 'code', 'strike', 'undo', 'redo'],
|
||||
},
|
||||
'Channel::Telegram': {
|
||||
marks: ['strong', 'em', 'link', 'code'],
|
||||
nodes: [],
|
||||
menu: ['strong', 'em', 'link', 'code', 'undo', 'redo'],
|
||||
},
|
||||
'Channel::Instagram': {
|
||||
marks: ['strong', 'em', 'code', 'strike'],
|
||||
nodes: ['bulletList', 'orderedList'],
|
||||
menu: [
|
||||
'strong',
|
||||
'em',
|
||||
'code',
|
||||
'bulletList',
|
||||
'orderedList',
|
||||
'strike',
|
||||
'undo',
|
||||
'redo',
|
||||
],
|
||||
},
|
||||
'Channel::Voice': {
|
||||
marks: [],
|
||||
nodes: [],
|
||||
menu: [],
|
||||
},
|
||||
// Special contexts (not actual channels)
|
||||
'Context::Default': {
|
||||
marks: ['strong', 'em', 'code', 'link', 'strike'],
|
||||
nodes: ['bulletList', 'orderedList', 'codeBlock', 'blockquote'],
|
||||
menu: [
|
||||
'strong',
|
||||
'em',
|
||||
'code',
|
||||
'link',
|
||||
'strike',
|
||||
'bulletList',
|
||||
'orderedList',
|
||||
'undo',
|
||||
'redo',
|
||||
],
|
||||
},
|
||||
'Context::MessageSignature': {
|
||||
marks: ['strong', 'em', 'link'],
|
||||
nodes: ['image'],
|
||||
menu: ['strong', 'em', 'link', 'undo', 'redo', 'imageUpload'],
|
||||
},
|
||||
'Context::InboxSettings': {
|
||||
marks: ['strong', 'em', 'link'],
|
||||
nodes: [],
|
||||
menu: ['strong', 'em', 'link', 'undo', 'redo'],
|
||||
},
|
||||
};
|
||||
export const MESSAGE_EDITOR_MENU_OPTIONS = [
|
||||
'strong',
|
||||
'em',
|
||||
'link',
|
||||
'undo',
|
||||
'redo',
|
||||
'bulletList',
|
||||
'orderedList',
|
||||
'code',
|
||||
];
|
||||
|
||||
export const MESSAGE_SIGNATURE_EDITOR_MENU_OPTIONS = [
|
||||
'strong',
|
||||
'em',
|
||||
'link',
|
||||
'undo',
|
||||
'redo',
|
||||
'imageUpload',
|
||||
];
|
||||
|
||||
// Editor menu options for Full Editor
|
||||
export const ARTICLE_EDITOR_MENU_OPTIONS = [
|
||||
'strong',
|
||||
'em',
|
||||
@@ -153,86 +33,14 @@ export const ARTICLE_EDITOR_MENU_OPTIONS = [
|
||||
'code',
|
||||
];
|
||||
|
||||
/**
|
||||
* Markdown formatting patterns for stripping unsupported formatting.
|
||||
*
|
||||
* Maps camelCase type names to ProseMirror snake_case schema names.
|
||||
* Order matters: codeBlock before code to avoid partial matches.
|
||||
*/
|
||||
export const MARKDOWN_PATTERNS = [
|
||||
// --- BLOCK NODES ---
|
||||
{
|
||||
type: 'codeBlock', // PM: code_block, eg: ```js\ncode\n```
|
||||
patterns: [
|
||||
{ pattern: /`{3}(?:\w+)?\n?([\s\S]*?)`{3}/g, replacement: '$1' },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'blockquote', // PM: blockquote, eg: > quote
|
||||
patterns: [{ pattern: /^> ?/gm, replacement: '' }],
|
||||
},
|
||||
{
|
||||
type: 'bulletList', // PM: bullet_list, eg: - item
|
||||
patterns: [{ pattern: /^[\t ]*[-*+]\s+/gm, replacement: '' }],
|
||||
},
|
||||
{
|
||||
type: 'orderedList', // PM: ordered_list, eg: 1. item
|
||||
patterns: [{ pattern: /^[\t ]*\d+\.\s+/gm, replacement: '' }],
|
||||
},
|
||||
{
|
||||
type: 'heading', // PM: heading, eg: ## Heading
|
||||
patterns: [{ pattern: /^#{1,6}\s+/gm, replacement: '' }],
|
||||
},
|
||||
{
|
||||
type: 'horizontalRule', // PM: horizontal_rule, eg: ---
|
||||
patterns: [{ pattern: /^(?:---|___|\*\*\*)\s*$/gm, replacement: '' }],
|
||||
},
|
||||
{
|
||||
type: 'image', // PM: image, eg: 
|
||||
patterns: [{ pattern: /!\[([^\]]*)\]\([^)]+\)/g, replacement: '$1' }],
|
||||
},
|
||||
{
|
||||
type: 'hardBreak', // PM: hard_break, eg: line\\\n or line \n
|
||||
patterns: [
|
||||
{ pattern: /\\\n/g, replacement: '\n' },
|
||||
{ pattern: / {2,}\n/g, replacement: '\n' },
|
||||
],
|
||||
},
|
||||
// --- INLINE MARKS ---
|
||||
{
|
||||
type: 'strong', // PM: strong, eg: **bold** or __bold__
|
||||
patterns: [
|
||||
{ pattern: /\*\*(.+?)\*\*/g, replacement: '$1' },
|
||||
{ pattern: /__(.+?)__/g, replacement: '$1' },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'em', // PM: em, eg: *italic* or _italic_
|
||||
patterns: [
|
||||
{ pattern: /(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g, replacement: '$1' },
|
||||
{ pattern: /(?<!_)_(?!_)(.+?)(?<!_)_(?!_)/g, replacement: '$1' },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'strike', // PM: strike, eg: ~~strikethrough~~
|
||||
patterns: [{ pattern: /~~(.+?)~~/g, replacement: '$1' }],
|
||||
},
|
||||
{
|
||||
type: 'code', // PM: code, eg: `inline code`
|
||||
patterns: [{ pattern: /`([^`]+)`/g, replacement: '$1' }],
|
||||
},
|
||||
{
|
||||
type: 'link', // PM: link, eg: [text](url)
|
||||
patterns: [{ pattern: /\[([^\]]+)\]\([^)]+\)/g, replacement: '$1' }],
|
||||
},
|
||||
export const WIDGET_BUILDER_EDITOR_MENU_OPTIONS = [
|
||||
'strong',
|
||||
'em',
|
||||
'link',
|
||||
'undo',
|
||||
'redo',
|
||||
];
|
||||
|
||||
export const CHANNEL_WITH_RICH_SIGNATURE = [
|
||||
'Channel::Email',
|
||||
'Channel::WebWidget',
|
||||
];
|
||||
|
||||
// Editor image resize options for Message Editor
|
||||
export const MESSAGE_EDITOR_IMAGE_RESIZES = [
|
||||
{
|
||||
name: 'Small',
|
||||
|
||||
@@ -5,52 +5,6 @@ import {
|
||||
} from '@chatwoot/prosemirror-schema';
|
||||
import { replaceVariablesInMessage } from '@chatwoot/utils';
|
||||
import * as Sentry from '@sentry/vue';
|
||||
import {
|
||||
FORMATTING,
|
||||
MARKDOWN_PATTERNS,
|
||||
CHANNEL_WITH_RICH_SIGNATURE,
|
||||
} from 'dashboard/constants/editor';
|
||||
import camelcaseKeys from 'camelcase-keys';
|
||||
|
||||
/**
|
||||
* Removes zero-width spaces and related invisible characters from text.
|
||||
* Also handles backslash-newline patterns from hard breaks (Shift+Enter).
|
||||
* These characters can interfere with signature detection and content handling.
|
||||
*
|
||||
* @param {string} text - The text to clean
|
||||
* @returns {string} - The cleaned text without zero-width spaces
|
||||
*/
|
||||
export function removeZeroWidthSpaces(text) {
|
||||
if (!text) return '';
|
||||
return text
|
||||
.replace(/\u200B\\\n/g, '\n') // Remove zero-width space + backslash + newline, keep newline
|
||||
.replace(/\u200B\n/g, '\n') // Remove zero-width space + newline, keep newline
|
||||
.replace(/\\\n/g, '\n') // Remove backslash before newline (hard break), keep newline
|
||||
.replace(/\u200B/g, ''); // Remove standalone zero-width spaces
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract text from markdown, and remove all images, code blocks, links, headers, bold, italic, lists etc.
|
||||
* Links will be converted to text, and not removed.
|
||||
*
|
||||
* @param {string} markdown - markdown text to be extracted
|
||||
* @returns {string} - The extracted text.
|
||||
*/
|
||||
export function extractTextFromMarkdown(markdown) {
|
||||
if (!markdown) return '';
|
||||
return markdown
|
||||
.replace(/```[\s\S]*?```/g, '') // Remove code blocks
|
||||
.replace(/`.*?`/g, '') // Remove inline code
|
||||
.replace(/!\[.*?\]\(.*?\)/g, '') // Remove images before removing links
|
||||
.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1') // Remove links but keep the text
|
||||
.replace(/#+\s*|[*_-]{1,3}/g, '') // Remove headers, bold, italic, lists etc.
|
||||
.split('\n')
|
||||
.map(line => line.trim())
|
||||
.filter(Boolean)
|
||||
.join('\n') // Trim each line & remove any lines only having spaces
|
||||
.replace(/\n{2,}/g, '\n') // Remove multiple consecutive newlines (blank lines)
|
||||
.trim(); // Trim any extra space
|
||||
}
|
||||
|
||||
/**
|
||||
* The delimiter used to separate the signature from the rest of the body.
|
||||
@@ -63,9 +17,6 @@ export const SIGNATURE_DELIMITER = '--';
|
||||
*/
|
||||
export function cleanSignature(signature) {
|
||||
try {
|
||||
// Remove zero-width spaces before processing
|
||||
signature = removeZeroWidthSpaces(signature);
|
||||
|
||||
// remove any horizontal rule tokens
|
||||
signature = signature
|
||||
.replace(/^( *\* *){3,} *$/gm, '')
|
||||
@@ -75,17 +26,14 @@ export function cleanSignature(signature) {
|
||||
const nodes = new MessageMarkdownTransformer(messageSchema).parse(
|
||||
signature
|
||||
);
|
||||
let result = MessageMarkdownSerializer.serialize(nodes);
|
||||
|
||||
// Remove zero-width spaces after serialization as well
|
||||
return removeZeroWidthSpaces(result);
|
||||
return MessageMarkdownSerializer.serialize(nodes);
|
||||
} catch (e) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.warn(e);
|
||||
Sentry.captureException(e);
|
||||
// The parser can break on some cases
|
||||
// for example, Token type `hr` not supported by Markdown parser
|
||||
return removeZeroWidthSpaces(signature);
|
||||
return signature;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,8 +56,7 @@ function appendDelimiter(signature) {
|
||||
* @returns {number} - The index of the last occurrence of the signature in the body, or -1 if not found.
|
||||
*/
|
||||
export function findSignatureInBody(body, signature) {
|
||||
// Remove zero-width spaces from body before comparison
|
||||
const trimmedBody = removeZeroWidthSpaces(body).trimEnd();
|
||||
const trimmedBody = body.trimEnd();
|
||||
const cleanedSignature = cleanSignature(signature);
|
||||
|
||||
// check if body ends with signature
|
||||
@@ -120,69 +67,38 @@ export function findSignatureInBody(body, signature) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the channel supports image signatures.
|
||||
*
|
||||
* @param {string} channelType - The channel type.
|
||||
* @returns {boolean} - True if the channel supports image signatures.
|
||||
*/
|
||||
export function supportsImageSignature(channelType) {
|
||||
return CHANNEL_WITH_RICH_SIGNATURE.includes(channelType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends the signature to the body, separated by the signature delimiter.
|
||||
* Automatically strips images for channels that don't support image signatures.
|
||||
*
|
||||
* @param {string} body - The body to append the signature to.
|
||||
* @param {string} signature - The signature to append.
|
||||
* @param {string} channelType - Optional. The channel type to determine if images should be stripped.
|
||||
* @returns {string} - The body with the signature appended.
|
||||
*/
|
||||
export function appendSignature(body, signature, channelType) {
|
||||
// Remove zero-width spaces from body before processing
|
||||
const cleanedBody = removeZeroWidthSpaces(body);
|
||||
|
||||
// For channels that don't support images, strip markdown formatting
|
||||
const shouldStripImages = channelType && !supportsImageSignature(channelType);
|
||||
const preparedSignature = shouldStripImages
|
||||
? extractTextFromMarkdown(signature)
|
||||
: signature;
|
||||
const cleanedSignature = cleanSignature(preparedSignature);
|
||||
export function appendSignature(body, signature) {
|
||||
const cleanedSignature = cleanSignature(signature);
|
||||
// if signature is already present, return body
|
||||
if (findSignatureInBody(cleanedBody, cleanedSignature) > -1) {
|
||||
return cleanedBody;
|
||||
if (findSignatureInBody(body, cleanedSignature) > -1) {
|
||||
return body;
|
||||
}
|
||||
|
||||
return `${cleanedBody.trimEnd()}\n\n${appendDelimiter(cleanedSignature)}`;
|
||||
return `${body.trimEnd()}\n\n${appendDelimiter(cleanedSignature)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the signature from the body, along with the signature delimiter.
|
||||
* Tries to find both the original signature and the stripped version (for non-image channels).
|
||||
*
|
||||
* @param {string} body - The body to remove the signature from.
|
||||
* @param {string} signature - The signature to remove.
|
||||
* @returns {string} - The body with the signature removed.
|
||||
*/
|
||||
export function removeSignature(body, signature) {
|
||||
// Remove zero-width spaces from body before processing
|
||||
let newBody = removeZeroWidthSpaces(body);
|
||||
|
||||
// Build list of signatures to try: original first, then stripped version
|
||||
// Always try both to handle cases where channelType is unknown or inbox is being removed
|
||||
// this will find the index of the signature if it exists
|
||||
// Regardless of extra spaces or new lines after the signature, the index will be the same if present
|
||||
const cleanedSignature = cleanSignature(signature);
|
||||
const strippedSignature = cleanSignature(extractTextFromMarkdown(signature));
|
||||
const signaturesToTry =
|
||||
cleanedSignature === strippedSignature
|
||||
? [cleanedSignature]
|
||||
: [cleanedSignature, strippedSignature];
|
||||
const signatureIndex = findSignatureInBody(body, cleanedSignature);
|
||||
|
||||
// Find the first matching signature
|
||||
const signatureIndex = signaturesToTry.reduce(
|
||||
(index, sig) => (index === -1 ? findSignatureInBody(newBody, sig) : index),
|
||||
-1
|
||||
);
|
||||
// no need to trim the ends here, because it will simply be removed in the next method
|
||||
let newBody = body;
|
||||
|
||||
// if signature is present, remove it and trim it
|
||||
// trimming will ensure any spaces or new lines before the signature are removed
|
||||
@@ -220,6 +136,28 @@ export function replaceSignature(body, oldSignature, newSignature) {
|
||||
return appendSignature(withoutSignature, newSignature);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract text from markdown, and remove all images, code blocks, links, headers, bold, italic, lists etc.
|
||||
* Links will be converted to text, and not removed.
|
||||
*
|
||||
* @param {string} markdown - markdown text to be extracted
|
||||
* @returns
|
||||
*/
|
||||
export function extractTextFromMarkdown(markdown) {
|
||||
return markdown
|
||||
.replace(/```[\s\S]*?```/g, '') // Remove code blocks
|
||||
.replace(/`.*?`/g, '') // Remove inline code
|
||||
.replace(/!\[.*?\]\(.*?\)/g, '') // Remove images before removing links
|
||||
.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1') // Remove links but keep the text
|
||||
.replace(/#+\s*|[*_-]{1,3}/g, '') // Remove headers, bold, italic, lists etc.
|
||||
.split('\n')
|
||||
.map(line => line.trim())
|
||||
.filter(Boolean)
|
||||
.join('\n') // Trim each line & remove any lines only having spaces
|
||||
.replace(/\n{2,}/g, '\n') // Remove multiple consecutive newlines (blank lines)
|
||||
.trim(); // Trim any extra space
|
||||
}
|
||||
|
||||
/**
|
||||
* Scrolls the editor view into current cursor position
|
||||
*
|
||||
@@ -345,47 +283,6 @@ export function setURLWithQueryAndSize(selectedImageNode, size, editorView) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Strips unsupported markdown formatting from content based on the editor schema.
|
||||
* This ensures canned responses with rich formatting can be inserted into channels
|
||||
* that don't support certain formatting (e.g., API channels don't support bold).
|
||||
*
|
||||
* @param {string} content - The markdown content to sanitize
|
||||
* @param {Object} schema - The ProseMirror schema with supported marks and nodes
|
||||
* @returns {string} - Content with unsupported formatting stripped
|
||||
*/
|
||||
export function stripUnsupportedFormatting(content, schema) {
|
||||
if (!content || typeof content !== 'string') return content;
|
||||
if (!schema) return content;
|
||||
|
||||
let sanitizedContent = content;
|
||||
|
||||
// Get supported marks and nodes from the schema
|
||||
// Note: ProseMirror uses snake_case internally (code_block, bullet_list, etc.)
|
||||
// but our FORMATTING constant uses camelCase (codeBlock, bulletList, etc.)
|
||||
// We use camelcase-keys to normalize node names for comparison
|
||||
const supportedMarks = Object.keys(schema.marks || {});
|
||||
const nodeKeys = Object.keys(schema.nodes || {});
|
||||
const nodeKeysObj = Object.fromEntries(nodeKeys.map(k => [k, true]));
|
||||
const supportedNodes = Object.keys(camelcaseKeys(nodeKeysObj));
|
||||
|
||||
// Process each formatting type in order (codeBlock before code is important!)
|
||||
MARKDOWN_PATTERNS.forEach(({ type, patterns }) => {
|
||||
// Check if this format type is supported by the schema
|
||||
const isMarkSupported = supportedMarks.includes(type);
|
||||
const isNodeSupported = supportedNodes.includes(type);
|
||||
|
||||
// If not supported, strip the formatting
|
||||
if (!isMarkSupported && !isNodeSupported) {
|
||||
patterns.forEach(({ pattern, replacement }) => {
|
||||
sanitizedContent = sanitizedContent.replace(pattern, replacement);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return sanitizedContent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Content Node Creation Helper Functions for
|
||||
* - mention
|
||||
@@ -416,17 +313,8 @@ const createNode = (editorView, nodeType, content) => {
|
||||
|
||||
return mentionNode;
|
||||
}
|
||||
case 'cannedResponse': {
|
||||
// Strip unsupported formatting before parsing to ensure content can be inserted
|
||||
// into channels that don't support certain markdown features (e.g., API channels)
|
||||
const sanitizedContent = stripUnsupportedFormatting(
|
||||
content,
|
||||
state.schema
|
||||
);
|
||||
return new MessageMarkdownTransformer(state.schema).parse(
|
||||
sanitizedContent
|
||||
);
|
||||
}
|
||||
case 'cannedResponse':
|
||||
return new MessageMarkdownTransformer(messageSchema).parse(content);
|
||||
case 'variable':
|
||||
return state.schema.text(`{{${content}}}`);
|
||||
case 'emoji':
|
||||
@@ -501,85 +389,3 @@ export const getContentNode = (
|
||||
? creator(editorView, content, from, to, variables)
|
||||
: { node: null, from, to };
|
||||
};
|
||||
|
||||
/**
|
||||
* Get the formatting configuration for a specific channel type.
|
||||
* Returns the appropriate marks, nodes, and menu items for the editor.
|
||||
*
|
||||
* @param {string} channelType - The channel type (e.g., 'Channel::FacebookPage', 'Channel::WebWidget')
|
||||
* @returns {Object} The formatting configuration with marks, nodes, and menu properties
|
||||
*/
|
||||
export function getFormattingForEditor(channelType) {
|
||||
return FORMATTING[channelType] || FORMATTING['Context::Default'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Menu Positioning Helpers
|
||||
* Handles floating menu bar positioning for text selection in the editor.
|
||||
*/
|
||||
|
||||
const MENU_CONFIG = { H: 46, W: 300, GAP: 10 };
|
||||
|
||||
/**
|
||||
* Calculate selection coordinates with bias to handle line-wraps correctly.
|
||||
* @param {EditorView} editorView - ProseMirror editor view
|
||||
* @param {Selection} selection - Current text selection
|
||||
* @param {DOMRect} rect - Container bounding rect
|
||||
* @returns {{start: Object, end: Object, selTop: number, onTop: boolean}}
|
||||
*/
|
||||
export function getSelectionCoords(editorView, selection, rect) {
|
||||
const start = editorView.coordsAtPos(selection.from, 1);
|
||||
const end = editorView.coordsAtPos(selection.to, -1);
|
||||
|
||||
const selTop = Math.min(start.top, end.top);
|
||||
const spaceAbove = selTop - rect.top;
|
||||
const onTop =
|
||||
spaceAbove > MENU_CONFIG.H + MENU_CONFIG.GAP || end.bottom > rect.bottom;
|
||||
|
||||
return { start, end, selTop, onTop };
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate anchor position based on selection visibility and RTL direction.
|
||||
* @param {Object} coords - Selection coordinates from getSelectionCoords
|
||||
* @param {DOMRect} rect - Container bounding rect
|
||||
* @param {boolean} isRtl - Whether text direction is RTL
|
||||
* @returns {number} Anchor x-position for menu
|
||||
*/
|
||||
export function getMenuAnchor(coords, rect, isRtl) {
|
||||
const { start, end, onTop } = coords;
|
||||
|
||||
if (!onTop) return end.left;
|
||||
|
||||
// If start of selection is visible, align to text. Else stick to container edge.
|
||||
if (start.top >= rect.top) return isRtl ? start.right : start.left;
|
||||
|
||||
return isRtl ? rect.right - MENU_CONFIG.GAP : rect.left + MENU_CONFIG.GAP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate final menu position (left, top) within container bounds.
|
||||
* @param {Object} coords - Selection coordinates from getSelectionCoords
|
||||
* @param {DOMRect} rect - Container bounding rect
|
||||
* @param {boolean} isRtl - Whether text direction is RTL
|
||||
* @returns {{left: number, top: number, width: number}}
|
||||
*/
|
||||
export function calculateMenuPosition(coords, rect, isRtl) {
|
||||
const { start, end, selTop, onTop } = coords;
|
||||
|
||||
const anchor = getMenuAnchor(coords, rect, isRtl);
|
||||
|
||||
// Calculate Left: shift by width if RTL, then make relative to container
|
||||
const rawLeft = (isRtl ? anchor - MENU_CONFIG.W : anchor) - rect.left;
|
||||
|
||||
// Ensure menu stays within container bounds
|
||||
const left = Math.min(Math.max(0, rawLeft), rect.width - MENU_CONFIG.W);
|
||||
|
||||
// Calculate Top: align to selection or bottom of selection
|
||||
const top = onTop
|
||||
? Math.max(-26, selTop - rect.top - MENU_CONFIG.H - MENU_CONFIG.GAP)
|
||||
: Math.max(start.bottom, end.bottom) - rect.top + MENU_CONFIG.GAP;
|
||||
return { left, top, width: MENU_CONFIG.W };
|
||||
}
|
||||
|
||||
/* End Menu Positioning Helpers */
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
// Moved from editorHelper.spec.js to editorContentHelper.spec.js
|
||||
// the mock of chatwoot/prosemirror-schema is getting conflicted with other specs
|
||||
import { getContentNode } from '../editorHelper';
|
||||
import { MessageMarkdownTransformer } from '@chatwoot/prosemirror-schema';
|
||||
import {
|
||||
MessageMarkdownTransformer,
|
||||
messageSchema,
|
||||
} from '@chatwoot/prosemirror-schema';
|
||||
import { replaceVariablesInMessage } from '@chatwoot/utils';
|
||||
|
||||
vi.mock('@chatwoot/prosemirror-schema', () => ({
|
||||
MessageMarkdownTransformer: vi.fn(),
|
||||
messageSchema: {},
|
||||
}));
|
||||
|
||||
vi.mock('@chatwoot/utils', () => ({
|
||||
@@ -58,18 +62,12 @@ describe('getContentNode', () => {
|
||||
const to = 10;
|
||||
const updatedMessage = 'Hello John';
|
||||
|
||||
// Mock the node that will be returned by parse
|
||||
const mockNode = { textContent: updatedMessage };
|
||||
|
||||
replaceVariablesInMessage.mockReturnValue(updatedMessage);
|
||||
MessageMarkdownTransformer.mockImplementation(() => ({
|
||||
parse: vi.fn().mockReturnValue({ textContent: updatedMessage }),
|
||||
}));
|
||||
|
||||
// Mock MessageMarkdownTransformer instance with parse method
|
||||
const mockTransformer = {
|
||||
parse: vi.fn().mockReturnValue(mockNode),
|
||||
};
|
||||
MessageMarkdownTransformer.mockImplementation(() => mockTransformer);
|
||||
|
||||
const result = getContentNode(
|
||||
const { node } = getContentNode(
|
||||
editorView,
|
||||
'cannedResponse',
|
||||
content,
|
||||
@@ -81,15 +79,8 @@ describe('getContentNode', () => {
|
||||
message: content,
|
||||
variables,
|
||||
});
|
||||
expect(MessageMarkdownTransformer).toHaveBeenCalledWith(
|
||||
editorView.state.schema
|
||||
);
|
||||
expect(mockTransformer.parse).toHaveBeenCalledWith(updatedMessage);
|
||||
expect(result.node).toBe(mockNode);
|
||||
expect(result.node.textContent).toBe(updatedMessage);
|
||||
// When textContent matches updatedMessage, from should remain unchanged
|
||||
expect(result.from).toBe(from);
|
||||
expect(result.to).toBe(to);
|
||||
expect(MessageMarkdownTransformer).toHaveBeenCalledWith(messageSchema);
|
||||
expect(node.textContent).toBe(updatedMessage);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -5,18 +5,11 @@ import {
|
||||
replaceSignature,
|
||||
cleanSignature,
|
||||
extractTextFromMarkdown,
|
||||
supportsImageSignature,
|
||||
insertAtCursor,
|
||||
findNodeToInsertImage,
|
||||
setURLWithQueryAndSize,
|
||||
getContentNode,
|
||||
getFormattingForEditor,
|
||||
getSelectionCoords,
|
||||
getMenuAnchor,
|
||||
calculateMenuPosition,
|
||||
stripUnsupportedFormatting,
|
||||
} from '../editorHelper';
|
||||
import { FORMATTING } from 'dashboard/constants/editor';
|
||||
import { EditorState } from '@chatwoot/prosemirror-schema';
|
||||
import { EditorView } from '@chatwoot/prosemirror-schema';
|
||||
import { Schema } from 'prosemirror-model';
|
||||
@@ -145,47 +138,6 @@ describe('appendSignature', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('appendSignature with channelType', () => {
|
||||
const signatureWithImage =
|
||||
'Thanks\n';
|
||||
const strippedSignature = 'Thanks';
|
||||
|
||||
it('keeps images for Email channel', () => {
|
||||
const result = appendSignature(
|
||||
'Hello',
|
||||
signatureWithImage,
|
||||
'Channel::Email'
|
||||
);
|
||||
expect(result).toContain(';
|
||||
});
|
||||
it('keeps images for WebWidget channel', () => {
|
||||
const result = appendSignature(
|
||||
'Hello',
|
||||
signatureWithImage,
|
||||
'Channel::WebWidget'
|
||||
);
|
||||
expect(result).toContain(';
|
||||
});
|
||||
it('strips images for Api channel', () => {
|
||||
const result = appendSignature('Hello', signatureWithImage, 'Channel::Api');
|
||||
expect(result).not.toContain(';
|
||||
expect(result).toContain(strippedSignature);
|
||||
});
|
||||
it('strips images for WhatsApp channel', () => {
|
||||
const result = appendSignature(
|
||||
'Hello',
|
||||
signatureWithImage,
|
||||
'Channel::Whatsapp'
|
||||
);
|
||||
expect(result).not.toContain(';
|
||||
expect(result).toContain(strippedSignature);
|
||||
});
|
||||
it('keeps images when channelType is not provided', () => {
|
||||
const result = appendSignature('Hello', signatureWithImage);
|
||||
expect(result).toContain(';
|
||||
});
|
||||
});
|
||||
|
||||
describe('cleanSignature', () => {
|
||||
it('removes any instance of horizontal rule', () => {
|
||||
const options = [
|
||||
@@ -244,37 +196,6 @@ describe('removeSignature', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('removeSignature with stripped signature', () => {
|
||||
const signatureWithImage =
|
||||
'Thanks\n';
|
||||
|
||||
it('removes stripped signature from body', () => {
|
||||
// Simulate a body where signature was added with images stripped
|
||||
const bodyWithStrippedSignature = 'Hello\n\n--\n\nThanks';
|
||||
const result = removeSignature(
|
||||
bodyWithStrippedSignature,
|
||||
signatureWithImage
|
||||
);
|
||||
expect(result).toBe('Hello\n\n');
|
||||
});
|
||||
it('removes original signature from body', () => {
|
||||
// Simulate a body where signature was added with images (using cleanSignature format)
|
||||
const cleanedSig = cleanSignature(signatureWithImage);
|
||||
const bodyWithOriginalSignature = `Hello\n\n--\n\n${cleanedSig}`;
|
||||
const result = removeSignature(
|
||||
bodyWithOriginalSignature,
|
||||
signatureWithImage
|
||||
);
|
||||
expect(result).toBe('Hello\n\n');
|
||||
});
|
||||
it('handles signature without images', () => {
|
||||
const simpleSignature = 'Best regards';
|
||||
const body = 'Hello\n\n--\n\nBest regards';
|
||||
const result = removeSignature(body, simpleSignature);
|
||||
expect(result).toBe('Hello\n\n');
|
||||
});
|
||||
});
|
||||
|
||||
describe('replaceSignature', () => {
|
||||
it('appends the new signature if not present', () => {
|
||||
Object.keys(DOES_NOT_HAVE_SIGNATURE).forEach(key => {
|
||||
@@ -331,35 +252,21 @@ describe('extractTextFromMarkdown', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('supportsImageSignature', () => {
|
||||
it('returns true for Email channel', () => {
|
||||
expect(supportsImageSignature('Channel::Email')).toBe(true);
|
||||
});
|
||||
it('returns true for WebWidget channel', () => {
|
||||
expect(supportsImageSignature('Channel::WebWidget')).toBe(true);
|
||||
});
|
||||
it('returns false for Api channel', () => {
|
||||
expect(supportsImageSignature('Channel::Api')).toBe(false);
|
||||
});
|
||||
it('returns false for WhatsApp channel', () => {
|
||||
expect(supportsImageSignature('Channel::Whatsapp')).toBe(false);
|
||||
});
|
||||
it('returns false for Telegram channel', () => {
|
||||
expect(supportsImageSignature('Channel::Telegram')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('insertAtCursor', () => {
|
||||
it('should return undefined if editorView is not provided', () => {
|
||||
const result = insertAtCursor(undefined, schema.text('Hello'), 0);
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should insert text node at cursor position', () => {
|
||||
it('should unwrap doc nodes that are wrapped in a paragraph', () => {
|
||||
const docNode = schema.node('doc', null, [
|
||||
schema.node('paragraph', null, [schema.text('Hello')]),
|
||||
]);
|
||||
|
||||
const editorState = createEditorState();
|
||||
const editorView = new EditorView(document.body, { state: editorState });
|
||||
|
||||
insertAtCursor(editorView, schema.text('Hello'), 0);
|
||||
insertAtCursor(editorView, docNode, 0);
|
||||
|
||||
// Check if node was unwrapped and inserted correctly
|
||||
expect(editorView.state.doc.firstChild.firstChild.text).toBe('Hello');
|
||||
@@ -719,329 +626,3 @@ describe('getContentNode', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('getFormattingForEditor', () => {
|
||||
describe('channel-specific formatting', () => {
|
||||
it('returns full formatting for Email channel', () => {
|
||||
const result = getFormattingForEditor('Channel::Email');
|
||||
|
||||
expect(result).toEqual(FORMATTING['Channel::Email']);
|
||||
});
|
||||
|
||||
it('returns full formatting for WebWidget channel', () => {
|
||||
const result = getFormattingForEditor('Channel::WebWidget');
|
||||
|
||||
expect(result).toEqual(FORMATTING['Channel::WebWidget']);
|
||||
});
|
||||
|
||||
it('returns limited formatting for WhatsApp channel', () => {
|
||||
const result = getFormattingForEditor('Channel::Whatsapp');
|
||||
|
||||
expect(result).toEqual(FORMATTING['Channel::Whatsapp']);
|
||||
});
|
||||
|
||||
it('returns no formatting for API channel', () => {
|
||||
const result = getFormattingForEditor('Channel::Api');
|
||||
|
||||
expect(result).toEqual(FORMATTING['Channel::Api']);
|
||||
});
|
||||
|
||||
it('returns limited formatting for FacebookPage channel', () => {
|
||||
const result = getFormattingForEditor('Channel::FacebookPage');
|
||||
|
||||
expect(result).toEqual(FORMATTING['Channel::FacebookPage']);
|
||||
});
|
||||
|
||||
it('returns no formatting for TwitterProfile channel', () => {
|
||||
const result = getFormattingForEditor('Channel::TwitterProfile');
|
||||
|
||||
expect(result).toEqual(FORMATTING['Channel::TwitterProfile']);
|
||||
});
|
||||
|
||||
it('returns no formatting for SMS channel', () => {
|
||||
const result = getFormattingForEditor('Channel::Sms');
|
||||
|
||||
expect(result).toEqual(FORMATTING['Channel::Sms']);
|
||||
});
|
||||
|
||||
it('returns limited formatting for Telegram channel', () => {
|
||||
const result = getFormattingForEditor('Channel::Telegram');
|
||||
|
||||
expect(result).toEqual(FORMATTING['Channel::Telegram']);
|
||||
});
|
||||
|
||||
it('returns formatting for Instagram channel', () => {
|
||||
const result = getFormattingForEditor('Channel::Instagram');
|
||||
|
||||
expect(result).toEqual(FORMATTING['Channel::Instagram']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('context-specific formatting', () => {
|
||||
it('returns default formatting for Context::Default', () => {
|
||||
const result = getFormattingForEditor('Context::Default');
|
||||
|
||||
expect(result).toEqual(FORMATTING['Context::Default']);
|
||||
});
|
||||
|
||||
it('returns signature formatting for Context::MessageSignature', () => {
|
||||
const result = getFormattingForEditor('Context::MessageSignature');
|
||||
|
||||
expect(result).toEqual(FORMATTING['Context::MessageSignature']);
|
||||
});
|
||||
|
||||
it('returns widget builder formatting for Context::InboxSettings', () => {
|
||||
const result = getFormattingForEditor('Context::InboxSettings');
|
||||
|
||||
expect(result).toEqual(FORMATTING['Context::InboxSettings']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('fallback behavior', () => {
|
||||
it('returns default formatting for unknown channel type', () => {
|
||||
const result = getFormattingForEditor('Channel::Unknown');
|
||||
|
||||
expect(result).toEqual(FORMATTING['Context::Default']);
|
||||
});
|
||||
|
||||
it('returns default formatting for null channel type', () => {
|
||||
const result = getFormattingForEditor(null);
|
||||
|
||||
expect(result).toEqual(FORMATTING['Context::Default']);
|
||||
});
|
||||
|
||||
it('returns default formatting for undefined channel type', () => {
|
||||
const result = getFormattingForEditor(undefined);
|
||||
|
||||
expect(result).toEqual(FORMATTING['Context::Default']);
|
||||
});
|
||||
|
||||
it('returns default formatting for empty string', () => {
|
||||
const result = getFormattingForEditor('');
|
||||
|
||||
expect(result).toEqual(FORMATTING['Context::Default']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('return value structure', () => {
|
||||
it('always returns an object with marks, nodes, and menu properties', () => {
|
||||
const result = getFormattingForEditor('Channel::Email');
|
||||
|
||||
expect(result).toHaveProperty('marks');
|
||||
expect(result).toHaveProperty('nodes');
|
||||
expect(result).toHaveProperty('menu');
|
||||
expect(Array.isArray(result.marks)).toBe(true);
|
||||
expect(Array.isArray(result.nodes)).toBe(true);
|
||||
expect(Array.isArray(result.menu)).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('stripUnsupportedFormatting', () => {
|
||||
describe('when schema supports all formatting', () => {
|
||||
const fullSchema = {
|
||||
marks: { strong: {}, em: {}, code: {}, strike: {}, link: {} },
|
||||
nodes: { bulletList: {}, orderedList: {}, codeBlock: {}, blockquote: {} },
|
||||
};
|
||||
|
||||
it('preserves all formatting when schema supports it', () => {
|
||||
const content = '**bold** and *italic* and `code`';
|
||||
expect(stripUnsupportedFormatting(content, fullSchema)).toBe(content);
|
||||
});
|
||||
|
||||
it('preserves links when schema supports them', () => {
|
||||
const content = 'Check [this link](https://example.com)';
|
||||
expect(stripUnsupportedFormatting(content, fullSchema)).toBe(content);
|
||||
});
|
||||
|
||||
it('preserves lists when schema supports them', () => {
|
||||
const content = '- item 1\n- item 2\n1. first\n2. second';
|
||||
expect(stripUnsupportedFormatting(content, fullSchema)).toBe(content);
|
||||
});
|
||||
});
|
||||
|
||||
describe('when schema has no formatting support (eg:SMS channel)', () => {
|
||||
const emptySchema = {
|
||||
marks: {},
|
||||
nodes: {},
|
||||
};
|
||||
|
||||
it('strips bold formatting', () => {
|
||||
expect(stripUnsupportedFormatting('**bold text**', emptySchema)).toBe(
|
||||
'bold text'
|
||||
);
|
||||
expect(stripUnsupportedFormatting('__bold text__', emptySchema)).toBe(
|
||||
'bold text'
|
||||
);
|
||||
});
|
||||
|
||||
it('strips italic formatting', () => {
|
||||
expect(stripUnsupportedFormatting('*italic text*', emptySchema)).toBe(
|
||||
'italic text'
|
||||
);
|
||||
expect(stripUnsupportedFormatting('_italic text_', emptySchema)).toBe(
|
||||
'italic text'
|
||||
);
|
||||
});
|
||||
|
||||
it('strips inline code formatting', () => {
|
||||
expect(stripUnsupportedFormatting('`inline code`', emptySchema)).toBe(
|
||||
'inline code'
|
||||
);
|
||||
});
|
||||
|
||||
it('strips strikethrough formatting', () => {
|
||||
expect(stripUnsupportedFormatting('~~strikethrough~~', emptySchema)).toBe(
|
||||
'strikethrough'
|
||||
);
|
||||
});
|
||||
|
||||
it('strips links but keeps text', () => {
|
||||
expect(
|
||||
stripUnsupportedFormatting(
|
||||
'Check [this link](https://example.com)',
|
||||
emptySchema
|
||||
)
|
||||
).toBe('Check this link');
|
||||
});
|
||||
|
||||
it('strips bullet list markers', () => {
|
||||
expect(
|
||||
stripUnsupportedFormatting('- item 1\n- item 2', emptySchema)
|
||||
).toBe('item 1\nitem 2');
|
||||
expect(
|
||||
stripUnsupportedFormatting('* item 1\n* item 2', emptySchema)
|
||||
).toBe('item 1\nitem 2');
|
||||
});
|
||||
|
||||
it('strips ordered list markers', () => {
|
||||
expect(
|
||||
stripUnsupportedFormatting('1. first\n2. second', emptySchema)
|
||||
).toBe('first\nsecond');
|
||||
});
|
||||
|
||||
it('strips code block markers', () => {
|
||||
expect(
|
||||
stripUnsupportedFormatting('```javascript\ncode here\n```', emptySchema)
|
||||
).toBe('code here\n');
|
||||
});
|
||||
|
||||
it('strips blockquote markers', () => {
|
||||
expect(stripUnsupportedFormatting('> quoted text', emptySchema)).toBe(
|
||||
'quoted text'
|
||||
);
|
||||
});
|
||||
|
||||
it('handles complex content with multiple formatting types', () => {
|
||||
const content =
|
||||
'**Bold** and *italic* with `code` and [link](url)\n- list item';
|
||||
const expected = 'Bold and italic with code and link\nlist item';
|
||||
expect(stripUnsupportedFormatting(content, emptySchema)).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('when schema has partial support', () => {
|
||||
const partialSchema = {
|
||||
marks: { strong: {}, em: {} },
|
||||
nodes: {},
|
||||
};
|
||||
|
||||
it('preserves supported marks and strips unsupported ones', () => {
|
||||
const content = '**bold** and `code`';
|
||||
expect(stripUnsupportedFormatting(content, partialSchema)).toBe(
|
||||
'**bold** and code'
|
||||
);
|
||||
});
|
||||
|
||||
it('strips unsupported nodes but keeps supported marks', () => {
|
||||
const content = '**bold** text\n- list item';
|
||||
expect(stripUnsupportedFormatting(content, partialSchema)).toBe(
|
||||
'**bold** text\nlist item'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('edge cases', () => {
|
||||
it('returns content unchanged if content is empty', () => {
|
||||
expect(stripUnsupportedFormatting('', {})).toBe('');
|
||||
});
|
||||
|
||||
it('returns content unchanged if content is null', () => {
|
||||
expect(stripUnsupportedFormatting(null, {})).toBe(null);
|
||||
});
|
||||
|
||||
it('returns content unchanged if content is undefined', () => {
|
||||
expect(stripUnsupportedFormatting(undefined, {})).toBe(undefined);
|
||||
});
|
||||
|
||||
it('returns content unchanged if schema is null', () => {
|
||||
expect(stripUnsupportedFormatting('**bold**', null)).toBe('**bold**');
|
||||
});
|
||||
|
||||
it('handles nested formatting correctly', () => {
|
||||
const emptySchema = { marks: {}, nodes: {} };
|
||||
// After stripping bold (**), the remaining *and italic* becomes italic and is stripped too
|
||||
expect(
|
||||
stripUnsupportedFormatting('**bold *and italic***', emptySchema)
|
||||
).toBe('bold and italic');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Menu positioning helpers', () => {
|
||||
const mockEditorView = {
|
||||
coordsAtPos: vi.fn((pos, bias) => {
|
||||
// Return different coords based on position
|
||||
if (bias === 1) return { top: 100, bottom: 120, left: 50, right: 100 };
|
||||
return { top: 100, bottom: 120, left: 150, right: 200 };
|
||||
}),
|
||||
};
|
||||
|
||||
const wrapperRect = { top: 50, bottom: 300, left: 0, right: 400, width: 400 };
|
||||
|
||||
describe('getSelectionCoords', () => {
|
||||
it('returns selection coordinates with onTop flag', () => {
|
||||
const selection = { from: 0, to: 10 };
|
||||
const result = getSelectionCoords(mockEditorView, selection, wrapperRect);
|
||||
|
||||
expect(result).toHaveProperty('start');
|
||||
expect(result).toHaveProperty('end');
|
||||
expect(result).toHaveProperty('selTop');
|
||||
expect(result).toHaveProperty('onTop');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getMenuAnchor', () => {
|
||||
it('returns end.left when menu is below selection', () => {
|
||||
const coords = { start: { left: 50 }, end: { left: 150 }, onTop: false };
|
||||
expect(getMenuAnchor(coords, wrapperRect, false)).toBe(150);
|
||||
});
|
||||
|
||||
it('returns start.left for LTR when menu is above and visible', () => {
|
||||
const coords = { start: { top: 100, left: 50 }, end: {}, onTop: true };
|
||||
expect(getMenuAnchor(coords, wrapperRect, false)).toBe(50);
|
||||
});
|
||||
|
||||
it('returns start.right for RTL when menu is above and visible', () => {
|
||||
const coords = { start: { top: 100, right: 100 }, end: {}, onTop: true };
|
||||
expect(getMenuAnchor(coords, wrapperRect, true)).toBe(100);
|
||||
});
|
||||
});
|
||||
|
||||
describe('calculateMenuPosition', () => {
|
||||
it('returns bounded left and top positions', () => {
|
||||
const coords = {
|
||||
start: { top: 100, bottom: 120, left: 50 },
|
||||
end: { top: 100, bottom: 120, left: 150 },
|
||||
selTop: 100,
|
||||
onTop: false,
|
||||
};
|
||||
const result = calculateMenuPosition(coords, wrapperRect, false);
|
||||
|
||||
expect(result).toHaveProperty('left');
|
||||
expect(result).toHaveProperty('top');
|
||||
expect(result).toHaveProperty('width', 300);
|
||||
expect(result.left).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -20,7 +20,8 @@
|
||||
"CHANGE_STATUS": "Change status",
|
||||
"SNOOZE_UNTIL": "Snooze",
|
||||
"UPDATE_SUCCESFUL": "Conversation status updated successfully.",
|
||||
"UPDATE_FAILED": "Failed to update conversations. Please try again."
|
||||
"UPDATE_FAILED": "Failed to update conversations. Please try again.",
|
||||
"REQUIRED_ATTRIBUTES_MISSING": "Some conversations need required attributes before resolving and were skipped."
|
||||
},
|
||||
"LABELS": {
|
||||
"ASSIGN_LABELS": "Assign labels",
|
||||
|
||||
@@ -196,6 +196,7 @@
|
||||
"INSERT_READ_MORE": "Read more",
|
||||
"DISMISS_REPLY": "Dismiss reply",
|
||||
"REPLYING_TO": "Replying to:",
|
||||
"TIP_FORMAT_ICON": "Show rich text editor",
|
||||
"TIP_EMOJI_ICON": "Show emoji selector",
|
||||
"TIP_ATTACH_ICON": "Attach files",
|
||||
"TIP_AUDIORECORDER_ICON": "Record audio",
|
||||
|
||||
@@ -377,7 +377,8 @@
|
||||
"INFO_SHORT": "Automatically mark offline when you aren't using the app."
|
||||
},
|
||||
"DOCS": "Read docs",
|
||||
"SECURITY": "Security"
|
||||
"SECURITY": "Security",
|
||||
"CONVERSATION_WORKFLOW": "Conversation Workflow"
|
||||
},
|
||||
"BILLING_SETTINGS": {
|
||||
"TITLE": "Billing",
|
||||
@@ -399,39 +400,15 @@
|
||||
"DESCRIPTION": "Manage usage and credits for Captain AI.",
|
||||
"BUTTON_TXT": "Buy more credits",
|
||||
"DOCUMENTS": "Documents",
|
||||
"RESPONSES": "Credits",
|
||||
"UPGRADE": "Captain is not available on the free plan, upgrade now to get access to assistants, copilot and more.",
|
||||
"REFRESH_CREDITS": "Refresh"
|
||||
"RESPONSES": "Responses",
|
||||
"UPGRADE": "Captain is not available on the free plan, upgrade now to get access to assistants, copilot and more."
|
||||
},
|
||||
"CHAT_WITH_US": {
|
||||
"TITLE": "Need help?",
|
||||
"DESCRIPTION": "Do you face any issues in billing? We are here to help.",
|
||||
"BUTTON_TXT": "Chat with us"
|
||||
},
|
||||
"NO_BILLING_USER": "Your billing account is being configured. Please refresh the page and try again.",
|
||||
"TOPUP": {
|
||||
"BUY_CREDITS": "Buy more credits",
|
||||
"MODAL_TITLE": "Buy AI Credits",
|
||||
"MODAL_DESCRIPTION": "Purchase additional credits for Captain AI.",
|
||||
"CREDITS": "CREDITS",
|
||||
"ONE_TIME": "one-time",
|
||||
"POPULAR": "Most Popular",
|
||||
"NOTE_TITLE": "Note:",
|
||||
"NOTE_DESCRIPTION": "Credits are added immediately and expire in 6 months. An active subscription is required to use credits. Purchased credits are consumed after your monthly plan credits.",
|
||||
"CANCEL": "Cancel",
|
||||
"PURCHASE": "Purchase Credits",
|
||||
"LOADING": "Loading options...",
|
||||
"FETCH_ERROR": "Failed to load credit options. Please try again.",
|
||||
"PURCHASE_ERROR": "Failed to process purchase. Please try again.",
|
||||
"PURCHASE_SUCCESS": "Successfully added {credits} credits to your account",
|
||||
"CONFIRM": {
|
||||
"TITLE": "Confirm Purchase",
|
||||
"DESCRIPTION": "You are about to purchase {credits} credits for {amount}.",
|
||||
"INSTANT_DEDUCTION_NOTE": "Your saved card will be charged immediately upon confirmation.",
|
||||
"GO_BACK": "Go Back",
|
||||
"CONFIRM_PURCHASE": "Confirm Purchase"
|
||||
}
|
||||
}
|
||||
"NO_BILLING_USER": "Your billing account is being configured. Please refresh the page and try again."
|
||||
},
|
||||
"SECURITY_SETTINGS": {
|
||||
"TITLE": "Security",
|
||||
@@ -505,6 +482,46 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"CONVERSATION_WORKFLOW": {
|
||||
"INDEX": {
|
||||
"HEADER": {
|
||||
"TITLE": "Conversation Workflows",
|
||||
"DESCRIPTION": "Configure rules and required fields for conversation resolution."
|
||||
}
|
||||
},
|
||||
"REQUIRED_ATTRIBUTES": {
|
||||
"TITLE": "Attributes required on resolution",
|
||||
"DESCRIPTION": "When resolving a conversation, agents will be prompted to fill these attributes if they haven't yet.",
|
||||
"NO_ATTRIBUTES": "No attributes added yet",
|
||||
"ADD": {
|
||||
"TITLE": "Add Attributes",
|
||||
"SEARCH_PLACEHOLDER": "Search attributes"
|
||||
},
|
||||
"SAVE": {
|
||||
"SUCCESS": "Required attributes updated",
|
||||
"ERROR": "Could not update required attributes, please try again"
|
||||
},
|
||||
"MODAL": {
|
||||
"TITLE": "Resolve conversation",
|
||||
"DESCRIPTION": "Please fill in the following custom attributes before resolving this conversation",
|
||||
"ACTIONS": {
|
||||
"RESOLVE": "Resolve conversation",
|
||||
"CANCEL": "Cancel"
|
||||
},
|
||||
"PLACEHOLDERS": {
|
||||
"TEXT": "Write a note...",
|
||||
"NUMBER": "Enter a number",
|
||||
"LINK": "Add a link",
|
||||
"DATE": "Pick a date",
|
||||
"LIST": "Select an option"
|
||||
},
|
||||
"CHECKBOX": {
|
||||
"YES": "Yes",
|
||||
"NO": "No"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"CREATE_ACCOUNT": {
|
||||
"NO_ACCOUNT_WARNING": "Uh oh! We could not find any Chatwoot accounts. Please create a new account to continue.",
|
||||
"NEW_ACCOUNT": "New Account",
|
||||
|
||||
@@ -5,9 +5,7 @@ import {
|
||||
useFunctionGetter,
|
||||
useStore,
|
||||
} from 'dashboard/composables/store';
|
||||
import { useAccount } from 'dashboard/composables/useAccount';
|
||||
import { useUISettings } from 'dashboard/composables/useUISettings';
|
||||
import { FEATURE_FLAGS } from 'dashboard/featureFlags';
|
||||
|
||||
import AccordionItem from 'dashboard/components/Accordion/AccordionItem.vue';
|
||||
import ContactConversations from './ContactConversations.vue';
|
||||
@@ -54,22 +52,12 @@ const isShopifyFeatureEnabled = computed(
|
||||
() => shopifyIntegration.value.enabled
|
||||
);
|
||||
|
||||
const { isCloudFeatureEnabled } = useAccount();
|
||||
|
||||
const isLinearFeatureEnabled = computed(() =>
|
||||
isCloudFeatureEnabled(FEATURE_FLAGS.LINEAR)
|
||||
);
|
||||
|
||||
const linearIntegration = useFunctionGetter(
|
||||
'integrations/getIntegration',
|
||||
'linear'
|
||||
);
|
||||
|
||||
const isLinearClientIdConfigured = computed(() => {
|
||||
return !!linearIntegration.value?.id;
|
||||
});
|
||||
|
||||
const isLinearConnected = computed(
|
||||
const isLinearIntegrationEnabled = computed(
|
||||
() => linearIntegration.value?.enabled || false
|
||||
);
|
||||
|
||||
@@ -250,13 +238,7 @@ onMounted(() => {
|
||||
<MacrosList :conversation-id="conversationId" />
|
||||
</AccordionItem>
|
||||
</woot-feature-toggle>
|
||||
<div
|
||||
v-else-if="
|
||||
element.name === 'linear_issues' &&
|
||||
isLinearFeatureEnabled &&
|
||||
isLinearClientIdConfigured
|
||||
"
|
||||
>
|
||||
<div v-else-if="element.name === 'linear_issues'">
|
||||
<AccordionItem
|
||||
:title="$t('CONVERSATION_SIDEBAR.ACCORDION.LINEAR_ISSUES')"
|
||||
:is-open="isContactSidebarItemOpen('is_linear_issues_open')"
|
||||
@@ -265,7 +247,7 @@ onMounted(() => {
|
||||
value => toggleSidebarUIState('is_linear_issues_open', value)
|
||||
"
|
||||
>
|
||||
<LinearSetupCTA v-if="!isLinearConnected" />
|
||||
<LinearSetupCTA v-if="!isLinearIntegrationEnabled" />
|
||||
<LinearIssuesList v-else :conversation-id="conversationId" />
|
||||
</AccordionItem>
|
||||
</div>
|
||||
|
||||
@@ -2,20 +2,32 @@
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
import BaseSettingsHeader from '../components/BaseSettingsHeader.vue';
|
||||
import AddAttribute from './AddAttribute.vue';
|
||||
import CustomAttribute from './CustomAttribute.vue';
|
||||
import EditAttribute from './EditAttribute.vue';
|
||||
import SettingsLayout from '../SettingsLayout.vue';
|
||||
import Button from 'dashboard/components-next/button/Button.vue';
|
||||
import TabBar from 'dashboard/components-next/tabbar/TabBar.vue';
|
||||
import AttributeListItem from 'dashboard/components-next/ConversationWorkflow/AttributeListItem.vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useStoreGetters, useStore } from 'dashboard/composables/store';
|
||||
import {
|
||||
useStoreGetters,
|
||||
useStore,
|
||||
useMapGetter,
|
||||
} from 'dashboard/composables/store';
|
||||
import { useAccount } from 'dashboard/composables/useAccount';
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const getters = useStoreGetters();
|
||||
const store = useStore();
|
||||
const { currentAccount } = useAccount();
|
||||
const inboxes = useMapGetter('inboxes/getInboxes');
|
||||
|
||||
const showAddPopup = ref(false);
|
||||
const selectedTabIndex = ref(0);
|
||||
const uiFlags = computed(() => getters['attributes/getUIFlags'].value);
|
||||
const showEditPopup = ref(false);
|
||||
const showDeletePopup = ref(false);
|
||||
const selectedAttribute = ref({});
|
||||
|
||||
const openAddPopup = () => {
|
||||
showAddPopup.value = true;
|
||||
@@ -23,6 +35,14 @@ const openAddPopup = () => {
|
||||
const hideAddPopup = () => {
|
||||
showAddPopup.value = false;
|
||||
};
|
||||
const hideEditPopup = () => {
|
||||
showEditPopup.value = false;
|
||||
selectedAttribute.value = {};
|
||||
};
|
||||
const closeDelete = () => {
|
||||
showDeletePopup.value = false;
|
||||
selectedAttribute.value = {};
|
||||
};
|
||||
|
||||
const tabs = computed(() => {
|
||||
return [
|
||||
@@ -49,9 +69,63 @@ const attributes = computed(() =>
|
||||
getters['attributes/getAttributesByModel'].value(attributeModel.value)
|
||||
);
|
||||
|
||||
const onClickTabChange = index => {
|
||||
selectedTabIndex.value = index;
|
||||
const onClickTabChange = payload => {
|
||||
selectedTabIndex.value = typeof payload === 'number' ? payload : payload?.key;
|
||||
};
|
||||
|
||||
const handleEditAttribute = attribute => {
|
||||
selectedAttribute.value = attribute;
|
||||
showEditPopup.value = true;
|
||||
};
|
||||
|
||||
const handleDeleteAttribute = attribute => {
|
||||
selectedAttribute.value = attribute;
|
||||
showDeletePopup.value = true;
|
||||
};
|
||||
|
||||
const requiredAttributeKeys = computed(
|
||||
() => currentAccount.value?.settings?.conversation_required_attributes || []
|
||||
);
|
||||
|
||||
const hasPreChatBadge = attribute => {
|
||||
return (inboxes.value || []).some(inbox => {
|
||||
const fields =
|
||||
inbox?.pre_chat_form_options?.pre_chat_fields ||
|
||||
inbox?.channel?.pre_chat_form_options?.pre_chat_fields ||
|
||||
[];
|
||||
return fields.some(field => field.name === attribute.attribute_key);
|
||||
});
|
||||
};
|
||||
|
||||
const buildBadges = attribute => {
|
||||
const badges = [];
|
||||
if (hasPreChatBadge(attribute)) {
|
||||
badges.push({
|
||||
type: 'pre-chat',
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
attribute.attribute_model === 'conversation_attribute' &&
|
||||
requiredAttributeKeys.value.includes(attribute.attribute_key)
|
||||
) {
|
||||
badges.push({
|
||||
type: 'resolution',
|
||||
});
|
||||
}
|
||||
|
||||
return badges;
|
||||
};
|
||||
|
||||
const derivedAttributes = computed(() =>
|
||||
attributes.value.map(attribute => ({
|
||||
...attribute,
|
||||
label: attribute.attribute_display_name,
|
||||
type: attribute.attribute_display_type,
|
||||
value: attribute.attribute_key,
|
||||
badges: buildBadges(attribute),
|
||||
}))
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -77,27 +151,25 @@ const onClickTabChange = index => {
|
||||
</template>
|
||||
</BaseSettingsHeader>
|
||||
</template>
|
||||
<template #preBody>
|
||||
<woot-tabs
|
||||
class="font-medium [&_ul]:p-0 mb-4"
|
||||
:index="selectedTabIndex"
|
||||
@change="onClickTabChange"
|
||||
>
|
||||
<woot-tabs-item
|
||||
v-for="(tab, index) in tabs"
|
||||
:key="tab.key"
|
||||
:index="index"
|
||||
:name="tab.name"
|
||||
:show-badge="false"
|
||||
is-compact
|
||||
/>
|
||||
</woot-tabs>
|
||||
</template>
|
||||
<template #body>
|
||||
<CustomAttribute
|
||||
:key="attributeModel"
|
||||
:attribute-model="attributeModel"
|
||||
/>
|
||||
<div class="flex flex-col gap-6">
|
||||
<TabBar
|
||||
:tabs="tabs.map(tab => ({ label: tab.name, key: tab.key }))"
|
||||
:initial-active-tab="selectedTabIndex"
|
||||
class="max-w-xl"
|
||||
@change="onClickTabChange"
|
||||
/>
|
||||
<div class="grid gap-3">
|
||||
<AttributeListItem
|
||||
v-for="attribute in derivedAttributes"
|
||||
:key="attribute.id"
|
||||
:attribute="attribute"
|
||||
:badges="attribute.badges"
|
||||
@edit="handleEditAttribute"
|
||||
@delete="handleDeleteAttribute"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<AddAttribute
|
||||
v-if="showAddPopup"
|
||||
@@ -105,5 +177,39 @@ const onClickTabChange = index => {
|
||||
:on-close="hideAddPopup"
|
||||
:selected-attribute-model-tab="selectedTabIndex"
|
||||
/>
|
||||
<woot-modal v-model:show="showEditPopup" :on-close="hideEditPopup">
|
||||
<EditAttribute
|
||||
:selected-attribute="selectedAttribute"
|
||||
:is-updating="uiFlags.isUpdating"
|
||||
@on-close="hideEditPopup"
|
||||
/>
|
||||
</woot-modal>
|
||||
<woot-confirm-delete-modal
|
||||
v-if="showDeletePopup"
|
||||
v-model:show="showDeletePopup"
|
||||
:title="
|
||||
$t('ATTRIBUTES_MGMT.DELETE.CONFIRM.TITLE', {
|
||||
attributeName: selectedAttribute.attribute_display_name,
|
||||
})
|
||||
"
|
||||
:message="$t('ATTRIBUTES_MGMT.DELETE.CONFIRM.MESSAGE')"
|
||||
:confirm-text="`${$t('ATTRIBUTES_MGMT.DELETE.CONFIRM.YES')} ${
|
||||
selectedAttribute.attribute_display_name || ''
|
||||
}`"
|
||||
:reject-text="$t('ATTRIBUTES_MGMT.DELETE.CONFIRM.NO')"
|
||||
:confirm-value="selectedAttribute.attribute_display_name"
|
||||
:confirm-place-holder-text="
|
||||
$t('ATTRIBUTES_MGMT.DELETE.CONFIRM.PLACE_HOLDER', {
|
||||
attributeName: selectedAttribute.attribute_display_name,
|
||||
})
|
||||
"
|
||||
@on-confirm="
|
||||
() => {
|
||||
store.dispatch('attributes/delete', selectedAttribute.id);
|
||||
closeDelete();
|
||||
}
|
||||
"
|
||||
@on-close="closeDelete"
|
||||
/>
|
||||
</SettingsLayout>
|
||||
</template>
|
||||
|
||||
@@ -11,7 +11,6 @@ import BillingMeter from './components/BillingMeter.vue';
|
||||
import BillingCard from './components/BillingCard.vue';
|
||||
import BillingHeader from './components/BillingHeader.vue';
|
||||
import DetailItem from './components/DetailItem.vue';
|
||||
import PurchaseCreditsModal from './components/PurchaseCreditsModal.vue';
|
||||
import BaseSettingsHeader from '../components/BaseSettingsHeader.vue';
|
||||
import SettingsLayout from '../SettingsLayout.vue';
|
||||
import ButtonV4 from 'next/button/Button.vue';
|
||||
@@ -24,7 +23,6 @@ const {
|
||||
documentLimits,
|
||||
responseLimits,
|
||||
fetchLimits,
|
||||
isFetchingLimits,
|
||||
} = useCaptain();
|
||||
|
||||
const uiFlags = useMapGetter('accounts/getUIFlags');
|
||||
@@ -34,7 +32,6 @@ const BILLING_REFRESH_ATTEMPTED = 'billing_refresh_attempted';
|
||||
|
||||
// State for handling refresh attempts and loading
|
||||
const isWaitingForBilling = ref(false);
|
||||
const purchaseCreditsModalRef = ref(null);
|
||||
|
||||
const customAttributes = computed(() => {
|
||||
return currentAccount.value.custom_attributes || {};
|
||||
@@ -48,11 +45,6 @@ const planName = computed(() => {
|
||||
return customAttributes.value.plan_name;
|
||||
});
|
||||
|
||||
const canPurchaseCredits = computed(() => {
|
||||
const plan = planName.value?.toLowerCase();
|
||||
return plan && plan !== 'hacker';
|
||||
});
|
||||
|
||||
/**
|
||||
* Computed property for subscribed quantity
|
||||
* @returns {number|undefined}
|
||||
@@ -79,9 +71,8 @@ const hasABillingPlan = computed(() => {
|
||||
const fetchAccountDetails = async () => {
|
||||
if (!hasABillingPlan.value) {
|
||||
await store.dispatch('accounts/subscription');
|
||||
fetchLimits();
|
||||
}
|
||||
// Always fetch limits for billing page to show credit usage
|
||||
fetchLimits();
|
||||
};
|
||||
|
||||
const handleBillingPageLogic = async () => {
|
||||
@@ -128,15 +119,6 @@ const onToggleChatWindow = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const openPurchaseCreditsModal = () => {
|
||||
purchaseCreditsModalRef.value?.open();
|
||||
};
|
||||
|
||||
const handleTopupSuccess = () => {
|
||||
// Refresh limits to show updated credit balance
|
||||
fetchLimits();
|
||||
};
|
||||
|
||||
onMounted(handleBillingPageLogic);
|
||||
</script>
|
||||
|
||||
@@ -196,27 +178,9 @@ onMounted(handleBillingPageLogic);
|
||||
:description="$t('BILLING_SETTINGS.CAPTAIN.DESCRIPTION')"
|
||||
>
|
||||
<template #action>
|
||||
<div class="flex gap-2">
|
||||
<ButtonV4
|
||||
sm
|
||||
flushed
|
||||
slate
|
||||
icon="i-lucide-refresh-cw"
|
||||
:is-loading="isFetchingLimits"
|
||||
@click="fetchLimits"
|
||||
>
|
||||
{{ $t('BILLING_SETTINGS.CAPTAIN.REFRESH_CREDITS') }}
|
||||
</ButtonV4>
|
||||
<ButtonV4
|
||||
v-if="canPurchaseCredits"
|
||||
sm
|
||||
solid
|
||||
blue
|
||||
@click="openPurchaseCreditsModal"
|
||||
>
|
||||
{{ $t('BILLING_SETTINGS.TOPUP.BUY_CREDITS') }}
|
||||
</ButtonV4>
|
||||
</div>
|
||||
<ButtonV4 sm faded slate disabled>
|
||||
{{ $t('BILLING_SETTINGS.CAPTAIN.BUTTON_TXT') }}
|
||||
</ButtonV4>
|
||||
</template>
|
||||
<div v-if="captainLimits && responseLimits" class="px-5">
|
||||
<BillingMeter
|
||||
@@ -259,10 +223,6 @@ onMounted(handleBillingPageLogic);
|
||||
</ButtonV4>
|
||||
</BillingHeader>
|
||||
</section>
|
||||
<PurchaseCreditsModal
|
||||
ref="purchaseCreditsModalRef"
|
||||
@success="handleTopupSuccess"
|
||||
/>
|
||||
</template>
|
||||
</SettingsLayout>
|
||||
</template>
|
||||
|
||||
-101
@@ -1,101 +0,0 @@
|
||||
<script setup>
|
||||
defineProps({
|
||||
credits: {
|
||||
type: Number,
|
||||
required: true,
|
||||
},
|
||||
amount: {
|
||||
type: Number,
|
||||
required: true,
|
||||
},
|
||||
currency: {
|
||||
type: String,
|
||||
default: 'usd',
|
||||
},
|
||||
isSelected: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
isPopular: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
name: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
});
|
||||
|
||||
const emit = defineEmits(['select']);
|
||||
|
||||
const formatCredits = credits => {
|
||||
return credits.toLocaleString();
|
||||
};
|
||||
|
||||
const formatAmount = (amount, currency) => {
|
||||
return new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency: currency.toUpperCase(),
|
||||
minimumFractionDigits: 0,
|
||||
}).format(amount);
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<label
|
||||
class="relative flex flex-col p-6 border-2 rounded-xl transition-all cursor-pointer bg-n-solid-1 hover:bg-n-solid-2"
|
||||
:class="[
|
||||
isSelected ? 'border-woot-500' : 'border-n-weak hover:border-n-strong',
|
||||
]"
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
:name="name"
|
||||
:value="credits"
|
||||
:checked="isSelected"
|
||||
class="sr-only"
|
||||
@change="emit('select')"
|
||||
/>
|
||||
<span
|
||||
v-if="isPopular"
|
||||
class="absolute -top-3 left-4 px-3 py-1 text-xs font-medium rounded"
|
||||
:class="
|
||||
isSelected ? 'bg-woot-500 text-white' : 'bg-n-solid-3 text-n-slate-11'
|
||||
"
|
||||
>
|
||||
{{ $t('BILLING_SETTINGS.TOPUP.POPULAR') }}
|
||||
</span>
|
||||
<div
|
||||
v-if="isSelected"
|
||||
class="absolute top-4 right-4 flex items-center justify-center w-6 h-6 rounded-full bg-woot-500"
|
||||
>
|
||||
<svg
|
||||
class="w-4 h-4 text-white"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M5 13l4 4L19 7"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<span class="text-3xl font-normal text-n-slate-12 mb-2 tracking-tighter">
|
||||
{{ formatCredits(credits) }}
|
||||
</span>
|
||||
<span
|
||||
class="text-xs font-normal text-n-slate-11 uppercase tracking-tight mb-6"
|
||||
>
|
||||
{{ $t('BILLING_SETTINGS.TOPUP.CREDITS') }}
|
||||
</span>
|
||||
<span class="text-2xl font-normal text-n-slate-12 tracking-tight">
|
||||
{{ formatAmount(amount, currency) }}
|
||||
<span class="text-sm text-n-slate-11 ml-0.5">{{
|
||||
$t('BILLING_SETTINGS.TOPUP.ONE_TIME')
|
||||
}}</span>
|
||||
</span>
|
||||
</label>
|
||||
</template>
|
||||
-220
@@ -1,220 +0,0 @@
|
||||
<script setup>
|
||||
import { ref, computed } from 'vue';
|
||||
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 CreditPackageCard from './CreditPackageCard.vue';
|
||||
import EnterpriseAccountAPI from 'dashboard/api/enterprise/account';
|
||||
|
||||
const emit = defineEmits(['close', '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';
|
||||
|
||||
const dialogRef = ref(null);
|
||||
const selectedCredits = ref(null);
|
||||
const isLoading = ref(false);
|
||||
const currentStep = ref(STEP_SELECT);
|
||||
|
||||
const selectedOption = computed(() => {
|
||||
return TOPUP_OPTIONS.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 formattedCredits = computed(() => {
|
||||
if (!selectedOption.value) return '';
|
||||
return selectedOption.value.credits.toLocaleString();
|
||||
});
|
||||
|
||||
const dialogTitle = computed(() => {
|
||||
return currentStep.value === STEP_SELECT
|
||||
? t('BILLING_SETTINGS.TOPUP.MODAL_TITLE')
|
||||
: t('BILLING_SETTINGS.TOPUP.CONFIRM.TITLE');
|
||||
});
|
||||
|
||||
const dialogDescription = computed(() => {
|
||||
return currentStep.value === STEP_SELECT
|
||||
? t('BILLING_SETTINGS.TOPUP.MODAL_DESCRIPTION')
|
||||
: '';
|
||||
});
|
||||
|
||||
const dialogWidth = computed(() => {
|
||||
return currentStep.value === STEP_SELECT ? 'xl' : 'md';
|
||||
});
|
||||
|
||||
const handlePackageSelect = credits => {
|
||||
selectedCredits.value = credits;
|
||||
};
|
||||
|
||||
const open = () => {
|
||||
const popularOption = TOPUP_OPTIONS.find(
|
||||
o => o.credits === POPULAR_CREDITS_AMOUNT
|
||||
);
|
||||
selectedCredits.value = popularOption?.credits || TOPUP_OPTIONS[0]?.credits;
|
||||
currentStep.value = STEP_SELECT;
|
||||
isLoading.value = false;
|
||||
dialogRef.value?.open();
|
||||
};
|
||||
|
||||
const close = () => {
|
||||
dialogRef.value?.close();
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
emit('close');
|
||||
};
|
||||
|
||||
const goToConfirmStep = () => {
|
||||
if (!selectedOption.value) return;
|
||||
currentStep.value = STEP_CONFIRM;
|
||||
};
|
||||
|
||||
const goBackToSelectStep = () => {
|
||||
currentStep.value = STEP_SELECT;
|
||||
};
|
||||
|
||||
const handlePurchase = async () => {
|
||||
if (!selectedOption.value) return;
|
||||
|
||||
isLoading.value = true;
|
||||
try {
|
||||
const response = await EnterpriseAccountAPI.createTopupCheckout(
|
||||
selectedOption.value.credits
|
||||
);
|
||||
|
||||
close();
|
||||
emit('success', response.data);
|
||||
useAlert(
|
||||
t('BILLING_SETTINGS.TOPUP.PURCHASE_SUCCESS', {
|
||||
credits: response.data.credits,
|
||||
})
|
||||
);
|
||||
} catch (error) {
|
||||
const errorMessage =
|
||||
error.response?.data?.error || t('BILLING_SETTINGS.TOPUP.PURCHASE_ERROR');
|
||||
useAlert(errorMessage);
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
defineExpose({ open, close });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog
|
||||
ref="dialogRef"
|
||||
:title="dialogTitle"
|
||||
:description="dialogDescription"
|
||||
: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)"
|
||||
/>
|
||||
</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>
|
||||
|
||||
<!-- Step 2: Confirm Purchase -->
|
||||
<template v-else>
|
||||
<div class="flex flex-col gap-4">
|
||||
<p class="text-sm text-n-slate-11">
|
||||
{{
|
||||
$t('BILLING_SETTINGS.TOPUP.CONFIRM.DESCRIPTION', {
|
||||
credits: formattedCredits,
|
||||
amount: formattedAmount,
|
||||
})
|
||||
}}
|
||||
</p>
|
||||
|
||||
<div class="p-2.5 rounded-lg bg-n-amber-2 border border-n-amber-6">
|
||||
<p class="text-sm text-n-amber-11">
|
||||
{{ $t('BILLING_SETTINGS.TOPUP.CONFIRM.INSTANT_DEDUCTION_NOTE') }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template #footer>
|
||||
<!-- Step 1 Footer -->
|
||||
<div
|
||||
v-if="currentStep === 'select'"
|
||||
class="flex items-center justify-between w-full gap-3"
|
||||
>
|
||||
<Button
|
||||
variant="faded"
|
||||
color="slate"
|
||||
:label="$t('BILLING_SETTINGS.TOPUP.CANCEL')"
|
||||
class="w-full"
|
||||
@click="close"
|
||||
/>
|
||||
<Button
|
||||
color="blue"
|
||||
:label="$t('BILLING_SETTINGS.TOPUP.PURCHASE')"
|
||||
class="w-full"
|
||||
:disabled="!selectedCredits"
|
||||
@click="goToConfirmStep"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Step 2 Footer -->
|
||||
<div v-else class="flex items-center justify-between w-full gap-3">
|
||||
<Button
|
||||
variant="faded"
|
||||
color="slate"
|
||||
:label="$t('BILLING_SETTINGS.TOPUP.CONFIRM.GO_BACK')"
|
||||
class="w-full"
|
||||
:disabled="isLoading"
|
||||
@click="goBackToSelectStep"
|
||||
/>
|
||||
<Button
|
||||
color="blue"
|
||||
:label="$t('BILLING_SETTINGS.TOPUP.CONFIRM.CONFIRM_PURCHASE')"
|
||||
class="w-full"
|
||||
:is-loading="isLoading"
|
||||
@click="handlePurchase"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</Dialog>
|
||||
</template>
|
||||
@@ -110,7 +110,6 @@ export default {
|
||||
v-model="content"
|
||||
class="message-editor [&>div]:px-1"
|
||||
:class="{ editor_warning: v$.content.$error }"
|
||||
channel-type="Context::Default"
|
||||
enable-variables
|
||||
:enable-canned-responses="false"
|
||||
:placeholder="$t('CANNED_MGMT.ADD.FORM.CONTENT.PLACEHOLDER')"
|
||||
|
||||
@@ -114,7 +114,6 @@ export default {
|
||||
v-model="content"
|
||||
class="message-editor [&>div]:px-1"
|
||||
:class="{ editor_warning: v$.content.$error }"
|
||||
channel-type="Context::Default"
|
||||
enable-variables
|
||||
:enable-canned-responses="false"
|
||||
:placeholder="$t('CANNED_MGMT.EDIT.FORM.CONTENT.PLACEHOLDER')"
|
||||
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
import { frontendURL } from '../../../../helper/URLHelper';
|
||||
import SettingsWrapper from '../SettingsWrapper.vue';
|
||||
import ConversationWorkflowIndex from './Index.vue';
|
||||
|
||||
export default {
|
||||
routes: [
|
||||
{
|
||||
path: frontendURL('accounts/:accountId/settings/conversation-workflow'),
|
||||
component: SettingsWrapper,
|
||||
children: [
|
||||
{
|
||||
path: '',
|
||||
redirect: to => {
|
||||
return { name: 'conversation_workflow_index', params: to.params };
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'index',
|
||||
name: 'conversation_workflow_index',
|
||||
component: ConversationWorkflowIndex,
|
||||
meta: {
|
||||
permissions: ['administrator'],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,28 @@
|
||||
<script setup>
|
||||
import BaseSettingsHeader from '../components/BaseSettingsHeader.vue';
|
||||
import SettingsLayout from '../SettingsLayout.vue';
|
||||
import ConversationRequiredAttributes from 'dashboard/components-next/ConversationWorkflow/ConversationRequiredAttributes.vue';
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<SettingsLayout :no-records-found="false" class="gap-10">
|
||||
<template #header>
|
||||
<BaseSettingsHeader
|
||||
:title="$t('CONVERSATION_WORKFLOW.INDEX.HEADER.TITLE')"
|
||||
:description="$t('CONVERSATION_WORKFLOW.INDEX.HEADER.DESCRIPTION')"
|
||||
feature-name="assignment-policy"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<template #body>
|
||||
<div class="flex">
|
||||
<ConversationRequiredAttributes
|
||||
:title="$t('CONVERSATION_WORKFLOW.REQUIRED_ATTRIBUTES.TITLE')"
|
||||
:description="
|
||||
$t('CONVERSATION_WORKFLOW.REQUIRED_ATTRIBUTES.DESCRIPTION')
|
||||
"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</SettingsLayout>
|
||||
</template>
|
||||
@@ -27,6 +27,7 @@ import { FEATURE_FLAGS } from '../../../../featureFlags';
|
||||
import SenderNameExamplePreview from './components/SenderNameExamplePreview.vue';
|
||||
import NextButton from 'dashboard/components-next/button/Button.vue';
|
||||
import { INBOX_TYPES } from 'dashboard/helper/inbox';
|
||||
import { WIDGET_BUILDER_EDITOR_MENU_OPTIONS } from 'dashboard/constants/editor';
|
||||
import { getInboxIconByType } from 'dashboard/helper/inbox';
|
||||
import Editor from 'dashboard/components-next/Editor/Editor.vue';
|
||||
|
||||
@@ -80,6 +81,7 @@ export default {
|
||||
selectedTabIndex: 0,
|
||||
selectedPortalSlug: '',
|
||||
showBusinessNameInput: false,
|
||||
welcomeTaglineEditorMenuOptions: WIDGET_BUILDER_EDITOR_MENU_OPTIONS,
|
||||
healthData: null,
|
||||
isLoadingHealth: false,
|
||||
healthError: null,
|
||||
@@ -624,7 +626,7 @@ export default {
|
||||
)
|
||||
"
|
||||
:max-length="255"
|
||||
channel-type="Context::InboxSettings"
|
||||
:enabled-menu-options="welcomeTaglineEditorMenuOptions"
|
||||
/>
|
||||
|
||||
<label v-if="isAWebWidgetInbox" class="pb-4">
|
||||
|
||||
@@ -7,6 +7,7 @@ import { useVuelidate } from '@vuelidate/core';
|
||||
import { required } from '@vuelidate/validators';
|
||||
import { LOCAL_STORAGE_KEYS } from 'dashboard/constants/localStorage';
|
||||
import { LocalStorage } from 'shared/helpers/localStorage';
|
||||
import { WIDGET_BUILDER_EDITOR_MENU_OPTIONS } from 'dashboard/constants/editor';
|
||||
import NextButton from 'dashboard/components-next/button/Button.vue';
|
||||
import Avatar from 'next/avatar/Avatar.vue';
|
||||
import Editor from 'dashboard/components-next/Editor/Editor.vue';
|
||||
@@ -75,6 +76,7 @@ export default {
|
||||
checked: false,
|
||||
},
|
||||
],
|
||||
welcomeTaglineEditorMenuOptions: WIDGET_BUILDER_EDITOR_MENU_OPTIONS,
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
@@ -335,7 +337,7 @@ export default {
|
||||
)
|
||||
"
|
||||
:max-length="255"
|
||||
channel-type="Context::InboxSettings"
|
||||
:enabled-menu-options="welcomeTaglineEditorMenuOptions"
|
||||
class="mb-4"
|
||||
/>
|
||||
<label>
|
||||
|
||||
@@ -5,6 +5,7 @@ import router from '../../../../index';
|
||||
import NextButton from 'dashboard/components-next/button/Button.vue';
|
||||
import PageHeader from '../../SettingsSubPageHeader.vue';
|
||||
import GreetingsEditor from 'shared/components/GreetingsEditor.vue';
|
||||
import { WIDGET_BUILDER_EDITOR_MENU_OPTIONS } from 'dashboard/constants/editor';
|
||||
import Editor from 'dashboard/components-next/Editor/Editor.vue';
|
||||
|
||||
export default {
|
||||
@@ -23,6 +24,7 @@ export default {
|
||||
channelWelcomeTagline: '',
|
||||
greetingEnabled: false,
|
||||
greetingMessage: '',
|
||||
welcomeTaglineEditorMenuOptions: WIDGET_BUILDER_EDITOR_MENU_OPTIONS,
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
@@ -145,7 +147,7 @@ export default {
|
||||
)
|
||||
"
|
||||
:max-length="255"
|
||||
channel-type="Context::InboxSettings"
|
||||
:enabled-menu-options="welcomeTaglineEditorMenuOptions"
|
||||
class="mb-4"
|
||||
/>
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script setup>
|
||||
import { ref, watch } from 'vue';
|
||||
import WootMessageEditor from 'dashboard/components/widgets/WootWriter/Editor.vue';
|
||||
import { MESSAGE_SIGNATURE_EDITOR_MENU_OPTIONS } from 'dashboard/constants/editor';
|
||||
import NextButton from 'dashboard/components-next/button/Button.vue';
|
||||
|
||||
const props = defineProps({
|
||||
@@ -11,6 +12,7 @@ const props = defineProps({
|
||||
});
|
||||
|
||||
const emit = defineEmits(['updateSignature']);
|
||||
const customEditorMenuList = MESSAGE_SIGNATURE_EDITOR_MENU_OPTIONS;
|
||||
const signature = ref(props.messageSignature);
|
||||
watch(
|
||||
() => props.messageSignature ?? '',
|
||||
@@ -32,7 +34,7 @@ const updateSignature = () => {
|
||||
class="message-editor h-[10rem] !px-3"
|
||||
is-format-mode
|
||||
:placeholder="$t('PROFILE_SETTINGS.FORM.MESSAGE_SIGNATURE.PLACEHOLDER')"
|
||||
channel-type="Context::MessageSignature"
|
||||
:enabled-menu-options="customEditorMenuList"
|
||||
:enable-suggestions="false"
|
||||
show-image-resize-toolbar
|
||||
/>
|
||||
|
||||
@@ -24,6 +24,7 @@ import teams from './teams/teams.routes';
|
||||
import customRoles from './customRoles/customRole.routes';
|
||||
import profile from './profile/profile.routes';
|
||||
import security from './security/security.routes';
|
||||
import conversationWorkflow from './conversationWorkflow/conversationWorkflow.routes';
|
||||
|
||||
export default {
|
||||
routes: [
|
||||
@@ -63,5 +64,6 @@ export default {
|
||||
...customRoles.routes,
|
||||
...profile.routes,
|
||||
...security.routes,
|
||||
...conversationWorkflow.routes,
|
||||
],
|
||||
};
|
||||
|
||||
@@ -18,7 +18,6 @@ const state = {
|
||||
isFetchingItem: false,
|
||||
isUpdating: false,
|
||||
isCheckoutInProcess: false,
|
||||
isFetchingLimits: false,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -142,14 +141,11 @@ export const actions = {
|
||||
},
|
||||
|
||||
limits: async ({ commit }) => {
|
||||
commit(types.default.SET_ACCOUNT_UI_FLAG, { isFetchingLimits: true });
|
||||
try {
|
||||
const response = await EnterpriseAccountAPI.getLimits();
|
||||
commit(types.default.SET_ACCOUNT_LIMITS, response.data);
|
||||
} catch (error) {
|
||||
// silent error
|
||||
} finally {
|
||||
commit(types.default.SET_ACCOUNT_UI_FLAG, { isFetchingLimits: false });
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
+15
-36
@@ -30,15 +30,21 @@ class DataImportJob < ApplicationJob
|
||||
def parse_csv_and_build_contacts
|
||||
contacts = []
|
||||
rejected_contacts = []
|
||||
# Ensuring that importing non utf-8 characters will not throw error
|
||||
data = @data_import.import_file.download
|
||||
utf8_data = data.force_encoding('UTF-8')
|
||||
|
||||
with_import_file do |file|
|
||||
csv_reader(file).each do |row|
|
||||
current_contact = @contact_manager.build_contact(row.to_h.with_indifferent_access)
|
||||
if current_contact.valid?
|
||||
contacts << current_contact
|
||||
else
|
||||
append_rejected_contact(row, current_contact, rejected_contacts)
|
||||
end
|
||||
# Ensure that the data is valid UTF-8, preserving valid characters
|
||||
clean_data = utf8_data.valid_encoding? ? utf8_data : utf8_data.encode('UTF-16le', invalid: :replace, replace: '').encode('UTF-8')
|
||||
|
||||
csv = CSV.parse(clean_data, headers: true)
|
||||
|
||||
csv.each do |row|
|
||||
current_contact = @contact_manager.build_contact(row.to_h.with_indifferent_access)
|
||||
if current_contact.valid?
|
||||
contacts << current_contact
|
||||
else
|
||||
append_rejected_contact(row, current_contact, rejected_contacts)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -69,7 +75,7 @@ class DataImportJob < ApplicationJob
|
||||
end
|
||||
|
||||
def generate_csv_data(rejected_contacts)
|
||||
headers = csv_headers
|
||||
headers = CSV.parse(@data_import.import_file.download, headers: true).headers
|
||||
headers << 'errors'
|
||||
return if rejected_contacts.blank?
|
||||
|
||||
@@ -93,31 +99,4 @@ class DataImportJob < ApplicationJob
|
||||
def send_import_failed_notification_to_admin
|
||||
AdministratorNotifications::AccountNotificationMailer.with(account: @data_import.account).contact_import_failed.deliver_later
|
||||
end
|
||||
|
||||
def csv_headers
|
||||
header_row = nil
|
||||
with_import_file do |file|
|
||||
header_row = csv_reader(file).first
|
||||
end
|
||||
header_row&.headers || []
|
||||
end
|
||||
|
||||
def csv_reader(file)
|
||||
file.rewind
|
||||
raw_data = file.read
|
||||
utf8_data = raw_data.force_encoding('UTF-8')
|
||||
clean_data = utf8_data.valid_encoding? ? utf8_data : utf8_data.encode('UTF-16le', invalid: :replace, replace: '').encode('UTF-8')
|
||||
|
||||
CSV.new(StringIO.new(clean_data), headers: true)
|
||||
end
|
||||
|
||||
def with_import_file
|
||||
temp_dir = Rails.root.join('tmp/imports')
|
||||
FileUtils.mkdir_p(temp_dir)
|
||||
|
||||
@data_import.import_file.open(tmpdir: temp_dir) do |file|
|
||||
file.binmode
|
||||
yield file
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -2,6 +2,10 @@ class DeleteObjectJob < ApplicationJob
|
||||
queue_as :low
|
||||
|
||||
BATCH_SIZE = 5_000
|
||||
HEAVY_ASSOCIATIONS = {
|
||||
Account => %i[conversations contacts inboxes reporting_events],
|
||||
Inbox => %i[conversations contact_inboxes reporting_events]
|
||||
}.freeze
|
||||
|
||||
def perform(object, user = nil, ip = nil)
|
||||
# Pre-purge heavy associations for large objects to avoid
|
||||
@@ -15,18 +19,11 @@ class DeleteObjectJob < ApplicationJob
|
||||
|
||||
private
|
||||
|
||||
def heavy_associations
|
||||
{
|
||||
Account => %i[conversations contacts inboxes reporting_events],
|
||||
Inbox => %i[conversations contact_inboxes reporting_events]
|
||||
}.freeze
|
||||
end
|
||||
|
||||
def purge_heavy_associations(object)
|
||||
klass = heavy_associations.keys.find { |k| object.is_a?(k) }
|
||||
klass = HEAVY_ASSOCIATIONS.keys.find { |k| object.is_a?(k) }
|
||||
return unless klass
|
||||
|
||||
heavy_associations[klass].each do |assoc|
|
||||
HEAVY_ASSOCIATIONS[klass].each do |assoc|
|
||||
next unless object.respond_to?(assoc)
|
||||
|
||||
batch_destroy(object.public_send(assoc))
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
# Handles attachment processing for ConversationReplyMailer flows.
|
||||
module ConversationReplyMailerAttachmentHelper
|
||||
private
|
||||
|
||||
def process_attachments_as_files_for_email_reply
|
||||
# Attachment processing for direct email replies (when replying to a single message)
|
||||
#
|
||||
# How attachments are handled:
|
||||
# 1. Total file size (<20MB): Added directly to the email as proper attachments
|
||||
# 2. Total file size (>20MB): Added to @large_attachments to be displayed as links in the email
|
||||
|
||||
@options[:attachments] = []
|
||||
@large_attachments = []
|
||||
current_total_size = 0
|
||||
|
||||
@message.attachments.each do |attachment|
|
||||
current_total_size = handle_attachment_inline(current_total_size, attachment)
|
||||
end
|
||||
end
|
||||
|
||||
def read_blob_content(blob)
|
||||
buffer = +''
|
||||
blob.open do |file|
|
||||
while (chunk = file.read(64.kilobytes))
|
||||
buffer << chunk
|
||||
end
|
||||
end
|
||||
buffer
|
||||
end
|
||||
|
||||
def handle_attachment_inline(current_total_size, attachment)
|
||||
blob = attachment.file.blob
|
||||
return current_total_size if blob.blank?
|
||||
|
||||
file_size = blob.byte_size
|
||||
attachment_name = attachment.file.filename.to_s
|
||||
|
||||
if current_total_size + file_size <= 20.megabytes
|
||||
content = read_blob_content(blob)
|
||||
mail.attachments[attachment_name] = {
|
||||
mime_type: attachment.file.content_type || 'application/octet-stream',
|
||||
content: content
|
||||
}
|
||||
@options[:attachments] << { name: attachment_name }
|
||||
current_total_size + file_size
|
||||
else
|
||||
@large_attachments << attachment
|
||||
current_total_size
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,6 +1,4 @@
|
||||
module ConversationReplyMailerHelper
|
||||
include ConversationReplyMailerAttachmentHelper
|
||||
|
||||
def prepare_mail(cc_bcc_enabled)
|
||||
@options = {
|
||||
to: to_emails,
|
||||
@@ -29,6 +27,34 @@ module ConversationReplyMailerHelper
|
||||
mail(@options)
|
||||
end
|
||||
|
||||
def process_attachments_as_files_for_email_reply
|
||||
# Attachment processing for direct email replies (when replying to a single message)
|
||||
#
|
||||
# How attachments are handled:
|
||||
# 1. Total file size (<20MB): Added directly to the email as proper attachments
|
||||
# 2. Total file size (>20MB): Added to @large_attachments to be displayed as links in the email
|
||||
|
||||
@options[:attachments] = []
|
||||
@large_attachments = []
|
||||
current_total_size = 0
|
||||
|
||||
@message.attachments.each do |attachment|
|
||||
raw_data = attachment.file.download
|
||||
attachment_name = attachment.file.filename.to_s
|
||||
file_size = raw_data.bytesize
|
||||
|
||||
# Attach files directly until we hit 20MB total
|
||||
# After reaching 20MB, send remaining files as links
|
||||
if current_total_size + file_size <= 20.megabytes
|
||||
mail.attachments[attachment_name] = raw_data
|
||||
@options[:attachments] << { name: attachment_name }
|
||||
current_total_size += file_size
|
||||
else
|
||||
@large_attachments << attachment
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def oauth_smtp_settings
|
||||
|
||||
@@ -37,7 +37,11 @@ class Account < ApplicationRecord
|
||||
'auto_resolve_message': { 'type': %w[string null] },
|
||||
'auto_resolve_ignore_waiting': { 'type': %w[boolean null] },
|
||||
'audio_transcriptions': { 'type': %w[boolean null] },
|
||||
'auto_resolve_label': { 'type': %w[string null] }
|
||||
'auto_resolve_label': { 'type': %w[string null] },
|
||||
'conversation_required_attributes': {
|
||||
'type': %w[array null],
|
||||
'items': { 'type': 'string' }
|
||||
}
|
||||
},
|
||||
'required': [],
|
||||
'additionalProperties': true
|
||||
@@ -55,7 +59,7 @@ class Account < ApplicationRecord
|
||||
attribute_resolver: ->(record) { record.settings }
|
||||
|
||||
store_accessor :settings, :auto_resolve_after, :auto_resolve_message, :auto_resolve_ignore_waiting
|
||||
store_accessor :settings, :audio_transcriptions, :auto_resolve_label
|
||||
store_accessor :settings, :audio_transcriptions, :auto_resolve_label, :conversation_required_attributes
|
||||
|
||||
has_many :account_users, dependent: :destroy_async
|
||||
has_many :agent_bot_inboxes, dependent: :destroy_async
|
||||
|
||||
@@ -40,7 +40,7 @@ class Attachment < ApplicationRecord
|
||||
validate :acceptable_file
|
||||
validates :external_url, length: { maximum: Limits::URL_LENGTH_LIMIT }
|
||||
enum file_type: { :image => 0, :audio => 1, :video => 2, :file => 3, :location => 4, :fallback => 5, :share => 6, :story_mention => 7,
|
||||
:contact => 8, :ig_reel => 9, :ig_post => 10, :ig_story => 11 }
|
||||
:contact => 8, :ig_reel => 9 }
|
||||
|
||||
def push_event_data
|
||||
return unless file_type
|
||||
|
||||
@@ -130,39 +130,30 @@ class Channel::Telegram < ApplicationRecord
|
||||
def convert_markdown_to_telegram_html(text)
|
||||
# ref: https://core.telegram.org/bots/api#html-style
|
||||
|
||||
# Escape HTML entities first to prevent HTML injection
|
||||
# This ensures only markdown syntax is converted, not raw HTML
|
||||
escaped_text = CGI.escapeHTML(text)
|
||||
# escape html tags in text. We are subbing \n to <br> since commonmark will strip exta '\n'
|
||||
text = CGI.escapeHTML(text.gsub("\n", '<br>'))
|
||||
|
||||
# Parse markdown with extensions:
|
||||
# - strikethrough: support ~~text~~
|
||||
# - hardbreaks: preserve all newlines as <br>
|
||||
html = CommonMarker.render_html(escaped_text, [:HARDBREAKS], [:strikethrough]).strip
|
||||
# convert markdown to html
|
||||
html = CommonMarker.render_html(text).strip
|
||||
|
||||
# Convert paragraph breaks to double newlines to preserve them
|
||||
# CommonMarker creates <p> tags for paragraph breaks, but Telegram doesn't support <p>
|
||||
html_with_breaks = html.gsub(%r{</p>\s*<p>}, "\n\n")
|
||||
# remove all html tags except b, strong, i, em, u, ins, s, strike, del, a, code, pre, blockquote
|
||||
stripped_html = Rails::HTML5::SafeListSanitizer.new.sanitize(html, tags: %w[b strong i em u ins s strike del a code pre blockquote],
|
||||
attributes: %w[href])
|
||||
|
||||
# Remove opening and closing <p> tags
|
||||
html_with_breaks = html_with_breaks.gsub(%r{</?p>}, '')
|
||||
|
||||
# Sanitize to only allowed tags
|
||||
stripped_html = Rails::HTML5::SafeListSanitizer.new.sanitize(html_with_breaks, tags: %w[b strong i em u ins s strike del a code pre blockquote],
|
||||
attributes: %w[href])
|
||||
|
||||
# Convert <br /> tags to newlines for Telegram
|
||||
stripped_html.gsub(%r{<br\s*/?>}, "\n")
|
||||
# converted escaped br tags to \n
|
||||
stripped_html.gsub('<br>', "\n")
|
||||
end
|
||||
|
||||
def message_request(chat_id, text, reply_markup = nil, reply_to_message_id = nil, business_connection_id: nil)
|
||||
# text is already converted to HTML by MessageContentPresenter
|
||||
text_payload = convert_markdown_to_telegram_html(text)
|
||||
|
||||
business_body = {}
|
||||
business_body[:business_connection_id] = business_connection_id if business_connection_id
|
||||
|
||||
HTTParty.post("#{telegram_api_url}/sendMessage",
|
||||
body: {
|
||||
chat_id: chat_id,
|
||||
text: text,
|
||||
text: text_payload,
|
||||
reply_markup: reply_markup,
|
||||
parse_mode: 'HTML',
|
||||
reply_to_message_id: reply_to_message_id
|
||||
|
||||
@@ -53,7 +53,7 @@ class Integrations::App
|
||||
when 'slack'
|
||||
GlobalConfigService.load('SLACK_CLIENT_SECRET', nil).present?
|
||||
when 'linear'
|
||||
account.feature_enabled?('linear_integration') && GlobalConfigService.load('LINEAR_CLIENT_ID', nil).present?
|
||||
GlobalConfigService.load('LINEAR_CLIENT_ID', nil).present?
|
||||
when 'shopify'
|
||||
shopify_enabled?(account)
|
||||
when 'leadsquared'
|
||||
|
||||
@@ -30,8 +30,4 @@ class AccountPolicy < ApplicationPolicy
|
||||
def toggle_deletion?
|
||||
@account_user.administrator?
|
||||
end
|
||||
|
||||
def topup_checkout?
|
||||
@account_user.administrator?
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,18 +1,11 @@
|
||||
class MessageContentPresenter < SimpleDelegator
|
||||
def outgoing_content
|
||||
content_to_send = if should_append_survey_link?
|
||||
survey_link = survey_url(conversation.uuid)
|
||||
custom_message = inbox.csat_config&.dig('message')
|
||||
custom_message.present? ? "#{custom_message} #{survey_link}" : I18n.t('conversations.survey.response', link: survey_link)
|
||||
else
|
||||
content
|
||||
end
|
||||
return content unless should_append_survey_link?
|
||||
|
||||
Messages::MarkdownRendererService.new(
|
||||
content_to_send,
|
||||
conversation.inbox.channel_type,
|
||||
conversation.inbox.channel
|
||||
).render
|
||||
survey_link = survey_url(conversation.uuid)
|
||||
custom_message = inbox.csat_config&.dig('message')
|
||||
|
||||
custom_message.present? ? "#{custom_message} #{survey_link}" : I18n.t('conversations.survey.response', link: survey_link)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
@@ -59,20 +59,11 @@ class Instagram::MessageText < Instagram::BaseMessageText
|
||||
# We can safely create an unknown contact, making this integration work.
|
||||
return unknown_user(ig_scope_id) if error_code == 9010
|
||||
|
||||
# Handle error code 100: Object doesn't exist or missing permissions
|
||||
# This typically occurs when trying to fetch a user that doesn't exist or has privacy restrictions
|
||||
# We can safely create an unknown contact, similar to error 9010
|
||||
return unknown_user(ig_scope_id) if error_code == 100
|
||||
|
||||
Rails.logger.warn("[InstagramUserFetchError]: account_id #{@inbox.account_id} inbox_id #{@inbox.id} ig_scope_id #{ig_scope_id}")
|
||||
Rails.logger.warn("[InstagramUserFetchError]: #{error_message} #{error_code}")
|
||||
|
||||
exception = StandardError.new("#{error_message} (Code: #{error_code}, IG Scope ID: #{ig_scope_id})")
|
||||
ChatwootExceptionTracker.new(exception, account: @inbox.account).capture_exception
|
||||
|
||||
# Explicitly return empty hash for any unhandled error codes
|
||||
# This prevents the exception tracker result from being returned
|
||||
{}
|
||||
end
|
||||
|
||||
def base_uri
|
||||
|
||||
@@ -1,113 +0,0 @@
|
||||
class Messages::MarkdownRendererService
|
||||
CHANNEL_RENDERERS = {
|
||||
'Channel::Email' => :render_html,
|
||||
'Channel::WebWidget' => :render_html,
|
||||
'Channel::Telegram' => :render_telegram_html,
|
||||
'Channel::Whatsapp' => :render_whatsapp,
|
||||
'Channel::FacebookPage' => :render_instagram,
|
||||
'Channel::Instagram' => :render_instagram,
|
||||
'Channel::Line' => :render_line,
|
||||
'Channel::TwitterProfile' => :render_plain_text,
|
||||
'Channel::Sms' => :render_plain_text,
|
||||
'Channel::TwilioSms' => :render_plain_text
|
||||
}.freeze
|
||||
|
||||
def initialize(content, channel_type, channel = nil)
|
||||
@content = content
|
||||
@channel_type = channel_type
|
||||
@channel = channel
|
||||
end
|
||||
|
||||
def render
|
||||
return @content if @content.blank?
|
||||
|
||||
renderer_method = CHANNEL_RENDERERS[effective_channel_type]
|
||||
renderer_method ? send(renderer_method) : @content
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def effective_channel_type
|
||||
# For Twilio SMS channel, check if it's actually WhatsApp
|
||||
if @channel_type == 'Channel::TwilioSms' && @channel&.whatsapp?
|
||||
'Channel::Whatsapp'
|
||||
else
|
||||
@channel_type
|
||||
end
|
||||
end
|
||||
|
||||
def commonmarker_doc
|
||||
@commonmarker_doc ||= CommonMarker.render_doc(@content, [:DEFAULT, :STRIKETHROUGH_DOUBLE_TILDE])
|
||||
end
|
||||
|
||||
def render_html
|
||||
markdown_renderer = BaseMarkdownRenderer.new
|
||||
doc = CommonMarker.render_doc(@content, :DEFAULT, [:strikethrough])
|
||||
markdown_renderer.render(doc)
|
||||
end
|
||||
|
||||
def render_telegram_html
|
||||
# Strip whitespace from whitespace-only lines to normalize newlines
|
||||
normalized_content = @content.gsub(/^[ \t]+$/m, '')
|
||||
content_with_preserved_newlines = preserve_multiple_newlines(normalized_content)
|
||||
renderer = Messages::MarkdownRenderers::TelegramRenderer.new
|
||||
doc = CommonMarker.render_doc(content_with_preserved_newlines, [:STRIKETHROUGH_DOUBLE_TILDE], [:strikethrough])
|
||||
result = renderer.render(doc).gsub(/\n+\z/, '')
|
||||
restore_multiple_newlines(result)
|
||||
end
|
||||
|
||||
def render_whatsapp
|
||||
# Strip whitespace from whitespace-only lines to normalize newlines
|
||||
normalized_content = @content.gsub(/^[ \t]+$/m, '')
|
||||
content_with_preserved_newlines = preserve_multiple_newlines(normalized_content)
|
||||
renderer = Messages::MarkdownRenderers::WhatsAppRenderer.new
|
||||
doc = CommonMarker.render_doc(content_with_preserved_newlines, [:DEFAULT, :STRIKETHROUGH_DOUBLE_TILDE])
|
||||
result = renderer.render(doc).gsub(/\n+\z/, '')
|
||||
restore_multiple_newlines(result)
|
||||
end
|
||||
|
||||
def render_instagram
|
||||
# Strip whitespace from whitespace-only lines to normalize newlines
|
||||
normalized_content = @content.gsub(/^[ \t]+$/m, '')
|
||||
content_with_preserved_newlines = preserve_multiple_newlines(normalized_content)
|
||||
renderer = Messages::MarkdownRenderers::InstagramRenderer.new
|
||||
doc = CommonMarker.render_doc(content_with_preserved_newlines, [:DEFAULT, :STRIKETHROUGH_DOUBLE_TILDE])
|
||||
result = renderer.render(doc).gsub(/\n+\z/, '')
|
||||
restore_multiple_newlines(result)
|
||||
end
|
||||
|
||||
def render_line
|
||||
# Strip whitespace from whitespace-only lines to normalize newlines
|
||||
normalized_content = @content.gsub(/^[ \t]+$/m, '')
|
||||
content_with_preserved_newlines = preserve_multiple_newlines(normalized_content)
|
||||
renderer = Messages::MarkdownRenderers::LineRenderer.new
|
||||
doc = CommonMarker.render_doc(content_with_preserved_newlines, [:DEFAULT, :STRIKETHROUGH_DOUBLE_TILDE])
|
||||
result = renderer.render(doc).gsub(/\n+\z/, '')
|
||||
restore_multiple_newlines(result)
|
||||
end
|
||||
|
||||
def render_plain_text
|
||||
# Strip whitespace from whitespace-only lines to normalize newlines
|
||||
normalized_content = @content.gsub(/^[ \t]+$/m, '')
|
||||
content_with_preserved_newlines = preserve_multiple_newlines(normalized_content)
|
||||
renderer = Messages::MarkdownRenderers::PlainTextRenderer.new
|
||||
doc = CommonMarker.render_doc(content_with_preserved_newlines, [:DEFAULT, :STRIKETHROUGH_DOUBLE_TILDE])
|
||||
result = renderer.render(doc).gsub(/\n+\z/, '')
|
||||
restore_multiple_newlines(result)
|
||||
end
|
||||
|
||||
# Preserve multiple consecutive newlines (3+) by replacing them with placeholders
|
||||
# Standard markdown treats 2 newlines as paragraph break, we preserve 3+
|
||||
def preserve_multiple_newlines(content)
|
||||
content.gsub(/\n{3,}/) do |match|
|
||||
"{{PRESERVE_#{match.length}_NEWLINES}}"
|
||||
end
|
||||
end
|
||||
|
||||
# Restore multiple newlines from placeholders
|
||||
def restore_multiple_newlines(content)
|
||||
content.gsub(/\{\{PRESERVE_(\d+)_NEWLINES\}\}/) do |_match|
|
||||
"\n" * Regexp.last_match(1).to_i
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,39 +0,0 @@
|
||||
class Messages::MarkdownRenderers::BaseMarkdownRenderer < CommonMarker::Renderer
|
||||
def document(_node)
|
||||
out(:children)
|
||||
end
|
||||
|
||||
def paragraph(_node)
|
||||
out(:children)
|
||||
cr
|
||||
end
|
||||
|
||||
def text(node)
|
||||
out(node.string_content)
|
||||
end
|
||||
|
||||
def softbreak(_node)
|
||||
out(' ')
|
||||
end
|
||||
|
||||
def linebreak(_node)
|
||||
out("\n")
|
||||
end
|
||||
|
||||
def strikethrough(_node)
|
||||
out('<del>')
|
||||
out(:children)
|
||||
out('</del>')
|
||||
end
|
||||
|
||||
def method_missing(method_name, node = nil, *args, **kwargs, &)
|
||||
return super unless node.is_a?(CommonMarker::Node)
|
||||
|
||||
out(:children)
|
||||
cr unless %i[text softbreak linebreak].include?(node.type)
|
||||
end
|
||||
|
||||
def respond_to_missing?(_method_name, _include_private = false)
|
||||
true
|
||||
end
|
||||
end
|
||||
@@ -1,48 +0,0 @@
|
||||
class Messages::MarkdownRenderers::InstagramRenderer < Messages::MarkdownRenderers::BaseMarkdownRenderer
|
||||
def initialize
|
||||
super
|
||||
@list_item_number = 0
|
||||
end
|
||||
|
||||
def strong(_node)
|
||||
out('*', :children, '*')
|
||||
end
|
||||
|
||||
def emph(_node)
|
||||
out('_', :children, '_')
|
||||
end
|
||||
|
||||
def code(node)
|
||||
out(node.string_content)
|
||||
end
|
||||
|
||||
def link(node)
|
||||
out(node.url)
|
||||
end
|
||||
|
||||
def list(node)
|
||||
@list_type = node.list_type
|
||||
@list_item_number = @list_type == :ordered_list ? node.list_start : 0
|
||||
out(:children)
|
||||
cr
|
||||
end
|
||||
|
||||
def list_item(_node)
|
||||
if @list_type == :ordered_list
|
||||
out("#{@list_item_number}. ", :children)
|
||||
@list_item_number += 1
|
||||
else
|
||||
out('- ', :children)
|
||||
end
|
||||
cr
|
||||
end
|
||||
|
||||
def blockquote(_node)
|
||||
out(:children)
|
||||
cr
|
||||
end
|
||||
|
||||
def softbreak(_node)
|
||||
out("\n")
|
||||
end
|
||||
end
|
||||
@@ -1,36 +0,0 @@
|
||||
class Messages::MarkdownRenderers::LineRenderer < Messages::MarkdownRenderers::BaseMarkdownRenderer
|
||||
def strong(_node)
|
||||
out(' *', :children, '* ')
|
||||
end
|
||||
|
||||
def emph(_node)
|
||||
out(' _', :children, '_ ')
|
||||
end
|
||||
|
||||
def code(node)
|
||||
out(' `', node.string_content, '` ')
|
||||
end
|
||||
|
||||
def link(node)
|
||||
out(node.url)
|
||||
end
|
||||
|
||||
def list(_node)
|
||||
out(:children)
|
||||
cr
|
||||
end
|
||||
|
||||
def list_item(_node)
|
||||
out(:children)
|
||||
cr
|
||||
end
|
||||
|
||||
def code_block(node)
|
||||
out(' ```', "\n", node.string_content, '``` ', "\n")
|
||||
end
|
||||
|
||||
def blockquote(_node)
|
||||
out(:children)
|
||||
cr
|
||||
end
|
||||
end
|
||||
@@ -1,62 +0,0 @@
|
||||
class Messages::MarkdownRenderers::PlainTextRenderer < Messages::MarkdownRenderers::BaseMarkdownRenderer
|
||||
def initialize
|
||||
super
|
||||
@list_item_number = 0
|
||||
end
|
||||
|
||||
def link(node)
|
||||
out(:children)
|
||||
out(' ', node.url) if node.url.present?
|
||||
end
|
||||
|
||||
def strong(_node)
|
||||
out(:children)
|
||||
end
|
||||
|
||||
def emph(_node)
|
||||
out(:children)
|
||||
end
|
||||
|
||||
def code(node)
|
||||
out(node.string_content)
|
||||
end
|
||||
|
||||
def list(node)
|
||||
@list_type = node.list_type
|
||||
@list_item_number = @list_type == :ordered_list ? node.list_start : 0
|
||||
out(:children)
|
||||
cr
|
||||
end
|
||||
|
||||
def list_item(_node)
|
||||
if @list_type == :ordered_list
|
||||
out("#{@list_item_number}. ", :children)
|
||||
@list_item_number += 1
|
||||
else
|
||||
out('- ', :children)
|
||||
end
|
||||
cr
|
||||
end
|
||||
|
||||
def blockquote(_node)
|
||||
out(:children)
|
||||
cr
|
||||
end
|
||||
|
||||
def code_block(node)
|
||||
out(node.string_content, "\n")
|
||||
end
|
||||
|
||||
def header(_node)
|
||||
out(:children)
|
||||
cr
|
||||
end
|
||||
|
||||
def thematic_break(_node)
|
||||
out("\n")
|
||||
end
|
||||
|
||||
def softbreak(_node)
|
||||
out("\n")
|
||||
end
|
||||
end
|
||||
@@ -1,60 +0,0 @@
|
||||
class Messages::MarkdownRenderers::TelegramRenderer < Messages::MarkdownRenderers::BaseMarkdownRenderer
|
||||
def initialize
|
||||
super
|
||||
@list_item_number = 0
|
||||
end
|
||||
|
||||
def strong(_node)
|
||||
out('<strong>', :children, '</strong>')
|
||||
end
|
||||
|
||||
def emph(_node)
|
||||
out('<em>', :children, '</em>')
|
||||
end
|
||||
|
||||
def code(node)
|
||||
out('<code>', node.string_content, '</code>')
|
||||
end
|
||||
|
||||
def link(node)
|
||||
out('<a href="', node.url, '">', :children, '</a>')
|
||||
end
|
||||
|
||||
def strikethrough(_node)
|
||||
out('<del>', :children, '</del>')
|
||||
end
|
||||
|
||||
def blockquote(_node)
|
||||
out('<blockquote>', :children, '</blockquote>')
|
||||
end
|
||||
|
||||
def code_block(node)
|
||||
out('<pre>', node.string_content, '</pre>')
|
||||
end
|
||||
|
||||
def list(node)
|
||||
@list_type = node.list_type
|
||||
@list_item_number = @list_type == :ordered_list ? node.list_start : 0
|
||||
out(:children)
|
||||
cr
|
||||
end
|
||||
|
||||
def list_item(_node)
|
||||
if @list_type == :ordered_list
|
||||
out("#{@list_item_number}. ", :children)
|
||||
@list_item_number += 1
|
||||
else
|
||||
out('• ', :children)
|
||||
end
|
||||
cr
|
||||
end
|
||||
|
||||
def header(_node)
|
||||
out('<strong>', :children, '</strong>')
|
||||
cr
|
||||
end
|
||||
|
||||
def softbreak(_node)
|
||||
out("\n")
|
||||
end
|
||||
end
|
||||
@@ -1,36 +0,0 @@
|
||||
class Messages::MarkdownRenderers::WhatsAppRenderer < Messages::MarkdownRenderers::BaseMarkdownRenderer
|
||||
def strong(_node)
|
||||
out('*', :children, '*')
|
||||
end
|
||||
|
||||
def emph(_node)
|
||||
out('_', :children, '_')
|
||||
end
|
||||
|
||||
def code(node)
|
||||
out('`', node.string_content, '`')
|
||||
end
|
||||
|
||||
def link(node)
|
||||
out(node.url)
|
||||
end
|
||||
|
||||
def list(_node)
|
||||
out(:children)
|
||||
cr
|
||||
end
|
||||
|
||||
def list_item(_node)
|
||||
out('- ', :children)
|
||||
cr
|
||||
end
|
||||
|
||||
def blockquote(_node)
|
||||
out('> ', :children)
|
||||
cr
|
||||
end
|
||||
|
||||
def softbreak(_node)
|
||||
out("\n")
|
||||
end
|
||||
end
|
||||
@@ -96,16 +96,11 @@ class Telegram::SendAttachmentsService
|
||||
# Telegram picks up the file name from original field name, so we need to save the file with the original name.
|
||||
# Hence not using Tempfile here.
|
||||
def save_attachment_to_tempfile(attachment)
|
||||
temp_dir = Rails.root.join('tmp/uploads', "telegram-#{attachment.message_id}")
|
||||
raw_data = attachment.file.download
|
||||
temp_dir = Rails.root.join('tmp/uploads')
|
||||
FileUtils.mkdir_p(temp_dir)
|
||||
temp_file_path = File.join(temp_dir, attachment.file.filename.to_s)
|
||||
|
||||
File.open(temp_file_path, 'wb') do |file|
|
||||
attachment.file.blob.open do |blob_file|
|
||||
IO.copy_stream(blob_file, file)
|
||||
end
|
||||
end
|
||||
|
||||
File.write(temp_file_path, raw_data, mode: 'wb')
|
||||
temp_file_path
|
||||
end
|
||||
|
||||
|
||||
@@ -3,6 +3,6 @@ json.payload do
|
||||
json.id inbox_member.user.id
|
||||
json.name inbox_member.user.available_name
|
||||
json.avatar_url inbox_member.user.avatar_url
|
||||
json.availability_status inbox_member.user.account_users.find_by(account_id: @current_account.id)&.availability_status
|
||||
json.availability_status inbox_member.user.account_users.find_by(account_id: @current_account.id).availability_status
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<% if @message.content_attributes.dig('email', 'html_content', 'reply').present? %>
|
||||
<%= @message.content_attributes.dig('email', 'html_content', 'reply').html_safe %>
|
||||
<% elsif @message.content %>
|
||||
<%= @message.outgoing_content.html_safe %>
|
||||
<%= ChatwootMarkdownRenderer.new(@message.outgoing_content).render_message %>
|
||||
<% end %>
|
||||
<% if @large_attachments.present? %>
|
||||
<p>Attachments:</p>
|
||||
|
||||
@@ -122,13 +122,6 @@ en:
|
||||
invalid_token: Invalid or expired MFA token
|
||||
invalid_credentials: Invalid credentials or verification code
|
||||
feature_unavailable: MFA feature is not available. Please configure encryption keys.
|
||||
topup:
|
||||
credits_required: Credits amount is required
|
||||
invalid_credits: Invalid credits amount
|
||||
invalid_option: Invalid topup option
|
||||
plan_not_eligible: Top-ups are only available for paid plans. Please upgrade your plan first.
|
||||
stripe_customer_not_configured: Stripe customer not configured
|
||||
no_payment_method: No payment methods found. Please add a payment method before making a purchase.
|
||||
profile:
|
||||
mfa:
|
||||
enabled: MFA enabled successfully
|
||||
@@ -204,8 +197,6 @@ en:
|
||||
messages:
|
||||
instagram_story_content: '%{story_sender} mentioned you in the story: '
|
||||
instagram_deleted_story_content: This story is no longer available.
|
||||
instagram_shared_story_content: 'Shared story'
|
||||
instagram_shared_post_content: 'Shared post'
|
||||
deleted: This message was deleted
|
||||
whatsapp:
|
||||
list_button_label: 'Choose an item'
|
||||
|
||||
@@ -438,7 +438,6 @@ Rails.application.routes.draw do
|
||||
post :subscription
|
||||
get :limits
|
||||
post :toggle_deletion
|
||||
post :topup_checkout
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -17,7 +17,7 @@ class Api::V1::Accounts::SlaPoliciesController < Api::V1::Accounts::EnterpriseAc
|
||||
end
|
||||
|
||||
def destroy
|
||||
::DeleteObjectJob.perform_later(@sla_policy, Current.user, request.ip) if @sla_policy.present?
|
||||
@sla_policy.destroy!
|
||||
head :ok
|
||||
end
|
||||
|
||||
|
||||
@@ -55,22 +55,6 @@ class Enterprise::Api::V1::AccountsController < Api::BaseController
|
||||
end
|
||||
end
|
||||
|
||||
def topup_checkout
|
||||
return render json: { error: I18n.t('errors.topup.credits_required') }, status: :unprocessable_entity if params[:credits].blank?
|
||||
|
||||
service = Enterprise::Billing::TopupCheckoutService.new(account: @account)
|
||||
result = service.create_checkout_session(credits: params[:credits].to_i)
|
||||
|
||||
@account.reload
|
||||
render json: result.merge(
|
||||
id: @account.id,
|
||||
limits: @account.limits,
|
||||
custom_attributes: @account.custom_attributes
|
||||
)
|
||||
rescue Enterprise::Billing::TopupCheckoutService::Error, Stripe::StripeError => e
|
||||
render_could_not_create_error(e.message)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def check_cloud_env
|
||||
|
||||
@@ -1,83 +1,31 @@
|
||||
module Captain::ChatHelper
|
||||
include Integrations::LlmInstrumentation
|
||||
include Captain::ChatResponseHelper
|
||||
include Captain::ToolExecutionHelper
|
||||
|
||||
def request_chat_completion
|
||||
log_chat_completion_request
|
||||
|
||||
chat = build_chat
|
||||
|
||||
add_messages_to_chat(chat)
|
||||
with_agent_session do
|
||||
response = chat.ask(conversation_messages.last[:content])
|
||||
build_response(response)
|
||||
response = instrument_llm_call(instrumentation_params) do
|
||||
@client.chat(
|
||||
parameters: chat_parameters
|
||||
)
|
||||
end
|
||||
handle_response(response)
|
||||
end
|
||||
rescue StandardError => e
|
||||
Rails.logger.error "#{self.class.name} Assistant: #{@assistant.id}, Error in chat completion: #{e}"
|
||||
raise e
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def build_chat
|
||||
llm_chat = chat(model: @model, temperature: temperature)
|
||||
llm_chat.with_params(response_format: { type: 'json_object' })
|
||||
|
||||
llm_chat = setup_tools(llm_chat)
|
||||
setup_system_instructions(llm_chat)
|
||||
setup_event_handlers(llm_chat)
|
||||
|
||||
llm_chat
|
||||
end
|
||||
|
||||
def setup_tools(chat)
|
||||
@tools&.each do |tool|
|
||||
chat.with_tool(tool)
|
||||
end
|
||||
chat
|
||||
end
|
||||
|
||||
def setup_system_instructions(chat)
|
||||
system_messages = @messages.select { |m| m[:role] == 'system' || m[:role] == :system }
|
||||
combined_instructions = system_messages.pluck(:content).join("\n\n")
|
||||
chat.with_instructions(combined_instructions)
|
||||
end
|
||||
|
||||
def setup_event_handlers(chat)
|
||||
chat.on_new_message { start_llm_turn_span(instrumentation_params(chat)) }
|
||||
chat.on_end_message { |message| end_llm_turn_span(message) }
|
||||
chat.on_tool_call { |tool_call| handle_tool_call(tool_call) }
|
||||
chat.on_tool_result { |result| handle_tool_result(result) }
|
||||
|
||||
chat
|
||||
end
|
||||
|
||||
def handle_tool_call(tool_call)
|
||||
persist_thinking_message(tool_call)
|
||||
start_tool_span(tool_call)
|
||||
@pending_tool_calls ||= []
|
||||
@pending_tool_calls.push(tool_call)
|
||||
end
|
||||
|
||||
def handle_tool_result(result)
|
||||
end_tool_span(result)
|
||||
persist_tool_completion
|
||||
end
|
||||
|
||||
def add_messages_to_chat(chat)
|
||||
conversation_messages[0...-1].each do |msg|
|
||||
chat.add_message(role: msg[:role].to_sym, content: msg[:content])
|
||||
end
|
||||
end
|
||||
|
||||
def instrumentation_params(chat = nil)
|
||||
def instrumentation_params
|
||||
{
|
||||
span_name: "llm.captain.#{feature_name}",
|
||||
account_id: resolved_account_id,
|
||||
conversation_id: @conversation_id,
|
||||
feature_name: feature_name,
|
||||
model: @model,
|
||||
messages: chat ? chat.messages.map { |m| { role: m.role.to_s, content: m.content.to_s } } : @messages,
|
||||
messages: @messages,
|
||||
temperature: temperature,
|
||||
metadata: {
|
||||
assistant_id: @assistant&.id
|
||||
@@ -85,8 +33,14 @@ module Captain::ChatHelper
|
||||
}
|
||||
end
|
||||
|
||||
def conversation_messages
|
||||
@messages.reject { |m| m[:role] == 'system' || m[:role] == :system }
|
||||
def chat_parameters
|
||||
{
|
||||
model: @model,
|
||||
messages: @messages,
|
||||
tools: @tool_registry&.registered_tools || [],
|
||||
response_format: { type: 'json_object' },
|
||||
temperature: temperature
|
||||
}
|
||||
end
|
||||
|
||||
def temperature
|
||||
@@ -97,6 +51,8 @@ module Captain::ChatHelper
|
||||
@account&.id || @assistant&.account_id
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Ensures all LLM calls and tool executions within an agentic loop
|
||||
# are grouped under a single trace/session in Langfuse.
|
||||
#
|
||||
@@ -122,7 +78,7 @@ module Captain::ChatHelper
|
||||
def log_chat_completion_request
|
||||
Rails.logger.info(
|
||||
"#{self.class.name} Assistant: #{@assistant.id}, Requesting chat completion
|
||||
for messages #{@messages} with #{@tools&.length || 0} tools
|
||||
for messages #{@messages} with #{@tool_registry&.registered_tools&.length || 0} tools
|
||||
"
|
||||
)
|
||||
end
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
module Captain::ChatResponseHelper
|
||||
private
|
||||
|
||||
def build_response(response)
|
||||
Rails.logger.debug { "#{self.class.name} Assistant: #{@assistant.id}, Received response #{response}" }
|
||||
|
||||
parsed = parse_json_response(response.content)
|
||||
|
||||
persist_message(parsed, 'assistant')
|
||||
parsed
|
||||
end
|
||||
|
||||
def parse_json_response(content)
|
||||
content = content.gsub('```json', '').gsub('```', '')
|
||||
content = content.strip
|
||||
JSON.parse(content)
|
||||
rescue JSON::ParserError => e
|
||||
Rails.logger.error "#{self.class.name} Assistant: #{@assistant.id}, Error parsing JSON response: #{e.message}"
|
||||
{ 'content' => content }
|
||||
end
|
||||
|
||||
def persist_thinking_message(tool_call)
|
||||
return if @copilot_thread.blank?
|
||||
|
||||
tool_name = tool_call.name.to_s
|
||||
|
||||
persist_message(
|
||||
{
|
||||
'content' => "Using #{tool_name}",
|
||||
'function_name' => tool_name
|
||||
},
|
||||
'assistant_thinking'
|
||||
)
|
||||
end
|
||||
|
||||
def persist_tool_completion
|
||||
return if @copilot_thread.blank?
|
||||
|
||||
tool_call = @pending_tool_calls&.pop
|
||||
return unless tool_call
|
||||
|
||||
tool_name = tool_call.name.to_s
|
||||
|
||||
persist_message(
|
||||
{
|
||||
'content' => "Completed #{tool_name}",
|
||||
'function_name' => tool_name
|
||||
},
|
||||
'assistant_thinking'
|
||||
)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,83 @@
|
||||
module Captain::ToolExecutionHelper
|
||||
private
|
||||
|
||||
def handle_response(response)
|
||||
Rails.logger.debug { "#{self.class.name} Assistant: #{@assistant.id}, Received response #{response}" }
|
||||
message = response.dig('choices', 0, 'message')
|
||||
|
||||
if message['tool_calls']
|
||||
process_tool_calls(message['tool_calls'])
|
||||
else
|
||||
message = JSON.parse(message['content'].strip)
|
||||
persist_message(message, 'assistant')
|
||||
message
|
||||
end
|
||||
end
|
||||
|
||||
def process_tool_calls(tool_calls)
|
||||
append_tool_calls(tool_calls)
|
||||
tool_calls.each { |tool_call| process_tool_call(tool_call) }
|
||||
request_chat_completion
|
||||
end
|
||||
|
||||
def process_tool_call(tool_call)
|
||||
arguments = JSON.parse(tool_call['function']['arguments'])
|
||||
function_name = tool_call['function']['name']
|
||||
tool_call_id = tool_call['id']
|
||||
|
||||
if @tool_registry.respond_to?(function_name)
|
||||
execute_tool(function_name, arguments, tool_call_id)
|
||||
else
|
||||
process_invalid_tool_call(function_name, tool_call_id)
|
||||
end
|
||||
end
|
||||
|
||||
def execute_tool(function_name, arguments, tool_call_id)
|
||||
persist_tool_status(function_name, 'captain.copilot.using_tool')
|
||||
result = perform_tool_call(function_name, arguments)
|
||||
persist_tool_status(function_name, 'captain.copilot.completed_tool_call')
|
||||
append_tool_response(result, tool_call_id)
|
||||
end
|
||||
|
||||
def perform_tool_call(function_name, arguments)
|
||||
instrument_tool_call(function_name, arguments) do
|
||||
@tool_registry.send(function_name, arguments)
|
||||
end
|
||||
rescue StandardError => e
|
||||
Rails.logger.error "Tool #{function_name} failed: #{e.message}"
|
||||
"Error executing #{function_name}: #{e.message}"
|
||||
end
|
||||
|
||||
def persist_tool_status(function_name, translation_key)
|
||||
persist_message(
|
||||
{
|
||||
content: I18n.t(translation_key, function_name: function_name),
|
||||
function_name: function_name
|
||||
},
|
||||
'assistant_thinking'
|
||||
)
|
||||
end
|
||||
|
||||
def append_tool_calls(tool_calls)
|
||||
@messages << {
|
||||
role: 'assistant',
|
||||
tool_calls: tool_calls
|
||||
}
|
||||
end
|
||||
|
||||
def process_invalid_tool_call(function_name, tool_call_id)
|
||||
persist_message(
|
||||
{ content: I18n.t('captain.copilot.invalid_tool_call'), function_name: function_name },
|
||||
'assistant_thinking'
|
||||
)
|
||||
append_tool_response(I18n.t('captain.copilot.tool_not_available'), tool_call_id)
|
||||
end
|
||||
|
||||
def append_tool_response(content, tool_call_id)
|
||||
@messages << {
|
||||
role: 'tool',
|
||||
tool_call_id: tool_call_id,
|
||||
content: content
|
||||
}
|
||||
end
|
||||
end
|
||||
@@ -1,18 +1,10 @@
|
||||
module Enterprise::DeleteObjectJob
|
||||
private
|
||||
|
||||
def heavy_associations
|
||||
super.merge(
|
||||
SlaPolicy => %i[applied_slas]
|
||||
).freeze
|
||||
end
|
||||
|
||||
def process_post_deletion_tasks(object, user, ip)
|
||||
create_audit_entry(object, user, ip)
|
||||
end
|
||||
|
||||
def create_audit_entry(object, user, ip)
|
||||
return unless %w[Inbox Conversation SlaPolicy].include?(object.class.to_s) && user.present?
|
||||
return unless %w[Inbox Conversation].include?(object.class.to_s) && user.present?
|
||||
|
||||
Enterprise::AuditLog.create(
|
||||
auditable: object,
|
||||
|
||||
@@ -66,31 +66,6 @@ module Concerns::Toolable
|
||||
[auth_config['username'], auth_config['password']]
|
||||
end
|
||||
|
||||
def build_metadata_headers(state)
|
||||
{}.tap do |headers|
|
||||
add_base_headers(headers, state)
|
||||
add_conversation_headers(headers, state[:conversation]) if state[:conversation]
|
||||
add_contact_headers(headers, state[:contact]) if state[:contact]
|
||||
end
|
||||
end
|
||||
|
||||
def add_base_headers(headers, state)
|
||||
headers['X-Chatwoot-Account-Id'] = state[:account_id].to_s if state[:account_id]
|
||||
headers['X-Chatwoot-Assistant-Id'] = state[:assistant_id].to_s if state[:assistant_id]
|
||||
headers['X-Chatwoot-Tool-Slug'] = slug if slug.present?
|
||||
end
|
||||
|
||||
def add_conversation_headers(headers, conversation)
|
||||
headers['X-Chatwoot-Conversation-Id'] = conversation[:id].to_s if conversation[:id]
|
||||
headers['X-Chatwoot-Conversation-Display-Id'] = conversation[:display_id].to_s if conversation[:display_id]
|
||||
end
|
||||
|
||||
def add_contact_headers(headers, contact)
|
||||
headers['X-Chatwoot-Contact-Id'] = contact[:id].to_s if contact[:id]
|
||||
headers['X-Chatwoot-Contact-Email'] = contact[:email].to_s if contact[:email].present?
|
||||
headers['X-Chatwoot-Contact-Phone'] = contact[:phone_number].to_s if contact[:phone_number].present?
|
||||
end
|
||||
|
||||
def format_response(raw_response_body)
|
||||
return raw_response_body if response_template.blank?
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ class SlaPolicy < ApplicationRecord
|
||||
validates :name, presence: true
|
||||
|
||||
has_many :conversations, dependent: :nullify
|
||||
has_many :applied_slas, dependent: :destroy_async
|
||||
has_many :applied_slas, dependent: :destroy
|
||||
|
||||
def push_event_data
|
||||
{
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
class Captain::Copilot::ChatService < Llm::BaseAiService
|
||||
require 'openai'
|
||||
|
||||
class Captain::Copilot::ChatService < Llm::BaseOpenAiService
|
||||
include Captain::ChatHelper
|
||||
|
||||
attr_reader :assistant, :account, :user, :copilot_thread, :previous_history, :messages
|
||||
@@ -12,10 +14,9 @@ class Captain::Copilot::ChatService < Llm::BaseAiService
|
||||
@copilot_thread = nil
|
||||
@previous_history = []
|
||||
@conversation_id = config[:conversation_id]
|
||||
|
||||
setup_user(config)
|
||||
setup_message_history(config)
|
||||
@tools = build_tools
|
||||
register_tools
|
||||
@messages = build_messages(config)
|
||||
end
|
||||
|
||||
@@ -59,19 +60,16 @@ class Captain::Copilot::ChatService < Llm::BaseAiService
|
||||
end
|
||||
end
|
||||
|
||||
def build_tools
|
||||
tools = []
|
||||
|
||||
tools << Captain::Tools::SearchDocumentationService.new(@assistant, user: @user)
|
||||
tools << Captain::Tools::Copilot::GetConversationService.new(@assistant, user: @user)
|
||||
tools << Captain::Tools::Copilot::SearchConversationsService.new(@assistant, user: @user)
|
||||
tools << Captain::Tools::Copilot::GetContactService.new(@assistant, user: @user)
|
||||
tools << Captain::Tools::Copilot::GetArticleService.new(@assistant, user: @user)
|
||||
tools << Captain::Tools::Copilot::SearchArticlesService.new(@assistant, user: @user)
|
||||
tools << Captain::Tools::Copilot::SearchContactsService.new(@assistant, user: @user)
|
||||
tools << Captain::Tools::Copilot::SearchLinearIssuesService.new(@assistant, user: @user)
|
||||
|
||||
tools.select(&:active?)
|
||||
def register_tools
|
||||
@tool_registry = Captain::ToolRegistryService.new(@assistant, user: @user)
|
||||
@tool_registry.register_tool(Captain::Tools::SearchDocumentationService)
|
||||
@tool_registry.register_tool(Captain::Tools::Copilot::GetArticleService)
|
||||
@tool_registry.register_tool(Captain::Tools::Copilot::GetContactService)
|
||||
@tool_registry.register_tool(Captain::Tools::Copilot::GetConversationService)
|
||||
@tool_registry.register_tool(Captain::Tools::Copilot::SearchArticlesService)
|
||||
@tool_registry.register_tool(Captain::Tools::Copilot::SearchContactsService)
|
||||
@tool_registry.register_tool(Captain::Tools::Copilot::SearchConversationsService)
|
||||
@tool_registry.register_tool(Captain::Tools::Copilot::SearchLinearIssuesService)
|
||||
end
|
||||
|
||||
def system_message
|
||||
@@ -79,16 +77,12 @@ class Captain::Copilot::ChatService < Llm::BaseAiService
|
||||
role: 'system',
|
||||
content: Captain::Llm::SystemPromptsService.copilot_response_generator(
|
||||
@assistant.config['product_name'],
|
||||
tools_summary,
|
||||
@tool_registry.tools_summary,
|
||||
@assistant.config
|
||||
)
|
||||
}
|
||||
end
|
||||
|
||||
def tools_summary
|
||||
@tools.map { |tool| "- #{tool.class.name}: #{tool.class.description}" }.join("\n")
|
||||
end
|
||||
|
||||
def account_id_context
|
||||
{
|
||||
role: 'system',
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
class Captain::Llm::AssistantChatService < Llm::BaseAiService
|
||||
require 'openai'
|
||||
|
||||
class Captain::Llm::AssistantChatService < Llm::BaseOpenAiService
|
||||
include Captain::ChatHelper
|
||||
|
||||
def initialize(assistant: nil, conversation_id: nil)
|
||||
@@ -6,10 +8,9 @@ class Captain::Llm::AssistantChatService < Llm::BaseAiService
|
||||
|
||||
@assistant = assistant
|
||||
@conversation_id = conversation_id
|
||||
|
||||
@messages = [system_message]
|
||||
@response = ''
|
||||
@tools = build_tools
|
||||
register_tools
|
||||
end
|
||||
|
||||
# additional_message: A single message (String) from the user that should be appended to the chat.
|
||||
@@ -27,8 +28,9 @@ class Captain::Llm::AssistantChatService < Llm::BaseAiService
|
||||
|
||||
private
|
||||
|
||||
def build_tools
|
||||
[Captain::Tools::SearchDocumentationService.new(@assistant, user: nil)]
|
||||
def register_tools
|
||||
@tool_registry = Captain::ToolRegistryService.new(@assistant, user: nil)
|
||||
@tool_registry.register_tool(Captain::Tools::SearchDocumentationService)
|
||||
end
|
||||
|
||||
def system_message
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
class Captain::Llm::ContactAttributesService < Llm::LegacyBaseOpenAiService
|
||||
class Captain::Llm::ContactAttributesService < Llm::BaseOpenAiService
|
||||
def initialize(assistant, conversation)
|
||||
super()
|
||||
@assistant = assistant
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
class Captain::Llm::ContactNotesService < Llm::LegacyBaseOpenAiService
|
||||
class Captain::Llm::ContactNotesService < Llm::BaseOpenAiService
|
||||
def initialize(assistant, conversation)
|
||||
super()
|
||||
@assistant = assistant
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
class Captain::Llm::ConversationFaqService < Llm::LegacyBaseOpenAiService
|
||||
class Captain::Llm::ConversationFaqService < Llm::BaseOpenAiService
|
||||
DISTANCE_THRESHOLD = 0.3
|
||||
|
||||
def initialize(assistant, conversation)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
require 'openai'
|
||||
|
||||
class Captain::Llm::EmbeddingService < Llm::LegacyBaseOpenAiService
|
||||
class Captain::Llm::EmbeddingService < Llm::BaseOpenAiService
|
||||
class EmbeddingsError < StandardError; end
|
||||
|
||||
def self.embedding_model
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
class Captain::Llm::FaqGeneratorService < Llm::LegacyBaseOpenAiService
|
||||
class Captain::Llm::FaqGeneratorService < Llm::BaseOpenAiService
|
||||
def initialize(content, language = 'english')
|
||||
super()
|
||||
@language = language
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
class Captain::Llm::PaginatedFaqGeneratorService < Llm::LegacyBaseOpenAiService
|
||||
class Captain::Llm::PaginatedFaqGeneratorService < Llm::BaseOpenAiService
|
||||
# Default pages per chunk - easily configurable
|
||||
DEFAULT_PAGES_PER_CHUNK = 10
|
||||
MAX_ITERATIONS = 20 # Safety limit to prevent infinite loops
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
class Captain::Llm::PdfProcessingService < Llm::LegacyBaseOpenAiService
|
||||
class Captain::Llm::PdfProcessingService < Llm::BaseOpenAiService
|
||||
def initialize(document)
|
||||
super()
|
||||
@document = document
|
||||
@@ -29,16 +29,12 @@ class Captain::Llm::PdfProcessingService < Llm::LegacyBaseOpenAiService
|
||||
end
|
||||
end
|
||||
|
||||
def with_tempfile
|
||||
def with_tempfile(&)
|
||||
Tempfile.create(['pdf_upload', '.pdf'], binmode: true) do |temp_file|
|
||||
document.pdf_file.blob.open do |blob_file|
|
||||
IO.copy_stream(blob_file, temp_file)
|
||||
end
|
||||
temp_file.write(document.pdf_file.download)
|
||||
temp_file.close
|
||||
|
||||
temp_file.flush
|
||||
temp_file.rewind
|
||||
|
||||
yield temp_file
|
||||
File.open(temp_file.path, 'rb', &)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
class Captain::Onboarding::WebsiteAnalyzerService < Llm::LegacyBaseOpenAiService
|
||||
class Captain::Onboarding::WebsiteAnalyzerService < Llm::BaseOpenAiService
|
||||
MAX_CONTENT_LENGTH = 8000
|
||||
|
||||
def initialize(website_url)
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
class Captain::Tools::BaseTool < RubyLLM::Tool
|
||||
attr_accessor :assistant
|
||||
|
||||
def initialize(assistant, user: nil)
|
||||
@assistant = assistant
|
||||
@user = user
|
||||
super()
|
||||
end
|
||||
|
||||
def active?
|
||||
true
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def user_has_permission(permission)
|
||||
return false if @user.blank?
|
||||
|
||||
account_user = AccountUser.find_by(account_id: @assistant.account_id, user_id: @user.id)
|
||||
return false if account_user.blank?
|
||||
|
||||
return account_user.custom_role.permissions.include?(permission) if account_user.custom_role.present?
|
||||
|
||||
account_user.administrator? || account_user.agent?
|
||||
end
|
||||
end
|
||||
@@ -1,11 +1,32 @@
|
||||
class Captain::Tools::Copilot::GetArticleService < Captain::Tools::BaseTool
|
||||
def self.name
|
||||
class Captain::Tools::Copilot::GetArticleService < Captain::Tools::BaseService
|
||||
def name
|
||||
'get_article'
|
||||
end
|
||||
description 'Get details of an article including its content and metadata'
|
||||
param :article_id, type: :number, desc: 'The ID of the article to retrieve', required: true
|
||||
|
||||
def execute(article_id:)
|
||||
def description
|
||||
'Get details of an article including its content and metadata'
|
||||
end
|
||||
|
||||
def parameters
|
||||
{
|
||||
type: 'object',
|
||||
properties: {
|
||||
article_id: {
|
||||
type: 'number',
|
||||
description: 'The ID of the article to retrieve'
|
||||
}
|
||||
},
|
||||
required: %w[article_id]
|
||||
}
|
||||
end
|
||||
|
||||
def execute(arguments)
|
||||
article_id = arguments['article_id']
|
||||
|
||||
Rails.logger.info { "#{self.class.name}: Article ID: #{article_id}" }
|
||||
|
||||
return 'Missing required parameters' if article_id.blank?
|
||||
|
||||
article = Article.find_by(id: article_id, account_id: @assistant.account_id)
|
||||
return 'Article not found' if article.nil?
|
||||
|
||||
|
||||
@@ -1,11 +1,32 @@
|
||||
class Captain::Tools::Copilot::GetContactService < Captain::Tools::BaseTool
|
||||
def self.name
|
||||
class Captain::Tools::Copilot::GetContactService < Captain::Tools::BaseService
|
||||
def name
|
||||
'get_contact'
|
||||
end
|
||||
description 'Get details of a contact including their profile information'
|
||||
param :contact_id, type: :number, desc: 'The ID of the contact to retrieve', required: true
|
||||
|
||||
def execute(contact_id:)
|
||||
def description
|
||||
'Get details of a contact including their profile information'
|
||||
end
|
||||
|
||||
def parameters
|
||||
{
|
||||
type: 'object',
|
||||
properties: {
|
||||
contact_id: {
|
||||
type: 'number',
|
||||
description: 'The ID of the contact to retrieve'
|
||||
}
|
||||
},
|
||||
required: %w[contact_id]
|
||||
}
|
||||
end
|
||||
|
||||
def execute(arguments)
|
||||
contact_id = arguments['contact_id']
|
||||
|
||||
Rails.logger.info "#{self.class.name}: Contact ID: #{contact_id}"
|
||||
|
||||
return 'Missing required parameters' if contact_id.blank?
|
||||
|
||||
contact = Contact.find_by(id: contact_id, account_id: @assistant.account_id)
|
||||
return 'Contact not found' if contact.nil?
|
||||
|
||||
|
||||
@@ -1,12 +1,32 @@
|
||||
class Captain::Tools::Copilot::GetConversationService < Captain::Tools::BaseTool
|
||||
def self.name
|
||||
class Captain::Tools::Copilot::GetConversationService < Captain::Tools::BaseService
|
||||
def name
|
||||
'get_conversation'
|
||||
end
|
||||
description 'Get details of a conversation including messages and contact information'
|
||||
|
||||
param :conversation_id, type: :integer, desc: 'ID of the conversation to retrieve', required: true
|
||||
def description
|
||||
'Get details of a conversation including messages and contact information'
|
||||
end
|
||||
|
||||
def parameters
|
||||
{
|
||||
type: 'object',
|
||||
properties: {
|
||||
conversation_id: {
|
||||
type: 'number',
|
||||
description: 'The ID of the conversation to retrieve'
|
||||
}
|
||||
},
|
||||
required: %w[conversation_id]
|
||||
}
|
||||
end
|
||||
|
||||
def execute(arguments)
|
||||
conversation_id = arguments['conversation_id']
|
||||
|
||||
Rails.logger.info "#{self.class.name}: Conversation ID: #{conversation_id}"
|
||||
|
||||
return 'Missing required parameters' if conversation_id.blank?
|
||||
|
||||
def execute(conversation_id:)
|
||||
conversation = Conversation.find_by(display_id: conversation_id, account_id: @assistant.account_id)
|
||||
return 'Conversation not found' if conversation.blank?
|
||||
|
||||
|
||||
@@ -1,18 +1,36 @@
|
||||
class Captain::Tools::Copilot::SearchArticlesService < Captain::Tools::BaseTool
|
||||
def self.name
|
||||
class Captain::Tools::Copilot::SearchArticlesService < Captain::Tools::BaseService
|
||||
def name
|
||||
'search_articles'
|
||||
end
|
||||
description 'Search articles based on parameters'
|
||||
param :query, desc: 'Search articles by title or content (partial match)', required: false
|
||||
param :category_id, type: :number, desc: 'Filter articles by category ID', required: false
|
||||
param :status, type: :string, desc: 'Filter articles by status - MUST BE ONE OF: draft, published, archived', required: false
|
||||
|
||||
def execute(query: nil, category_id: nil, status: nil)
|
||||
articles = fetch_articles(query: query, category_id: category_id, status: status)
|
||||
def description
|
||||
'Search articles based on parameters'
|
||||
end
|
||||
|
||||
def parameters
|
||||
{
|
||||
type: 'object',
|
||||
properties: properties,
|
||||
required: ['query']
|
||||
}
|
||||
end
|
||||
|
||||
def execute(arguments)
|
||||
query = arguments['query']
|
||||
category_id = arguments['category_id']
|
||||
status = arguments['status']
|
||||
|
||||
Rails.logger.info "#{self.class.name}: Query: #{query}, Category ID: #{category_id}, Status: #{status}"
|
||||
|
||||
return 'Missing required parameters' if query.blank?
|
||||
|
||||
articles = fetch_articles(query, category_id, status)
|
||||
|
||||
return 'No articles found' unless articles.exists?
|
||||
|
||||
total_count = articles.count
|
||||
articles = articles.limit(100)
|
||||
|
||||
<<~RESPONSE
|
||||
#{total_count > 100 ? "Found #{total_count} articles (showing first 100)" : "Total number of articles: #{total_count}"}
|
||||
#{articles.map(&:to_llm_text).join("\n---\n")}
|
||||
@@ -25,11 +43,29 @@ class Captain::Tools::Copilot::SearchArticlesService < Captain::Tools::BaseTool
|
||||
|
||||
private
|
||||
|
||||
def fetch_articles(query:, category_id:, status:)
|
||||
def fetch_articles(query, category_id, status)
|
||||
articles = Article.where(account_id: @assistant.account_id)
|
||||
articles = articles.where('title ILIKE :query OR content ILIKE :query', query: "%#{query}%") if query.present?
|
||||
articles = articles.where(category_id: category_id) if category_id.present?
|
||||
articles = articles.where(status: status) if status.present?
|
||||
articles
|
||||
end
|
||||
|
||||
def properties
|
||||
{
|
||||
query: {
|
||||
type: 'string',
|
||||
description: 'Search articles by title or content (partial match)'
|
||||
},
|
||||
category_id: {
|
||||
type: 'number',
|
||||
description: 'Filter articles by category ID'
|
||||
},
|
||||
status: {
|
||||
type: 'string',
|
||||
enum: %w[draft published archived],
|
||||
description: 'Filter articles by status'
|
||||
}
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,14 +1,27 @@
|
||||
class Captain::Tools::Copilot::SearchContactsService < Captain::Tools::BaseTool
|
||||
def self.name
|
||||
class Captain::Tools::Copilot::SearchContactsService < Captain::Tools::BaseService
|
||||
def name
|
||||
'search_contacts'
|
||||
end
|
||||
|
||||
description 'Search contacts based on query parameters'
|
||||
param :email, type: :string, desc: 'Filter contacts by email'
|
||||
param :phone_number, type: :string, desc: 'Filter contacts by phone number'
|
||||
param :name, type: :string, desc: 'Filter contacts by name (partial match)'
|
||||
def description
|
||||
'Search contacts based on query parameters'
|
||||
end
|
||||
|
||||
def parameters
|
||||
{
|
||||
type: 'object',
|
||||
properties: properties,
|
||||
required: []
|
||||
}
|
||||
end
|
||||
|
||||
def execute(arguments)
|
||||
email = arguments['email']
|
||||
phone_number = arguments['phone_number']
|
||||
name = arguments['name']
|
||||
|
||||
Rails.logger.info "#{self.class.name} Email: #{email}, Phone Number: #{phone_number}, Name: #{name}"
|
||||
|
||||
def execute(email: nil, phone_number: nil, name: nil)
|
||||
contacts = Contact.where(account_id: @assistant.account_id)
|
||||
contacts = contacts.where(email: email) if email.present?
|
||||
contacts = contacts.where(phone_number: phone_number) if phone_number.present?
|
||||
@@ -26,4 +39,23 @@ class Captain::Tools::Copilot::SearchContactsService < Captain::Tools::BaseTool
|
||||
def active?
|
||||
user_has_permission('contact_manage')
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def properties
|
||||
{
|
||||
email: {
|
||||
type: 'string',
|
||||
description: 'Filter contacts by email'
|
||||
},
|
||||
phone_number: {
|
||||
type: 'string',
|
||||
description: 'Filter contacts by phone number'
|
||||
},
|
||||
name: {
|
||||
type: 'string',
|
||||
description: 'Filter contacts by name (partial match)'
|
||||
}
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user