mirror of
https://github.com/lingble/chatwoot.git
synced 2025-10-29 10:12:34 +00:00
feat: allow quoted email thread in reply (#12545)
This PR adds the ability to include the thread history as a quoted text ## Preview https://github.com/user-attachments/assets/c96a85e5-8ac8-4021-86ca-57509b4eea9f
This commit is contained in:
@@ -20,6 +20,7 @@ class Messages::MessageBuilder
|
||||
@message = @conversation.messages.build(message_params)
|
||||
process_attachments
|
||||
process_emails
|
||||
process_email_content
|
||||
@message.save!
|
||||
@message
|
||||
end
|
||||
@@ -92,6 +93,14 @@ class Messages::MessageBuilder
|
||||
@message.content_attributes[:to_emails] = to_emails
|
||||
end
|
||||
|
||||
def process_email_content
|
||||
return unless should_process_email_content?
|
||||
|
||||
@message.content_attributes ||= {}
|
||||
email_attributes = build_email_attributes
|
||||
@message.content_attributes[:email] = email_attributes
|
||||
end
|
||||
|
||||
def process_email_string(email_string)
|
||||
return [] if email_string.blank?
|
||||
|
||||
@@ -153,4 +162,52 @@ class Messages::MessageBuilder
|
||||
source_id: @params[:source_id]
|
||||
}.merge(external_created_at).merge(automation_rule_id).merge(campaign_id).merge(template_params)
|
||||
end
|
||||
|
||||
def email_inbox?
|
||||
@conversation.inbox&.inbox_type == 'Email'
|
||||
end
|
||||
|
||||
def should_process_email_content?
|
||||
email_inbox? && !@private && @message.content.present?
|
||||
end
|
||||
|
||||
def build_email_attributes
|
||||
email_attributes = ensure_indifferent_access(@message.content_attributes[:email] || {})
|
||||
normalized_content = normalize_email_body(@message.content)
|
||||
|
||||
email_attributes[:html_content] = build_html_content(normalized_content)
|
||||
email_attributes[:text_content] = build_text_content(normalized_content)
|
||||
email_attributes
|
||||
end
|
||||
|
||||
def build_html_content(normalized_content)
|
||||
html_content = ensure_indifferent_access(@message.content_attributes.dig(:email, :html_content) || {})
|
||||
rendered_html = render_email_html(normalized_content)
|
||||
html_content[:full] = rendered_html
|
||||
html_content[:reply] = rendered_html
|
||||
html_content
|
||||
end
|
||||
|
||||
def build_text_content(normalized_content)
|
||||
text_content = ensure_indifferent_access(@message.content_attributes.dig(:email, :text_content) || {})
|
||||
text_content[:full] = normalized_content
|
||||
text_content[:reply] = normalized_content
|
||||
text_content
|
||||
end
|
||||
|
||||
def ensure_indifferent_access(hash)
|
||||
return {} if hash.blank?
|
||||
|
||||
hash.respond_to?(:with_indifferent_access) ? hash.with_indifferent_access : hash
|
||||
end
|
||||
|
||||
def normalize_email_body(content)
|
||||
content.to_s.gsub("\r\n", "\n")
|
||||
end
|
||||
|
||||
def render_email_html(content)
|
||||
return '' if content.blank?
|
||||
|
||||
ChatwootMarkdownRenderer.new(content).render_message.to_s
|
||||
end
|
||||
end
|
||||
|
||||
@@ -5,9 +5,8 @@ import { sanitizeTextForRender } from '@chatwoot/utils';
|
||||
import { allowedCssProperties } from 'lettersanitizer';
|
||||
|
||||
import Icon from 'next/icon/Icon.vue';
|
||||
import { EmailQuoteExtractor } from './removeReply.js';
|
||||
import { EmailQuoteExtractor } from 'dashboard/helper/emailQuoteExtractor.js';
|
||||
import BaseBubble from 'next/message/bubbles/Base.vue';
|
||||
import FormattedContent from 'next/message/bubbles/Text/FormattedContent.vue';
|
||||
import AttachmentChips from 'next/message/chips/AttachmentChips.vue';
|
||||
import EmailMeta from './EmailMeta.vue';
|
||||
import TranslationToggle from 'dashboard/components-next/message/TranslationToggle.vue';
|
||||
@@ -47,15 +46,6 @@ const originalEmailHtml = computed(
|
||||
originalEmailText.value
|
||||
);
|
||||
|
||||
const messageContent = computed(() => {
|
||||
// If translations exist and we're showing translations (not original)
|
||||
if (hasTranslations.value && !renderOriginal.value) {
|
||||
return translationContent.value;
|
||||
}
|
||||
// Otherwise show original content
|
||||
return content.value;
|
||||
});
|
||||
|
||||
const textToShow = computed(() => {
|
||||
// If translations exist and we're showing translations (not original)
|
||||
if (hasTranslations.value && !renderOriginal.value) {
|
||||
@@ -136,37 +126,30 @@ const handleSeeOriginal = () => {
|
||||
{{ $t('EMAIL_HEADER.EXPAND') }}
|
||||
</button>
|
||||
</div>
|
||||
<FormattedContent
|
||||
v-if="isOutgoing && content"
|
||||
class="text-n-slate-12"
|
||||
:content="messageContent"
|
||||
<Letter
|
||||
v-if="showQuotedMessage"
|
||||
:key="`letter-quoted-${translationKeySuffix}`"
|
||||
class-name="prose prose-bubble !max-w-none letter-render"
|
||||
:allowed-css-properties="[
|
||||
...allowedCssProperties,
|
||||
'transform',
|
||||
'transform-origin',
|
||||
]"
|
||||
:html="fullHTML"
|
||||
:text="textToShow"
|
||||
/>
|
||||
<Letter
|
||||
v-else
|
||||
:key="`letter-unquoted-${translationKeySuffix}`"
|
||||
class-name="prose prose-bubble !max-w-none letter-render"
|
||||
:html="unquotedHTML"
|
||||
:allowed-css-properties="[
|
||||
...allowedCssProperties,
|
||||
'transform',
|
||||
'transform-origin',
|
||||
]"
|
||||
:text="textToShow"
|
||||
/>
|
||||
<template v-else>
|
||||
<Letter
|
||||
v-if="showQuotedMessage"
|
||||
:key="`letter-quoted-${translationKeySuffix}`"
|
||||
class-name="prose prose-bubble !max-w-none letter-render"
|
||||
:allowed-css-properties="[
|
||||
...allowedCssProperties,
|
||||
'transform',
|
||||
'transform-origin',
|
||||
]"
|
||||
:html="fullHTML"
|
||||
:text="textToShow"
|
||||
/>
|
||||
<Letter
|
||||
v-else
|
||||
:key="`letter-unquoted-${translationKeySuffix}`"
|
||||
class-name="prose prose-bubble !max-w-none letter-render"
|
||||
:html="unquotedHTML"
|
||||
:allowed-css-properties="[
|
||||
...allowedCssProperties,
|
||||
'transform',
|
||||
'transform-origin',
|
||||
]"
|
||||
:text="textToShow"
|
||||
/>
|
||||
</template>
|
||||
<button
|
||||
v-if="hasQuotedMessage"
|
||||
class="text-n-slate-11 px-1 leading-none text-sm bg-n-alpha-black2 text-center flex items-center gap-1 mt-2"
|
||||
|
||||
@@ -118,6 +118,14 @@ export default {
|
||||
type: String,
|
||||
default: '',
|
||||
},
|
||||
showQuotedReplyToggle: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
quotedReplyEnabled: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
},
|
||||
emits: [
|
||||
'replaceText',
|
||||
@@ -125,6 +133,7 @@ export default {
|
||||
'toggleEditor',
|
||||
'selectWhatsappTemplate',
|
||||
'selectContentTemplate',
|
||||
'toggleQuotedReply',
|
||||
],
|
||||
setup() {
|
||||
const { setSignatureFlagForInbox, fetchSignatureFlagFromUISettings } =
|
||||
@@ -249,6 +258,11 @@ export default {
|
||||
isFetchingAppIntegrations() {
|
||||
return this.uiFlags.isFetching;
|
||||
},
|
||||
quotedReplyToggleTooltip() {
|
||||
return this.quotedReplyEnabled
|
||||
? this.$t('CONVERSATION.REPLYBOX.QUOTED_REPLY.DISABLE_TOOLTIP')
|
||||
: this.$t('CONVERSATION.REPLYBOX.QUOTED_REPLY.ENABLE_TOOLTIP');
|
||||
},
|
||||
},
|
||||
mounted() {
|
||||
ActiveStorage.start();
|
||||
@@ -339,6 +353,16 @@ export default {
|
||||
sm
|
||||
@click="toggleMessageSignature"
|
||||
/>
|
||||
<NextButton
|
||||
v-if="showQuotedReplyToggle"
|
||||
v-tooltip.top-end="quotedReplyToggleTooltip"
|
||||
icon="i-ph-quotes"
|
||||
:variant="quotedReplyEnabled ? 'solid' : 'faded'"
|
||||
color="slate"
|
||||
sm
|
||||
:aria-pressed="quotedReplyEnabled"
|
||||
@click="$emit('toggleQuotedReply')"
|
||||
/>
|
||||
<NextButton
|
||||
v-if="enableWhatsAppTemplates"
|
||||
v-tooltip.top-end="$t('CONVERSATION.FOOTER.WHATSAPP_TEMPLATES')"
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
<script setup>
|
||||
import { computed, ref } from 'vue';
|
||||
import { useMessageFormatter } from 'shared/composables/useMessageFormatter';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import NextButton from 'dashboard/components-next/button/Button.vue';
|
||||
|
||||
const props = defineProps({
|
||||
quotedEmailText: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
previewText: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
});
|
||||
|
||||
const emit = defineEmits(['toggle']);
|
||||
|
||||
const { t } = useI18n();
|
||||
const { formatMessage } = useMessageFormatter();
|
||||
|
||||
const isExpanded = ref(false);
|
||||
|
||||
const formattedQuotedEmailText = computed(() => {
|
||||
if (!props.quotedEmailText) {
|
||||
return '';
|
||||
}
|
||||
return formatMessage(props.quotedEmailText, false, false, true);
|
||||
});
|
||||
|
||||
const toggleExpand = () => {
|
||||
isExpanded.value = !isExpanded.value;
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="mt-2">
|
||||
<div
|
||||
class="relative rounded-md px-3 py-2 text-xs text-n-slate-12 bg-n-slate-3 dark:bg-n-solid-3"
|
||||
>
|
||||
<div class="absolute top-2 right-2 z-10 flex items-center gap-1">
|
||||
<NextButton
|
||||
v-tooltip="
|
||||
isExpanded
|
||||
? t('CONVERSATION.REPLYBOX.QUOTED_REPLY.COLLAPSE')
|
||||
: t('CONVERSATION.REPLYBOX.QUOTED_REPLY.EXPAND')
|
||||
"
|
||||
ghost
|
||||
slate
|
||||
xs
|
||||
:icon="isExpanded ? 'i-lucide-minimize' : 'i-lucide-maximize'"
|
||||
@click="toggleExpand"
|
||||
/>
|
||||
<NextButton
|
||||
v-tooltip="t('CONVERSATION.REPLYBOX.QUOTED_REPLY.REMOVE_PREVIEW')"
|
||||
ghost
|
||||
slate
|
||||
xs
|
||||
icon="i-lucide-x"
|
||||
@click="emit('toggle')"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
v-dompurify-html="formattedQuotedEmailText"
|
||||
class="w-full max-w-none break-words prose prose-sm dark:prose-invert cursor-pointer pr-8"
|
||||
:class="{
|
||||
'line-clamp-1': !isExpanded,
|
||||
'max-h-60 overflow-y-auto': isExpanded,
|
||||
}"
|
||||
:title="previewText"
|
||||
@click="toggleExpand"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -5,6 +5,7 @@ import { useAlert } from 'dashboard/composables';
|
||||
import { useUISettings } from 'dashboard/composables/useUISettings';
|
||||
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';
|
||||
@@ -16,6 +17,7 @@ import ReplyBottomPanel from 'dashboard/components/widgets/WootWriter/ReplyBotto
|
||||
import ArticleSearchPopover from 'dashboard/routes/dashboard/helpcenter/components/ArticleSearch/SearchPopover.vue';
|
||||
import MessageSignatureMissingAlert from './MessageSignatureMissingAlert.vue';
|
||||
import ReplyBoxBanner from './ReplyBoxBanner.vue';
|
||||
import QuotedEmailPreview from './QuotedEmailPreview.vue';
|
||||
import { REPLY_EDITOR_MODES } from 'dashboard/components/widgets/WootWriter/constants';
|
||||
import WootMessageEditor from 'dashboard/components/widgets/WootWriter/Editor.vue';
|
||||
import AudioRecorder from 'dashboard/components/widgets/WootWriter/AudioRecorder.vue';
|
||||
@@ -32,6 +34,12 @@ import { MESSAGE_MAX_LENGTH } from 'shared/helpers/MessageTypeHelper';
|
||||
import inboxMixin, { INBOX_FEATURES } from 'shared/mixins/inboxMixin';
|
||||
import { trimContent, debounce, getRecipients } from '@chatwoot/utils';
|
||||
import wootConstants from 'dashboard/constants/globals';
|
||||
import {
|
||||
extractQuotedEmailText,
|
||||
buildQuotedEmailHeader,
|
||||
truncatePreviewText,
|
||||
appendQuotedTextToMessage,
|
||||
} from 'dashboard/helper/quotedEmailHelper';
|
||||
import { CONVERSATION_EVENTS } from '../../../helper/AnalyticsHelper/events';
|
||||
import fileUploadMixin from 'dashboard/mixins/fileUploadMixin';
|
||||
import {
|
||||
@@ -65,6 +73,7 @@ export default {
|
||||
ContentTemplates,
|
||||
WhatsappTemplates,
|
||||
WootMessageEditor,
|
||||
QuotedEmailPreview,
|
||||
},
|
||||
mixins: [inboxMixin, fileUploadMixin, keyboardEventListenerMixins],
|
||||
props: {
|
||||
@@ -80,6 +89,8 @@ export default {
|
||||
updateUISettings,
|
||||
isEditorHotKeyEnabled,
|
||||
fetchSignatureFlagFromUISettings,
|
||||
setQuotedReplyFlagForInbox,
|
||||
fetchQuotedReplyFlagFromUISettings,
|
||||
} = useUISettings();
|
||||
|
||||
const replyEditor = useTemplateRef('replyEditor');
|
||||
@@ -89,6 +100,8 @@ export default {
|
||||
updateUISettings,
|
||||
isEditorHotKeyEnabled,
|
||||
fetchSignatureFlagFromUISettings,
|
||||
setQuotedReplyFlagForInbox,
|
||||
fetchQuotedReplyFlagFromUISettings,
|
||||
replyEditor,
|
||||
};
|
||||
},
|
||||
@@ -130,6 +143,8 @@ export default {
|
||||
currentUser: 'getCurrentUser',
|
||||
lastEmail: 'getLastEmailInSelectedChat',
|
||||
globalConfig: 'globalConfig/get',
|
||||
accountId: 'getCurrentAccountId',
|
||||
isFeatureEnabledonAccount: 'accounts/isFeatureEnabledonAccount',
|
||||
}),
|
||||
currentContact() {
|
||||
return this.$store.getters['contacts/getContact'](
|
||||
@@ -367,6 +382,51 @@ export default {
|
||||
const { slug = '' } = portal;
|
||||
return slug;
|
||||
},
|
||||
isQuotedEmailReplyEnabled() {
|
||||
return this.isFeatureEnabledonAccount(
|
||||
this.accountId,
|
||||
FEATURE_FLAGS.QUOTED_EMAIL_REPLY
|
||||
);
|
||||
},
|
||||
quotedReplyPreference() {
|
||||
if (!this.isAnEmailChannel || !this.isQuotedEmailReplyEnabled) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return !!this.fetchQuotedReplyFlagFromUISettings(this.channelType);
|
||||
},
|
||||
lastEmailWithQuotedContent() {
|
||||
if (!this.isAnEmailChannel) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const lastEmail = this.lastEmail;
|
||||
if (!lastEmail || lastEmail.private) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return lastEmail;
|
||||
},
|
||||
quotedEmailText() {
|
||||
return extractQuotedEmailText(this.lastEmailWithQuotedContent);
|
||||
},
|
||||
quotedEmailPreviewText() {
|
||||
return truncatePreviewText(this.quotedEmailText, 80);
|
||||
},
|
||||
shouldShowQuotedReplyToggle() {
|
||||
return (
|
||||
this.isAnEmailChannel &&
|
||||
!this.isOnPrivateNote &&
|
||||
this.isQuotedEmailReplyEnabled
|
||||
);
|
||||
},
|
||||
shouldShowQuotedPreview() {
|
||||
return (
|
||||
this.shouldShowQuotedReplyToggle &&
|
||||
this.quotedReplyPreference &&
|
||||
!!this.quotedEmailText
|
||||
);
|
||||
},
|
||||
},
|
||||
watch: {
|
||||
currentChat(conversation, oldConversation) {
|
||||
@@ -516,6 +576,36 @@ export default {
|
||||
);
|
||||
}
|
||||
},
|
||||
toggleQuotedReply() {
|
||||
if (!this.isAnEmailChannel) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextValue = !this.quotedReplyPreference;
|
||||
this.setQuotedReplyFlagForInbox(this.channelType, nextValue);
|
||||
},
|
||||
shouldIncludeQuotedEmail() {
|
||||
return (
|
||||
this.isQuotedEmailReplyEnabled &&
|
||||
this.quotedReplyPreference &&
|
||||
this.shouldShowQuotedReplyToggle &&
|
||||
!!this.quotedEmailText
|
||||
);
|
||||
},
|
||||
getMessageWithQuotedEmailText(message) {
|
||||
if (!this.shouldIncludeQuotedEmail()) {
|
||||
return message;
|
||||
}
|
||||
|
||||
const quotedText = this.quotedEmailText || '';
|
||||
const header = buildQuotedEmailHeader(
|
||||
this.lastEmailWithQuotedContent,
|
||||
this.currentContact,
|
||||
this.inbox
|
||||
);
|
||||
|
||||
return appendQuotedTextToMessage(message, quotedText, header);
|
||||
},
|
||||
resetRecorderAndClearAttachments() {
|
||||
// Reset audio recorder UI state
|
||||
this.resetAudioRecorderInput();
|
||||
@@ -965,9 +1055,11 @@ export default {
|
||||
return multipleMessagePayload;
|
||||
},
|
||||
getMessagePayload(message) {
|
||||
const messageWithQuote = this.getMessageWithQuotedEmailText(message);
|
||||
|
||||
let messagePayload = {
|
||||
conversationId: this.currentChat.id,
|
||||
message,
|
||||
message: messageWithQuote,
|
||||
private: this.isPrivate,
|
||||
sender: this.sender,
|
||||
};
|
||||
@@ -995,7 +1087,6 @@ export default {
|
||||
if (this.toEmails && !this.isOnPrivateNote) {
|
||||
messagePayload.toEmails = this.toEmails;
|
||||
}
|
||||
|
||||
return messagePayload;
|
||||
},
|
||||
setCcEmails(value) {
|
||||
@@ -1160,6 +1251,12 @@ export default {
|
||||
@toggle-variables-menu="toggleVariablesMenu"
|
||||
@clear-selection="clearEditorSelection"
|
||||
/>
|
||||
<QuotedEmailPreview
|
||||
v-if="shouldShowQuotedPreview"
|
||||
:quoted-email-text="quotedEmailText"
|
||||
:preview-text="quotedEmailPreviewText"
|
||||
@toggle="toggleQuotedReply"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
v-if="hasAttachments && !showAudioRecorderEditor"
|
||||
@@ -1195,6 +1292,8 @@ export default {
|
||||
:show-editor-toggle="isAPIInbox && !isOnPrivateNote"
|
||||
:show-emoji-picker="showEmojiPicker"
|
||||
:show-file-upload="showFileUpload"
|
||||
:show-quoted-reply-toggle="shouldShowQuotedReplyToggle"
|
||||
:quoted-reply-enabled="quotedReplyPreference"
|
||||
:toggle-audio-recorder-play-pause="toggleAudioRecorderPlayPause"
|
||||
:toggle-audio-recorder="toggleAudioRecorder"
|
||||
:toggle-emoji-picker="toggleEmojiPicker"
|
||||
@@ -1206,6 +1305,7 @@ export default {
|
||||
@toggle-editor="toggleRichContentEditor"
|
||||
@replace-text="replaceText"
|
||||
@toggle-insert-article="toggleInsertArticle"
|
||||
@toggle-quoted-reply="toggleQuotedReply"
|
||||
/>
|
||||
<WhatsappTemplates
|
||||
:inbox-id="inbox.id"
|
||||
|
||||
@@ -13,6 +13,7 @@ const getUISettingsMock = ref({
|
||||
conversation_sidebar_items_order: DEFAULT_CONVERSATION_SIDEBAR_ITEMS_ORDER,
|
||||
contact_sidebar_items_order: DEFAULT_CONTACT_SIDEBAR_ITEMS_ORDER,
|
||||
editor_message_key: 'enter',
|
||||
channel_email_quoted_reply_enabled: true,
|
||||
});
|
||||
|
||||
vi.mock('dashboard/composables/store', () => ({
|
||||
@@ -37,6 +38,7 @@ describe('useUISettings', () => {
|
||||
DEFAULT_CONVERSATION_SIDEBAR_ITEMS_ORDER,
|
||||
contact_sidebar_items_order: DEFAULT_CONTACT_SIDEBAR_ITEMS_ORDER,
|
||||
editor_message_key: 'enter',
|
||||
channel_email_quoted_reply_enabled: true,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -51,6 +53,7 @@ describe('useUISettings', () => {
|
||||
DEFAULT_CONVERSATION_SIDEBAR_ITEMS_ORDER,
|
||||
contact_sidebar_items_order: DEFAULT_CONTACT_SIDEBAR_ITEMS_ORDER,
|
||||
editor_message_key: 'enter',
|
||||
channel_email_quoted_reply_enabled: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -65,6 +68,7 @@ describe('useUISettings', () => {
|
||||
DEFAULT_CONVERSATION_SIDEBAR_ITEMS_ORDER,
|
||||
contact_sidebar_items_order: DEFAULT_CONTACT_SIDEBAR_ITEMS_ORDER,
|
||||
editor_message_key: 'enter',
|
||||
channel_email_quoted_reply_enabled: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -100,6 +104,7 @@ describe('useUISettings', () => {
|
||||
contact_sidebar_items_order: DEFAULT_CONTACT_SIDEBAR_ITEMS_ORDER,
|
||||
email_signature_enabled: true,
|
||||
editor_message_key: 'enter',
|
||||
channel_email_quoted_reply_enabled: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -109,6 +114,26 @@ describe('useUISettings', () => {
|
||||
expect(fetchSignatureFlagFromUISettings('email')).toBe(undefined);
|
||||
});
|
||||
|
||||
it('sets quoted reply flag for inbox correctly', () => {
|
||||
const { setQuotedReplyFlagForInbox } = useUISettings();
|
||||
setQuotedReplyFlagForInbox('Channel::Email', false);
|
||||
expect(mockDispatch).toHaveBeenCalledWith('updateUISettings', {
|
||||
uiSettings: {
|
||||
is_ct_labels_open: true,
|
||||
conversation_sidebar_items_order:
|
||||
DEFAULT_CONVERSATION_SIDEBAR_ITEMS_ORDER,
|
||||
contact_sidebar_items_order: DEFAULT_CONTACT_SIDEBAR_ITEMS_ORDER,
|
||||
editor_message_key: 'enter',
|
||||
channel_email_quoted_reply_enabled: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('fetches quoted reply flag from UI settings correctly', () => {
|
||||
const { fetchQuotedReplyFlagFromUISettings } = useUISettings();
|
||||
expect(fetchQuotedReplyFlagFromUISettings('Channel::Email')).toBe(true);
|
||||
});
|
||||
|
||||
it('returns correct value for isEditorHotKeyEnabled when editor_message_key is configured', () => {
|
||||
getUISettingsMock.value.enter_to_send_enabled = false;
|
||||
const { isEditorHotKeyEnabled } = useUISettings();
|
||||
|
||||
@@ -87,6 +87,13 @@ const setSignatureFlagForInbox = (channelType, value, updateUISettings) => {
|
||||
updateUISettings({ [`${slugifiedChannel}_signature_enabled`]: value });
|
||||
};
|
||||
|
||||
const setQuotedReplyFlagForInbox = (channelType, value, updateUISettings) => {
|
||||
if (!channelType) return;
|
||||
|
||||
const slugifiedChannel = slugifyChannel(channelType);
|
||||
updateUISettings({ [`${slugifiedChannel}_quoted_reply_enabled`]: value });
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches the signature flag for a specific channel type from UI settings.
|
||||
* @param {string} channelType - The type of the channel.
|
||||
@@ -100,6 +107,13 @@ const fetchSignatureFlagFromUISettings = (channelType, uiSettings) => {
|
||||
return uiSettings.value[`${slugifiedChannel}_signature_enabled`];
|
||||
};
|
||||
|
||||
const fetchQuotedReplyFlagFromUISettings = (channelType, uiSettings) => {
|
||||
if (!channelType) return false;
|
||||
|
||||
const slugifiedChannel = slugifyChannel(channelType);
|
||||
return uiSettings.value[`${slugifiedChannel}_quoted_reply_enabled`];
|
||||
};
|
||||
|
||||
/**
|
||||
* Checks if a specific editor hotkey is enabled.
|
||||
* @param {string} key - The key to check.
|
||||
@@ -147,6 +161,10 @@ export function useUISettings() {
|
||||
setSignatureFlagForInbox(channelType, value, updateUISettings),
|
||||
fetchSignatureFlagFromUISettings: channelType =>
|
||||
fetchSignatureFlagFromUISettings(channelType, uiSettings),
|
||||
setQuotedReplyFlagForInbox: (channelType, value) =>
|
||||
setQuotedReplyFlagForInbox(channelType, value, updateUISettings),
|
||||
fetchQuotedReplyFlagFromUISettings: channelType =>
|
||||
fetchQuotedReplyFlagFromUISettings(channelType, uiSettings),
|
||||
isEditorHotKeyEnabled: key => isEditorHotKeyEnabled(key, uiSettings),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -40,6 +40,7 @@ export const FEATURE_FLAGS = {
|
||||
CONTACT_CHATWOOT_SUPPORT_TEAM: 'contact_chatwoot_support_team',
|
||||
CAPTAIN_V2: 'captain_integration_v2',
|
||||
SAML: 'saml',
|
||||
QUOTED_EMAIL_REPLY: 'quoted_email_reply',
|
||||
};
|
||||
|
||||
export const PREMIUM_FEATURES = [
|
||||
|
||||
@@ -10,6 +10,8 @@ const QUOTE_INDICATORS = [
|
||||
'[class*="Quote"]',
|
||||
];
|
||||
|
||||
const BLOCKQUOTE_FALLBACK_SELECTOR = 'blockquote';
|
||||
|
||||
// Regex patterns for quote identification
|
||||
const QUOTE_PATTERNS = [
|
||||
/On .* wrote:/i,
|
||||
@@ -36,6 +38,8 @@ export class EmailQuoteExtractor {
|
||||
});
|
||||
});
|
||||
|
||||
this.removeTrailingBlockquote(tempDiv);
|
||||
|
||||
// Remove text-based quotes
|
||||
const textNodeQuotes = this.findTextNodeQuotes(tempDiv);
|
||||
textNodeQuotes.forEach(el => {
|
||||
@@ -62,6 +66,10 @@ export class EmailQuoteExtractor {
|
||||
}
|
||||
}
|
||||
|
||||
if (this.findTrailingBlockquote(tempDiv)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check for text-based quotes
|
||||
const textNodeQuotes = this.findTextNodeQuotes(tempDiv);
|
||||
return textNodeQuotes.length > 0;
|
||||
@@ -123,4 +131,26 @@ export class EmailQuoteExtractor {
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove fallback blockquote if it is the last top-level element.
|
||||
* @param {Element} rootElement - Root element containing the HTML
|
||||
*/
|
||||
static removeTrailingBlockquote(rootElement) {
|
||||
const trailingBlockquote = this.findTrailingBlockquote(rootElement);
|
||||
trailingBlockquote?.remove();
|
||||
}
|
||||
|
||||
/**
|
||||
* Locate a fallback blockquote that is the last top-level element.
|
||||
* @param {Element} rootElement - Root element containing the HTML
|
||||
* @returns {Element|null} The trailing blockquote element if present
|
||||
*/
|
||||
static findTrailingBlockquote(rootElement) {
|
||||
const lastElement = rootElement.lastElementChild;
|
||||
if (lastElement?.matches?.(BLOCKQUOTE_FALLBACK_SELECTOR)) {
|
||||
return lastElement;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
332
app/javascript/dashboard/helper/quotedEmailHelper.js
Normal file
332
app/javascript/dashboard/helper/quotedEmailHelper.js
Normal file
@@ -0,0 +1,332 @@
|
||||
import { format, parseISO, isValid as isValidDate } from 'date-fns';
|
||||
|
||||
/**
|
||||
* Extracts plain text from HTML content
|
||||
* @param {string} html - HTML content to convert
|
||||
* @returns {string} Plain text content
|
||||
*/
|
||||
export const extractPlainTextFromHtml = html => {
|
||||
if (!html) {
|
||||
return '';
|
||||
}
|
||||
if (typeof document === 'undefined') {
|
||||
return html.replace(/<[^>]*>/g, ' ');
|
||||
}
|
||||
const tempDiv = document.createElement('div');
|
||||
tempDiv.innerHTML = html;
|
||||
return tempDiv.textContent || tempDiv.innerText || '';
|
||||
};
|
||||
|
||||
/**
|
||||
* Extracts sender name from email message
|
||||
* @param {Object} lastEmail - Last email message object
|
||||
* @param {Object} contact - Contact object
|
||||
* @returns {string} Sender name
|
||||
*/
|
||||
export const getEmailSenderName = (lastEmail, contact) => {
|
||||
const senderName = lastEmail?.sender?.name;
|
||||
if (senderName && senderName.trim()) {
|
||||
return senderName.trim();
|
||||
}
|
||||
|
||||
const contactName = contact?.name;
|
||||
return contactName && contactName.trim() ? contactName.trim() : '';
|
||||
};
|
||||
|
||||
/**
|
||||
* Extracts sender email from email message
|
||||
* @param {Object} lastEmail - Last email message object
|
||||
* @param {Object} contact - Contact object
|
||||
* @returns {string} Sender email address
|
||||
*/
|
||||
export const getEmailSenderEmail = (lastEmail, contact) => {
|
||||
const senderEmail = lastEmail?.sender?.email;
|
||||
if (senderEmail && senderEmail.trim()) {
|
||||
return senderEmail.trim();
|
||||
}
|
||||
|
||||
const contentAttributes =
|
||||
lastEmail?.contentAttributes || lastEmail?.content_attributes || {};
|
||||
const emailMeta = contentAttributes.email || {};
|
||||
|
||||
if (Array.isArray(emailMeta.from) && emailMeta.from.length > 0) {
|
||||
const fromAddress = emailMeta.from[0];
|
||||
if (fromAddress && fromAddress.trim()) {
|
||||
return fromAddress.trim();
|
||||
}
|
||||
}
|
||||
|
||||
const contactEmail = contact?.email;
|
||||
return contactEmail && contactEmail.trim() ? contactEmail.trim() : '';
|
||||
};
|
||||
|
||||
/**
|
||||
* Extracts date from email message
|
||||
* @param {Object} lastEmail - Last email message object
|
||||
* @returns {Date|null} Email date
|
||||
*/
|
||||
export const getEmailDate = lastEmail => {
|
||||
const contentAttributes =
|
||||
lastEmail?.contentAttributes || lastEmail?.content_attributes || {};
|
||||
const emailMeta = contentAttributes.email || {};
|
||||
|
||||
if (emailMeta.date) {
|
||||
const parsedDate = parseISO(emailMeta.date);
|
||||
if (isValidDate(parsedDate)) {
|
||||
return parsedDate;
|
||||
}
|
||||
}
|
||||
|
||||
const createdAt = lastEmail?.created_at;
|
||||
if (createdAt) {
|
||||
const timestamp = Number(createdAt);
|
||||
if (!Number.isNaN(timestamp)) {
|
||||
const milliseconds = timestamp > 1e12 ? timestamp : timestamp * 1000;
|
||||
const derivedDate = new Date(milliseconds);
|
||||
if (!Number.isNaN(derivedDate.getTime())) {
|
||||
return derivedDate;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Formats date for quoted email header
|
||||
* @param {Date} date - Date to format
|
||||
* @returns {string} Formatted date string
|
||||
*/
|
||||
export const formatQuotedEmailDate = date => {
|
||||
try {
|
||||
return format(date, "EEE, MMM d, yyyy 'at' p");
|
||||
} catch (error) {
|
||||
const fallbackDate = new Date(date);
|
||||
if (!Number.isNaN(fallbackDate.getTime())) {
|
||||
return format(fallbackDate, "EEE, MMM d, yyyy 'at' p");
|
||||
}
|
||||
}
|
||||
|
||||
return '';
|
||||
};
|
||||
|
||||
/**
|
||||
* Extracts inbox email address from last email message
|
||||
* @param {Object} lastEmail - Last email message object
|
||||
* @param {Object} inbox - Inbox object
|
||||
* @returns {string} Inbox email address
|
||||
*/
|
||||
export const getInboxEmail = (lastEmail, inbox) => {
|
||||
const contentAttributes =
|
||||
lastEmail?.contentAttributes || lastEmail?.content_attributes || {};
|
||||
const emailMeta = contentAttributes.email || {};
|
||||
|
||||
if (Array.isArray(emailMeta.to) && emailMeta.to.length > 0) {
|
||||
const toAddress = emailMeta.to[0];
|
||||
if (toAddress && toAddress.trim()) {
|
||||
return toAddress.trim();
|
||||
}
|
||||
}
|
||||
|
||||
const inboxEmail = inbox?.email;
|
||||
return inboxEmail && inboxEmail.trim() ? inboxEmail.trim() : '';
|
||||
};
|
||||
|
||||
/**
|
||||
* Builds quoted email header from contact (for incoming messages)
|
||||
* @param {Object} lastEmail - Last email message object
|
||||
* @param {Object} contact - Contact object
|
||||
* @returns {string} Formatted header string
|
||||
*/
|
||||
export const buildQuotedEmailHeaderFromContact = (lastEmail, contact) => {
|
||||
if (!lastEmail) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const quotedDate = getEmailDate(lastEmail);
|
||||
const senderEmail = getEmailSenderEmail(lastEmail, contact);
|
||||
|
||||
if (!quotedDate || !senderEmail) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const formattedDate = formatQuotedEmailDate(quotedDate);
|
||||
if (!formattedDate) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const senderName = getEmailSenderName(lastEmail, contact);
|
||||
const hasName = !!senderName;
|
||||
const contactLabel = hasName
|
||||
? `${senderName} <${senderEmail}>`
|
||||
: `<${senderEmail}>`;
|
||||
|
||||
return `On ${formattedDate} ${contactLabel} wrote:`;
|
||||
};
|
||||
|
||||
/**
|
||||
* Builds quoted email header from inbox (for outgoing messages)
|
||||
* @param {Object} lastEmail - Last email message object
|
||||
* @param {Object} inbox - Inbox object
|
||||
* @returns {string} Formatted header string
|
||||
*/
|
||||
export const buildQuotedEmailHeaderFromInbox = (lastEmail, inbox) => {
|
||||
if (!lastEmail) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const quotedDate = getEmailDate(lastEmail);
|
||||
const inboxEmail = getInboxEmail(lastEmail, inbox);
|
||||
|
||||
if (!quotedDate || !inboxEmail) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const formattedDate = formatQuotedEmailDate(quotedDate);
|
||||
if (!formattedDate) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const inboxName = inbox?.name;
|
||||
const hasName = !!inboxName;
|
||||
const inboxLabel = hasName
|
||||
? `${inboxName} <${inboxEmail}>`
|
||||
: `<${inboxEmail}>`;
|
||||
|
||||
return `On ${formattedDate} ${inboxLabel} wrote:`;
|
||||
};
|
||||
|
||||
/**
|
||||
* Builds quoted email header based on message type
|
||||
* @param {Object} lastEmail - Last email message object
|
||||
* @param {Object} contact - Contact object
|
||||
* @param {Object} inbox - Inbox object
|
||||
* @returns {string} Formatted header string
|
||||
*/
|
||||
export const buildQuotedEmailHeader = (lastEmail, contact, inbox) => {
|
||||
if (!lastEmail) {
|
||||
return '';
|
||||
}
|
||||
|
||||
// MESSAGE_TYPE.OUTGOING = 1, MESSAGE_TYPE.INCOMING = 0
|
||||
const isOutgoing = lastEmail.message_type === 1;
|
||||
|
||||
if (isOutgoing) {
|
||||
return buildQuotedEmailHeaderFromInbox(lastEmail, inbox);
|
||||
}
|
||||
|
||||
return buildQuotedEmailHeaderFromContact(lastEmail, contact);
|
||||
};
|
||||
|
||||
/**
|
||||
* Formats text as markdown blockquote
|
||||
* @param {string} text - Text to format
|
||||
* @param {string} header - Optional header to prepend
|
||||
* @returns {string} Formatted blockquote
|
||||
*/
|
||||
export const formatQuotedTextAsBlockquote = (text, header = '') => {
|
||||
const normalizedLines = text
|
||||
? String(text).replace(/\r\n/g, '\n').split('\n')
|
||||
: [];
|
||||
|
||||
if (!header && !normalizedLines.length) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const quotedLines = [];
|
||||
|
||||
if (header) {
|
||||
quotedLines.push(`> ${header}`);
|
||||
quotedLines.push('>');
|
||||
}
|
||||
|
||||
normalizedLines.forEach(line => {
|
||||
const trimmedLine = line.trimEnd();
|
||||
quotedLines.push(trimmedLine ? `> ${trimmedLine}` : '>');
|
||||
});
|
||||
|
||||
return quotedLines.join('\n');
|
||||
};
|
||||
|
||||
/**
|
||||
* Extracts quoted email text from last email message
|
||||
* @param {Object} lastEmail - Last email message object
|
||||
* @returns {string} Quoted email text
|
||||
*/
|
||||
export const extractQuotedEmailText = lastEmail => {
|
||||
if (!lastEmail) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const contentAttributes =
|
||||
lastEmail.contentAttributes || lastEmail.content_attributes || {};
|
||||
const emailContent = contentAttributes.email || {};
|
||||
const textContent = emailContent.textContent || emailContent.text_content;
|
||||
|
||||
if (textContent?.reply) {
|
||||
return textContent.reply;
|
||||
}
|
||||
if (textContent?.full) {
|
||||
return textContent.full;
|
||||
}
|
||||
|
||||
const htmlContent = emailContent.htmlContent || emailContent.html_content;
|
||||
if (htmlContent?.reply) {
|
||||
return extractPlainTextFromHtml(htmlContent.reply);
|
||||
}
|
||||
if (htmlContent?.full) {
|
||||
return extractPlainTextFromHtml(htmlContent.full);
|
||||
}
|
||||
|
||||
const fallbackContent =
|
||||
lastEmail.content || lastEmail.processed_message_content || '';
|
||||
|
||||
return fallbackContent;
|
||||
};
|
||||
|
||||
/**
|
||||
* Truncates text for preview display
|
||||
* @param {string} text - Text to truncate
|
||||
* @param {number} maxLength - Maximum length (default: 80)
|
||||
* @returns {string} Truncated text
|
||||
*/
|
||||
export const truncatePreviewText = (text, maxLength = 80) => {
|
||||
const preview = text.trim().replace(/\s+/g, ' ');
|
||||
if (!preview) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (preview.length <= maxLength) {
|
||||
return preview;
|
||||
}
|
||||
return `${preview.slice(0, maxLength - 3)}...`;
|
||||
};
|
||||
|
||||
/**
|
||||
* Appends quoted text to message
|
||||
* @param {string} message - Original message
|
||||
* @param {string} quotedText - Text to quote
|
||||
* @param {string} header - Quote header
|
||||
* @returns {string} Message with quoted text appended
|
||||
*/
|
||||
export const appendQuotedTextToMessage = (message, quotedText, header) => {
|
||||
const baseMessage = message ? String(message) : '';
|
||||
const quotedBlock = formatQuotedTextAsBlockquote(quotedText, header);
|
||||
|
||||
if (!quotedBlock) {
|
||||
return baseMessage;
|
||||
}
|
||||
|
||||
if (!baseMessage) {
|
||||
return quotedBlock;
|
||||
}
|
||||
|
||||
let separator = '\n\n';
|
||||
if (baseMessage.endsWith('\n\n')) {
|
||||
separator = '';
|
||||
} else if (baseMessage.endsWith('\n')) {
|
||||
separator = '\n';
|
||||
}
|
||||
|
||||
return `${baseMessage}${separator}${quotedBlock}`;
|
||||
};
|
||||
@@ -0,0 +1,99 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { EmailQuoteExtractor } from '../emailQuoteExtractor.js';
|
||||
|
||||
const SAMPLE_EMAIL_HTML = `
|
||||
<p>method</p>
|
||||
<blockquote>
|
||||
<p>On Mon, Sep 29, 2025 at 5:18 PM John <a href="mailto:shivam@chatwoot.com">shivam@chatwoot.com</a> wrote:</p>
|
||||
<p>Hi</p>
|
||||
<blockquote>
|
||||
<p>On Mon, Sep 29, 2025 at 5:17 PM Shivam Mishra <a href="mailto:shivam@chatwoot.com">shivam@chatwoot.com</a> wrote:</p>
|
||||
<p>Yes, it is.</p>
|
||||
<p>On Mon, Sep 29, 2025 at 5:16 PM John from Shaneforwoot < shaneforwoot@gmail.com> wrote:</p>
|
||||
<blockquote>
|
||||
<p>Hey</p>
|
||||
<p>On Mon, Sep 29, 2025 at 4:59 PM John shivam@chatwoot.com wrote:</p>
|
||||
<p>This is another quoted quoted text reply</p>
|
||||
<p>This is nice</p>
|
||||
<p>On Mon, Sep 29, 2025 at 4:21 PM John from Shaneforwoot < > shaneforwoot@gmail.com> wrote:</p>
|
||||
<p>Hey there, this is a reply from Chatwoot, notice the quoted text</p>
|
||||
<p>Hey there</p>
|
||||
<p>This is an email text, enjoy reading this</p>
|
||||
<p>-- Shivam Mishra, Chatwoot</p>
|
||||
</blockquote>
|
||||
</blockquote>
|
||||
</blockquote>
|
||||
`;
|
||||
|
||||
const EMAIL_WITH_SIGNATURE = `
|
||||
<p>Latest reply here.</p>
|
||||
<p>Thanks,</p>
|
||||
<p>Jane Doe</p>
|
||||
<blockquote>
|
||||
<p>On Mon, Sep 22, Someone wrote:</p>
|
||||
<p>Previous reply content</p>
|
||||
</blockquote>
|
||||
`;
|
||||
|
||||
const EMAIL_WITH_FOLLOW_UP_CONTENT = `
|
||||
<blockquote>
|
||||
<p>Inline quote that should stay</p>
|
||||
</blockquote>
|
||||
<p>Internal note follows</p>
|
||||
<p>Regards,</p>
|
||||
`;
|
||||
|
||||
describe('EmailQuoteExtractor', () => {
|
||||
it('removes blockquote-based quotes from the email body', () => {
|
||||
const cleanedHtml = EmailQuoteExtractor.extractQuotes(SAMPLE_EMAIL_HTML);
|
||||
|
||||
const container = document.createElement('div');
|
||||
container.innerHTML = cleanedHtml;
|
||||
|
||||
expect(container.querySelectorAll('blockquote').length).toBe(0);
|
||||
expect(container.textContent?.trim()).toBe('method');
|
||||
expect(container.textContent).not.toContain(
|
||||
'On Mon, Sep 29, 2025 at 5:18 PM'
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps blockquote fallback when it is not the last top-level element', () => {
|
||||
const cleanedHtml = EmailQuoteExtractor.extractQuotes(
|
||||
EMAIL_WITH_FOLLOW_UP_CONTENT
|
||||
);
|
||||
|
||||
const container = document.createElement('div');
|
||||
container.innerHTML = cleanedHtml;
|
||||
|
||||
expect(container.querySelector('blockquote')).not.toBeNull();
|
||||
expect(container.lastElementChild?.tagName).toBe('P');
|
||||
});
|
||||
|
||||
it('detects quote indicators in nested blockquotes', () => {
|
||||
const result = EmailQuoteExtractor.hasQuotes(SAMPLE_EMAIL_HTML);
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it('does not flag blockquotes that are followed by other elements', () => {
|
||||
expect(EmailQuoteExtractor.hasQuotes(EMAIL_WITH_FOLLOW_UP_CONTENT)).toBe(
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
it('returns false when no quote indicators are present', () => {
|
||||
const html = '<p>Plain content</p>';
|
||||
expect(EmailQuoteExtractor.hasQuotes(html)).toBe(false);
|
||||
});
|
||||
|
||||
it('removes trailing blockquotes while preserving trailing signatures', () => {
|
||||
const cleanedHtml = EmailQuoteExtractor.extractQuotes(EMAIL_WITH_SIGNATURE);
|
||||
|
||||
expect(cleanedHtml).toContain('<p>Thanks,</p>');
|
||||
expect(cleanedHtml).toContain('<p>Jane Doe</p>');
|
||||
expect(cleanedHtml).not.toContain('<blockquote');
|
||||
});
|
||||
|
||||
it('detects quotes for trailing blockquotes even when signatures follow text', () => {
|
||||
expect(EmailQuoteExtractor.hasQuotes(EMAIL_WITH_SIGNATURE)).toBe(true);
|
||||
});
|
||||
});
|
||||
326
app/javascript/dashboard/helper/specs/quotedEmailHelper.spec.js
Normal file
326
app/javascript/dashboard/helper/specs/quotedEmailHelper.spec.js
Normal file
@@ -0,0 +1,326 @@
|
||||
import {
|
||||
extractPlainTextFromHtml,
|
||||
getEmailSenderName,
|
||||
getEmailSenderEmail,
|
||||
getEmailDate,
|
||||
formatQuotedEmailDate,
|
||||
buildQuotedEmailHeader,
|
||||
formatQuotedTextAsBlockquote,
|
||||
extractQuotedEmailText,
|
||||
truncatePreviewText,
|
||||
appendQuotedTextToMessage,
|
||||
} from '../quotedEmailHelper';
|
||||
|
||||
describe('quotedEmailHelper', () => {
|
||||
describe('extractPlainTextFromHtml', () => {
|
||||
it('returns empty string for null or undefined', () => {
|
||||
expect(extractPlainTextFromHtml(null)).toBe('');
|
||||
expect(extractPlainTextFromHtml(undefined)).toBe('');
|
||||
});
|
||||
|
||||
it('strips HTML tags and returns plain text', () => {
|
||||
const html = '<p>Hello <strong>world</strong></p>';
|
||||
const result = extractPlainTextFromHtml(html);
|
||||
expect(result).toBe('Hello world');
|
||||
});
|
||||
|
||||
it('handles complex HTML structure', () => {
|
||||
const html = '<div><p>Line 1</p><p>Line 2</p></div>';
|
||||
const result = extractPlainTextFromHtml(html);
|
||||
expect(result).toContain('Line 1');
|
||||
expect(result).toContain('Line 2');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getEmailSenderName', () => {
|
||||
it('returns sender name from lastEmail', () => {
|
||||
const lastEmail = { sender: { name: 'John Doe' } };
|
||||
const result = getEmailSenderName(lastEmail, {});
|
||||
expect(result).toBe('John Doe');
|
||||
});
|
||||
|
||||
it('returns contact name if sender name not available', () => {
|
||||
const lastEmail = { sender: {} };
|
||||
const contact = { name: 'Jane Smith' };
|
||||
const result = getEmailSenderName(lastEmail, contact);
|
||||
expect(result).toBe('Jane Smith');
|
||||
});
|
||||
|
||||
it('returns empty string if neither available', () => {
|
||||
const result = getEmailSenderName({}, {});
|
||||
expect(result).toBe('');
|
||||
});
|
||||
|
||||
it('trims whitespace from names', () => {
|
||||
const lastEmail = { sender: { name: ' John Doe ' } };
|
||||
const result = getEmailSenderName(lastEmail, {});
|
||||
expect(result).toBe('John Doe');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getEmailSenderEmail', () => {
|
||||
it('returns sender email from lastEmail', () => {
|
||||
const lastEmail = { sender: { email: 'john@example.com' } };
|
||||
const result = getEmailSenderEmail(lastEmail, {});
|
||||
expect(result).toBe('john@example.com');
|
||||
});
|
||||
|
||||
it('returns email from contentAttributes if sender email not available', () => {
|
||||
const lastEmail = {
|
||||
contentAttributes: {
|
||||
email: { from: ['jane@example.com'] },
|
||||
},
|
||||
};
|
||||
const result = getEmailSenderEmail(lastEmail, {});
|
||||
expect(result).toBe('jane@example.com');
|
||||
});
|
||||
|
||||
it('returns contact email as fallback', () => {
|
||||
const lastEmail = {};
|
||||
const contact = { email: 'contact@example.com' };
|
||||
const result = getEmailSenderEmail(lastEmail, contact);
|
||||
expect(result).toBe('contact@example.com');
|
||||
});
|
||||
|
||||
it('trims whitespace from emails', () => {
|
||||
const lastEmail = { sender: { email: ' john@example.com ' } };
|
||||
const result = getEmailSenderEmail(lastEmail, {});
|
||||
expect(result).toBe('john@example.com');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getEmailDate', () => {
|
||||
it('returns parsed date from email metadata', () => {
|
||||
const lastEmail = {
|
||||
contentAttributes: {
|
||||
email: { date: '2024-01-15T10:30:00Z' },
|
||||
},
|
||||
};
|
||||
const result = getEmailDate(lastEmail);
|
||||
expect(result).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
it('returns date from created_at timestamp', () => {
|
||||
const lastEmail = { created_at: 1705318200 };
|
||||
const result = getEmailDate(lastEmail);
|
||||
expect(result).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
it('handles millisecond timestamps', () => {
|
||||
const lastEmail = { created_at: 1705318200000 };
|
||||
const result = getEmailDate(lastEmail);
|
||||
expect(result).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
it('returns null if no valid date found', () => {
|
||||
const result = getEmailDate({});
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatQuotedEmailDate', () => {
|
||||
it('formats date correctly', () => {
|
||||
const date = new Date('2024-01-15T10:30:00Z');
|
||||
const result = formatQuotedEmailDate(date);
|
||||
expect(result).toMatch(/Mon, Jan 15, 2024 at/);
|
||||
});
|
||||
|
||||
it('returns empty string for invalid date', () => {
|
||||
const result = formatQuotedEmailDate('invalid');
|
||||
expect(result).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildQuotedEmailHeader', () => {
|
||||
it('builds complete header with name and email', () => {
|
||||
const lastEmail = {
|
||||
sender: { name: 'John Doe', email: 'john@example.com' },
|
||||
contentAttributes: {
|
||||
email: { date: '2024-01-15T10:30:00Z' },
|
||||
},
|
||||
};
|
||||
const result = buildQuotedEmailHeader(lastEmail, {});
|
||||
expect(result).toContain('John Doe');
|
||||
expect(result).toContain('john@example.com');
|
||||
expect(result).toContain('wrote:');
|
||||
});
|
||||
|
||||
it('builds header without name if not available', () => {
|
||||
const lastEmail = {
|
||||
sender: { email: 'john@example.com' },
|
||||
contentAttributes: {
|
||||
email: { date: '2024-01-15T10:30:00Z' },
|
||||
},
|
||||
};
|
||||
const result = buildQuotedEmailHeader(lastEmail, {});
|
||||
expect(result).toContain('<john@example.com>');
|
||||
expect(result).not.toContain('undefined');
|
||||
});
|
||||
|
||||
it('returns empty string if missing required data', () => {
|
||||
expect(buildQuotedEmailHeader(null, {})).toBe('');
|
||||
expect(buildQuotedEmailHeader({}, {})).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatQuotedTextAsBlockquote', () => {
|
||||
it('formats single line text', () => {
|
||||
const result = formatQuotedTextAsBlockquote('Hello world');
|
||||
expect(result).toBe('> Hello world');
|
||||
});
|
||||
|
||||
it('formats multi-line text', () => {
|
||||
const text = 'Line 1\nLine 2\nLine 3';
|
||||
const result = formatQuotedTextAsBlockquote(text);
|
||||
expect(result).toBe('> Line 1\n> Line 2\n> Line 3');
|
||||
});
|
||||
|
||||
it('includes header if provided', () => {
|
||||
const result = formatQuotedTextAsBlockquote('Hello', 'Header text');
|
||||
expect(result).toContain('> Header text');
|
||||
expect(result).toContain('>\n> Hello');
|
||||
});
|
||||
|
||||
it('handles empty lines correctly', () => {
|
||||
const text = 'Line 1\n\nLine 3';
|
||||
const result = formatQuotedTextAsBlockquote(text);
|
||||
expect(result).toBe('> Line 1\n>\n> Line 3');
|
||||
});
|
||||
|
||||
it('returns empty string for empty input', () => {
|
||||
expect(formatQuotedTextAsBlockquote('')).toBe('');
|
||||
expect(formatQuotedTextAsBlockquote('', '')).toBe('');
|
||||
});
|
||||
|
||||
it('handles Windows line endings', () => {
|
||||
const text = 'Line 1\r\nLine 2';
|
||||
const result = formatQuotedTextAsBlockquote(text);
|
||||
expect(result).toBe('> Line 1\n> Line 2');
|
||||
});
|
||||
});
|
||||
|
||||
describe('extractQuotedEmailText', () => {
|
||||
it('extracts text from textContent.reply', () => {
|
||||
const lastEmail = {
|
||||
contentAttributes: {
|
||||
email: { textContent: { reply: 'Reply text' } },
|
||||
},
|
||||
};
|
||||
const result = extractQuotedEmailText(lastEmail);
|
||||
expect(result).toBe('Reply text');
|
||||
});
|
||||
|
||||
it('falls back to textContent.full', () => {
|
||||
const lastEmail = {
|
||||
contentAttributes: {
|
||||
email: { textContent: { full: 'Full text' } },
|
||||
},
|
||||
};
|
||||
const result = extractQuotedEmailText(lastEmail);
|
||||
expect(result).toBe('Full text');
|
||||
});
|
||||
|
||||
it('extracts from htmlContent and converts to plain text', () => {
|
||||
const lastEmail = {
|
||||
contentAttributes: {
|
||||
email: { htmlContent: { reply: '<p>HTML reply</p>' } },
|
||||
},
|
||||
};
|
||||
const result = extractQuotedEmailText(lastEmail);
|
||||
expect(result).toBe('HTML reply');
|
||||
});
|
||||
|
||||
it('uses fallback content if structured content not available', () => {
|
||||
const lastEmail = { content: 'Fallback content' };
|
||||
const result = extractQuotedEmailText(lastEmail);
|
||||
expect(result).toBe('Fallback content');
|
||||
});
|
||||
|
||||
it('returns empty string for null or missing email', () => {
|
||||
expect(extractQuotedEmailText(null)).toBe('');
|
||||
expect(extractQuotedEmailText({})).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('truncatePreviewText', () => {
|
||||
it('returns full text if under max length', () => {
|
||||
const text = 'Short text';
|
||||
const result = truncatePreviewText(text, 80);
|
||||
expect(result).toBe('Short text');
|
||||
});
|
||||
|
||||
it('truncates text exceeding max length', () => {
|
||||
const text = 'A'.repeat(100);
|
||||
const result = truncatePreviewText(text, 80);
|
||||
expect(result).toHaveLength(80);
|
||||
expect(result).toContain('...');
|
||||
});
|
||||
|
||||
it('collapses multiple spaces', () => {
|
||||
const text = 'Text with spaces';
|
||||
const result = truncatePreviewText(text);
|
||||
expect(result).toBe('Text with spaces');
|
||||
});
|
||||
|
||||
it('trims whitespace', () => {
|
||||
const text = ' Text with spaces ';
|
||||
const result = truncatePreviewText(text);
|
||||
expect(result).toBe('Text with spaces');
|
||||
});
|
||||
|
||||
it('returns empty string for empty input', () => {
|
||||
expect(truncatePreviewText('')).toBe('');
|
||||
expect(truncatePreviewText(' ')).toBe('');
|
||||
});
|
||||
|
||||
it('uses default max length of 80', () => {
|
||||
const text = 'A'.repeat(100);
|
||||
const result = truncatePreviewText(text);
|
||||
expect(result).toHaveLength(80);
|
||||
});
|
||||
});
|
||||
|
||||
describe('appendQuotedTextToMessage', () => {
|
||||
it('appends quoted text to message', () => {
|
||||
const message = 'My reply';
|
||||
const quotedText = 'Original message';
|
||||
const header = 'On date sender wrote:';
|
||||
const result = appendQuotedTextToMessage(message, quotedText, header);
|
||||
|
||||
expect(result).toContain('My reply');
|
||||
expect(result).toContain('> On date sender wrote:');
|
||||
expect(result).toContain('> Original message');
|
||||
});
|
||||
|
||||
it('returns only quoted text if message is empty', () => {
|
||||
const result = appendQuotedTextToMessage('', 'Quoted', 'Header');
|
||||
expect(result).toContain('> Header');
|
||||
expect(result).toContain('> Quoted');
|
||||
expect(result).not.toContain('\n\n\n');
|
||||
});
|
||||
|
||||
it('returns message if no quoted text', () => {
|
||||
const result = appendQuotedTextToMessage('Message', '', '');
|
||||
expect(result).toBe('Message');
|
||||
});
|
||||
|
||||
it('handles proper spacing with double newline', () => {
|
||||
const result = appendQuotedTextToMessage('Message', 'Quoted', 'Header');
|
||||
expect(result).toContain('Message\n\n>');
|
||||
});
|
||||
|
||||
it('does not add extra newlines if message already ends with newlines', () => {
|
||||
const result = appendQuotedTextToMessage(
|
||||
'Message\n\n',
|
||||
'Quoted',
|
||||
'Header'
|
||||
);
|
||||
expect(result).not.toContain('\n\n\n');
|
||||
});
|
||||
|
||||
it('adds single newline if message ends with one newline', () => {
|
||||
const result = appendQuotedTextToMessage('Message\n', 'Quoted', 'Header');
|
||||
expect(result).toContain('Message\n\n>');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -227,6 +227,13 @@
|
||||
"YES": "Send",
|
||||
"CANCEL": "Cancel"
|
||||
}
|
||||
},
|
||||
"QUOTED_REPLY": {
|
||||
"ENABLE_TOOLTIP": "Include quoted email thread",
|
||||
"DISABLE_TOOLTIP": "Don't include quoted email thread",
|
||||
"REMOVE_PREVIEW": "Remove quoted email thread",
|
||||
"COLLAPSE": "Collapse preview",
|
||||
"EXPAND": "Expand preview"
|
||||
}
|
||||
},
|
||||
"VISIBLE_TO_AGENTS": "Private Note: Only visible to you and your team",
|
||||
|
||||
@@ -220,3 +220,6 @@
|
||||
display_name: Reply Mailer Migration
|
||||
enabled: false
|
||||
chatwoot_internal: true
|
||||
- name: quoted_email_reply
|
||||
display_name: Quoted Email Reply
|
||||
enabled: false
|
||||
|
||||
Reference in New Issue
Block a user