Compare commits

..
76 changed files with 149 additions and 3910 deletions
+1 -1
View File
@@ -144,7 +144,7 @@ jobs:
# Backend tests with parallelization
backend-tests:
<<: *defaults
parallelism: 20
parallelism: 16
steps:
- checkout
- node/install:
@@ -158,7 +158,6 @@ class Messages::Instagram::BaseMessageBuilder < Messages::Messenger::MessageBuil
account_id: conversation.account_id,
inbox_id: conversation.inbox_id,
message_type: message_type,
status: @outgoing_echo ? :delivered : :sent,
source_id: message_identifier,
content: message_content,
sender: @outgoing_echo ? nil : contact,
@@ -167,7 +166,6 @@ class Messages::Instagram::BaseMessageBuilder < Messages::Messenger::MessageBuil
}
}
params[:content_attributes][:external_echo] = true if @outgoing_echo
params[:content_attributes][:is_unsupported] = true if message_is_unsupported?
params
end
@@ -1,68 +0,0 @@
class V2::Reports::FirstResponseTimeDistributionBuilder
include DateRangeHelper
attr_reader :account, :params
def initialize(account:, params:)
@account = account
@params = params
end
def build
build_distribution
end
private
def build_distribution
results = fetch_aggregated_counts
map_to_channel_types(results)
end
def fetch_aggregated_counts
ReportingEvent
.where(account_id: account.id, name: 'first_response')
.where(range_condition)
.group(:inbox_id)
.select(
:inbox_id,
bucket_case_statements
)
end
def bucket_case_statements
<<~SQL.squish
COUNT(CASE WHEN value < 3600 THEN 1 END) AS bucket_0_1h,
COUNT(CASE WHEN value >= 3600 AND value < 14400 THEN 1 END) AS bucket_1_4h,
COUNT(CASE WHEN value >= 14400 AND value < 28800 THEN 1 END) AS bucket_4_8h,
COUNT(CASE WHEN value >= 28800 AND value < 86400 THEN 1 END) AS bucket_8_24h,
COUNT(CASE WHEN value >= 86400 THEN 1 END) AS bucket_24h_plus
SQL
end
def range_condition
range.present? ? { created_at: range } : {}
end
def inbox_channel_types
@inbox_channel_types ||= account.inboxes.pluck(:id, :channel_type).to_h
end
def map_to_channel_types(results)
results.each_with_object({}) do |row, hash|
channel_type = inbox_channel_types[row.inbox_id]
next unless channel_type
hash[channel_type] ||= empty_buckets
hash[channel_type]['0-1h'] += row.bucket_0_1h
hash[channel_type]['1-4h'] += row.bucket_1_4h
hash[channel_type]['4-8h'] += row.bucket_4_8h
hash[channel_type]['8-24h'] += row.bucket_8_24h
hash[channel_type]['24h+'] += row.bucket_24h_plus
end
end
def empty_buckets
{ '0-1h' => 0, '1-4h' => 0, '4-8h' => 0, '8-24h' => 0, '24h+' => 0 }
end
end
@@ -70,10 +70,8 @@ class Api::V1::Accounts::ConversationsController < Api::V1::Accounts::BaseContro
def transcript
render json: { error: 'email param missing' }, status: :unprocessable_entity and return if params[:email].blank?
return head :too_many_requests unless @conversation.account.within_email_rate_limit?
ConversationReplyMailer.with(account: @conversation.account).conversation_transcript(@conversation, params[:email])&.deliver_later
@conversation.account.increment_email_sent_count
head :ok
end
@@ -35,9 +35,12 @@ class Api::V1::Widget::ConversationsController < Api::V1::Widget::BaseController
end
def transcript
return head :too_many_requests unless conversation.present? && conversation.account.within_email_rate_limit?
send_transcript_email
if conversation.present? && conversation.contact.present? && conversation.contact.email.present?
ConversationReplyMailer.with(account: conversation.account).conversation_transcript(
conversation,
conversation.contact.email
)&.deliver_later
end
head :ok
end
@@ -74,16 +77,6 @@ class Api::V1::Widget::ConversationsController < Api::V1::Widget::BaseController
private
def send_transcript_email
return if conversation.contact&.email.blank?
ConversationReplyMailer.with(account: conversation.account).conversation_transcript(
conversation,
conversation.contact.email
)&.deliver_later
conversation.account.increment_email_sent_count
end
def trigger_typing_event(event)
Rails.configuration.dispatcher.dispatch(event, Time.zone.now, conversation: conversation, user: @contact)
end
@@ -70,14 +70,6 @@ class Api::V2::Accounts::ReportsController < Api::V1::Accounts::BaseController
render json: builder.build
end
def first_response_time_distribution
builder = V2::Reports::FirstResponseTimeDistributionBuilder.new(
account: Current.account,
params: first_response_time_distribution_params
)
render json: builder.build
end
private
def generate_csv(filename, template)
@@ -164,11 +156,4 @@ class Api::V2::Accounts::ReportsController < Api::V1::Accounts::BaseController
label_ids: params[:label_ids]
}
end
def first_response_time_distribution_params
{
since: params[:since],
until: params[:until]
}
end
end
@@ -42,7 +42,7 @@ class SuperAdmin::AppConfigsController < SuperAdmin::ApplicationController
'facebook' => %w[FB_APP_ID FB_VERIFY_TOKEN FB_APP_SECRET IG_VERIFY_TOKEN FACEBOOK_API_VERSION ENABLE_MESSENGER_CHANNEL_HUMAN_AGENT],
'shopify' => %w[SHOPIFY_CLIENT_ID SHOPIFY_CLIENT_SECRET],
'microsoft' => %w[AZURE_APP_ID AZURE_APP_SECRET],
'email' => %w[MAILER_INBOUND_EMAIL_DOMAIN ACCOUNT_EMAILS_LIMIT ACCOUNT_EMAILS_PLAN_LIMITS],
'email' => ['MAILER_INBOUND_EMAIL_DOMAIN'],
'linear' => %w[LINEAR_CLIENT_ID LINEAR_CLIENT_SECRET],
'slack' => %w[SLACK_CLIENT_ID SLACK_CLIENT_SECRET],
'instagram' => %w[INSTAGRAM_APP_ID INSTAGRAM_APP_SECRET INSTAGRAM_VERIFY_TOKEN INSTAGRAM_API_VERSION ENABLE_INSTAGRAM_CHANNEL_HUMAN_AGENT],
@@ -37,17 +37,14 @@ class TasksAPI extends ApiClient {
/**
* Summarizes a conversation.
* @param {string} conversationId - The conversation ID to summarize.
* @param {Object} [options] - Additional options.
* @param {boolean} [options.forceRegenerate] - Force regeneration of cached summary.
* @param {AbortSignal} [options.signal] - AbortSignal to cancel the request.
* @param {AbortSignal} [signal] - AbortSignal to cancel the request.
* @returns {Promise} A promise that resolves with the summary.
*/
summarize(conversationId, { forceRegenerate = false, signal } = {}) {
summarize(conversationId, signal) {
return axios.post(
`${this.url}/summarize`,
{
conversation_display_id: conversationId,
force_regenerate: forceRegenerate,
},
{ signal }
);
@@ -18,9 +18,7 @@ const dialogRef = ref(null);
const uiFlags = useMapGetter('captainResponses/getUIFlags');
const responses = useMapGetter('captainResponses/getRecords');
const meta = useMapGetter('captainResponses/getMeta');
const isFetching = computed(() => uiFlags.value.fetchingList);
const totalCount = computed(() => meta.value.totalCount || 0);
const handleClose = () => {
emit('close');
@@ -39,7 +37,7 @@ defineExpose({ dialogRef });
<Dialog
ref="dialogRef"
type="edit"
:title="`${t('CAPTAIN.DOCUMENTS.RELATED_RESPONSES.TITLE')} (${totalCount})`"
:title="t('CAPTAIN.DOCUMENTS.RELATED_RESPONSES.TITLE')"
:description="t('CAPTAIN.DOCUMENTS.RELATED_RESPONSES.DESCRIPTION')"
:show-cancel-button="false"
:show-confirm-button="false"
@@ -3,14 +3,12 @@ import { onMounted, computed, ref, toRefs } from 'vue';
import { useTimeoutFn } from '@vueuse/core';
import { provideMessageContext } from './provider.js';
import { useTrack } from 'dashboard/composables';
import { useMapGetter } from 'dashboard/composables/store';
import { emitter } from 'shared/helpers/mitt';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';
import { LocalStorage } from 'shared/helpers/localStorage';
import { ACCOUNT_EVENTS } from 'dashboard/helper/AnalyticsHelper/events';
import { LOCAL_STORAGE_KEYS } from 'dashboard/constants/localStorage';
import { getInboxIconByType } from 'dashboard/helper/inbox';
import { BUS_EVENTS } from 'shared/constants/busEvents';
import {
MESSAGE_TYPES,
@@ -141,8 +139,6 @@ const showBackgroundHighlight = ref(false);
const showContextMenu = ref(false);
const { t } = useI18n();
const route = useRoute();
const inboxGetter = useMapGetter('inboxes/getInbox');
const inbox = computed(() => inboxGetter.value(props.inboxId) || {});
/**
* Computes the message variant based on props
@@ -166,10 +162,6 @@ const variant = computed(() => {
if (props.contentAttributes?.isUnsupported)
return MESSAGE_VARIANTS.UNSUPPORTED;
if (props.contentAttributes?.externalEcho) {
return MESSAGE_VARIANTS.AGENT;
}
const isBot = !props.sender || props.sender.type === SENDER_TYPES.AGENT_BOT;
if (isBot && props.messageType === MESSAGE_TYPES.OUTGOING) {
return MESSAGE_VARIANTS.BOT;
@@ -432,18 +424,6 @@ function handleReplyTo() {
}
const avatarInfo = computed(() => {
if (props.contentAttributes?.externalEcho) {
const { name, avatar_url, channel_type, medium } = inbox.value;
const iconName = avatar_url
? null
: getInboxIconByType(channel_type, medium);
return {
name: iconName ? '' : name || t('CONVERSATION.NATIVE_APP'),
src: avatar_url || '',
iconName,
};
}
// If no sender, return bot info
if (!props.sender) {
return {
@@ -471,9 +451,6 @@ const avatarInfo = computed(() => {
});
const avatarTooltip = computed(() => {
if (props.contentAttributes?.externalEcho) {
return t('CONVERSATION.NATIVE_APP_ADVISORY');
}
if (avatarInfo.value.name === '') return '';
return `${t('CONVERSATION.SENT_BY')} ${avatarInfo.value.name}`;
});
@@ -507,7 +484,7 @@ provideMessageContext({
<div
v-if="shouldRenderMessage"
:id="`message${props.id}`"
class="flex w-full mb-2 message-bubble-container"
class="flex mb-2 w-full message-bubble-container"
:data-message-id="props.id"
:class="[
flexOrientationClass,
@@ -1,7 +1,6 @@
<script setup>
import { computed, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useStore, useMapGetter } from 'dashboard/composables/store';
import { getLastMessage } from 'dashboard/helper/conversationHelper';
import { frontendURL, conversationUrl } from 'dashboard/helper/URLHelper';
@@ -15,8 +14,6 @@ import PriorityMark from './PriorityMark.vue';
import SLACardLabel from './components/SLACardLabel.vue';
import ContextMenu from 'dashboard/components/ui/ContextMenu.vue';
import VoiceCallStatus from './VoiceCallStatus.vue';
import ConversationSummary from './ConversationSummary.vue';
import Spinner from 'dashboard/components-next/spinner/Spinner.vue';
const props = defineProps({
activeLabel: { type: String, default: '' },
@@ -49,10 +46,8 @@ const emit = defineEmits([
const router = useRouter();
const store = useStore();
const { t } = useI18n();
const hovered = ref(false);
const summaryRef = ref(null);
const showContextMenu = ref(false);
const contextMenu = ref({
x: null,
@@ -349,15 +344,12 @@ const deleteConversation = () => {
class="absolute flex flex-col ltr:right-3 rtl:left-3"
:class="showMetaSection ? 'top-8' : 'top-4'"
>
<div class="flex items-center gap-1 ml-auto">
<ConversationSummary ref="summaryRef" :chat="chat" />
<span class="font-normal leading-4 text-xxs">
<TimeAgo
:last-activity-timestamp="chat.timestamp"
:created-at-timestamp="chat.created_at"
/>
</span>
</div>
<span class="ml-auto font-normal leading-4 text-xxs">
<TimeAgo
:last-activity-timestamp="chat.timestamp"
:created-at-timestamp="chat.created_at"
/>
</span>
<span
class="shadow-lg rounded-full text-xxs font-semibold h-4 leading-4 ltr:ml-auto rtl:mr-auto mt-1 min-w-[1rem] px-1 py-0 text-center text-white bg-n-teal-9"
:class="hasUnread ? 'block' : 'hidden'"
@@ -374,26 +366,6 @@ const deleteConversation = () => {
<SLACardLabel :chat="chat" class="ltr:mr-1 rtl:ml-1" />
</template>
</CardLabels>
<!-- Expanded Summary Section -->
<div
v-if="summaryRef?.isExpanded"
class="mt-2 mx-2 mb-1 p-3 bg-n-alpha-1 dark:bg-n-alpha-2 rounded-lg"
>
<div v-if="summaryRef?.isLoading" class="flex items-center gap-2">
<Spinner :size="16" class="text-n-slate-10" />
<span class="text-xs text-n-slate-11">
{{ t('CHAT_LIST.SUMMARY.LOADING') }}
</span>
</div>
<div v-else-if="summaryRef?.error" class="text-xs text-n-ruby-11">
{{ summaryRef.error }}
</div>
<div
v-else-if="summaryRef?.formattedSummary"
class="text-xs text-n-slate-11 [&_ul]:list-disc [&_ul]:pl-4 [&_ol]:list-decimal [&_ol]:pl-4 [&_li]:my-0.5 [&_p]:my-1 [&_p:first-child]:mt-0 [&_p:last-child]:mb-0 [&_strong]:text-n-slate-12"
v-html="summaryRef.formattedSummary"
/>
</div>
</div>
<ContextMenu
v-if="showContextMenu"
@@ -1,116 +0,0 @@
<script setup>
import { ref, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useStore } from 'dashboard/composables/store';
import { useAccount } from 'dashboard/composables/useAccount';
import { useMessageFormatter } from 'shared/composables/useMessageFormatter';
import { FEATURE_FLAGS } from 'dashboard/featureFlags';
import TasksAPI from 'dashboard/api/captain/tasks';
import Button from 'dashboard/components-next/button/Button.vue';
import { useTrack } from 'dashboard/composables';
import { CAPTAIN_EVENTS } from 'dashboard/helper/AnalyticsHelper/events';
const props = defineProps({
chat: {
type: Object,
required: true,
},
});
const { t } = useI18n();
const store = useStore();
const { isCloudFeatureEnabled } = useAccount();
const { formatMessage } = useMessageFormatter();
const isExpanded = ref(false);
const isLoading = ref(false);
const error = ref('');
const captainTasksEnabled = computed(() => {
return isCloudFeatureEnabled(FEATURE_FLAGS.CAPTAIN_TASKS);
});
const cachedSummary = computed(() => props.chat?.cached_summary || '');
const cachedSummaryAt = computed(() => props.chat?.cached_summary_at || 0);
const lastActivityAt = computed(() => props.chat?.last_activity_at || 0);
const isStale = computed(() => {
if (!cachedSummaryAt.value) return true;
return lastActivityAt.value > cachedSummaryAt.value;
});
const formattedSummary = computed(() => {
return cachedSummary.value ? formatMessage(cachedSummary.value) : '';
});
const fetchSummary = async () => {
isLoading.value = true;
error.value = '';
try {
const result = await TasksAPI.summarize(props.chat.id, {
forceRegenerate: false,
});
const {
data: { message: generatedSummary },
} = result;
if (generatedSummary) {
store.dispatch('updateConversationCachedSummary', {
conversationId: props.chat.id,
cachedSummary: generatedSummary,
cachedSummaryAt: Math.floor(Date.now() / 1000),
});
}
} catch (e) {
if (e.name !== 'AbortError' && e.name !== 'CanceledError') {
error.value = e.response?.data?.error || t('CHAT_LIST.SUMMARY.ERROR');
}
} finally {
isLoading.value = false;
}
};
const toggleSummary = async () => {
if (isExpanded.value) {
isExpanded.value = false;
return;
}
isExpanded.value = true;
useTrack(CAPTAIN_EVENTS.SUMMARIZE_USED, {
conversationId: props.chat.id,
uiFrom: 'conversation_list',
});
// Only fetch if no cached summary
if (!cachedSummary.value && !error.value) {
await fetchSummary();
}
};
const onButtonClick = e => {
e.stopPropagation();
toggleSummary();
};
defineExpose({
isExpanded,
isLoading,
error,
formattedSummary,
captainTasksEnabled,
isStale,
});
</script>
<template>
<Button
v-if="captainTasksEnabled"
icon="i-material-symbols-auto-awesome"
slate
ghost
xs
:title="t('CHAT_LIST.SUMMARY.TITLE')"
class="opacity-0 group-hover:opacity-100 transition-opacity"
:class="{ '!opacity-100': isExpanded }"
@click="onButtonClick"
/>
</template>
@@ -34,21 +34,11 @@ function getEventPrefix(action) {
* @param {string} action - The action type
* @param {number} conversationId - The conversation ID
* @param {number} [followUpCount] - Optional follow-up count
* @param {string} [uiFrom] - Optional UI source identifier
* @returns {Object} The payload object
*/
function buildPayload(
action,
conversationId,
followUpCount = undefined,
uiFrom = undefined
) {
function buildPayload(action, conversationId, followUpCount = undefined) {
const payload = { conversationId };
if (uiFrom) {
payload.uiFrom = uiFrom;
}
// Add operation for rewrite actions
if (REWRITE_ACTIONS.includes(action)) {
payload.operation = action;
@@ -85,7 +75,6 @@ export function useCopilotReply() {
const trackedConversationId = ref(null);
const conversationId = computed(() => currentChat.value?.id);
const uiFrom = 'editor';
const isActive = computed(() => showEditor.value || isGenerating.value);
const isButtonDisabled = computed(
@@ -108,8 +97,7 @@ export function useCopilotReply() {
buildPayload(
currentAction.value,
trackedConversationId.value,
followUpCount.value,
uiFrom
followUpCount.value
)
);
}
@@ -180,7 +168,7 @@ export function useCopilotReply() {
const eventKey = `${getEventPrefix(action)}_USED`;
useTrack(
CAPTAIN_EVENTS[eventKey],
buildPayload(action, trackedConversationId.value, undefined, uiFrom)
buildPayload(action, trackedConversationId.value)
);
}
isGenerating.value = false;
@@ -206,7 +194,6 @@ export function useCopilotReply() {
// Track follow-up sent event
useTrack(CAPTAIN_EVENTS.FOLLOW_UP_SENT, {
conversationId: trackedConversationId.value,
uiFrom,
});
followUpCount.value += 1;
@@ -250,8 +237,7 @@ export function useCopilotReply() {
buildPayload(
currentAction.value,
trackedConversationId.value,
followUpCount.value,
uiFrom
followUpCount.value
)
);
}
@@ -2,7 +2,6 @@ import { computed } from 'vue';
import { useStore, useStoreGetters } from 'dashboard/composables/store';
export const DEFAULT_CONVERSATION_SIDEBAR_ITEMS_ORDER = Object.freeze([
{ name: 'conversation_summary' },
{ name: 'conversation_actions' },
{ name: 'macros' },
{ name: 'conversation_info' },
@@ -127,7 +127,6 @@ const validateSingleAction = action => {
'resolve_conversation',
'remove_assigned_team',
'open_conversation',
'pending_conversation',
];
if (
@@ -150,8 +150,7 @@
"ADD_PRIVATE_NOTE": "Add a Private Note",
"CHANGE_PRIORITY": "Change Priority",
"ADD_SLA": "Add SLA",
"OPEN_CONVERSATION": "Open conversation",
"PENDING_CONVERSATION": "Mark conversation as pending"
"OPEN_CONVERSATION": "Open conversation"
},
"MESSAGE_TYPES": {
"INCOMING": "Incoming Message",
@@ -137,11 +137,6 @@
"HIDE_QUOTED_TEXT": "Hide Quoted Text",
"SHOW_QUOTED_TEXT": "Show Quoted Text",
"MESSAGE_READ": "Read",
"SENDING": "Sending",
"SUMMARY": {
"TITLE": "Generate Summary",
"LOADING": "Generating summary...",
"ERROR": "Failed to generate summary"
}
"SENDING": "Sending"
}
}
@@ -253,8 +253,6 @@
"MESSAGE_ERROR": "Unable to send this message, please try again later",
"SENT_BY": "Sent by:",
"BOT": "Bot",
"NATIVE_APP": "Native app",
"NATIVE_APP_ADVISORY": "This message was sent from the native app. Reply from Chatwoot to maintain the message window.",
"SEND_FAILED": "Couldn't send message! Try again",
"TRY_AGAIN": "retry",
"ASSIGNMENT": {
@@ -349,7 +347,6 @@
"CONVERSATION_ACTIONS": "Conversation Actions",
"CONVERSATION_LABELS": "Conversation Labels",
"CONVERSATION_INFO": "Conversation Information",
"CONVERSATION_SUMMARY": "AI Summary",
"CONTACT_NOTES": "Contact Notes",
"CONTACT_ATTRIBUTES": "Contact Attributes",
"PREVIOUS_CONVERSATION": "Previous Conversations",
@@ -357,16 +354,6 @@
"LINEAR_ISSUES": "Linked Linear Issues",
"SHOPIFY_ORDERS": "Shopify Orders"
},
"SUMMARY": {
"DESCRIPTION": "Generate an AI-powered summary of this conversation",
"GENERATE": "Generate Summary",
"REGENERATE": "Regenerate",
"REFRESH": "Refresh",
"RETRY": "Retry",
"STALE": "Summary may be outdated",
"ERROR": "Failed to generate summary",
"EMPTY": "No summary available"
},
"SHOPIFY": {
"ORDER_ID": "Order #{id}",
"ERROR": "Error loading orders",
@@ -13,7 +13,6 @@ import AccordionItem from 'dashboard/components/Accordion/AccordionItem.vue';
import ContactConversations from './ContactConversations.vue';
import ConversationAction from './ConversationAction.vue';
import ConversationParticipant from './ConversationParticipant.vue';
import ConversationSummary from './ConversationSummary.vue';
import ContactInfo from './contact/ContactInfo.vue';
import ContactNotes from './contact/ContactNotes.vue';
import ConversationInfo from './ConversationInfo.vue';
@@ -45,7 +44,6 @@ const {
const dragging = ref(false);
const conversationSidebarItems = ref([]);
const summaryRef = ref(null);
const shopifyIntegration = useFunctionGetter(
'integrations/getIntegration',
@@ -62,10 +60,6 @@ const isLinearFeatureEnabled = computed(() =>
isCloudFeatureEnabled(FEATURE_FLAGS.LINEAR)
);
const isCaptainTasksEnabled = computed(() =>
isCloudFeatureEnabled(FEATURE_FLAGS.CAPTAIN_TASKS)
);
const linearIntegration = useFunctionGetter(
'integrations/getIntegration',
'linear'
@@ -156,31 +150,7 @@ onMounted(() => {
>
<template #item="{ element }">
<div
v-if="
element.name === 'conversation_summary' && isCaptainTasksEnabled
"
>
<AccordionItem
:title="$t('CONVERSATION_SIDEBAR.ACCORDION.CONVERSATION_SUMMARY')"
:is-open="isContactSidebarItemOpen('is_conv_summary_open')"
compact
@toggle="
value => {
toggleSidebarUIState('is_conv_summary_open', value);
if (value && summaryRef) {
summaryRef.fetchSummary();
}
}
"
>
<ConversationSummary
ref="summaryRef"
:conversation-id="conversationId"
/>
</AccordionItem>
</div>
<div
v-else-if="element.name === 'conversation_actions'"
v-if="element.name === 'conversation_actions'"
class="conversation--actions"
>
<AccordionItem
@@ -1,179 +0,0 @@
<script setup>
import { ref, computed, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useStore, useMapGetter } from 'dashboard/composables/store';
import { useAccount } from 'dashboard/composables/useAccount';
import { useMessageFormatter } from 'shared/composables/useMessageFormatter';
import { FEATURE_FLAGS } from 'dashboard/featureFlags';
import TasksAPI from 'dashboard/api/captain/tasks';
import Button from 'dashboard/components-next/button/Button.vue';
import Spinner from 'dashboard/components-next/spinner/Spinner.vue';
import { useTrack } from 'dashboard/composables';
import { CAPTAIN_EVENTS } from 'dashboard/helper/AnalyticsHelper/events';
const props = defineProps({
conversationId: {
type: [Number, String],
required: true,
},
});
const { t } = useI18n();
const store = useStore();
const { isCloudFeatureEnabled } = useAccount();
const { formatMessage } = useMessageFormatter();
const currentChat = useMapGetter('getSelectedChat');
const isLoading = ref(false);
const error = ref('');
const captainTasksEnabled = computed(() => {
return isCloudFeatureEnabled(FEATURE_FLAGS.CAPTAIN_TASKS);
});
const cachedSummary = computed(() => currentChat.value?.cached_summary || '');
const cachedSummaryAt = computed(
() => currentChat.value?.cached_summary_at || 0
);
const lastActivityAt = computed(() => currentChat.value?.last_activity_at || 0);
const uiFrom = 'conversation_sidebar';
const isStale = computed(() => {
if (!cachedSummaryAt.value) return true;
return lastActivityAt.value > cachedSummaryAt.value;
});
const hasSummary = computed(() => !!cachedSummary.value);
const formattedSummary = computed(() => {
return cachedSummary.value ? formatMessage(cachedSummary.value) : '';
});
const fetchSummary = async (forceRegenerate = false) => {
if (!captainTasksEnabled.value) return;
isLoading.value = true;
error.value = '';
try {
const result = await TasksAPI.summarize(props.conversationId, {
forceRegenerate,
});
const {
data: { message: generatedSummary },
} = result;
if (generatedSummary) {
store.dispatch('updateConversationCachedSummary', {
conversationId: currentChat.value.id,
cachedSummary: generatedSummary,
cachedSummaryAt: Math.floor(Date.now() / 1000),
});
}
} catch (e) {
if (e.name !== 'AbortError' && e.name !== 'CanceledError') {
error.value =
e.response?.data?.error || t('CONVERSATION_SIDEBAR.SUMMARY.ERROR');
}
} finally {
isLoading.value = false;
}
};
const trackSummary = action => {
useTrack(CAPTAIN_EVENTS.SUMMARIZE_USED, {
conversationId: props.conversationId,
uiFrom,
action,
});
};
const generateSummary = () => {
trackSummary('generate');
return fetchSummary(false);
};
const regenerate = () => {
trackSummary('regenerate');
return fetchSummary(true);
};
const retryGenerate = () => {
trackSummary('retry');
return fetchSummary(true);
};
watch(
() => props.conversationId,
() => {
error.value = '';
}
);
defineExpose({
fetchSummary,
captainTasksEnabled,
cachedSummary,
isStale,
});
</script>
<template>
<div v-if="captainTasksEnabled" class="p-3">
<div v-if="isLoading" class="flex items-center justify-center py-4">
<Spinner :size="20" class="text-n-slate-10" />
</div>
<div v-else-if="error" class="text-sm text-n-ruby-11">
{{ error }}
<Button
:label="t('CONVERSATION_SIDEBAR.SUMMARY.RETRY')"
size="sm"
variant="link"
class="ml-2"
@click="retryGenerate"
/>
</div>
<div v-else-if="!hasSummary" class="flex flex-col items-center gap-3 py-2">
<p class="text-sm text-n-slate-11 text-center mb-0">
{{ t('CONVERSATION_SIDEBAR.SUMMARY.DESCRIPTION') }}
</p>
<Button
:label="t('CONVERSATION_SIDEBAR.SUMMARY.GENERATE')"
icon="i-material-symbols-auto-awesome"
size="sm"
@click="generateSummary"
/>
</div>
<template v-else>
<div
v-if="isStale"
class="flex items-center gap-2 mb-2 text-xs text-n-amber-11"
>
<span>{{ t('CONVERSATION_SIDEBAR.SUMMARY.STALE') }}</span>
<Button
:label="t('CONVERSATION_SIDEBAR.SUMMARY.REFRESH')"
size="xs"
variant="link"
@click="regenerate"
/>
</div>
<div
class="summary-content text-sm text-n-slate-11 [&_ul]:list-disc [&_ul]:pl-4 [&_ol]:list-decimal [&_ol]:pl-4 [&_li]:my-1 [&_p]:my-2 [&_p:first-child]:mt-0 [&_p:last-child]:mb-0 [&_strong]:text-n-slate-12"
v-html="formattedSummary"
/>
<div class="mt-3 pt-3 border-t border-n-weak">
<Button
:label="t('CONVERSATION_SIDEBAR.SUMMARY.REGENERATE')"
icon="i-lucide-refresh-cw"
size="sm"
variant="faded"
color="slate"
@click="regenerate"
/>
</div>
</template>
</div>
</template>
@@ -116,10 +116,6 @@ export const AUTOMATIONS = {
key: 'open_conversation',
name: 'OPEN_CONVERSATION',
},
{
key: 'pending_conversation',
name: 'PENDING_CONVERSATION',
},
{
key: 'resolve_conversation',
name: 'RESOLVE_CONVERSATION',
@@ -236,10 +232,6 @@ export const AUTOMATIONS = {
key: 'snooze_conversation',
name: 'SNOOZE_CONVERSATION',
},
{
key: 'pending_conversation',
name: 'PENDING_CONVERSATION',
},
{
key: 'resolve_conversation',
name: 'RESOLVE_CONVERSATION',
@@ -368,10 +360,6 @@ export const AUTOMATIONS = {
key: 'snooze_conversation',
name: 'SNOOZE_CONVERSATION',
},
{
key: 'pending_conversation',
name: 'PENDING_CONVERSATION',
},
{
key: 'resolve_conversation',
name: 'RESOLVE_CONVERSATION',
@@ -494,10 +482,6 @@ export const AUTOMATIONS = {
key: 'snooze_conversation',
name: 'SNOOZE_CONVERSATION',
},
{
key: 'pending_conversation',
name: 'PENDING_CONVERSATION',
},
{
key: 'send_webhook_event',
name: 'SEND_WEBHOOK_EVENT',
@@ -684,11 +668,6 @@ export const AUTOMATION_ACTION_TYPES = [
label: 'OPEN_CONVERSATION',
inputType: null,
},
{
key: 'pending_conversation',
label: 'PENDING_CONVERSATION',
inputType: null,
},
{
key: 'send_webhook_event',
label: 'SEND_WEBHOOK_EVENT',
@@ -412,17 +412,6 @@ const actions = {
});
},
updateConversationCachedSummary(
{ commit },
{ conversationId, cachedSummary, cachedSummaryAt }
) {
commit(types.UPDATE_CONVERSATION_CACHED_SUMMARY, {
conversationId,
cachedSummary,
cachedSummaryAt,
});
},
setChatStatusFilter({ commit }, data) {
commit(types.CHANGE_CHAT_STATUS_FILTER, data);
},
@@ -116,16 +116,6 @@ export const mutations = {
chat.last_activity_at = lastActivityAt;
}
},
[types.UPDATE_CONVERSATION_CACHED_SUMMARY](
_state,
{ conversationId, cachedSummary, cachedSummaryAt }
) {
const [chat] = _state.allConversations.filter(c => c.id === conversationId);
if (chat) {
chat.cached_summary = cachedSummary;
chat.cached_summary_at = cachedSummaryAt;
}
},
[types.ASSIGN_PRIORITY](_state, { priority, conversationId }) {
const [chat] = _state.allConversations.filter(c => c.id === conversationId);
chat.priority = priority;
@@ -51,7 +51,6 @@ export default {
UPDATE_CONVERSATION_CUSTOM_ATTRIBUTES:
'UPDATE_CONVERSATION_CUSTOM_ATTRIBUTES',
UPDATE_CONVERSATION_LAST_ACTIVITY: 'UPDATE_CONVERSATION_LAST_ACTIVITY',
UPDATE_CONVERSATION_CACHED_SUMMARY: 'UPDATE_CONVERSATION_CACHED_SUMMARY',
UPDATE_CONVERSATION_CALL_STATUS: 'UPDATE_CONVERSATION_CALL_STATUS',
UPDATE_MESSAGE_CALL_STATUS: 'UPDATE_MESSAGE_CALL_STATUS',
SET_MISSING_MESSAGES: 'SET_MISSING_MESSAGES',
-1
View File
@@ -3,7 +3,6 @@ class ConversationReplyEmailJob < ApplicationJob
def perform(conversation_id, last_queued_id)
conversation = Conversation.find(conversation_id)
return unless conversation.account.active?
if conversation.messages.incoming&.last&.content_type == 'incoming_email'
ConversationReplyMailer.with(account: conversation.account).reply_without_summary(conversation, last_queued_id).deliver_later
+1 -1
View File
@@ -54,7 +54,7 @@ class Webhooks::TiktokEventsJob < MutexApplicationJob
# Receive real-time notifications if you send a message to a user.
def im_send_msg
# This can be either an echo message or a message sent directly via tiktok application
::Tiktok::MessageService.new(channel: channel, content: content, outgoing_echo: true).perform
::Tiktok::MessageService.new(channel: channel, content: content).perform
end
# Receive real-time notifications if a user outside the European Economic Area (EEA), Switzerland, or the UK sends a message to you.
-50
View File
@@ -9,56 +9,6 @@ class Webhooks::WhatsappEventsJob < ApplicationJob
return
end
if message_echo_event?(params)
handle_message_echo(channel, params)
else
handle_message_events(channel, params)
end
end
# Detects if the webhook is an SMB message echo event (message sent from WhatsApp Business app)
# This is part of WhatsApp coexistence feature where businesses can respond from both
# Chatwoot and the WhatsApp Business app, with messages synced to Chatwoot.
#
# Regular message payload (field: "messages"):
# {
# "entry": [{
# "changes": [{
# "field": "messages",
# "value": {
# "contacts": [{ "wa_id": "919745786257", "profile": { "name": "Customer" } }],
# "messages": [{ "from": "919745786257", "id": "wamid...", "text": { "body": "Hello" } }]
# }
# }]
# }]
# }
#
# Echo message payload (field: "smb_message_echoes"):
# {
# "entry": [{
# "changes": [{
# "field": "smb_message_echoes",
# "value": {
# "message_echoes": [{ "from": "971545296927", "to": "919745786257", "id": "wamid...", "text": { "body": "Hi" } }]
# }
# }]
# }]
# }
#
# Key differences:
# - field: "smb_message_echoes" instead of "messages"
# - message_echoes[] instead of messages[]
# - "from" is the business number, "to" is the contact (reversed from regular messages)
# - No "contacts" array in echo payload
def message_echo_event?(params)
params.dig(:entry, 0, :changes, 0, :field) == 'smb_message_echoes'
end
def handle_message_echo(channel, params)
Whatsapp::IncomingMessageWhatsappCloudService.new(inbox: channel.inbox, params: params, outgoing_echo: true).perform
end
def handle_message_events(channel, params)
case channel.provider
when 'whatsapp_cloud'
Whatsapp::IncomingMessageWhatsappCloudService.new(inbox: channel.inbox, params: params).perform
-1
View File
@@ -38,7 +38,6 @@ class ConversationReplyMailer < ApplicationMailer
return unless smtp_config_set_or_development?
init_conversation_attributes(message.conversation)
@message = message
prepare_mail(true)
end
-1
View File
@@ -29,7 +29,6 @@ class Account < ApplicationRecord
include Featurable
include CacheKeys
include CaptainFeaturable
include AccountEmailRateLimitable
SETTINGS_PARAMS_SCHEMA = {
'type': 'object',
+2 -2
View File
@@ -41,8 +41,8 @@ class AutomationRule < ApplicationRecord
def actions_attributes
%w[send_message add_label remove_label send_email_to_team assign_team assign_agent send_webhook_event mute_conversation
send_attachment change_status resolve_conversation open_conversation pending_conversation snooze_conversation change_priority
send_email_transcript add_private_note].freeze
send_attachment change_status resolve_conversation open_conversation snooze_conversation change_priority send_email_transcript
add_private_note].freeze
end
def file_base_data
@@ -1,49 +0,0 @@
module AccountEmailRateLimitable
extend ActiveSupport::Concern
OUTBOUND_EMAIL_TTL = 25.hours.to_i
EMAIL_LIMIT_CONFIG_KEY = 'ACCOUNT_EMAILS_LIMIT'.freeze
def email_rate_limit
account_limit || global_limit || default_limit
end
def emails_sent_today
Redis::Alfred.get(email_count_cache_key).to_i
end
def within_email_rate_limit?
return true if emails_sent_today < email_rate_limit
Rails.logger.warn("Account #{id} reached daily email rate limit of #{email_rate_limit}. Sent: #{emails_sent_today}")
false
end
def increment_email_sent_count
Redis::Alfred.incr(email_count_cache_key).tap do |count|
Redis::Alfred.expire(email_count_cache_key, OUTBOUND_EMAIL_TTL) if count == 1
end
end
private
def email_count_cache_key
@email_count_cache_key ||= format(
Redis::Alfred::ACCOUNT_OUTBOUND_EMAIL_COUNT_KEY,
account_id: id,
date: Time.zone.today.to_s
)
end
def account_limit
self[:limits]&.dig('emails')&.to_i
end
def global_limit
GlobalConfig.get(EMAIL_LIMIT_CONFIG_KEY)[EMAIL_LIMIT_CONFIG_KEY]&.to_i
end
def default_limit
ChatwootApp.max_limit.to_i
end
end
+1 -2
View File
@@ -344,11 +344,10 @@ class Message < ApplicationRecord
# if the sender is not a user, it's not a human response
# if automation rule id is present, it's not a human response
# if campaign id is present, it's not a human response
# external echo messages are responses sent from the native app (WhatsApp Business, Instagram)
outgoing? &&
content_attributes['automation_rule_id'].blank? &&
additional_attributes['campaign_id'].blank? &&
(sender.is_a?(User) || content_attributes['external_echo'].present?)
sender.is_a?(User)
end
def bot_response?
-4
View File
@@ -22,10 +22,6 @@ class ActionService
@conversation.open!
end
def pending_conversation(_params)
@conversation.pending!
end
def change_status(status)
@conversation.update!(status: status[0])
end
@@ -9,7 +9,8 @@ class Messages::MarkdownRendererService
'Channel::Line' => :render_line,
'Channel::TwitterProfile' => :render_plain_text,
'Channel::Sms' => :render_plain_text,
'Channel::TwilioSms' => :render_plain_text
'Channel::TwilioSms' => :render_plain_text,
'Channel::Api' => :render_api_message
}.freeze
def initialize(content, channel_type, channel = nil)
@@ -56,6 +57,11 @@ class Messages::MarkdownRendererService
restore_multiple_newlines(result)
end
def render_api_message
# Convert literal \n strings to actual newlines for API channel messages
@content.gsub('\\n', "\n")
end
def render_whatsapp
# Strip whitespace from whitespace-only lines to normalize newlines
normalized_content = @content.gsub(/^[ \t]+$/m, '')
@@ -13,7 +13,6 @@ class Messages::SendEmailNotificationService
return unless Redis::Alfred.set(conversation_mail_key, message.id, nx: true, ex: 1.hour.to_i)
ConversationReplyEmailJob.set(wait: 2.minutes).perform_later(conversation.id, message.id)
message.account.increment_email_sent_count
end
private
@@ -21,7 +20,6 @@ class Messages::SendEmailNotificationService
def should_send_email_notification?
return false unless message.email_notifiable_message?
return false if message.conversation.contact.email.blank?
return false unless message.account.within_email_rate_limit?
email_reply_enabled?
end
@@ -7,22 +7,15 @@ class Notification::EmailNotificationService
# don't send emails if user is not confirmed
return if notification.user.confirmed_at.nil?
return unless user_subscribed_to_notification?
return unless notification.account.within_email_rate_limit?
send_notification_email
notification.account.increment_email_sent_count
# TODO : Clean up whatever happening over here
# Segregate the mailers properly
AgentNotifications::ConversationNotificationsMailer.with(account: notification.account).public_send(notification
.notification_type.to_s, notification.primary_actor, notification.user, notification.secondary_actor).deliver_later
end
private
# TODO : Clean up whatever happening over here
# Segregate the mailers properly
def send_notification_email
AgentNotifications::ConversationNotificationsMailer.with(account: notification.account).public_send(
notification.notification_type.to_s, notification.primary_actor, notification.user, notification.secondary_actor
).deliver_later
end
def user_subscribed_to_notification?
notification_setting = notification.user.notification_settings.find_by(account_id: notification.account.id)
return true if notification_setting.public_send("email_#{notification.notification_type}?")
+3 -3
View File
@@ -1,10 +1,11 @@
class Tiktok::MessageService
include Tiktok::MessagingHelpers
pattr_initialize [:channel!, :content!, :outgoing_echo]
pattr_initialize [:channel!, :content!]
def perform
if outgoing_message?
# Skip processing echo messages
message = find_message(tt_conversation_id, tt_message_id)
return if message.present?
end
@@ -38,7 +39,7 @@ class Tiktok::MessageService
updated_at: tt_message_time
)
message.sender = contact_inbox.contact if incoming_message? && !outgoing_echo
message.sender = contact_inbox.contact if incoming_message?
message.status = :delivered if outgoing_message?
create_message_attachments(message)
@@ -90,7 +91,6 @@ class Tiktok::MessageService
attributes = {}
attributes[:in_reply_to_external_id] = tt_referenced_message_id if tt_referenced_message_id
attributes[:is_unsupported] = true unless supported_message?
attributes[:external_echo] = true if outgoing_echo
attributes
end
+2 -22
View File
@@ -61,36 +61,16 @@ class Whatsapp::FacebookApiClient
end
def subscribe_waba_webhook(waba_id, callback_url, verify_token)
# Step 1: Subscribe app to WABA first (required before override)
# Meta requires the app to be subscribed before using override_callback_uri
# See: https://github.com/chatwoot/chatwoot/issues/13097
subscribe_app_to_waba(waba_id)
# Step 2: Override callback URL for this specific WABA
override_waba_callback(waba_id, callback_url, verify_token)
end
def subscribe_app_to_waba(waba_id)
response = HTTParty.post(
"#{BASE_URI}/#{@api_version}/#{waba_id}/subscribed_apps",
headers: request_headers
)
handle_response(response, 'App subscription to WABA failed')
end
def override_waba_callback(waba_id, callback_url, verify_token)
response = HTTParty.post(
"#{BASE_URI}/#{@api_version}/#{waba_id}/subscribed_apps",
headers: request_headers,
body: {
override_callback_uri: callback_url,
verify_token: verify_token,
subscribed_fields: %w[messages smb_message_echoes]
verify_token: verify_token
}.to_json
)
handle_response(response, 'Webhook callback override failed')
handle_response(response, 'Webhook subscription failed')
end
def unsubscribe_waba_webhook(waba_id)
@@ -4,23 +4,18 @@
class Whatsapp::IncomingMessageBaseService
include ::Whatsapp::IncomingMessageServiceHelpers
pattr_initialize [:inbox!, :params!, :outgoing_echo]
pattr_initialize [:inbox!, :params!]
def perform
processed_params
if processed_params.try(:[], :statuses).present?
process_statuses
elsif messages_data.present?
elsif processed_params.try(:[], :messages).present?
process_messages
end
end
# Returns messages array for both regular messages and echo events
def messages_data
@processed_params&.dig(:messages) || @processed_params&.dig(:message_echoes)
end
private
def process_messages
@@ -31,7 +26,7 @@ class Whatsapp::IncomingMessageBaseService
# Multiple webhook event can be received against the same message due to misconfigurations in the Meta
# business manager account. While we have not found the core reason yet, the following line ensure that
# there are no duplicate messages created.
return if find_message_by_source_id(messages_data.first[:id]) || message_under_process?
return if find_message_by_source_id(@processed_params[:messages].first[:id]) || message_under_process?
cache_message_source_id_in_redis
set_contact
@@ -62,7 +57,7 @@ class Whatsapp::IncomingMessageBaseService
end
def create_messages
message = messages_data.first
message = @processed_params[:messages].first
log_error(message) && return if error_webhook_event?(message)
process_in_reply_to(message)
@@ -72,44 +67,20 @@ class Whatsapp::IncomingMessageBaseService
def create_contact_messages(message)
message['contacts'].each do |contact|
# Pass source_id from parent message since contact objects don't have :id
create_message(contact, source_id: message[:id])
create_message(contact)
attach_contact(contact)
@message.save!
end
end
def create_regular_message(message)
create_message(message, source_id: message[:id])
create_message(message)
attach_files
attach_location if message_type == 'location'
@message.save!
end
def set_contact
if outgoing_echo
set_contact_from_echo
else
set_contact_from_message
end
end
def set_contact_from_echo
# For echo messages, contact phone is in the 'to' field
phone_number = messages_data.first[:to]
waid = processed_waid(phone_number)
contact_inbox = ::ContactInboxWithContactBuilder.new(
source_id: waid,
inbox: inbox,
contact_attributes: { name: "+#{phone_number}", phone_number: "+#{phone_number}" }
).perform
@contact_inbox = contact_inbox
@contact = contact_inbox.contact
end
def set_contact_from_message
contact_params = @processed_params[:contacts]&.first
return if contact_params.blank?
@@ -118,7 +89,7 @@ class Whatsapp::IncomingMessageBaseService
contact_inbox = ::ContactInboxWithContactBuilder.new(
source_id: waid,
inbox: inbox,
contact_attributes: { name: contact_params.dig(:profile, :name), phone_number: "+#{messages_data.first[:from]}" }
contact_attributes: { name: contact_params.dig(:profile, :name), phone_number: "+#{@processed_params[:messages].first[:from]}" }
).perform
@contact_inbox = contact_inbox
@@ -144,7 +115,7 @@ class Whatsapp::IncomingMessageBaseService
def attach_files
return if %w[text button interactive location contacts].include?(message_type)
attachment_payload = messages_data.first[message_type.to_sym]
attachment_payload = @processed_params[:messages].first[message_type.to_sym]
@message.content ||= attachment_payload[:caption]
attachment_file = download_attachment_file(attachment_payload)
@@ -162,7 +133,7 @@ class Whatsapp::IncomingMessageBaseService
end
def attach_location
location = messages_data.first['location']
location = @processed_params[:messages].first['location']
location_name = location['name'] ? "#{location['name']}, #{location['address']}" : ''
@message.attachments.new(
account_id: @message.account_id,
@@ -174,17 +145,14 @@ class Whatsapp::IncomingMessageBaseService
)
end
def create_message(message, source_id: nil)
def create_message(message)
@message = @conversation.messages.build(
content: message_content(message),
account_id: @inbox.account_id,
inbox_id: @inbox.id,
message_type: outgoing_echo ? :outgoing : :incoming,
# Set status to :delivered for echo messages to prevent SendReplyJob from trying to send them
status: outgoing_echo ? :delivered : :sent,
sender: outgoing_echo ? nil : @contact,
source_id: (source_id || message[:id]).to_s,
content_attributes: outgoing_echo ? { external_echo: true } : {},
message_type: :incoming,
sender: @contact,
source_id: message[:id].to_s,
in_reply_to_external_id: @in_reply_to_external_id
)
end
@@ -221,7 +189,7 @@ class Whatsapp::IncomingMessageBaseService
end
def contact_name_matches_phone_number?
phone_number = "+#{messages_data.first[:from]}"
phone_number = "+#{@processed_params[:messages].first[:from]}"
formatted_phone_number = TelephoneNumber.parse(phone_number).international_number
@contact.name == phone_number || @contact.name == formatted_phone_number
end
@@ -21,7 +21,7 @@ module Whatsapp::IncomingMessageServiceHelpers
end
def message_type
messages_data.first[:type]
@processed_params[:messages].first[:type]
end
def message_content(message)
@@ -70,19 +70,19 @@ module Whatsapp::IncomingMessageServiceHelpers
end
def message_under_process?
key = format(Redis::RedisKeys::MESSAGE_SOURCE_KEY, id: messages_data.first[:id])
key = format(Redis::RedisKeys::MESSAGE_SOURCE_KEY, id: @processed_params[:messages].first[:id])
Redis::Alfred.get(key)
end
def cache_message_source_id_in_redis
return if messages_data.blank?
return if @processed_params.try(:[], :messages).blank?
key = format(Redis::RedisKeys::MESSAGE_SOURCE_KEY, id: messages_data.first[:id])
key = format(Redis::RedisKeys::MESSAGE_SOURCE_KEY, id: @processed_params[:messages].first[:id])
::Redis::Alfred.setex(key, true)
end
def clear_message_source_id_from_redis
key = format(Redis::RedisKeys::MESSAGE_SOURCE_KEY, id: messages_data.first[:id])
key = format(Redis::RedisKeys::MESSAGE_SOURCE_KEY, id: @processed_params[:messages].first[:id])
::Redis::Alfred.delete(key)
end
end
@@ -56,8 +56,6 @@ json.first_reply_created_at conversation.first_reply_created_at.to_i
json.unread_count conversation.unread_incoming_messages.count
json.last_non_activity_message conversation.messages.where(account_id: conversation.account_id).non_activity_messages.first.try(:push_event_data)
json.last_activity_at conversation.last_activity_at.to_i
json.cached_summary conversation.cached_summary
json.cached_summary_at conversation.cached_summary_at.to_i
json.priority conversation.priority
json.waiting_since conversation.waiting_since.to_i.to_i
json.sla_policy_id conversation.sla_policy_id
-10
View File
@@ -107,16 +107,6 @@
value:
description: 'The support email address for your installation'
locked: false
- name: ACCOUNT_EMAILS_LIMIT
display_title: 'Account Email Sending Limit (Daily)'
description: 'Maximum number of non-channel emails an account can send per day'
value: 100
locked: false
- name: ACCOUNT_EMAILS_PLAN_LIMITS
display_title: 'Account Email Plan Limits (Daily)'
description: 'Per-plan daily email sending limits as JSON'
value:
type: code
# ------- End of Email Related Config ------- #
# ------- Facebook Channel Related Config ------- #
-1
View File
@@ -445,7 +445,6 @@ Rails.application.routes.draw do
get :conversation_traffic
get :bot_metrics
get :inbox_label_matrix
get :first_response_time_distribution
end
end
resource :year_in_review, only: [:show]
@@ -1,6 +0,0 @@
class AddCachedSummaryToConversations < ActiveRecord::Migration[7.1]
def change
add_column :conversations, :cached_summary, :text
add_column :conversations, :cached_summary_at, :datetime
end
end
@@ -1,11 +0,0 @@
class AddIndexToReportingEventsForResponseDistribution < ActiveRecord::Migration[7.1]
disable_ddl_transaction!
def change
add_index :reporting_events,
[:account_id, :name, :inbox_id, :created_at],
name: 'index_reporting_events_for_response_distribution',
algorithm: :concurrently,
if_not_exists: true
end
end
+1 -4
View File
@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[7.1].define(version: 2026_01_30_061021) do
ActiveRecord::Schema[7.1].define(version: 2026_01_20_121402) do
# These extensions should be enabled to support this database
enable_extension "pg_stat_statements"
enable_extension "pg_trgm"
@@ -681,8 +681,6 @@ ActiveRecord::Schema[7.1].define(version: 2026_01_30_061021) do
t.datetime "waiting_since"
t.text "cached_label_list"
t.bigint "assignee_agent_bot_id"
t.text "cached_summary"
t.datetime "cached_summary_at"
t.index ["account_id", "display_id"], name: "index_conversations_on_account_id_and_display_id", unique: true
t.index ["account_id", "id"], name: "index_conversations_on_id_and_account_id"
t.index ["account_id", "inbox_id", "status", "assignee_id"], name: "conv_acid_inbid_stat_asgnid_idx"
@@ -1117,7 +1115,6 @@ ActiveRecord::Schema[7.1].define(version: 2026_01_30_061021) do
t.datetime "event_start_time", precision: nil
t.datetime "event_end_time", precision: nil
t.index ["account_id", "name", "created_at"], name: "reporting_events__account_id__name__created_at"
t.index ["account_id", "name", "inbox_id", "created_at"], name: "index_reporting_events_for_response_distribution"
t.index ["account_id"], name: "index_reporting_events_on_account_id"
t.index ["conversation_id"], name: "index_reporting_events_on_conversation_id"
t.index ["created_at"], name: "index_reporting_events_on_created_at"
@@ -15,8 +15,7 @@ class Api::V1::Accounts::Captain::TasksController < Api::V1::Accounts::BaseContr
def summarize
result = Captain::SummaryService.new(
account: Current.account,
conversation_display_id: params[:conversation_display_id],
force_regenerate: params[:force_regenerate].present?
conversation_display_id: params[:conversation_display_id]
).perform
render_result(result)
@@ -2,6 +2,6 @@ require 'administrate/field/base'
class AccountLimitsField < Administrate::Field::Base
def to_s
data.present? ? data.to_json : { agents: nil, inboxes: nil, captain_responses: nil, captain_documents: nil, emails: nil }.to_json
data.present? ? data.to_json : { agents: nil, inboxes: nil, captain_responses: nil, captain_documents: nil }.to_json
end
end
@@ -1,4 +1,4 @@
module Enterprise::Account::PlanUsageAndLimits # rubocop:disable Metrics/ModuleLength
module Enterprise::Account::PlanUsageAndLimits
CAPTAIN_RESPONSES = 'captain_responses'.freeze
CAPTAIN_DOCUMENTS = 'captain_documents'.freeze
CAPTAIN_RESPONSES_USAGE = 'captain_responses_usage'.freeze
@@ -32,10 +32,6 @@ module Enterprise::Account::PlanUsageAndLimits # rubocop:disable Metrics/ModuleL
save
end
def email_rate_limit
account_limit || plan_email_limit || global_limit || default_limit
end
def subscribed_features
plan_features = InstallationConfig.find_by(name: 'CHATWOOT_CLOUD_PLAN_FEATURES')&.value
return [] if plan_features.blank?
@@ -72,16 +68,6 @@ module Enterprise::Account::PlanUsageAndLimits # rubocop:disable Metrics/ModuleL
}
end
def plan_email_limit
config = InstallationConfig.find_by(name: 'ACCOUNT_EMAILS_PLAN_LIMITS')&.value
return nil if config.blank? || plan_name.blank?
parsed = config.is_a?(String) ? JSON.parse(config) : config
parsed[plan_name.downcase]&.to_i
rescue StandardError
nil
end
def default_captain_limits
max_limits = { documents: ChatwootApp.max_limit, responses: ChatwootApp.max_limit }.with_indifferent_access
zero_limits = { documents: 0, responses: 0 }.with_indifferent_access
@@ -133,8 +119,7 @@ module Enterprise::Account::PlanUsageAndLimits # rubocop:disable Metrics/ModuleL
'inboxes' => { 'type': 'number' },
'agents' => { 'type': 'number' },
'captain_responses' => { 'type': 'number' },
'captain_documents' => { 'type': 'number' },
'emails' => { 'type': 'number' }
'captain_documents' => { 'type': 'number' }
},
'required' => [],
'additionalProperties' => false
+8 -73
View File
@@ -1,10 +1,14 @@
class Captain::SummaryService < Captain::BaseTaskService
pattr_initialize [:account!, :conversation_display_id!, { force_regenerate: false }]
pattr_initialize [:account!, :conversation_display_id!]
def perform
return cached_response if use_cache?
generate_and_cache_summary
make_api_call(
model: GPT_MODEL,
messages: [
{ role: 'system', content: prompt_from_file('summary') },
{ role: 'user', content: conversation.to_llm_text(include_contact_details: false) }
]
)
end
private
@@ -12,73 +16,4 @@ class Captain::SummaryService < Captain::BaseTaskService
def event_name
'summarize'
end
def use_cache?
return false if force_regenerate
return false if conversation.cached_summary.blank?
return false if conversation.cached_summary_at.blank?
conversation.cached_summary_at >= conversation.last_activity_at
end
def cached_response
{ message: conversation.cached_summary }
end
def generate_and_cache_summary
msg_count = conversation_message_count
result = make_api_call(
model: summary_model(msg_count),
messages: [
{ role: 'system', content: prompt_from_file('summary') },
{ role: 'user', content: build_summary_content(msg_count) }
]
)
cache_summary(result[:message]) if result[:message].present? && result[:error].blank?
result
end
def conversation_message_count
conversation.messages.where(message_type: [:incoming, :outgoing]).count
end
def summary_model(msg_count)
msg_count < 7 ? GPT_MODEL : 'gpt-4.1'
end
def build_summary_content(msg_count)
llm_text = conversation.to_llm_text(include_contact_details: false)
context = build_conversation_context(msg_count)
context.present? ? "#{llm_text}\n\n#{context}" : llm_text
end
def build_conversation_context(msg_count)
['Conversation Stats:', *context_fields(msg_count).compact].join("\n")
end
def context_fields(msg_count)
[
"Message count: #{msg_count}",
("Status: #{conversation.status}" if conversation.status.present?),
("Priority: #{conversation.priority}" if conversation.priority.present?),
("Labels: #{conversation.cached_label_list}" if conversation.cached_label_list.present?),
*account_context_fields
]
end
def account_context_fields
[
("Account industry: #{account.custom_attributes['industry']}" if account.custom_attributes&.dig('industry').present?),
("Summary language: #{account.locale}" if account.locale.present?)
]
end
def cache_summary(summary)
conversation.update(
cached_summary: summary,
cached_summary_at: Time.current
)
end
end
@@ -1,99 +1,28 @@
<prompt>
<role>AI support conversation summarizer</role>
As an AI-powered summarization tool, your task is to condense lengthy interactions between customer support agents and customers into brief, digestible summaries. The objective of these summaries is to provide a quick overview, enabling any agent, even those without prior context, to grasp the essence of the conversation promptly.
<goal>
Produce a high-signal bullet summary that lets a new agent understand the CURRENT STATE and know what to do next — in under 10 seconds.
Earlier bullets convey what happened and what the current state is. The final bullet is always the actionable next step.
</goal>
Make sure you strongly adhere to the following rules when generating the summary
<output_contract>
<format>bullet_list</format>
<only_output_bullets>true</only_output_bullets>
<bullet_count_rules>
<rule>Count the messages in the conversation to determine bullet limits.</rule>
<rule>1-3 messages → 1 bullet max</rule>
<rule>4-10 messages → 2-3 bullets max</rule>
<rule>11-30 messages → 3-4 bullets max</rule>
<rule>31+ messages → 5-6 bullets max</rule>
</bullet_count_rules>
<bullet_rules>
<single_sentence>true</single_sentence>
<concise>true</concise>
<no_redundancy>true</no_redundancy>
<no_prefixes>Do not prefix bullets with labels like "Next step:" or "Issue:" — ordering alone conveys structure.</no_prefixes>
</bullet_rules>
<language>
<rule>ALWAYS write the summary in the language specified by "Summary language" in the conversation context. This overrides the conversation language.</rule>
<rule>If no summary language is provided, match the primary language used in the conversation.</rule>
</language>
<markdown>
<bold_required>true</bold_required>
<code_in_backticks>true</code_in_backticks>
<no_headings>true</no_headings>
</markdown>
</output_contract>
1. Be brief and concise. The shorter the summary the better.
2. Aim to summarize the conversation in approximately 200 words, formatted as multiple small paragraphs that are easier to read.
3. Describe the customer intent in around 50 words.
4. Remove information that is not directly relevant to the customer's problem or the agent's solution. For example, personal anecdotes, small talk, etc.
5. Don't include segments of the conversation that didn't contribute meaningful content, like greetings or farewell.
6. The 'Action Items' should be a bullet list, arranged in order of priority if possible.
7. 'Action Items' should strictly encapsulate tasks committed to by the agent or left incomplete. Any suggestions made by the agent should not be included.
8. The 'Action Items' should be brief and concise
9. Mark important words or parts of sentences as bold.
10. Apply markdown syntax to format any included code, using backticks.
11. Include a section for "Follow-up Items" or "Open Questions" if there are any unresolved issues or outstanding questions.
12. If any section does not have any content, remove that section and the heading from the response
13. Do not insert your own opinions about the conversation.
<what_to_capture>
<priority_order>
<item>What is the customer trying to achieve right now?</item>
<item>What is the current blocker/problem?</item>
<item>What has already been done that changed the state?</item>
<item>What is the actionable next step (who does what)?</item>
</priority_order>
<skip_rule>If a priority item has no evidence in the conversation, skip it entirely — do not invent or guess.</skip_rule>
<last_bullet_rule>The final bullet must always be an actionable next step derived from the conversation.</last_bullet_rule>
</what_to_capture>
<context_awareness>
<business_context>If account industry or business context is provided, adapt the summary focus accordingly (e.g., e-commerce → order/payment/shipping; SaaS → features/bugs/subscriptions; healthcare → appointments/records).</business_context>
<labels>If conversation labels are provided, use them to understand the issue category and focus the summary on what matters for that category.</labels>
<adapt>Only use context that is explicitly provided. Do not assume industry or category if not stated.</adapt>
</context_awareness>
Reply in the user's language, as a markdown of the following format.
<importance_filter>
<include_only_if_actionable_or_state_changing>
<rule>A bullet must describe a blocker, a confirmed action taken, a decision, or a required next step.</rule>
<rule>Would removing this bullet prevent the agent from acting correctly? If no, omit it.</rule>
</include_only_if_actionable_or_state_changing>
<drop_as_noise>
<item>Greetings, thanks, apologies, pleasantries, offers of help.</item>
<item>Repeated statements that do not add new information.</item>
<item>Meta commentary like "the current blocker is…" if it repeats an earlier bullet.</item>
</drop_as_noise>
</importance_filter>
**Customer Intent**
<anti_hallucination>
<hard_rules>
<item>Use ONLY information explicitly present in the conversation.</item>
<item>Do NOT compute or derive facts (no time math like "15 minutes from now", no inferred causes).</item>
<item>Do NOT invent resolution, closure, or "no further steps" statements.</item>
<item>Do NOT restate the same fact in multiple bullets; merge into one.</item>
</hard_rules>
</anti_hallucination>
**Conversation Summary**
<formatting_rules>
<bold_usage>
<rule>Bold the key nouns/verbs (problem, blocker, action, next step, key artifact).</rule>
<examples>
<example>**Meeting invite** not received.</example>
<example>Agent **sent calendar invite** for **4:45 PM GMT+1**.</example>
</examples>
</bold_usage>
<role_words>
<rule>Prefer **Customer** and **Agent** over "user" and "support agent".</rule>
</role_words>
</formatting_rules>
**Action Items**
<final_validation>
<checklist>
<item>Every bullet is one sentence.</item>
<item>Every bullet contains at least one **bold** phrase.</item>
<item>No bullet contains inferred/derived info.</item>
<item>No two bullets repeat the same meaning.</item>
<item>Last bullet is an actionable next step.</item>
<item>Summary language matches "Summary language" from context (if provided), otherwise matches conversation language.</item>
<item>Bullet count respects the scaling rules for the message count.</item>
</checklist>
<reject_if_fails>true</reject_if_fails>
</final_validation>
</prompt>
**Follow-up Items**
-3
View File
@@ -49,7 +49,4 @@ module Redis::RedisKeys
# Track conversation assignments to agents for rate limiting
ASSIGNMENT_KEY = 'ASSIGNMENT::%<inbox_id>d::AGENT::%<agent_id>d::CONVERSATION::%<conversation_id>d'.freeze
ASSIGNMENT_KEY_PATTERN = 'ASSIGNMENT::%<inbox_id>d::AGENT::%<agent_id>d::*'.freeze
## Account Email Rate Limiting
ACCOUNT_OUTBOUND_EMAIL_COUNT_KEY = 'OUTBOUND_EMAIL_COUNT::%<account_id>d::%<date>s'.freeze
end
@@ -1,145 +0,0 @@
require 'rails_helper'
RSpec.describe V2::Reports::FirstResponseTimeDistributionBuilder do
let!(:account) { create(:account) }
let!(:web_widget_inbox) { create(:inbox, account: account, channel: create(:channel_widget, account: account)) }
let!(:email_inbox) { create(:inbox, account: account, channel: create(:channel_email, account: account)) }
let(:params) do
{
since: 1.week.ago.beginning_of_day.to_i.to_s,
until: Time.current.end_of_day.to_i.to_s
}
end
let(:builder) { described_class.new(account: account, params: params) }
describe '#build' do
subject(:report) { builder.build }
context 'when there are first response events across channels and time buckets' do
before do
# Web Widget: 0-1h bucket (30 minutes = 1800 seconds)
create(:reporting_event, account: account, inbox: web_widget_inbox, name: 'first_response',
value: 1_800, created_at: 2.days.ago)
# Web Widget: 1-4h bucket (2 hours = 7200 seconds)
create(:reporting_event, account: account, inbox: web_widget_inbox, name: 'first_response',
value: 7_200, created_at: 2.days.ago)
# Web Widget: 4-8h bucket (6 hours = 21600 seconds)
create(:reporting_event, account: account, inbox: web_widget_inbox, name: 'first_response',
value: 21_600, created_at: 3.days.ago)
# Email: 8-24h bucket (12 hours = 43200 seconds)
create(:reporting_event, account: account, inbox: email_inbox, name: 'first_response',
value: 43_200, created_at: 2.days.ago)
# Email: 24h+ bucket (48 hours = 172800 seconds)
create(:reporting_event, account: account, inbox: email_inbox, name: 'first_response',
value: 172_800, created_at: 1.day.ago)
end
it 'returns correct distribution for web widget channel' do
expect(report['Channel::WebWidget']).to eq({
'0-1h' => 1,
'1-4h' => 1,
'4-8h' => 1,
'8-24h' => 0,
'24h+' => 0
})
end
it 'returns correct distribution for email channel' do
expect(report['Channel::Email']).to eq({
'0-1h' => 0,
'1-4h' => 0,
'4-8h' => 0,
'8-24h' => 1,
'24h+' => 1
})
end
end
context 'when filtering by date range' do
before do
create(:reporting_event, account: account, inbox: web_widget_inbox, name: 'first_response',
value: 1_800, created_at: 2.days.ago)
create(:reporting_event, account: account, inbox: web_widget_inbox, name: 'first_response',
value: 1_800, created_at: 2.weeks.ago)
end
it 'only counts events within the date range' do
expect(report['Channel::WebWidget']['0-1h']).to eq(1)
end
end
context 'when there are no first response events' do
it 'returns an empty hash' do
expect(report).to eq({})
end
end
context 'when events belong to another account' do
let(:other_account) { create(:account) }
let(:other_inbox) { create(:inbox, account: other_account) }
before do
create(:reporting_event, account: other_account, inbox: other_inbox, name: 'first_response',
value: 1_800, created_at: 2.days.ago)
end
it 'does not include events from other accounts' do
expect(report).to eq({})
end
end
context 'when events have different names' do
before do
create(:reporting_event, account: account, inbox: web_widget_inbox, name: 'first_response',
value: 1_800, created_at: 2.days.ago)
create(:reporting_event, account: account, inbox: web_widget_inbox, name: 'conversation_resolved',
value: 1_800, created_at: 2.days.ago)
create(:reporting_event, account: account, inbox: web_widget_inbox, name: 'reply_time',
value: 1_800, created_at: 2.days.ago)
end
it 'only counts first_response events' do
expect(report['Channel::WebWidget']['0-1h']).to eq(1)
end
end
context 'when no date range params are provided' do
let(:params) { {} }
before do
create(:reporting_event, account: account, inbox: web_widget_inbox, name: 'first_response',
value: 1_800, created_at: 2.days.ago)
create(:reporting_event, account: account, inbox: web_widget_inbox, name: 'first_response',
value: 1_800, created_at: 2.months.ago)
end
it 'returns all events without date filtering' do
expect(report['Channel::WebWidget']['0-1h']).to eq(2)
end
end
context 'with boundary values for time buckets' do
before do
# Exactly at 1 hour boundary (should be in 1-4h bucket)
create(:reporting_event, account: account, inbox: web_widget_inbox, name: 'first_response',
value: 3_600, created_at: 2.days.ago)
# Just under 1 hour (should be in 0-1h bucket)
create(:reporting_event, account: account, inbox: web_widget_inbox, name: 'first_response',
value: 3_599, created_at: 2.days.ago)
# Exactly at 24 hour boundary (should be in 24h+ bucket)
create(:reporting_event, account: account, inbox: web_widget_inbox, name: 'first_response',
value: 86_400, created_at: 2.days.ago)
end
it 'correctly assigns boundary values to buckets' do
expect(report['Channel::WebWidget']).to eq({
'0-1h' => 1,
'1-4h' => 1,
'4-8h' => 0,
'8-24h' => 0,
'24h+' => 1
})
end
end
end
end
@@ -248,51 +248,4 @@ RSpec.describe Api::V2::Accounts::ReportsController, type: :request do
end
end
end
describe 'GET /api/v2/accounts/{account.id}/reports/first_response_time_distribution' do
let!(:web_widget_inbox) { create(:inbox, account: account, channel: create(:channel_widget, account: account)) }
context 'when unauthenticated' do
it 'returns unauthorized' do
get "/api/v2/accounts/#{account.id}/reports/first_response_time_distribution"
expect(response).to have_http_status(:unauthorized)
end
end
context 'when authenticated as agent' do
it 'returns unauthorized' do
get "/api/v2/accounts/#{account.id}/reports/first_response_time_distribution",
headers: agent.create_new_auth_token, as: :json
expect(response).to have_http_status(:unauthorized)
end
end
context 'when authenticated as admin' do
before do
create(:reporting_event, account: account, inbox: web_widget_inbox, name: 'first_response',
value: 1_800, created_at: 2.days.ago)
end
it 'returns the first response time distribution' do
get "/api/v2/accounts/#{account.id}/reports/first_response_time_distribution",
params: { since: 1.week.ago.to_i.to_s, until: Time.current.to_i.to_s },
headers: admin.create_new_auth_token, as: :json
expect(response).to have_http_status(:success)
body = response.parsed_body
expect(body).to be_a(Hash)
expect(body['Channel::WebWidget']).to include('0-1h', '1-4h', '4-8h', '8-24h', '24h+')
end
it 'returns correct counts in buckets' do
get "/api/v2/accounts/#{account.id}/reports/first_response_time_distribution",
params: { since: 1.week.ago.to_i.to_s, until: Time.current.to_i.to_s },
headers: admin.create_new_auth_token, as: :json
body = response.parsed_body
expect(body['Channel::WebWidget']['0-1h']).to eq(1)
end
end
end
end
@@ -1,63 +0,0 @@
require 'rails_helper'
RSpec.describe AccountEmailRateLimitable do
let(:account) { create(:account) }
describe '#email_rate_limit' do
it 'returns account-level override when set' do
account.update!(limits: { 'emails' => 50 })
expect(account.email_rate_limit).to eq(50)
end
it 'returns global config when no account override' do
InstallationConfig.where(name: 'ACCOUNT_EMAILS_LIMIT').first_or_create(value: 200)
expect(account.email_rate_limit).to eq(200)
end
it 'returns account override over global config' do
InstallationConfig.where(name: 'ACCOUNT_EMAILS_LIMIT').first_or_create(value: 200)
account.update!(limits: { 'emails' => 50 })
expect(account.email_rate_limit).to eq(50)
end
end
describe '#within_email_rate_limit?' do
before do
account.update!(limits: { 'emails' => 2 })
end
it 'returns true when under limit' do
expect(account).to be_within_email_rate_limit
end
it 'returns false when at limit' do
2.times { account.increment_email_sent_count }
expect(account).not_to be_within_email_rate_limit
end
end
describe '#increment_email_sent_count' do
it 'increments the counter' do
expect { account.increment_email_sent_count }.to change(account, :emails_sent_today).by(1)
end
it 'sets TTL on first increment' do
key = format(Redis::Alfred::ACCOUNT_OUTBOUND_EMAIL_COUNT_KEY, account_id: account.id, date: Time.zone.today.to_s)
allow(Redis::Alfred).to receive(:incr).and_return(1)
allow(Redis::Alfred).to receive(:expire)
account.increment_email_sent_count
expect(Redis::Alfred).to have_received(:expire).with(key, AccountEmailRateLimitable::OUTBOUND_EMAIL_TTL)
end
it 'does not reset TTL on subsequent increments' do
allow(Redis::Alfred).to receive(:incr).and_return(2)
allow(Redis::Alfred).to receive(:expire)
account.increment_email_sent_count
expect(Redis::Alfred).not_to have_received(:expire)
end
end
end
@@ -493,6 +493,31 @@ RSpec.describe Messages::MarkdownRendererService, type: :service do
result = described_class.new(content, channel_type).render
expect(result).to eq("- Item 1\n- Item 2")
end
it 'converts literal \\n strings to actual newlines' do
content = 'Hi \\ntext message \\nwith line \\nbreak'
result = described_class.new(content, channel_type).render
expect(result).to eq("Hi \ntext message \nwith line \nbreak")
end
it 'handles multiple literal \\n in sequence' do
content = 'Line 1\\n\\n\\nLine 2'
result = described_class.new(content, channel_type).render
expect(result).to eq("Line 1\n\n\nLine 2")
end
it 'preserves markdown formatting while converting \\n' do
content = '**bold**\\n_italic_\\n`code`'
result = described_class.new(content, channel_type).render
expect(result).to eq("**bold**\n_italic_\n`code`")
end
it 'handles real-world API payload with literal \\n strings' do
content = 'Hi \\ntext message \\nwith line \\nbreak'
result = described_class.new(content, channel_type).render
expect(result).to eq("Hi \ntext message \nwith line \nbreak")
expect(result).not_to include('\\n')
end
end
context 'when channel is Channel::TwitterProfile' do
@@ -99,20 +99,6 @@ describe Messages::SendEmailNotificationService do
end
end
context 'when account email rate limit is exceeded' do
let(:inbox) { create(:inbox, account: account, channel: create(:channel_widget, account: account, continuity_via_email: true)) }
let(:conversation) { create(:conversation, account: account, inbox: inbox) }
before do
conversation.contact.update!(email: 'test@example.com')
allow_any_instance_of(Account).to receive(:within_email_rate_limit?).and_return(false) # rubocop:disable RSpec/AnyInstance
end
it 'does not enqueue job' do
expect { service.perform }.not_to have_enqueued_job(ConversationReplyEmailJob)
end
end
context 'when channel does not support email notifications' do
let(:inbox) { create(:inbox, account: account, channel: create(:channel_sms, account: account)) }
let(:conversation) { create(:conversation, account: account, inbox: inbox) }
@@ -161,23 +161,10 @@ describe Whatsapp::FacebookApiClient do
context 'when successful' do
before do
# Step 1: Subscribe app to WABA (no body)
stub_request(:post, "https://graph.facebook.com/#{api_version}/#{waba_id}/subscribed_apps")
.with(
headers: { 'Authorization' => "Bearer #{access_token}", 'Content-Type' => 'application/json' }
)
.to_return(
status: 200,
body: { success: true }.to_json,
headers: { 'Content-Type' => 'application/json' }
)
# Step 2: Override callback URL (with body)
stub_request(:post, "https://graph.facebook.com/#{api_version}/#{waba_id}/subscribed_apps")
.with(
headers: { 'Authorization' => "Bearer #{access_token}", 'Content-Type' => 'application/json' },
body: { override_callback_uri: callback_url, verify_token: verify_token,
subscribed_fields: %w[messages smb_message_echoes] }.to_json
body: { override_callback_uri: callback_url, verify_token: verify_token }.to_json
)
.to_return(
status: 200,
@@ -192,45 +179,18 @@ describe Whatsapp::FacebookApiClient do
end
end
context 'when app subscription fails' do
context 'when failed' do
before do
stub_request(:post, "https://graph.facebook.com/#{api_version}/#{waba_id}/subscribed_apps")
.with(
headers: { 'Authorization' => "Bearer #{access_token}", 'Content-Type' => 'application/json' }
)
.to_return(status: 400, body: { error: 'App subscription to WABA failed' }.to_json)
end
it 'raises an error' do
expect { api_client.subscribe_waba_webhook(waba_id, callback_url, verify_token) }.to raise_error(/App subscription to WABA failed/)
end
end
context 'when callback override fails' do
before do
# Step 1 succeeds
stub_request(:post, "https://graph.facebook.com/#{api_version}/#{waba_id}/subscribed_apps")
.with(
headers: { 'Authorization' => "Bearer #{access_token}", 'Content-Type' => 'application/json' }
)
.to_return(
status: 200,
body: { success: true }.to_json,
headers: { 'Content-Type' => 'application/json' }
)
# Step 2 fails
stub_request(:post, "https://graph.facebook.com/#{api_version}/#{waba_id}/subscribed_apps")
.with(
headers: { 'Authorization' => "Bearer #{access_token}", 'Content-Type' => 'application/json' },
body: { override_callback_uri: callback_url, verify_token: verify_token,
subscribed_fields: %w[messages smb_message_echoes] }.to_json
body: { override_callback_uri: callback_url, verify_token: verify_token }.to_json
)
.to_return(status: 400, body: { error: 'Webhook callback override failed' }.to_json)
.to_return(status: 400, body: { error: 'Webhook subscription failed' }.to_json)
end
it 'raises an error' do
expect { api_client.subscribe_waba_webhook(waba_id, callback_url, verify_token) }.to raise_error(/Webhook callback override failed/)
expect { api_client.subscribe_waba_webhook(waba_id, callback_url, verify_token) }.to raise_error(/Webhook subscription failed/)
end
end
end
-10
View File
@@ -225,16 +225,6 @@ agent_conversation_metrics:
$ref: './resource/reports/conversation/agent.yml'
channel_summary:
$ref: './resource/reports/channel_summary.yml'
first_response_time_distribution:
$ref: './resource/reports/first_response_time_distribution.yml'
inbox_label_matrix:
$ref: './resource/reports/inbox_label_matrix.yml'
inbox_summary:
$ref: './resource/reports/inbox_summary.yml'
agent_summary:
$ref: './resource/reports/agent_summary.yml'
team_summary:
$ref: './resource/reports/team_summary.yml'
contact_detail:
$ref: ./resource/contact_detail.yml
@@ -1,39 +0,0 @@
type: array
description: Agent summary report containing conversation statistics grouped by agent.
items:
type: object
properties:
id:
type: number
description: The agent (user) ID
conversations_count:
type: number
description: Number of conversations assigned to the agent during the date range
resolved_conversations_count:
type: number
description: Number of conversations resolved by the agent during the date range
avg_resolution_time:
type: number
nullable: true
description: Average time (in seconds) to resolve conversations. Null if no data available.
avg_first_response_time:
type: number
nullable: true
description: Average time (in seconds) for the first response. Null if no data available.
avg_reply_time:
type: number
nullable: true
description: Average time (in seconds) between replies. Null if no data available.
example:
- id: 1
conversations_count: 150
resolved_conversations_count: 120
avg_resolution_time: 3600
avg_first_response_time: 300
avg_reply_time: 600
- id: 2
conversations_count: 75
resolved_conversations_count: 60
avg_resolution_time: 1800
avg_first_response_time: 180
avg_reply_time: 420
@@ -1,34 +0,0 @@
type: object
description: First response time distribution report grouped by channel type. Shows the count of conversations with first response times in different time buckets.
additionalProperties:
type: object
description: First response time distribution for a specific channel type (e.g., Channel::WebWidget, Channel::Api)
properties:
0-1h:
type: number
description: Number of conversations with first response time less than 1 hour
1-4h:
type: number
description: Number of conversations with first response time between 1-4 hours
4-8h:
type: number
description: Number of conversations with first response time between 4-8 hours
8-24h:
type: number
description: Number of conversations with first response time between 8-24 hours
24h+:
type: number
description: Number of conversations with first response time greater than 24 hours
example:
Channel::WebWidget:
0-1h: 150
1-4h: 80
4-8h: 45
8-24h: 30
24h+: 15
Channel::Api:
0-1h: 75
1-4h: 40
4-8h: 20
8-24h: 10
24h+: 5
@@ -1,50 +0,0 @@
type: object
description: Inbox-label matrix report showing the count of conversations for each inbox-label combination.
properties:
inboxes:
type: array
description: List of inboxes included in the report
items:
type: object
properties:
id:
type: number
description: The inbox ID
name:
type: string
description: The inbox name
labels:
type: array
description: List of labels included in the report
items:
type: object
properties:
id:
type: number
description: The label ID
title:
type: string
description: The label title
matrix:
type: array
description: 2D array where matrix[i][j] represents the count of conversations in inboxes[i] with labels[j]
items:
type: array
items:
type: number
example:
inboxes:
- id: 1
name: Website Chat
- id: 2
name: Email Support
labels:
- id: 1
title: bug
- id: 2
title: feature-request
- id: 3
title: urgent
matrix:
- [10, 5, 3]
- [8, 12, 2]
@@ -1,39 +0,0 @@
type: array
description: Inbox summary report containing conversation statistics grouped by inbox.
items:
type: object
properties:
id:
type: number
description: The inbox ID
conversations_count:
type: number
description: Number of conversations created in the inbox during the date range
resolved_conversations_count:
type: number
description: Number of conversations resolved in the inbox during the date range
avg_resolution_time:
type: number
nullable: true
description: Average time (in seconds) to resolve conversations. Null if no data available.
avg_first_response_time:
type: number
nullable: true
description: Average time (in seconds) for the first response. Null if no data available.
avg_reply_time:
type: number
nullable: true
description: Average time (in seconds) between replies. Null if no data available.
example:
- id: 1
conversations_count: 150
resolved_conversations_count: 120
avg_resolution_time: 3600
avg_first_response_time: 300
avg_reply_time: 600
- id: 2
conversations_count: 75
resolved_conversations_count: 60
avg_resolution_time: 1800
avg_first_response_time: 180
avg_reply_time: 420
@@ -1,39 +0,0 @@
type: array
description: Team summary report containing conversation statistics grouped by team.
items:
type: object
properties:
id:
type: number
description: The team ID
conversations_count:
type: number
description: Number of conversations assigned to the team during the date range
resolved_conversations_count:
type: number
description: Number of conversations resolved by the team during the date range
avg_resolution_time:
type: number
nullable: true
description: Average time (in seconds) to resolve conversations. Null if no data available.
avg_first_response_time:
type: number
nullable: true
description: Average time (in seconds) for the first response. Null if no data available.
avg_reply_time:
type: number
nullable: true
description: Average time (in seconds) between replies. Null if no data available.
example:
- id: 1
conversations_count: 250
resolved_conversations_count: 200
avg_resolution_time: 2800
avg_first_response_time: 240
avg_reply_time: 500
- id: 2
conversations_count: 180
resolved_conversations_count: 150
avg_resolution_time: 2400
avg_first_response_time: 200
avg_reply_time: 450
+1 -1
View File
@@ -18,6 +18,6 @@
</head>
<body>
<redoc spec-url='/swagger/swagger.json'></redoc>
<script src="https://cdn.jsdelivr.net/npm/redoc@2.1.5/bundles/redoc.standalone.js"> </script>
<script src="https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js"> </script>
</body>
</html>
@@ -1,23 +0,0 @@
tags:
- Reports
operationId: get-agent-summary-report
summary: Get conversation statistics grouped by agent
security:
- userApiKey: []
description: |
Get conversation statistics grouped by agent for a given date range.
Returns metrics for each agent including conversation counts, resolution counts,
average first response time, average resolution time, and average reply time.
responses:
'200':
description: Success
content:
application/json:
schema:
$ref: '#/components/schemas/agent_summary'
'403':
description: Access denied
content:
application/json:
schema:
$ref: '#/components/schemas/bad_request_error'
@@ -1,24 +0,0 @@
tags:
- Reports
operationId: get-first-response-time-distribution
summary: Get first response time distribution by channel
security:
- userApiKey: []
description: |
Get the distribution of first response times grouped by channel type.
Returns conversation counts in different time buckets (0-1h, 1-4h, 4-8h, 8-24h, 24h+) for each channel type.
**Note:** This API endpoint is available only in Chatwoot version 4.11.0 and above.
responses:
'200':
description: Success
content:
application/json:
schema:
$ref: '#/components/schemas/first_response_time_distribution'
'403':
description: Access denied
content:
application/json:
schema:
$ref: '#/components/schemas/bad_request_error'
@@ -1,25 +0,0 @@
tags:
- Reports
operationId: get-inbox-label-matrix
summary: Get inbox-label matrix report
security:
- userApiKey: []
description: |
Get a matrix showing the count of conversations for each inbox-label combination.
Returns a list of inboxes, labels, and a 2D matrix where each cell contains the count of conversations
in a specific inbox that have a specific label applied.
**Note:** This API endpoint is available only in Chatwoot version 4.11.0 and above.
responses:
'200':
description: Success
content:
application/json:
schema:
$ref: '#/components/schemas/inbox_label_matrix'
'403':
description: Access denied
content:
application/json:
schema:
$ref: '#/components/schemas/bad_request_error'
@@ -1,23 +0,0 @@
tags:
- Reports
operationId: get-inbox-summary-report
summary: Get conversation statistics grouped by inbox
security:
- userApiKey: []
description: |
Get conversation statistics grouped by inbox for a given date range.
Returns metrics for each inbox including conversation counts, resolution counts,
average first response time, average resolution time, and average reply time.
responses:
'200':
description: Success
content:
application/json:
schema:
$ref: '#/components/schemas/inbox_summary'
'403':
description: Access denied
content:
application/json:
schema:
$ref: '#/components/schemas/bad_request_error'
@@ -1,23 +0,0 @@
tags:
- Reports
operationId: get-team-summary-report
summary: Get conversation statistics grouped by team
security:
- userApiKey: []
description: |
Get conversation statistics grouped by team for a given date range.
Returns metrics for each team including conversation counts, resolution counts,
average first response time, average resolution time, and average reply time.
responses:
'200':
description: Success
content:
application/json:
schema:
$ref: '#/components/schemas/team_summary'
'403':
description: Access denied
content:
application/json:
schema:
$ref: '#/components/schemas/bad_request_error'
+5 -114
View File
@@ -653,123 +653,14 @@
schema:
type: string
description: The timestamp from where report should stop (Unix timestamp).
- in: query
name: business_hours
schema:
type: boolean
description: Whether to filter by business hours.
get:
$ref: './application/reports/channel_summary.yml'
# Inbox summary report
/api/v2/accounts/{account_id}/summary_reports/inbox:
parameters:
- $ref: '#/components/parameters/account_id'
- in: query
name: since
schema:
type: string
description: The timestamp from where report should start (Unix timestamp).
- in: query
name: until
schema:
type: string
description: The timestamp from where report should stop (Unix timestamp).
- in: query
name: business_hours
schema:
type: boolean
description: Whether to calculate metrics using business hours only.
get:
$ref: './application/reports/inbox_summary.yml'
# Agent summary report
/api/v2/accounts/{account_id}/summary_reports/agent:
parameters:
- $ref: '#/components/parameters/account_id'
- in: query
name: since
schema:
type: string
description: The timestamp from where report should start (Unix timestamp).
- in: query
name: until
schema:
type: string
description: The timestamp from where report should stop (Unix timestamp).
- in: query
name: business_hours
schema:
type: boolean
description: Whether to calculate metrics using business hours only.
get:
$ref: './application/reports/agent_summary.yml'
# Team summary report
/api/v2/accounts/{account_id}/summary_reports/team:
parameters:
- $ref: '#/components/parameters/account_id'
- in: query
name: since
schema:
type: string
description: The timestamp from where report should start (Unix timestamp).
- in: query
name: until
schema:
type: string
description: The timestamp from where report should stop (Unix timestamp).
- in: query
name: business_hours
schema:
type: boolean
description: Whether to calculate metrics using business hours only.
get:
$ref: './application/reports/team_summary.yml'
# First response time distribution report
/api/v2/accounts/{account_id}/reports/first_response_time_distribution:
parameters:
- $ref: '#/components/parameters/account_id'
- in: query
name: since
schema:
type: string
description: The timestamp from where report should start (Unix timestamp).
- in: query
name: until
schema:
type: string
description: The timestamp from where report should stop (Unix timestamp).
get:
$ref: './application/reports/first_response_time_distribution.yml'
# Inbox-label matrix report
/api/v2/accounts/{account_id}/reports/inbox_label_matrix:
parameters:
- $ref: '#/components/parameters/account_id'
- in: query
name: since
schema:
type: string
description: The timestamp from where report should start (Unix timestamp).
- in: query
name: until
schema:
type: string
description: The timestamp from where report should stop (Unix timestamp).
- in: query
name: inbox_ids
schema:
type: array
items:
type: integer
description: Filter by specific inbox IDs.
- in: query
name: label_ids
schema:
type: array
items:
type: integer
description: Filter by specific label IDs.
get:
$ref: './application/reports/inbox_label_matrix.yml'
# Conversations Messages
/accounts/{account_id}/conversations/{conversation_id}/messages:
parameters:
+8 -632
View File
@@ -7890,6 +7890,14 @@
"type": "string"
},
"description": "The timestamp from where report should stop (Unix timestamp)."
},
{
"in": "query",
"name": "business_hours",
"schema": {
"type": "boolean"
},
"description": "Whether to filter by business hours."
}
],
"get": {
@@ -7938,342 +7946,6 @@
}
}
},
"/api/v2/accounts/{account_id}/summary_reports/inbox": {
"parameters": [
{
"$ref": "#/components/parameters/account_id"
},
{
"in": "query",
"name": "since",
"schema": {
"type": "string"
},
"description": "The timestamp from where report should start (Unix timestamp)."
},
{
"in": "query",
"name": "until",
"schema": {
"type": "string"
},
"description": "The timestamp from where report should stop (Unix timestamp)."
},
{
"in": "query",
"name": "business_hours",
"schema": {
"type": "boolean"
},
"description": "Whether to calculate metrics using business hours only."
}
],
"get": {
"tags": [
"Reports"
],
"operationId": "get-inbox-summary-report",
"summary": "Get conversation statistics grouped by inbox",
"security": [
{
"userApiKey": []
}
],
"description": "Get conversation statistics grouped by inbox for a given date range.\nReturns metrics for each inbox including conversation counts, resolution counts,\naverage first response time, average resolution time, and average reply time.\n",
"responses": {
"200": {
"description": "Success",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/inbox_summary"
}
}
}
},
"403": {
"description": "Access denied",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/bad_request_error"
}
}
}
}
}
}
},
"/api/v2/accounts/{account_id}/summary_reports/agent": {
"parameters": [
{
"$ref": "#/components/parameters/account_id"
},
{
"in": "query",
"name": "since",
"schema": {
"type": "string"
},
"description": "The timestamp from where report should start (Unix timestamp)."
},
{
"in": "query",
"name": "until",
"schema": {
"type": "string"
},
"description": "The timestamp from where report should stop (Unix timestamp)."
},
{
"in": "query",
"name": "business_hours",
"schema": {
"type": "boolean"
},
"description": "Whether to calculate metrics using business hours only."
}
],
"get": {
"tags": [
"Reports"
],
"operationId": "get-agent-summary-report",
"summary": "Get conversation statistics grouped by agent",
"security": [
{
"userApiKey": []
}
],
"description": "Get conversation statistics grouped by agent for a given date range.\nReturns metrics for each agent including conversation counts, resolution counts,\naverage first response time, average resolution time, and average reply time.\n",
"responses": {
"200": {
"description": "Success",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/agent_summary"
}
}
}
},
"403": {
"description": "Access denied",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/bad_request_error"
}
}
}
}
}
}
},
"/api/v2/accounts/{account_id}/summary_reports/team": {
"parameters": [
{
"$ref": "#/components/parameters/account_id"
},
{
"in": "query",
"name": "since",
"schema": {
"type": "string"
},
"description": "The timestamp from where report should start (Unix timestamp)."
},
{
"in": "query",
"name": "until",
"schema": {
"type": "string"
},
"description": "The timestamp from where report should stop (Unix timestamp)."
},
{
"in": "query",
"name": "business_hours",
"schema": {
"type": "boolean"
},
"description": "Whether to calculate metrics using business hours only."
}
],
"get": {
"tags": [
"Reports"
],
"operationId": "get-team-summary-report",
"summary": "Get conversation statistics grouped by team",
"security": [
{
"userApiKey": []
}
],
"description": "Get conversation statistics grouped by team for a given date range.\nReturns metrics for each team including conversation counts, resolution counts,\naverage first response time, average resolution time, and average reply time.\n",
"responses": {
"200": {
"description": "Success",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/team_summary"
}
}
}
},
"403": {
"description": "Access denied",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/bad_request_error"
}
}
}
}
}
}
},
"/api/v2/accounts/{account_id}/reports/first_response_time_distribution": {
"parameters": [
{
"$ref": "#/components/parameters/account_id"
},
{
"in": "query",
"name": "since",
"schema": {
"type": "string"
},
"description": "The timestamp from where report should start (Unix timestamp)."
},
{
"in": "query",
"name": "until",
"schema": {
"type": "string"
},
"description": "The timestamp from where report should stop (Unix timestamp)."
}
],
"get": {
"tags": [
"Reports"
],
"operationId": "get-first-response-time-distribution",
"summary": "Get first response time distribution by channel",
"security": [
{
"userApiKey": []
}
],
"description": "Get the distribution of first response times grouped by channel type.\nReturns conversation counts in different time buckets (0-1h, 1-4h, 4-8h, 8-24h, 24h+) for each channel type.\n\n**Note:** This API endpoint is available only in Chatwoot version 4.11.0 and above.\n",
"responses": {
"200": {
"description": "Success",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/first_response_time_distribution"
}
}
}
},
"403": {
"description": "Access denied",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/bad_request_error"
}
}
}
}
}
}
},
"/api/v2/accounts/{account_id}/reports/inbox_label_matrix": {
"parameters": [
{
"$ref": "#/components/parameters/account_id"
},
{
"in": "query",
"name": "since",
"schema": {
"type": "string"
},
"description": "The timestamp from where report should start (Unix timestamp)."
},
{
"in": "query",
"name": "until",
"schema": {
"type": "string"
},
"description": "The timestamp from where report should stop (Unix timestamp)."
},
{
"in": "query",
"name": "inbox_ids",
"schema": {
"type": "array",
"items": {
"type": "integer"
}
},
"description": "Filter by specific inbox IDs."
},
{
"in": "query",
"name": "label_ids",
"schema": {
"type": "array",
"items": {
"type": "integer"
}
},
"description": "Filter by specific label IDs."
}
],
"get": {
"tags": [
"Reports"
],
"operationId": "get-inbox-label-matrix",
"summary": "Get inbox-label matrix report",
"security": [
{
"userApiKey": []
}
],
"description": "Get a matrix showing the count of conversations for each inbox-label combination.\nReturns a list of inboxes, labels, and a 2D matrix where each cell contains the count of conversations\nin a specific inbox that have a specific label applied.\n\n**Note:** This API endpoint is available only in Chatwoot version 4.11.0 and above.\n",
"responses": {
"200": {
"description": "Success",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/inbox_label_matrix"
}
}
}
},
"403": {
"description": "Access denied",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/bad_request_error"
}
}
}
}
}
}
},
"/accounts/{account_id}/conversations/{conversation_id}/messages": {
"parameters": [
{
@@ -12109,302 +11781,6 @@
}
}
},
"first_response_time_distribution": {
"type": "object",
"description": "First response time distribution report grouped by channel type. Shows the count of conversations with first response times in different time buckets.",
"additionalProperties": {
"type": "object",
"description": "First response time distribution for a specific channel type (e.g., Channel::WebWidget, Channel::Api)",
"properties": {
"0-1h": {
"type": "number",
"description": "Number of conversations with first response time less than 1 hour"
},
"1-4h": {
"type": "number",
"description": "Number of conversations with first response time between 1-4 hours"
},
"4-8h": {
"type": "number",
"description": "Number of conversations with first response time between 4-8 hours"
},
"8-24h": {
"type": "number",
"description": "Number of conversations with first response time between 8-24 hours"
},
"24h+": {
"type": "number",
"description": "Number of conversations with first response time greater than 24 hours"
}
}
},
"example": {
"Channel::WebWidget": {
"0-1h": 150,
"1-4h": 80,
"4-8h": 45,
"8-24h": 30,
"24h+": 15
},
"Channel::Api": {
"0-1h": 75,
"1-4h": 40,
"4-8h": 20,
"8-24h": 10,
"24h+": 5
}
}
},
"inbox_label_matrix": {
"type": "object",
"description": "Inbox-label matrix report showing the count of conversations for each inbox-label combination.",
"properties": {
"inboxes": {
"type": "array",
"description": "List of inboxes included in the report",
"items": {
"type": "object",
"properties": {
"id": {
"type": "number",
"description": "The inbox ID"
},
"name": {
"type": "string",
"description": "The inbox name"
}
}
}
},
"labels": {
"type": "array",
"description": "List of labels included in the report",
"items": {
"type": "object",
"properties": {
"id": {
"type": "number",
"description": "The label ID"
},
"title": {
"type": "string",
"description": "The label title"
}
}
}
},
"matrix": {
"type": "array",
"description": "2D array where matrix[i][j] represents the count of conversations in inboxes[i] with labels[j]",
"items": {
"type": "array",
"items": {
"type": "number"
}
}
}
},
"example": {
"inboxes": [
{
"id": 1,
"name": "Website Chat"
},
{
"id": 2,
"name": "Email Support"
}
],
"labels": [
{
"id": 1,
"title": "bug"
},
{
"id": 2,
"title": "feature-request"
},
{
"id": 3,
"title": "urgent"
}
],
"matrix": [
[
10,
5,
3
],
[
8,
12,
2
]
]
}
},
"inbox_summary": {
"type": "array",
"description": "Inbox summary report containing conversation statistics grouped by inbox.",
"items": {
"type": "object",
"properties": {
"id": {
"type": "number",
"description": "The inbox ID"
},
"conversations_count": {
"type": "number",
"description": "Number of conversations created in the inbox during the date range"
},
"resolved_conversations_count": {
"type": "number",
"description": "Number of conversations resolved in the inbox during the date range"
},
"avg_resolution_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) to resolve conversations. Null if no data available."
},
"avg_first_response_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) for the first response. Null if no data available."
},
"avg_reply_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) between replies. Null if no data available."
}
}
},
"example": [
{
"id": 1,
"conversations_count": 150,
"resolved_conversations_count": 120,
"avg_resolution_time": 3600,
"avg_first_response_time": 300,
"avg_reply_time": 600
},
{
"id": 2,
"conversations_count": 75,
"resolved_conversations_count": 60,
"avg_resolution_time": 1800,
"avg_first_response_time": 180,
"avg_reply_time": 420
}
]
},
"agent_summary": {
"type": "array",
"description": "Agent summary report containing conversation statistics grouped by agent.",
"items": {
"type": "object",
"properties": {
"id": {
"type": "number",
"description": "The agent (user) ID"
},
"conversations_count": {
"type": "number",
"description": "Number of conversations assigned to the agent during the date range"
},
"resolved_conversations_count": {
"type": "number",
"description": "Number of conversations resolved by the agent during the date range"
},
"avg_resolution_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) to resolve conversations. Null if no data available."
},
"avg_first_response_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) for the first response. Null if no data available."
},
"avg_reply_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) between replies. Null if no data available."
}
}
},
"example": [
{
"id": 1,
"conversations_count": 150,
"resolved_conversations_count": 120,
"avg_resolution_time": 3600,
"avg_first_response_time": 300,
"avg_reply_time": 600
},
{
"id": 2,
"conversations_count": 75,
"resolved_conversations_count": 60,
"avg_resolution_time": 1800,
"avg_first_response_time": 180,
"avg_reply_time": 420
}
]
},
"team_summary": {
"type": "array",
"description": "Team summary report containing conversation statistics grouped by team.",
"items": {
"type": "object",
"properties": {
"id": {
"type": "number",
"description": "The team ID"
},
"conversations_count": {
"type": "number",
"description": "Number of conversations assigned to the team during the date range"
},
"resolved_conversations_count": {
"type": "number",
"description": "Number of conversations resolved by the team during the date range"
},
"avg_resolution_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) to resolve conversations. Null if no data available."
},
"avg_first_response_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) for the first response. Null if no data available."
},
"avg_reply_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) between replies. Null if no data available."
}
}
},
"example": [
{
"id": 1,
"conversations_count": 250,
"resolved_conversations_count": 200,
"avg_resolution_time": 2800,
"avg_first_response_time": 240,
"avg_reply_time": 500
},
{
"id": 2,
"conversations_count": 180,
"resolved_conversations_count": 150,
"avg_resolution_time": 2400,
"avg_first_response_time": 200,
"avg_reply_time": 450
}
]
},
"contact_detail": {
"type": "object",
"properties": {
+8 -632
View File
@@ -6433,6 +6433,14 @@
"type": "string"
},
"description": "The timestamp from where report should stop (Unix timestamp)."
},
{
"in": "query",
"name": "business_hours",
"schema": {
"type": "boolean"
},
"description": "Whether to filter by business hours."
}
],
"get": {
@@ -6480,342 +6488,6 @@
}
}
}
},
"/api/v2/accounts/{account_id}/summary_reports/inbox": {
"parameters": [
{
"$ref": "#/components/parameters/account_id"
},
{
"in": "query",
"name": "since",
"schema": {
"type": "string"
},
"description": "The timestamp from where report should start (Unix timestamp)."
},
{
"in": "query",
"name": "until",
"schema": {
"type": "string"
},
"description": "The timestamp from where report should stop (Unix timestamp)."
},
{
"in": "query",
"name": "business_hours",
"schema": {
"type": "boolean"
},
"description": "Whether to calculate metrics using business hours only."
}
],
"get": {
"tags": [
"Reports"
],
"operationId": "get-inbox-summary-report",
"summary": "Get conversation statistics grouped by inbox",
"security": [
{
"userApiKey": []
}
],
"description": "Get conversation statistics grouped by inbox for a given date range.\nReturns metrics for each inbox including conversation counts, resolution counts,\naverage first response time, average resolution time, and average reply time.\n",
"responses": {
"200": {
"description": "Success",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/inbox_summary"
}
}
}
},
"403": {
"description": "Access denied",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/bad_request_error"
}
}
}
}
}
}
},
"/api/v2/accounts/{account_id}/summary_reports/agent": {
"parameters": [
{
"$ref": "#/components/parameters/account_id"
},
{
"in": "query",
"name": "since",
"schema": {
"type": "string"
},
"description": "The timestamp from where report should start (Unix timestamp)."
},
{
"in": "query",
"name": "until",
"schema": {
"type": "string"
},
"description": "The timestamp from where report should stop (Unix timestamp)."
},
{
"in": "query",
"name": "business_hours",
"schema": {
"type": "boolean"
},
"description": "Whether to calculate metrics using business hours only."
}
],
"get": {
"tags": [
"Reports"
],
"operationId": "get-agent-summary-report",
"summary": "Get conversation statistics grouped by agent",
"security": [
{
"userApiKey": []
}
],
"description": "Get conversation statistics grouped by agent for a given date range.\nReturns metrics for each agent including conversation counts, resolution counts,\naverage first response time, average resolution time, and average reply time.\n",
"responses": {
"200": {
"description": "Success",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/agent_summary"
}
}
}
},
"403": {
"description": "Access denied",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/bad_request_error"
}
}
}
}
}
}
},
"/api/v2/accounts/{account_id}/summary_reports/team": {
"parameters": [
{
"$ref": "#/components/parameters/account_id"
},
{
"in": "query",
"name": "since",
"schema": {
"type": "string"
},
"description": "The timestamp from where report should start (Unix timestamp)."
},
{
"in": "query",
"name": "until",
"schema": {
"type": "string"
},
"description": "The timestamp from where report should stop (Unix timestamp)."
},
{
"in": "query",
"name": "business_hours",
"schema": {
"type": "boolean"
},
"description": "Whether to calculate metrics using business hours only."
}
],
"get": {
"tags": [
"Reports"
],
"operationId": "get-team-summary-report",
"summary": "Get conversation statistics grouped by team",
"security": [
{
"userApiKey": []
}
],
"description": "Get conversation statistics grouped by team for a given date range.\nReturns metrics for each team including conversation counts, resolution counts,\naverage first response time, average resolution time, and average reply time.\n",
"responses": {
"200": {
"description": "Success",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/team_summary"
}
}
}
},
"403": {
"description": "Access denied",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/bad_request_error"
}
}
}
}
}
}
},
"/api/v2/accounts/{account_id}/reports/first_response_time_distribution": {
"parameters": [
{
"$ref": "#/components/parameters/account_id"
},
{
"in": "query",
"name": "since",
"schema": {
"type": "string"
},
"description": "The timestamp from where report should start (Unix timestamp)."
},
{
"in": "query",
"name": "until",
"schema": {
"type": "string"
},
"description": "The timestamp from where report should stop (Unix timestamp)."
}
],
"get": {
"tags": [
"Reports"
],
"operationId": "get-first-response-time-distribution",
"summary": "Get first response time distribution by channel",
"security": [
{
"userApiKey": []
}
],
"description": "Get the distribution of first response times grouped by channel type.\nReturns conversation counts in different time buckets (0-1h, 1-4h, 4-8h, 8-24h, 24h+) for each channel type.\n\n**Note:** This API endpoint is available only in Chatwoot version 4.11.0 and above.\n",
"responses": {
"200": {
"description": "Success",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/first_response_time_distribution"
}
}
}
},
"403": {
"description": "Access denied",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/bad_request_error"
}
}
}
}
}
}
},
"/api/v2/accounts/{account_id}/reports/inbox_label_matrix": {
"parameters": [
{
"$ref": "#/components/parameters/account_id"
},
{
"in": "query",
"name": "since",
"schema": {
"type": "string"
},
"description": "The timestamp from where report should start (Unix timestamp)."
},
{
"in": "query",
"name": "until",
"schema": {
"type": "string"
},
"description": "The timestamp from where report should stop (Unix timestamp)."
},
{
"in": "query",
"name": "inbox_ids",
"schema": {
"type": "array",
"items": {
"type": "integer"
}
},
"description": "Filter by specific inbox IDs."
},
{
"in": "query",
"name": "label_ids",
"schema": {
"type": "array",
"items": {
"type": "integer"
}
},
"description": "Filter by specific label IDs."
}
],
"get": {
"tags": [
"Reports"
],
"operationId": "get-inbox-label-matrix",
"summary": "Get inbox-label matrix report",
"security": [
{
"userApiKey": []
}
],
"description": "Get a matrix showing the count of conversations for each inbox-label combination.\nReturns a list of inboxes, labels, and a 2D matrix where each cell contains the count of conversations\nin a specific inbox that have a specific label applied.\n\n**Note:** This API endpoint is available only in Chatwoot version 4.11.0 and above.\n",
"responses": {
"200": {
"description": "Success",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/inbox_label_matrix"
}
}
}
},
"403": {
"description": "Access denied",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/bad_request_error"
}
}
}
}
}
}
}
},
"components": {
@@ -10616,302 +10288,6 @@
}
}
},
"first_response_time_distribution": {
"type": "object",
"description": "First response time distribution report grouped by channel type. Shows the count of conversations with first response times in different time buckets.",
"additionalProperties": {
"type": "object",
"description": "First response time distribution for a specific channel type (e.g., Channel::WebWidget, Channel::Api)",
"properties": {
"0-1h": {
"type": "number",
"description": "Number of conversations with first response time less than 1 hour"
},
"1-4h": {
"type": "number",
"description": "Number of conversations with first response time between 1-4 hours"
},
"4-8h": {
"type": "number",
"description": "Number of conversations with first response time between 4-8 hours"
},
"8-24h": {
"type": "number",
"description": "Number of conversations with first response time between 8-24 hours"
},
"24h+": {
"type": "number",
"description": "Number of conversations with first response time greater than 24 hours"
}
}
},
"example": {
"Channel::WebWidget": {
"0-1h": 150,
"1-4h": 80,
"4-8h": 45,
"8-24h": 30,
"24h+": 15
},
"Channel::Api": {
"0-1h": 75,
"1-4h": 40,
"4-8h": 20,
"8-24h": 10,
"24h+": 5
}
}
},
"inbox_label_matrix": {
"type": "object",
"description": "Inbox-label matrix report showing the count of conversations for each inbox-label combination.",
"properties": {
"inboxes": {
"type": "array",
"description": "List of inboxes included in the report",
"items": {
"type": "object",
"properties": {
"id": {
"type": "number",
"description": "The inbox ID"
},
"name": {
"type": "string",
"description": "The inbox name"
}
}
}
},
"labels": {
"type": "array",
"description": "List of labels included in the report",
"items": {
"type": "object",
"properties": {
"id": {
"type": "number",
"description": "The label ID"
},
"title": {
"type": "string",
"description": "The label title"
}
}
}
},
"matrix": {
"type": "array",
"description": "2D array where matrix[i][j] represents the count of conversations in inboxes[i] with labels[j]",
"items": {
"type": "array",
"items": {
"type": "number"
}
}
}
},
"example": {
"inboxes": [
{
"id": 1,
"name": "Website Chat"
},
{
"id": 2,
"name": "Email Support"
}
],
"labels": [
{
"id": 1,
"title": "bug"
},
{
"id": 2,
"title": "feature-request"
},
{
"id": 3,
"title": "urgent"
}
],
"matrix": [
[
10,
5,
3
],
[
8,
12,
2
]
]
}
},
"inbox_summary": {
"type": "array",
"description": "Inbox summary report containing conversation statistics grouped by inbox.",
"items": {
"type": "object",
"properties": {
"id": {
"type": "number",
"description": "The inbox ID"
},
"conversations_count": {
"type": "number",
"description": "Number of conversations created in the inbox during the date range"
},
"resolved_conversations_count": {
"type": "number",
"description": "Number of conversations resolved in the inbox during the date range"
},
"avg_resolution_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) to resolve conversations. Null if no data available."
},
"avg_first_response_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) for the first response. Null if no data available."
},
"avg_reply_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) between replies. Null if no data available."
}
}
},
"example": [
{
"id": 1,
"conversations_count": 150,
"resolved_conversations_count": 120,
"avg_resolution_time": 3600,
"avg_first_response_time": 300,
"avg_reply_time": 600
},
{
"id": 2,
"conversations_count": 75,
"resolved_conversations_count": 60,
"avg_resolution_time": 1800,
"avg_first_response_time": 180,
"avg_reply_time": 420
}
]
},
"agent_summary": {
"type": "array",
"description": "Agent summary report containing conversation statistics grouped by agent.",
"items": {
"type": "object",
"properties": {
"id": {
"type": "number",
"description": "The agent (user) ID"
},
"conversations_count": {
"type": "number",
"description": "Number of conversations assigned to the agent during the date range"
},
"resolved_conversations_count": {
"type": "number",
"description": "Number of conversations resolved by the agent during the date range"
},
"avg_resolution_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) to resolve conversations. Null if no data available."
},
"avg_first_response_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) for the first response. Null if no data available."
},
"avg_reply_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) between replies. Null if no data available."
}
}
},
"example": [
{
"id": 1,
"conversations_count": 150,
"resolved_conversations_count": 120,
"avg_resolution_time": 3600,
"avg_first_response_time": 300,
"avg_reply_time": 600
},
{
"id": 2,
"conversations_count": 75,
"resolved_conversations_count": 60,
"avg_resolution_time": 1800,
"avg_first_response_time": 180,
"avg_reply_time": 420
}
]
},
"team_summary": {
"type": "array",
"description": "Team summary report containing conversation statistics grouped by team.",
"items": {
"type": "object",
"properties": {
"id": {
"type": "number",
"description": "The team ID"
},
"conversations_count": {
"type": "number",
"description": "Number of conversations assigned to the team during the date range"
},
"resolved_conversations_count": {
"type": "number",
"description": "Number of conversations resolved by the team during the date range"
},
"avg_resolution_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) to resolve conversations. Null if no data available."
},
"avg_first_response_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) for the first response. Null if no data available."
},
"avg_reply_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) between replies. Null if no data available."
}
}
},
"example": [
{
"id": 1,
"conversations_count": 250,
"resolved_conversations_count": 200,
"avg_resolution_time": 2800,
"avg_first_response_time": 240,
"avg_reply_time": 500
},
{
"id": 2,
"conversations_count": 180,
"resolved_conversations_count": 150,
"avg_resolution_time": 2400,
"avg_first_response_time": 200,
"avg_reply_time": 450
}
]
},
"contact_detail": {
"type": "object",
"properties": {
-296
View File
@@ -4424,302 +4424,6 @@
}
}
},
"first_response_time_distribution": {
"type": "object",
"description": "First response time distribution report grouped by channel type. Shows the count of conversations with first response times in different time buckets.",
"additionalProperties": {
"type": "object",
"description": "First response time distribution for a specific channel type (e.g., Channel::WebWidget, Channel::Api)",
"properties": {
"0-1h": {
"type": "number",
"description": "Number of conversations with first response time less than 1 hour"
},
"1-4h": {
"type": "number",
"description": "Number of conversations with first response time between 1-4 hours"
},
"4-8h": {
"type": "number",
"description": "Number of conversations with first response time between 4-8 hours"
},
"8-24h": {
"type": "number",
"description": "Number of conversations with first response time between 8-24 hours"
},
"24h+": {
"type": "number",
"description": "Number of conversations with first response time greater than 24 hours"
}
}
},
"example": {
"Channel::WebWidget": {
"0-1h": 150,
"1-4h": 80,
"4-8h": 45,
"8-24h": 30,
"24h+": 15
},
"Channel::Api": {
"0-1h": 75,
"1-4h": 40,
"4-8h": 20,
"8-24h": 10,
"24h+": 5
}
}
},
"inbox_label_matrix": {
"type": "object",
"description": "Inbox-label matrix report showing the count of conversations for each inbox-label combination.",
"properties": {
"inboxes": {
"type": "array",
"description": "List of inboxes included in the report",
"items": {
"type": "object",
"properties": {
"id": {
"type": "number",
"description": "The inbox ID"
},
"name": {
"type": "string",
"description": "The inbox name"
}
}
}
},
"labels": {
"type": "array",
"description": "List of labels included in the report",
"items": {
"type": "object",
"properties": {
"id": {
"type": "number",
"description": "The label ID"
},
"title": {
"type": "string",
"description": "The label title"
}
}
}
},
"matrix": {
"type": "array",
"description": "2D array where matrix[i][j] represents the count of conversations in inboxes[i] with labels[j]",
"items": {
"type": "array",
"items": {
"type": "number"
}
}
}
},
"example": {
"inboxes": [
{
"id": 1,
"name": "Website Chat"
},
{
"id": 2,
"name": "Email Support"
}
],
"labels": [
{
"id": 1,
"title": "bug"
},
{
"id": 2,
"title": "feature-request"
},
{
"id": 3,
"title": "urgent"
}
],
"matrix": [
[
10,
5,
3
],
[
8,
12,
2
]
]
}
},
"inbox_summary": {
"type": "array",
"description": "Inbox summary report containing conversation statistics grouped by inbox.",
"items": {
"type": "object",
"properties": {
"id": {
"type": "number",
"description": "The inbox ID"
},
"conversations_count": {
"type": "number",
"description": "Number of conversations created in the inbox during the date range"
},
"resolved_conversations_count": {
"type": "number",
"description": "Number of conversations resolved in the inbox during the date range"
},
"avg_resolution_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) to resolve conversations. Null if no data available."
},
"avg_first_response_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) for the first response. Null if no data available."
},
"avg_reply_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) between replies. Null if no data available."
}
}
},
"example": [
{
"id": 1,
"conversations_count": 150,
"resolved_conversations_count": 120,
"avg_resolution_time": 3600,
"avg_first_response_time": 300,
"avg_reply_time": 600
},
{
"id": 2,
"conversations_count": 75,
"resolved_conversations_count": 60,
"avg_resolution_time": 1800,
"avg_first_response_time": 180,
"avg_reply_time": 420
}
]
},
"agent_summary": {
"type": "array",
"description": "Agent summary report containing conversation statistics grouped by agent.",
"items": {
"type": "object",
"properties": {
"id": {
"type": "number",
"description": "The agent (user) ID"
},
"conversations_count": {
"type": "number",
"description": "Number of conversations assigned to the agent during the date range"
},
"resolved_conversations_count": {
"type": "number",
"description": "Number of conversations resolved by the agent during the date range"
},
"avg_resolution_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) to resolve conversations. Null if no data available."
},
"avg_first_response_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) for the first response. Null if no data available."
},
"avg_reply_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) between replies. Null if no data available."
}
}
},
"example": [
{
"id": 1,
"conversations_count": 150,
"resolved_conversations_count": 120,
"avg_resolution_time": 3600,
"avg_first_response_time": 300,
"avg_reply_time": 600
},
{
"id": 2,
"conversations_count": 75,
"resolved_conversations_count": 60,
"avg_resolution_time": 1800,
"avg_first_response_time": 180,
"avg_reply_time": 420
}
]
},
"team_summary": {
"type": "array",
"description": "Team summary report containing conversation statistics grouped by team.",
"items": {
"type": "object",
"properties": {
"id": {
"type": "number",
"description": "The team ID"
},
"conversations_count": {
"type": "number",
"description": "Number of conversations assigned to the team during the date range"
},
"resolved_conversations_count": {
"type": "number",
"description": "Number of conversations resolved by the team during the date range"
},
"avg_resolution_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) to resolve conversations. Null if no data available."
},
"avg_first_response_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) for the first response. Null if no data available."
},
"avg_reply_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) between replies. Null if no data available."
}
}
},
"example": [
{
"id": 1,
"conversations_count": 250,
"resolved_conversations_count": 200,
"avg_resolution_time": 2800,
"avg_first_response_time": 240,
"avg_reply_time": 500
},
{
"id": 2,
"conversations_count": 180,
"resolved_conversations_count": 150,
"avg_resolution_time": 2400,
"avg_first_response_time": 200,
"avg_reply_time": 450
}
]
},
"contact_detail": {
"type": "object",
"properties": {
-296
View File
@@ -3839,302 +3839,6 @@
}
}
},
"first_response_time_distribution": {
"type": "object",
"description": "First response time distribution report grouped by channel type. Shows the count of conversations with first response times in different time buckets.",
"additionalProperties": {
"type": "object",
"description": "First response time distribution for a specific channel type (e.g., Channel::WebWidget, Channel::Api)",
"properties": {
"0-1h": {
"type": "number",
"description": "Number of conversations with first response time less than 1 hour"
},
"1-4h": {
"type": "number",
"description": "Number of conversations with first response time between 1-4 hours"
},
"4-8h": {
"type": "number",
"description": "Number of conversations with first response time between 4-8 hours"
},
"8-24h": {
"type": "number",
"description": "Number of conversations with first response time between 8-24 hours"
},
"24h+": {
"type": "number",
"description": "Number of conversations with first response time greater than 24 hours"
}
}
},
"example": {
"Channel::WebWidget": {
"0-1h": 150,
"1-4h": 80,
"4-8h": 45,
"8-24h": 30,
"24h+": 15
},
"Channel::Api": {
"0-1h": 75,
"1-4h": 40,
"4-8h": 20,
"8-24h": 10,
"24h+": 5
}
}
},
"inbox_label_matrix": {
"type": "object",
"description": "Inbox-label matrix report showing the count of conversations for each inbox-label combination.",
"properties": {
"inboxes": {
"type": "array",
"description": "List of inboxes included in the report",
"items": {
"type": "object",
"properties": {
"id": {
"type": "number",
"description": "The inbox ID"
},
"name": {
"type": "string",
"description": "The inbox name"
}
}
}
},
"labels": {
"type": "array",
"description": "List of labels included in the report",
"items": {
"type": "object",
"properties": {
"id": {
"type": "number",
"description": "The label ID"
},
"title": {
"type": "string",
"description": "The label title"
}
}
}
},
"matrix": {
"type": "array",
"description": "2D array where matrix[i][j] represents the count of conversations in inboxes[i] with labels[j]",
"items": {
"type": "array",
"items": {
"type": "number"
}
}
}
},
"example": {
"inboxes": [
{
"id": 1,
"name": "Website Chat"
},
{
"id": 2,
"name": "Email Support"
}
],
"labels": [
{
"id": 1,
"title": "bug"
},
{
"id": 2,
"title": "feature-request"
},
{
"id": 3,
"title": "urgent"
}
],
"matrix": [
[
10,
5,
3
],
[
8,
12,
2
]
]
}
},
"inbox_summary": {
"type": "array",
"description": "Inbox summary report containing conversation statistics grouped by inbox.",
"items": {
"type": "object",
"properties": {
"id": {
"type": "number",
"description": "The inbox ID"
},
"conversations_count": {
"type": "number",
"description": "Number of conversations created in the inbox during the date range"
},
"resolved_conversations_count": {
"type": "number",
"description": "Number of conversations resolved in the inbox during the date range"
},
"avg_resolution_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) to resolve conversations. Null if no data available."
},
"avg_first_response_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) for the first response. Null if no data available."
},
"avg_reply_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) between replies. Null if no data available."
}
}
},
"example": [
{
"id": 1,
"conversations_count": 150,
"resolved_conversations_count": 120,
"avg_resolution_time": 3600,
"avg_first_response_time": 300,
"avg_reply_time": 600
},
{
"id": 2,
"conversations_count": 75,
"resolved_conversations_count": 60,
"avg_resolution_time": 1800,
"avg_first_response_time": 180,
"avg_reply_time": 420
}
]
},
"agent_summary": {
"type": "array",
"description": "Agent summary report containing conversation statistics grouped by agent.",
"items": {
"type": "object",
"properties": {
"id": {
"type": "number",
"description": "The agent (user) ID"
},
"conversations_count": {
"type": "number",
"description": "Number of conversations assigned to the agent during the date range"
},
"resolved_conversations_count": {
"type": "number",
"description": "Number of conversations resolved by the agent during the date range"
},
"avg_resolution_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) to resolve conversations. Null if no data available."
},
"avg_first_response_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) for the first response. Null if no data available."
},
"avg_reply_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) between replies. Null if no data available."
}
}
},
"example": [
{
"id": 1,
"conversations_count": 150,
"resolved_conversations_count": 120,
"avg_resolution_time": 3600,
"avg_first_response_time": 300,
"avg_reply_time": 600
},
{
"id": 2,
"conversations_count": 75,
"resolved_conversations_count": 60,
"avg_resolution_time": 1800,
"avg_first_response_time": 180,
"avg_reply_time": 420
}
]
},
"team_summary": {
"type": "array",
"description": "Team summary report containing conversation statistics grouped by team.",
"items": {
"type": "object",
"properties": {
"id": {
"type": "number",
"description": "The team ID"
},
"conversations_count": {
"type": "number",
"description": "Number of conversations assigned to the team during the date range"
},
"resolved_conversations_count": {
"type": "number",
"description": "Number of conversations resolved by the team during the date range"
},
"avg_resolution_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) to resolve conversations. Null if no data available."
},
"avg_first_response_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) for the first response. Null if no data available."
},
"avg_reply_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) between replies. Null if no data available."
}
}
},
"example": [
{
"id": 1,
"conversations_count": 250,
"resolved_conversations_count": 200,
"avg_resolution_time": 2800,
"avg_first_response_time": 240,
"avg_reply_time": 500
},
{
"id": 2,
"conversations_count": 180,
"resolved_conversations_count": 150,
"avg_resolution_time": 2400,
"avg_first_response_time": 200,
"avg_reply_time": 450
}
]
},
"contact_detail": {
"type": "object",
"properties": {
-296
View File
@@ -4600,302 +4600,6 @@
}
}
},
"first_response_time_distribution": {
"type": "object",
"description": "First response time distribution report grouped by channel type. Shows the count of conversations with first response times in different time buckets.",
"additionalProperties": {
"type": "object",
"description": "First response time distribution for a specific channel type (e.g., Channel::WebWidget, Channel::Api)",
"properties": {
"0-1h": {
"type": "number",
"description": "Number of conversations with first response time less than 1 hour"
},
"1-4h": {
"type": "number",
"description": "Number of conversations with first response time between 1-4 hours"
},
"4-8h": {
"type": "number",
"description": "Number of conversations with first response time between 4-8 hours"
},
"8-24h": {
"type": "number",
"description": "Number of conversations with first response time between 8-24 hours"
},
"24h+": {
"type": "number",
"description": "Number of conversations with first response time greater than 24 hours"
}
}
},
"example": {
"Channel::WebWidget": {
"0-1h": 150,
"1-4h": 80,
"4-8h": 45,
"8-24h": 30,
"24h+": 15
},
"Channel::Api": {
"0-1h": 75,
"1-4h": 40,
"4-8h": 20,
"8-24h": 10,
"24h+": 5
}
}
},
"inbox_label_matrix": {
"type": "object",
"description": "Inbox-label matrix report showing the count of conversations for each inbox-label combination.",
"properties": {
"inboxes": {
"type": "array",
"description": "List of inboxes included in the report",
"items": {
"type": "object",
"properties": {
"id": {
"type": "number",
"description": "The inbox ID"
},
"name": {
"type": "string",
"description": "The inbox name"
}
}
}
},
"labels": {
"type": "array",
"description": "List of labels included in the report",
"items": {
"type": "object",
"properties": {
"id": {
"type": "number",
"description": "The label ID"
},
"title": {
"type": "string",
"description": "The label title"
}
}
}
},
"matrix": {
"type": "array",
"description": "2D array where matrix[i][j] represents the count of conversations in inboxes[i] with labels[j]",
"items": {
"type": "array",
"items": {
"type": "number"
}
}
}
},
"example": {
"inboxes": [
{
"id": 1,
"name": "Website Chat"
},
{
"id": 2,
"name": "Email Support"
}
],
"labels": [
{
"id": 1,
"title": "bug"
},
{
"id": 2,
"title": "feature-request"
},
{
"id": 3,
"title": "urgent"
}
],
"matrix": [
[
10,
5,
3
],
[
8,
12,
2
]
]
}
},
"inbox_summary": {
"type": "array",
"description": "Inbox summary report containing conversation statistics grouped by inbox.",
"items": {
"type": "object",
"properties": {
"id": {
"type": "number",
"description": "The inbox ID"
},
"conversations_count": {
"type": "number",
"description": "Number of conversations created in the inbox during the date range"
},
"resolved_conversations_count": {
"type": "number",
"description": "Number of conversations resolved in the inbox during the date range"
},
"avg_resolution_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) to resolve conversations. Null if no data available."
},
"avg_first_response_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) for the first response. Null if no data available."
},
"avg_reply_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) between replies. Null if no data available."
}
}
},
"example": [
{
"id": 1,
"conversations_count": 150,
"resolved_conversations_count": 120,
"avg_resolution_time": 3600,
"avg_first_response_time": 300,
"avg_reply_time": 600
},
{
"id": 2,
"conversations_count": 75,
"resolved_conversations_count": 60,
"avg_resolution_time": 1800,
"avg_first_response_time": 180,
"avg_reply_time": 420
}
]
},
"agent_summary": {
"type": "array",
"description": "Agent summary report containing conversation statistics grouped by agent.",
"items": {
"type": "object",
"properties": {
"id": {
"type": "number",
"description": "The agent (user) ID"
},
"conversations_count": {
"type": "number",
"description": "Number of conversations assigned to the agent during the date range"
},
"resolved_conversations_count": {
"type": "number",
"description": "Number of conversations resolved by the agent during the date range"
},
"avg_resolution_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) to resolve conversations. Null if no data available."
},
"avg_first_response_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) for the first response. Null if no data available."
},
"avg_reply_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) between replies. Null if no data available."
}
}
},
"example": [
{
"id": 1,
"conversations_count": 150,
"resolved_conversations_count": 120,
"avg_resolution_time": 3600,
"avg_first_response_time": 300,
"avg_reply_time": 600
},
{
"id": 2,
"conversations_count": 75,
"resolved_conversations_count": 60,
"avg_resolution_time": 1800,
"avg_first_response_time": 180,
"avg_reply_time": 420
}
]
},
"team_summary": {
"type": "array",
"description": "Team summary report containing conversation statistics grouped by team.",
"items": {
"type": "object",
"properties": {
"id": {
"type": "number",
"description": "The team ID"
},
"conversations_count": {
"type": "number",
"description": "Number of conversations assigned to the team during the date range"
},
"resolved_conversations_count": {
"type": "number",
"description": "Number of conversations resolved by the team during the date range"
},
"avg_resolution_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) to resolve conversations. Null if no data available."
},
"avg_first_response_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) for the first response. Null if no data available."
},
"avg_reply_time": {
"type": "number",
"nullable": true,
"description": "Average time (in seconds) between replies. Null if no data available."
}
}
},
"example": [
{
"id": 1,
"conversations_count": 250,
"resolved_conversations_count": 200,
"avg_resolution_time": 2800,
"avg_first_response_time": 240,
"avg_reply_time": 500
},
{
"id": 2,
"conversations_count": 180,
"resolved_conversations_count": 150,
"avg_resolution_time": 2400,
"avg_first_response_time": 200,
"avg_reply_time": 450
}
]
},
"contact_detail": {
"type": "object",
"properties": {