Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c80ab26ad9 | ||
|
|
e523db12f4 | ||
|
|
6b42ff8d39 | ||
|
|
a88fef2e1d | ||
|
|
ee9f1d7adb | ||
|
|
b711bfd2ca | ||
|
|
42af4b1d01 | ||
|
|
9a7318a9db | ||
|
|
48fa7bf72b | ||
|
|
469e724e3a | ||
|
|
0c101b1f6b | ||
|
|
ad4ec9e93b | ||
|
|
5c560c7628 | ||
|
|
8bacbd2b23 | ||
|
|
8aa37907c0 | ||
|
|
dbb164a37d | ||
|
|
fdcfed2cd7 |
@@ -1,79 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
class Api::V1::Accounts::AssignmentPoliciesController < Api::V1::Accounts::BaseController
|
||||
before_action :fetch_assignment_policy, only: [:show, :update, :destroy]
|
||||
before_action :check_authorization
|
||||
|
||||
def index
|
||||
@assignment_policies = Current.account.assignment_policies.includes(:inboxes)
|
||||
render json: { assignment_policies: serialize_assignment_policies(@assignment_policies) }
|
||||
end
|
||||
|
||||
def show
|
||||
render json: { assignment_policy: serialize_assignment_policy(@assignment_policy) }
|
||||
end
|
||||
|
||||
def create
|
||||
@assignment_policy = Current.account.assignment_policies.build(assignment_policy_params)
|
||||
|
||||
if @assignment_policy.save
|
||||
render json: { assignment_policy: serialize_assignment_policy(@assignment_policy) }, status: :created
|
||||
else
|
||||
render json: { errors: @assignment_policy.errors.full_messages }, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
def update
|
||||
if @assignment_policy.update(assignment_policy_params)
|
||||
render json: { assignment_policy: serialize_assignment_policy(@assignment_policy) }
|
||||
else
|
||||
render json: { errors: @assignment_policy.errors.full_messages }, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
def destroy
|
||||
if @assignment_policy.destroy
|
||||
head :ok
|
||||
else
|
||||
render json: { errors: @assignment_policy.errors.full_messages }, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def fetch_assignment_policy
|
||||
@assignment_policy = Current.account.assignment_policies.find(params[:id])
|
||||
end
|
||||
|
||||
def assignment_policy_params
|
||||
params.require(:assignment_policy).permit(
|
||||
:name, :description, :assignment_order, :conversation_priority,
|
||||
:fair_distribution_limit, :fair_distribution_window, :enabled
|
||||
)
|
||||
end
|
||||
|
||||
def serialize_assignment_policy(policy)
|
||||
{
|
||||
id: policy.id,
|
||||
name: policy.name,
|
||||
description: policy.description,
|
||||
assignment_order: policy.assignment_order,
|
||||
conversation_priority: policy.conversation_priority,
|
||||
fair_distribution_limit: policy.fair_distribution_limit,
|
||||
fair_distribution_window: policy.fair_distribution_window,
|
||||
enabled: policy.enabled,
|
||||
inbox_count: policy.inboxes.count,
|
||||
inboxes: policy.inboxes.map { |inbox| { id: inbox.id, name: inbox.name } },
|
||||
created_at: policy.created_at,
|
||||
updated_at: policy.updated_at
|
||||
}
|
||||
end
|
||||
|
||||
def serialize_assignment_policies(policies)
|
||||
policies.map { |policy| serialize_assignment_policy(policy) }
|
||||
end
|
||||
|
||||
def check_authorization
|
||||
authorize(AssignmentPolicy)
|
||||
end
|
||||
end
|
||||
@@ -1,81 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
class Api::V1::Accounts::InboxAssignmentPoliciesController < Api::V1::Accounts::BaseController
|
||||
before_action :fetch_inbox
|
||||
before_action :check_authorization
|
||||
|
||||
def show
|
||||
@inbox_assignment_policy = @inbox.inbox_assignment_policy
|
||||
|
||||
if @inbox_assignment_policy
|
||||
render json: {
|
||||
inbox_assignment_policy: serialize_inbox_assignment_policy(@inbox_assignment_policy)
|
||||
}
|
||||
else
|
||||
render json: {
|
||||
inbox_assignment_policy: nil,
|
||||
message: 'No assignment policy assigned to this inbox'
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
def create
|
||||
# Remove existing assignment if any
|
||||
@inbox.inbox_assignment_policy&.destroy
|
||||
|
||||
@assignment_policy = Current.account.assignment_policies.find(params[:assignment_policy_id])
|
||||
@inbox_assignment_policy = @inbox.build_inbox_assignment_policy(assignment_policy: @assignment_policy)
|
||||
|
||||
if @inbox_assignment_policy.save
|
||||
render json: {
|
||||
inbox_assignment_policy: serialize_inbox_assignment_policy(@inbox_assignment_policy)
|
||||
}, status: :created
|
||||
else
|
||||
render json: { errors: @inbox_assignment_policy.errors.full_messages }, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
def destroy
|
||||
@inbox_assignment_policy = @inbox.inbox_assignment_policy
|
||||
|
||||
if @inbox_assignment_policy
|
||||
if @inbox_assignment_policy.destroy
|
||||
head :ok
|
||||
else
|
||||
render json: { errors: @inbox_assignment_policy.errors.full_messages }, status: :unprocessable_entity
|
||||
end
|
||||
else
|
||||
render json: { error: 'No assignment policy found for this inbox' }, status: :not_found
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def fetch_inbox
|
||||
@inbox = Current.account.inboxes.find(params[:inbox_id])
|
||||
end
|
||||
|
||||
def check_authorization
|
||||
authorize(@inbox, :update?)
|
||||
end
|
||||
|
||||
def serialize_inbox_assignment_policy(inbox_assignment_policy)
|
||||
{
|
||||
id: inbox_assignment_policy.id,
|
||||
inbox_id: inbox_assignment_policy.inbox_id,
|
||||
assignment_policy_id: inbox_assignment_policy.assignment_policy_id,
|
||||
assignment_policy: {
|
||||
id: inbox_assignment_policy.assignment_policy.id,
|
||||
name: inbox_assignment_policy.assignment_policy.name,
|
||||
description: inbox_assignment_policy.assignment_policy.description,
|
||||
assignment_order: inbox_assignment_policy.assignment_policy.assignment_order,
|
||||
conversation_priority: inbox_assignment_policy.assignment_policy.conversation_priority,
|
||||
fair_distribution_limit: inbox_assignment_policy.assignment_policy.fair_distribution_limit,
|
||||
fair_distribution_window: inbox_assignment_policy.assignment_policy.fair_distribution_window,
|
||||
enabled: inbox_assignment_policy.assignment_policy.enabled
|
||||
},
|
||||
created_at: inbox_assignment_policy.created_at,
|
||||
updated_at: inbox_assignment_policy.updated_at
|
||||
}
|
||||
end
|
||||
end
|
||||
@@ -18,12 +18,25 @@ module ReportingEventHelper
|
||||
end
|
||||
|
||||
def last_non_human_activity(conversation)
|
||||
# check if a handoff event already exists
|
||||
handoff_event = ReportingEvent.where(conversation_id: conversation.id, name: 'conversation_bot_handoff').last
|
||||
# Try to get either a handoff or reopened event first
|
||||
# These will always take precedence over any other activity
|
||||
# Also, any of these events can happen at any time in the course of a conversation lifecycle.
|
||||
# So we pick the latest event
|
||||
event = ReportingEvent.where(
|
||||
conversation_id: conversation.id,
|
||||
name: %w[conversation_bot_handoff conversation_opened]
|
||||
).order(event_end_time: :desc).first
|
||||
|
||||
# if a handoff exists, last non human activity is when the handoff ended,
|
||||
# otherwise it's when the conversation was created
|
||||
handoff_event&.event_end_time || conversation.created_at
|
||||
return event.event_end_time if event&.event_end_time
|
||||
|
||||
# Fallback to bot resolved event
|
||||
# Because this will be closest to the most accurate activity instead of conversation.created_at
|
||||
bot_event = ReportingEvent.where(conversation_id: conversation.id, name: 'conversation_bot_resolved').last
|
||||
|
||||
return bot_event.event_end_time if bot_event&.event_end_time
|
||||
|
||||
# If no events found, return conversation creation time
|
||||
conversation.created_at
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
+15
-106
@@ -9,6 +9,7 @@ import Input from 'dashboard/components-next/input/Input.vue';
|
||||
import Button from 'dashboard/components-next/button/Button.vue';
|
||||
import ComboBox from 'dashboard/components-next/combobox/ComboBox.vue';
|
||||
import TagMultiSelectComboBox from 'dashboard/components-next/combobox/TagMultiSelectComboBox.vue';
|
||||
import WhatsAppTemplateParser from 'dashboard/components-next/whatsapp/WhatsAppTemplateParser.vue';
|
||||
|
||||
const emit = defineEmits(['submit', 'cancel']);
|
||||
|
||||
@@ -18,7 +19,9 @@ const formState = {
|
||||
uiFlags: useMapGetter('campaigns/getUIFlags'),
|
||||
labels: useMapGetter('labels/getLabels'),
|
||||
inboxes: useMapGetter('inboxes/getWhatsAppInboxes'),
|
||||
getWhatsAppTemplates: useMapGetter('inboxes/getWhatsAppTemplates'),
|
||||
getFilteredWhatsAppTemplates: useMapGetter(
|
||||
'inboxes/getFilteredWhatsAppTemplates'
|
||||
),
|
||||
};
|
||||
|
||||
const initialState = {
|
||||
@@ -30,7 +33,7 @@ const initialState = {
|
||||
};
|
||||
|
||||
const state = reactive({ ...initialState });
|
||||
const processedParams = ref({});
|
||||
const templateParserRef = ref(null);
|
||||
|
||||
const rules = {
|
||||
title: { required, minLength: minLength(1) },
|
||||
@@ -67,7 +70,7 @@ const inboxOptions = computed(() =>
|
||||
|
||||
const templateOptions = computed(() => {
|
||||
if (!state.inboxId) return [];
|
||||
const templates = formState.getWhatsAppTemplates.value(state.inboxId);
|
||||
const templates = formState.getFilteredWhatsAppTemplates.value(state.inboxId);
|
||||
return templates.map(template => {
|
||||
// Create a more user-friendly label from template name
|
||||
const friendlyName = template.name
|
||||
@@ -88,26 +91,6 @@ const selectedTemplate = computed(() => {
|
||||
?.template;
|
||||
});
|
||||
|
||||
const templateString = computed(() => {
|
||||
if (!selectedTemplate.value) return '';
|
||||
try {
|
||||
return (
|
||||
selectedTemplate.value.components?.find(
|
||||
component => component.type === 'BODY'
|
||||
)?.text || ''
|
||||
);
|
||||
} catch (error) {
|
||||
return '';
|
||||
}
|
||||
});
|
||||
|
||||
const processedString = computed(() => {
|
||||
if (!templateString.value) return '';
|
||||
return templateString.value.replace(/{{([^}]+)}}/g, (match, variable) => {
|
||||
return processedParams.value[variable] || `{{${variable}}}`;
|
||||
});
|
||||
});
|
||||
|
||||
const getErrorMessage = (field, errorKey) => {
|
||||
const baseKey = 'CAMPAIGN.WHATSAPP.CREATE.FORM';
|
||||
return v$.value[field].$error ? t(`${baseKey}.${errorKey}.ERROR`) : '';
|
||||
@@ -122,8 +105,7 @@ const formErrors = computed(() => ({
|
||||
}));
|
||||
|
||||
const hasRequiredTemplateParams = computed(() => {
|
||||
const params = Object.values(processedParams.value);
|
||||
return params.length === 0 || params.every(param => param.trim() !== '');
|
||||
return templateParserRef.value?.v$?.$invalid === false || true;
|
||||
});
|
||||
|
||||
const isSubmitDisabled = computed(
|
||||
@@ -135,32 +117,18 @@ const formatToUTCString = localDateTime =>
|
||||
|
||||
const resetState = () => {
|
||||
Object.assign(state, initialState);
|
||||
processedParams.value = {};
|
||||
v$.value.$reset();
|
||||
};
|
||||
|
||||
const handleCancel = () => emit('cancel');
|
||||
|
||||
const generateVariables = () => {
|
||||
const matchedVariables = templateString.value.match(/{{([^}]+)}}/g);
|
||||
if (!matchedVariables) {
|
||||
processedParams.value = {};
|
||||
return;
|
||||
}
|
||||
|
||||
const finalVars = matchedVariables.map(match => match.replace(/{{|}}/g, ''));
|
||||
processedParams.value = finalVars.reduce((acc, variable) => {
|
||||
acc[variable] = processedParams.value[variable] || '';
|
||||
return acc;
|
||||
}, {});
|
||||
};
|
||||
|
||||
const prepareCampaignDetails = () => {
|
||||
// Find the selected template to get its content
|
||||
const currentTemplate = selectedTemplate.value;
|
||||
const parserData = templateParserRef.value;
|
||||
|
||||
// Extract template content - this should be the template message body
|
||||
const templateContent = templateString.value;
|
||||
const templateContent = parserData?.renderedTemplate || '';
|
||||
|
||||
// Prepare template_params object with the same structure as used in contacts
|
||||
const templateParams = {
|
||||
@@ -168,7 +136,7 @@ const prepareCampaignDetails = () => {
|
||||
namespace: currentTemplate?.namespace || '',
|
||||
category: currentTemplate?.category || 'UTILITY',
|
||||
language: currentTemplate?.language || 'en_US',
|
||||
processed_params: processedParams.value,
|
||||
processed_params: parserData?.processedParams || {},
|
||||
};
|
||||
|
||||
return {
|
||||
@@ -198,15 +166,6 @@ watch(
|
||||
() => state.inboxId,
|
||||
() => {
|
||||
state.templateId = null;
|
||||
processedParams.value = {};
|
||||
}
|
||||
);
|
||||
|
||||
// Generate variables when template changes
|
||||
watch(
|
||||
() => state.templateId,
|
||||
() => {
|
||||
generateVariables();
|
||||
}
|
||||
);
|
||||
</script>
|
||||
@@ -254,62 +213,12 @@ watch(
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Template Preview -->
|
||||
<div
|
||||
<!-- Template Parser -->
|
||||
<WhatsAppTemplateParser
|
||||
v-if="selectedTemplate"
|
||||
class="flex flex-col gap-4 p-4 rounded-lg bg-n-alpha-black2"
|
||||
>
|
||||
<div class="flex justify-between items-center">
|
||||
<h3 class="text-sm font-medium text-n-slate-12">
|
||||
{{ selectedTemplate.name }}
|
||||
</h3>
|
||||
<span class="text-xs text-n-slate-11">
|
||||
{{ t('CAMPAIGN.WHATSAPP.CREATE.FORM.TEMPLATE.LANGUAGE') }}:
|
||||
{{ selectedTemplate.language || 'en' }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-2">
|
||||
<div class="rounded-md bg-n-alpha-black3">
|
||||
<div class="text-sm whitespace-pre-wrap text-n-slate-12">
|
||||
{{ processedString }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="text-xs text-n-slate-11">
|
||||
{{ t('CAMPAIGN.WHATSAPP.CREATE.FORM.TEMPLATE.CATEGORY') }}:
|
||||
{{ selectedTemplate.category || 'UTILITY' }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Template Variables -->
|
||||
<div
|
||||
v-if="Object.keys(processedParams).length > 0"
|
||||
class="flex flex-col gap-3"
|
||||
>
|
||||
<label class="text-sm font-medium text-n-slate-12">
|
||||
{{ t('CAMPAIGN.WHATSAPP.CREATE.FORM.TEMPLATE.VARIABLES_LABEL') }}
|
||||
</label>
|
||||
<div class="flex flex-col gap-2">
|
||||
<div
|
||||
v-for="(value, key) in processedParams"
|
||||
:key="key"
|
||||
class="flex gap-2 items-center"
|
||||
>
|
||||
<Input
|
||||
v-model="processedParams[key]"
|
||||
type="text"
|
||||
class="flex-1"
|
||||
:placeholder="
|
||||
t('CAMPAIGN.WHATSAPP.CREATE.FORM.TEMPLATE.VARIABLE_PLACEHOLDER', {
|
||||
variable: key,
|
||||
})
|
||||
"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
ref="templateParserRef"
|
||||
:template="selectedTemplate"
|
||||
/>
|
||||
|
||||
<div class="flex flex-col gap-1">
|
||||
<label for="audience" class="mb-0.5 text-sm font-medium text-n-slate-12">
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { ref, computed, onMounted, watch } from 'vue';
|
||||
import { useStore, useMapGetter } from 'dashboard/composables/store';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useWindowSize } from '@vueuse/core';
|
||||
import { useUISettings } from 'dashboard/composables/useUISettings';
|
||||
import { vOnClickOutside } from '@vueuse/components';
|
||||
import { useAlert } from 'dashboard/composables';
|
||||
@@ -15,6 +16,7 @@ import {
|
||||
processContactableInboxes,
|
||||
mergeInboxDetails,
|
||||
} from 'dashboard/components-next/NewConversation/helpers/composeConversationHelper';
|
||||
import wootConstants from 'dashboard/constants/globals';
|
||||
|
||||
import ComposeNewConversationForm from 'dashboard/components-next/NewConversation/components/ComposeNewConversationForm.vue';
|
||||
|
||||
@@ -37,9 +39,16 @@ const emit = defineEmits(['close']);
|
||||
|
||||
const store = useStore();
|
||||
const { t } = useI18n();
|
||||
const { width: windowWidth } = useWindowSize();
|
||||
|
||||
const { fetchSignatureFlagFromUISettings } = useUISettings();
|
||||
|
||||
const isSmallScreen = computed(
|
||||
() => windowWidth.value < wootConstants.SMALL_SCREEN_BREAKPOINT
|
||||
);
|
||||
|
||||
const viewInModal = computed(() => props.isModal || isSmallScreen.value);
|
||||
|
||||
const contacts = ref([]);
|
||||
const selectedContact = ref(null);
|
||||
const targetInbox = ref(null);
|
||||
@@ -67,7 +76,7 @@ const directUploadsEnabled = computed(
|
||||
const activeContact = computed(() => contactById.value(props.contactId));
|
||||
|
||||
const composePopoverClass = computed(() => {
|
||||
if (props.isModal) return '';
|
||||
if (viewInModal.value) return '';
|
||||
|
||||
return props.alignPosition === 'right'
|
||||
? 'absolute ltr:left-0 ltr:right-[unset] rtl:right-0 rtl:left-[unset]'
|
||||
@@ -179,14 +188,18 @@ const toggle = () => {
|
||||
|
||||
watch(
|
||||
activeContact,
|
||||
() => {
|
||||
if (activeContact.value && props.contactId) {
|
||||
const contactInboxes = activeContact.value?.contactInboxes || [];
|
||||
(currentContact, previousContact) => {
|
||||
if (currentContact && props.contactId) {
|
||||
// Reset on contact change
|
||||
if (currentContact?.id !== previousContact?.id) clearSelectedContact();
|
||||
|
||||
// First process the contactable inboxes to get the right structure
|
||||
const processedInboxes = processContactableInboxes(contactInboxes);
|
||||
const processedInboxes = processContactableInboxes(
|
||||
currentContact.contactInboxes || []
|
||||
);
|
||||
// Then Merge processedInboxes with the inboxes list
|
||||
selectedContact.value = {
|
||||
...activeContact.value,
|
||||
...currentContact,
|
||||
contactInboxes: mergeInboxDetails(processedInboxes, inboxesList.value),
|
||||
};
|
||||
}
|
||||
@@ -202,7 +215,7 @@ const handleClickOutside = () => {
|
||||
};
|
||||
|
||||
const onModalBackdropClick = () => {
|
||||
if (!props.isModal) return;
|
||||
if (!viewInModal.value) return;
|
||||
handleClickOutside();
|
||||
};
|
||||
|
||||
@@ -231,7 +244,7 @@ useKeyboardEvents(keyboardEvents);
|
||||
]"
|
||||
class="relative"
|
||||
:class="{
|
||||
'z-40': showComposeNewConversation,
|
||||
'z-50': showComposeNewConversation && !viewInModal,
|
||||
}"
|
||||
>
|
||||
<slot
|
||||
@@ -243,12 +256,12 @@ useKeyboardEvents(keyboardEvents);
|
||||
v-if="showComposeNewConversation"
|
||||
:class="{
|
||||
'fixed z-50 bg-n-alpha-black1 backdrop-blur-[4px] flex items-start pt-[clamp(3rem,15vh,12rem)] justify-center inset-0':
|
||||
isModal,
|
||||
viewInModal,
|
||||
}"
|
||||
@click.self="onModalBackdropClick"
|
||||
>
|
||||
<ComposeNewConversationForm
|
||||
:class="[{ 'mt-2': !isModal }, composePopoverClass]"
|
||||
:class="[{ 'mt-2': !viewInModal }, composePopoverClass]"
|
||||
:contacts="contacts"
|
||||
:contact-id="contactId"
|
||||
:is-loading="isSearching"
|
||||
|
||||
+4
-2
@@ -25,6 +25,7 @@ const props = defineProps({
|
||||
hasNoInbox: { type: Boolean, default: false },
|
||||
isDropdownActive: { type: Boolean, default: false },
|
||||
messageSignature: { type: String, default: '' },
|
||||
inboxId: { type: Number, default: null },
|
||||
});
|
||||
|
||||
const emit = defineEmits([
|
||||
@@ -150,9 +151,10 @@ useKeyboardEvents(keyboardEvents);
|
||||
<div
|
||||
class="flex items-center justify-between w-full h-[3.25rem] gap-2 px-4 py-3"
|
||||
>
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="flex gap-2 items-center">
|
||||
<WhatsAppOptions
|
||||
v-if="isWhatsappInbox"
|
||||
:inbox-id="inboxId"
|
||||
:message-templates="messageTemplates"
|
||||
@send-message="emit('sendWhatsappMessage', $event)"
|
||||
/>
|
||||
@@ -206,7 +208,7 @@ useKeyboardEvents(keyboardEvents);
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="flex gap-2 items-center">
|
||||
<Button
|
||||
:label="t('COMPOSE_NEW_CONVERSATION.FORM.ACTION_BUTTONS.DISCARD')"
|
||||
variant="faded"
|
||||
|
||||
+2
-1
@@ -265,7 +265,7 @@ const handleSendWhatsappMessage = async ({ message, templateParams }) => {
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="w-[42rem] divide-y divide-n-strong overflow-visible transition-all duration-300 ease-in-out top-full justify-between flex flex-col bg-n-alpha-3 border border-n-strong shadow-sm backdrop-blur-[100px] rounded-xl"
|
||||
class="w-[42rem] divide-y divide-n-strong overflow-visible transition-all duration-300 ease-in-out top-full justify-between flex flex-col bg-n-alpha-3 border border-n-strong shadow-sm backdrop-blur-[100px] rounded-xl min-w-0"
|
||||
>
|
||||
<ContactSelector
|
||||
:contacts="contacts"
|
||||
@@ -336,6 +336,7 @@ const handleSendWhatsappMessage = async ({ message, templateParams }) => {
|
||||
:is-loading="isCreating"
|
||||
:disable-send-button="isCreating"
|
||||
:has-selected-inbox="!!targetInbox"
|
||||
:inbox-id="targetInbox?.id"
|
||||
:has-no-inbox="showNoInboxAlert"
|
||||
:is-dropdown-active="isAnyDropdownActive"
|
||||
:message-signature="messageSignature"
|
||||
|
||||
+12
-23
@@ -1,24 +1,25 @@
|
||||
<script setup>
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useMapGetter } from 'dashboard/composables/store';
|
||||
|
||||
import Icon from 'dashboard/components-next/icon/Icon.vue';
|
||||
import Button from 'dashboard/components-next/button/Button.vue';
|
||||
import WhatsappTemplateParser from './WhatsappTemplateParser.vue';
|
||||
import WhatsappTemplate from './WhatsappTemplate.vue';
|
||||
|
||||
const props = defineProps({
|
||||
messageTemplates: {
|
||||
type: Array,
|
||||
default: () => [],
|
||||
inboxId: {
|
||||
type: Number,
|
||||
required: true,
|
||||
},
|
||||
});
|
||||
|
||||
const emit = defineEmits(['sendMessage']);
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
// TODO: Remove this when we support all formats
|
||||
const formatsToRemove = ['DOCUMENT', 'IMAGE', 'VIDEO'];
|
||||
const getFilteredWhatsAppTemplates = useMapGetter(
|
||||
'inboxes/getFilteredWhatsAppTemplates'
|
||||
);
|
||||
|
||||
const searchQuery = ref('');
|
||||
const selectedTemplate = ref(null);
|
||||
@@ -26,19 +27,7 @@ const selectedTemplate = ref(null);
|
||||
const showTemplatesMenu = ref(false);
|
||||
|
||||
const whatsAppTemplateMessages = computed(() => {
|
||||
// Add null check and ensure it's an array
|
||||
const templates = Array.isArray(props.messageTemplates)
|
||||
? props.messageTemplates
|
||||
: [];
|
||||
|
||||
// TODO: Remove the last filter when we support all formats
|
||||
return templates
|
||||
.filter(template => template?.status?.toLowerCase() === 'approved')
|
||||
.filter(template => {
|
||||
return template?.components?.every(component => {
|
||||
return !formatsToRemove.includes(component.format);
|
||||
});
|
||||
});
|
||||
return getFilteredWhatsAppTemplates.value(props.inboxId);
|
||||
});
|
||||
|
||||
const filteredTemplates = computed(() => {
|
||||
@@ -106,7 +95,7 @@ const handleSendMessage = template => {
|
||||
<div
|
||||
v-for="template in filteredTemplates"
|
||||
:key="template.id"
|
||||
class="flex flex-col w-full gap-2 p-2 rounded-lg cursor-pointer dark:hover:bg-n-alpha-3 hover:bg-n-alpha-1"
|
||||
class="flex flex-col gap-2 p-2 w-full rounded-lg cursor-pointer dark:hover:bg-n-alpha-3 hover:bg-n-alpha-1"
|
||||
@click="handleTemplateClick(template)"
|
||||
>
|
||||
<span class="text-sm text-n-slate-12">{{ template.name }}</span>
|
||||
@@ -115,12 +104,12 @@ const handleSendMessage = template => {
|
||||
</p>
|
||||
</div>
|
||||
<template v-if="filteredTemplates.length === 0">
|
||||
<p class="w-full pt-2 text-sm text-n-slate-11">
|
||||
<p class="pt-2 w-full text-sm text-n-slate-11">
|
||||
{{ t('COMPOSE_NEW_CONVERSATION.FORM.WHATSAPP_OPTIONS.EMPTY_STATE') }}
|
||||
</p>
|
||||
</template>
|
||||
</div>
|
||||
<WhatsappTemplateParser
|
||||
<WhatsappTemplate
|
||||
v-if="selectedTemplate"
|
||||
:template="selectedTemplate"
|
||||
@send-message="handleSendMessage"
|
||||
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
<script setup>
|
||||
import WhatsAppTemplateParser from 'dashboard/components-next/whatsapp/WhatsAppTemplateParser.vue';
|
||||
import Button from 'dashboard/components-next/button/Button.vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
defineProps({
|
||||
template: {
|
||||
type: Object,
|
||||
default: () => ({}),
|
||||
},
|
||||
});
|
||||
|
||||
const emit = defineEmits(['sendMessage', 'back']);
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const handleSendMessage = payload => {
|
||||
emit('sendMessage', payload);
|
||||
};
|
||||
|
||||
const handleBack = () => {
|
||||
emit('back');
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="absolute top-full mt-1.5 max-h-[30rem] overflow-y-auto ltr:left-0 rtl:right-0 flex flex-col gap-4 px-4 pt-6 pb-5 items-start w-[28.75rem] h-auto bg-n-solid-2 border border-n-strong shadow-sm rounded-lg"
|
||||
>
|
||||
<div class="w-full">
|
||||
<WhatsAppTemplateParser
|
||||
:template="template"
|
||||
@send-message="handleSendMessage"
|
||||
@back="handleBack"
|
||||
>
|
||||
<template #actions="{ sendMessage, goBack, disabled }">
|
||||
<div class="flex gap-3 justify-between items-end w-full h-14">
|
||||
<Button
|
||||
:label="
|
||||
t(
|
||||
'COMPOSE_NEW_CONVERSATION.FORM.WHATSAPP_OPTIONS.TEMPLATE_PARSER.BACK'
|
||||
)
|
||||
"
|
||||
color="slate"
|
||||
variant="faded"
|
||||
class="w-full font-medium"
|
||||
@click="goBack"
|
||||
/>
|
||||
<Button
|
||||
:label="
|
||||
t(
|
||||
'COMPOSE_NEW_CONVERSATION.FORM.WHATSAPP_OPTIONS.TEMPLATE_PARSER.SEND_MESSAGE'
|
||||
)
|
||||
"
|
||||
class="w-full font-medium"
|
||||
:disabled="disabled"
|
||||
@click="sendMessage"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</WhatsAppTemplateParser>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -509,10 +509,8 @@ const menuItems = computed(() => {
|
||||
class="bg-n-solid-2 rtl:border-l ltr:border-r border-n-weak flex flex-col text-sm pb-1 fixed top-0 ltr:left-0 rtl:right-0 h-full z-40 transition-transform duration-200 ease-in-out md:static w-[200px] basis-[200px] md:flex-shrink-0 md:ltr:translate-x-0 md:rtl:-translate-x-0"
|
||||
:class="[
|
||||
{
|
||||
'ltr:translate-x-0 rtl:-translate-x-0 shadow-lg md:shadow-none':
|
||||
isMobileSidebarOpen,
|
||||
'ltr:-translate-x-full rtl:translate-x-full md:translate-x-0':
|
||||
!isMobileSidebarOpen,
|
||||
'shadow-lg md:shadow-none': isMobileSidebarOpen,
|
||||
'ltr:-translate-x-full rtl:translate-x-full': !isMobileSidebarOpen,
|
||||
},
|
||||
]"
|
||||
>
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, watch } from 'vue';
|
||||
import { useVuelidate } from '@vuelidate/core';
|
||||
import { requiredIf } from '@vuelidate/validators';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
import Input from 'dashboard/components-next/input/Input.vue';
|
||||
import {
|
||||
buildTemplateParameters,
|
||||
allKeysRequired,
|
||||
replaceTemplateVariables,
|
||||
DEFAULT_LANGUAGE,
|
||||
DEFAULT_CATEGORY,
|
||||
COMPONENT_TYPES,
|
||||
MEDIA_FORMATS,
|
||||
findComponentByType,
|
||||
} from 'dashboard/helper/templateHelper';
|
||||
|
||||
const props = defineProps({
|
||||
template: {
|
||||
type: Object,
|
||||
default: () => ({}),
|
||||
validator: value => {
|
||||
if (!value || typeof value !== 'object') return false;
|
||||
if (!value.components || !Array.isArray(value.components)) return false;
|
||||
return true;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const emit = defineEmits(['sendMessage', 'resetTemplate', 'back']);
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const processedParams = ref({});
|
||||
|
||||
const languageLabel = computed(() => {
|
||||
return `${t('WHATSAPP_TEMPLATES.PARSER.LANGUAGE')}: ${props.template.language || DEFAULT_LANGUAGE}`;
|
||||
});
|
||||
|
||||
const categoryLabel = computed(() => {
|
||||
return `${t('WHATSAPP_TEMPLATES.PARSER.CATEGORY')}: ${props.template.category || DEFAULT_CATEGORY}`;
|
||||
});
|
||||
|
||||
const headerComponent = computed(() => {
|
||||
return findComponentByType(props.template, COMPONENT_TYPES.HEADER);
|
||||
});
|
||||
|
||||
const bodyComponent = computed(() => {
|
||||
return findComponentByType(props.template, COMPONENT_TYPES.BODY);
|
||||
});
|
||||
|
||||
const bodyText = computed(() => {
|
||||
return bodyComponent.value?.text || '';
|
||||
});
|
||||
|
||||
const hasMediaHeader = computed(() =>
|
||||
MEDIA_FORMATS.includes(headerComponent.value?.format)
|
||||
);
|
||||
|
||||
const formatType = computed(() => {
|
||||
const format = headerComponent.value?.format;
|
||||
return format ? format.charAt(0) + format.slice(1).toLowerCase() : '';
|
||||
});
|
||||
|
||||
const hasVariables = computed(() => {
|
||||
return bodyText.value?.match(/{{([^}]+)}}/g) !== null;
|
||||
});
|
||||
|
||||
const renderedTemplate = computed(() => {
|
||||
return replaceTemplateVariables(bodyText.value, processedParams.value);
|
||||
});
|
||||
|
||||
const isFormInvalid = computed(() => {
|
||||
if (!hasVariables.value && !hasMediaHeader.value) return false;
|
||||
|
||||
if (hasMediaHeader.value && !processedParams.value.header?.media_url) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (hasVariables.value && processedParams.value.body) {
|
||||
const hasEmptyBodyVariable = Object.values(processedParams.value.body).some(
|
||||
value => !value
|
||||
);
|
||||
if (hasEmptyBodyVariable) return true;
|
||||
}
|
||||
|
||||
if (processedParams.value.buttons) {
|
||||
const hasEmptyButtonParameter = processedParams.value.buttons.some(
|
||||
button => !button.parameter
|
||||
);
|
||||
if (hasEmptyButtonParameter) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
|
||||
const v$ = useVuelidate(
|
||||
{
|
||||
processedParams: {
|
||||
requiredIfKeysPresent: requiredIf(hasVariables),
|
||||
allKeysRequired,
|
||||
},
|
||||
},
|
||||
{ processedParams }
|
||||
);
|
||||
|
||||
const initializeTemplateParameters = () => {
|
||||
processedParams.value = buildTemplateParameters(
|
||||
props.template,
|
||||
hasMediaHeader.value
|
||||
);
|
||||
};
|
||||
|
||||
const updateMediaUrl = value => {
|
||||
processedParams.value.header ??= {};
|
||||
processedParams.value.header.media_url = value;
|
||||
};
|
||||
|
||||
const sendMessage = () => {
|
||||
v$.value.$touch();
|
||||
if (v$.value.$invalid) return;
|
||||
|
||||
const { name, category, language, namespace } = props.template;
|
||||
|
||||
const payload = {
|
||||
message: renderedTemplate.value,
|
||||
templateParams: {
|
||||
name,
|
||||
category,
|
||||
language,
|
||||
namespace,
|
||||
processed_params: processedParams.value,
|
||||
},
|
||||
};
|
||||
emit('sendMessage', payload);
|
||||
};
|
||||
|
||||
const resetTemplate = () => {
|
||||
emit('resetTemplate');
|
||||
};
|
||||
|
||||
const goBack = () => {
|
||||
emit('back');
|
||||
};
|
||||
|
||||
onMounted(initializeTemplateParameters);
|
||||
|
||||
watch(
|
||||
() => props.template,
|
||||
() => {
|
||||
initializeTemplateParameters();
|
||||
v$.value.$reset();
|
||||
},
|
||||
{ deep: true }
|
||||
);
|
||||
|
||||
defineExpose({
|
||||
processedParams,
|
||||
hasVariables,
|
||||
hasMediaHeader,
|
||||
headerComponent,
|
||||
renderedTemplate,
|
||||
v$,
|
||||
updateMediaUrl,
|
||||
sendMessage,
|
||||
resetTemplate,
|
||||
goBack,
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<div class="flex flex-col gap-4 p-4 mb-4 rounded-lg bg-n-alpha-black2">
|
||||
<div class="flex justify-between items-center">
|
||||
<h3 class="text-sm font-medium text-n-slate-12">
|
||||
{{ template.name }}
|
||||
</h3>
|
||||
<span class="text-xs text-n-slate-11">
|
||||
{{ languageLabel }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-2">
|
||||
<div class="rounded-md">
|
||||
<div class="text-sm whitespace-pre-wrap text-n-slate-12">
|
||||
{{ renderedTemplate }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="text-xs text-n-slate-11">
|
||||
{{ categoryLabel }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="hasVariables || hasMediaHeader">
|
||||
<div v-if="hasMediaHeader" class="mb-4">
|
||||
<p class="mb-2.5 text-sm font-semibold">
|
||||
{{
|
||||
$t('WHATSAPP_TEMPLATES.PARSER.MEDIA_HEADER_LABEL', {
|
||||
type: formatType,
|
||||
}) || `${formatType} Header`
|
||||
}}
|
||||
</p>
|
||||
<div class="flex items-center mb-2.5">
|
||||
<Input
|
||||
:model-value="processedParams.header?.media_url || ''"
|
||||
type="url"
|
||||
class="flex-1"
|
||||
:placeholder="
|
||||
t('WHATSAPP_TEMPLATES.PARSER.MEDIA_URL_LABEL', {
|
||||
type: formatType,
|
||||
})
|
||||
"
|
||||
@update:model-value="updateMediaUrl"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Body Variables Section -->
|
||||
<div v-if="processedParams.body">
|
||||
<p class="mb-2.5 text-sm font-semibold">
|
||||
{{ $t('WHATSAPP_TEMPLATES.PARSER.VARIABLES_LABEL') }}
|
||||
</p>
|
||||
<div
|
||||
v-for="(variable, key) in processedParams.body"
|
||||
:key="`body-${key}`"
|
||||
class="flex items-center mb-2.5"
|
||||
>
|
||||
<Input
|
||||
v-model="processedParams.body[key]"
|
||||
type="text"
|
||||
class="flex-1"
|
||||
:placeholder="
|
||||
t('WHATSAPP_TEMPLATES.PARSER.VARIABLE_PLACEHOLDER', {
|
||||
variable: key,
|
||||
})
|
||||
"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Button Variables Section -->
|
||||
<div v-if="processedParams.buttons">
|
||||
<p class="mb-2.5 text-sm font-semibold">
|
||||
{{ t('WHATSAPP_TEMPLATES.PARSER.BUTTON_PARAMETERS') }}
|
||||
</p>
|
||||
<div
|
||||
v-for="(button, index) in processedParams.buttons"
|
||||
:key="`button-${index}`"
|
||||
class="flex items-center mb-2.5"
|
||||
>
|
||||
<Input
|
||||
v-model="processedParams.buttons[index].parameter"
|
||||
type="text"
|
||||
class="flex-1"
|
||||
:placeholder="t('WHATSAPP_TEMPLATES.PARSER.BUTTON_PARAMETER')"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<p
|
||||
v-if="v$.$dirty && v$.$invalid"
|
||||
class="p-2.5 text-center rounded-md bg-n-ruby-9/20 text-n-ruby-9"
|
||||
>
|
||||
{{ $t('WHATSAPP_TEMPLATES.PARSER.FORM_ERROR_MESSAGE') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<slot
|
||||
name="actions"
|
||||
:send-message="sendMessage"
|
||||
:reset-template="resetTemplate"
|
||||
:go-back="goBack"
|
||||
:is-valid="!v$.$invalid"
|
||||
:disabled="isFormInvalid"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
+36
-143
@@ -1,4 +1,4 @@
|
||||
<script>
|
||||
<script setup>
|
||||
/**
|
||||
* This component handles parsing and sending WhatsApp message templates.
|
||||
* It works as follows:
|
||||
@@ -8,158 +8,51 @@
|
||||
* 4. Replaces placeholders with user-provided values.
|
||||
* 5. Emits events to send the processed message or reset the template.
|
||||
*/
|
||||
import { ref, computed, onMounted } from 'vue';
|
||||
import { useVuelidate } from '@vuelidate/core';
|
||||
import { requiredIf } from '@vuelidate/validators';
|
||||
|
||||
import WhatsAppTemplateParser from 'dashboard/components-next/whatsapp/WhatsAppTemplateParser.vue';
|
||||
import NextButton from 'dashboard/components-next/button/Button.vue';
|
||||
|
||||
export default {
|
||||
components: {
|
||||
NextButton,
|
||||
defineProps({
|
||||
template: {
|
||||
type: Object,
|
||||
default: () => ({}),
|
||||
},
|
||||
props: {
|
||||
template: {
|
||||
type: Object,
|
||||
default: () => ({}),
|
||||
},
|
||||
},
|
||||
emits: ['sendMessage', 'resetTemplate'],
|
||||
setup(props, { emit }) {
|
||||
const processVariable = str => {
|
||||
return str.replace(/{{|}}/g, '');
|
||||
};
|
||||
});
|
||||
|
||||
const allKeysRequired = value => {
|
||||
const keys = Object.keys(value);
|
||||
return keys.every(key => value[key]);
|
||||
};
|
||||
const emit = defineEmits(['sendMessage', 'resetTemplate']);
|
||||
|
||||
const processedParams = ref({});
|
||||
const handleSendMessage = payload => {
|
||||
emit('sendMessage', payload);
|
||||
};
|
||||
|
||||
const templateString = computed(() => {
|
||||
return props.template.components.find(
|
||||
component => component.type === 'BODY'
|
||||
).text;
|
||||
});
|
||||
|
||||
const variables = computed(() => {
|
||||
return templateString.value.match(/{{([^}]+)}}/g);
|
||||
});
|
||||
|
||||
const processedString = computed(() => {
|
||||
return templateString.value.replace(/{{([^}]+)}}/g, (match, variable) => {
|
||||
const variableKey = processVariable(variable);
|
||||
return processedParams.value[variableKey] || `{{${variable}}}`;
|
||||
});
|
||||
});
|
||||
|
||||
const v$ = useVuelidate(
|
||||
{
|
||||
processedParams: {
|
||||
requiredIfKeysPresent: requiredIf(variables),
|
||||
allKeysRequired,
|
||||
},
|
||||
},
|
||||
{ processedParams }
|
||||
);
|
||||
|
||||
const generateVariables = () => {
|
||||
const matchedVariables = templateString.value.match(/{{([^}]+)}}/g);
|
||||
if (!matchedVariables) return;
|
||||
|
||||
const finalVars = matchedVariables.map(i => processVariable(i));
|
||||
processedParams.value = finalVars.reduce((acc, variable) => {
|
||||
acc[variable] = '';
|
||||
return acc;
|
||||
}, {});
|
||||
};
|
||||
|
||||
const resetTemplate = () => {
|
||||
emit('resetTemplate');
|
||||
};
|
||||
|
||||
const sendMessage = () => {
|
||||
v$.value.$touch();
|
||||
if (v$.value.$invalid) return;
|
||||
|
||||
const payload = {
|
||||
message: processedString.value,
|
||||
templateParams: {
|
||||
name: props.template.name,
|
||||
category: props.template.category,
|
||||
language: props.template.language,
|
||||
namespace: props.template.namespace,
|
||||
processed_params: processedParams.value,
|
||||
},
|
||||
};
|
||||
emit('sendMessage', payload);
|
||||
};
|
||||
|
||||
onMounted(generateVariables);
|
||||
|
||||
return {
|
||||
processedParams,
|
||||
variables,
|
||||
templateString,
|
||||
processedString,
|
||||
v$,
|
||||
resetTemplate,
|
||||
sendMessage,
|
||||
};
|
||||
},
|
||||
const handleResetTemplate = () => {
|
||||
emit('resetTemplate');
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="w-full">
|
||||
<textarea
|
||||
v-model="processedString"
|
||||
rows="4"
|
||||
readonly
|
||||
class="template-input"
|
||||
/>
|
||||
<div v-if="variables" class="p-2.5">
|
||||
<p class="text-sm font-semibold mb-2.5">
|
||||
{{ $t('WHATSAPP_TEMPLATES.PARSER.VARIABLES_LABEL') }}
|
||||
</p>
|
||||
<div
|
||||
v-for="(variable, key) in processedParams"
|
||||
:key="key"
|
||||
class="items-center flex mb-2.5"
|
||||
>
|
||||
<span
|
||||
class="bg-n-alpha-black2 text-n-slate-12 inline-block rounded-md text-xs py-2.5 px-6"
|
||||
>
|
||||
{{ key }}
|
||||
</span>
|
||||
<woot-input
|
||||
v-model="processedParams[key]"
|
||||
type="text"
|
||||
class="flex-1 text-sm ml-2.5"
|
||||
:styles="{ marginBottom: 0 }"
|
||||
/>
|
||||
</div>
|
||||
<p
|
||||
v-if="v$.$dirty && v$.$invalid"
|
||||
class="bg-n-ruby-9/20 rounded-md text-n-ruby-9 p-2.5 text-center"
|
||||
>
|
||||
{{ $t('WHATSAPP_TEMPLATES.PARSER.FORM_ERROR_MESSAGE') }}
|
||||
</p>
|
||||
</div>
|
||||
<footer class="flex justify-end gap-2">
|
||||
<NextButton
|
||||
faded
|
||||
slate
|
||||
type="reset"
|
||||
:label="$t('WHATSAPP_TEMPLATES.PARSER.GO_BACK_LABEL')"
|
||||
@click="resetTemplate"
|
||||
/>
|
||||
<NextButton
|
||||
type="button"
|
||||
:label="$t('WHATSAPP_TEMPLATES.PARSER.SEND_MESSAGE_LABEL')"
|
||||
@click="sendMessage"
|
||||
/>
|
||||
</footer>
|
||||
<WhatsAppTemplateParser
|
||||
:template="template"
|
||||
@send-message="handleSendMessage"
|
||||
@reset-template="handleResetTemplate"
|
||||
>
|
||||
<template #actions="{ sendMessage, resetTemplate, disabled }">
|
||||
<footer class="flex gap-2 justify-end">
|
||||
<NextButton
|
||||
faded
|
||||
slate
|
||||
type="reset"
|
||||
:label="$t('WHATSAPP_TEMPLATES.PARSER.GO_BACK_LABEL')"
|
||||
@click="resetTemplate"
|
||||
/>
|
||||
<NextButton
|
||||
type="button"
|
||||
:label="$t('WHATSAPP_TEMPLATES.PARSER.SEND_MESSAGE_LABEL')"
|
||||
:disabled="disabled"
|
||||
@click="sendMessage"
|
||||
/>
|
||||
</footer>
|
||||
</template>
|
||||
</WhatsAppTemplateParser>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
+130
-67
@@ -1,60 +1,71 @@
|
||||
<script>
|
||||
<script setup>
|
||||
import { ref, computed, toRef } from 'vue';
|
||||
import { useAlert } from 'dashboard/composables';
|
||||
import { useFunctionGetter, useStore } from 'dashboard/composables/store';
|
||||
import {
|
||||
COMPONENT_TYPES,
|
||||
MEDIA_FORMATS,
|
||||
findComponentByType,
|
||||
} from 'dashboard/helper/templateHelper';
|
||||
import Icon from 'dashboard/components-next/icon/Icon.vue';
|
||||
// TODO: Remove this when we support all formats
|
||||
const formatsToRemove = ['DOCUMENT', 'IMAGE', 'VIDEO'];
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
export default {
|
||||
components: {
|
||||
Icon,
|
||||
},
|
||||
props: {
|
||||
inboxId: {
|
||||
type: Number,
|
||||
default: undefined,
|
||||
},
|
||||
},
|
||||
emits: ['onSelect'],
|
||||
data() {
|
||||
return {
|
||||
query: '',
|
||||
isRefreshing: false,
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
whatsAppTemplateMessages() {
|
||||
// TODO: Remove the last filter when we support all formats
|
||||
return this.$store.getters['inboxes/getWhatsAppTemplates'](this.inboxId)
|
||||
.filter(template => template.status.toLowerCase() === 'approved')
|
||||
.filter(template => {
|
||||
return template.components.every(component => {
|
||||
return !formatsToRemove.includes(component.format);
|
||||
});
|
||||
});
|
||||
},
|
||||
filteredTemplateMessages() {
|
||||
return this.whatsAppTemplateMessages.filter(template =>
|
||||
template.name.toLowerCase().includes(this.query.toLowerCase())
|
||||
);
|
||||
},
|
||||
},
|
||||
methods: {
|
||||
getTemplatebody(template) {
|
||||
return template.components.find(component => component.type === 'BODY')
|
||||
.text;
|
||||
},
|
||||
async refreshTemplates() {
|
||||
this.isRefreshing = true;
|
||||
try {
|
||||
await this.$store.dispatch('inboxes/syncTemplates', this.inboxId);
|
||||
useAlert(this.$t('WHATSAPP_TEMPLATES.PICKER.REFRESH_SUCCESS'));
|
||||
} catch (error) {
|
||||
useAlert(this.$t('WHATSAPP_TEMPLATES.PICKER.REFRESH_ERROR'));
|
||||
} finally {
|
||||
this.isRefreshing = false;
|
||||
}
|
||||
},
|
||||
const props = defineProps({
|
||||
inboxId: {
|
||||
type: Number,
|
||||
default: undefined,
|
||||
},
|
||||
});
|
||||
|
||||
const emit = defineEmits(['onSelect']);
|
||||
|
||||
const { t } = useI18n();
|
||||
const store = useStore();
|
||||
const query = ref('');
|
||||
const isRefreshing = ref(false);
|
||||
|
||||
const whatsAppTemplateMessages = useFunctionGetter(
|
||||
'inboxes/getFilteredWhatsAppTemplates',
|
||||
toRef(props, 'inboxId')
|
||||
);
|
||||
|
||||
const filteredTemplateMessages = computed(() =>
|
||||
whatsAppTemplateMessages.value.filter(template =>
|
||||
template.name.toLowerCase().includes(query.value.toLowerCase())
|
||||
)
|
||||
);
|
||||
|
||||
const getTemplateBody = template => {
|
||||
return findComponentByType(template, COMPONENT_TYPES.BODY)?.text || '';
|
||||
};
|
||||
|
||||
const getTemplateHeader = template => {
|
||||
return findComponentByType(template, COMPONENT_TYPES.HEADER);
|
||||
};
|
||||
|
||||
const getTemplateFooter = template => {
|
||||
return findComponentByType(template, COMPONENT_TYPES.FOOTER);
|
||||
};
|
||||
|
||||
const getTemplateButtons = template => {
|
||||
return findComponentByType(template, COMPONENT_TYPES.BUTTONS);
|
||||
};
|
||||
|
||||
const hasMediaContent = template => {
|
||||
const header = getTemplateHeader(template);
|
||||
return header && MEDIA_FORMATS.includes(header.format);
|
||||
};
|
||||
|
||||
const refreshTemplates = async () => {
|
||||
isRefreshing.value = true;
|
||||
try {
|
||||
await store.dispatch('inboxes/syncTemplates', props.inboxId);
|
||||
useAlert(t('WHATSAPP_TEMPLATES.PICKER.REFRESH_SUCCESS'));
|
||||
} catch (error) {
|
||||
useAlert(t('WHATSAPP_TEMPLATES.PICKER.REFRESH_ERROR'));
|
||||
} finally {
|
||||
isRefreshing.value = false;
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
@@ -68,14 +79,14 @@ export default {
|
||||
<input
|
||||
v-model="query"
|
||||
type="search"
|
||||
:placeholder="$t('WHATSAPP_TEMPLATES.PICKER.SEARCH_PLACEHOLDER')"
|
||||
:placeholder="t('WHATSAPP_TEMPLATES.PICKER.SEARCH_PLACEHOLDER')"
|
||||
class="reset-base w-full h-9 bg-transparent text-n-slate-12 !text-sm !outline-0"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
:disabled="isRefreshing"
|
||||
class="flex justify-center items-center w-9 h-9 rounded-lg bg-n-alpha-black2 outline outline-1 outline-n-weak hover:outline-n-slate-6 dark:hover:outline-n-slate-6 hover:bg-n-alpha-2 dark:hover:bg-n-solid-2 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
:title="$t('WHATSAPP_TEMPLATES.PICKER.REFRESH_BUTTON')"
|
||||
:title="t('WHATSAPP_TEMPLATES.PICKER.REFRESH_BUTTON')"
|
||||
@click="refreshTemplates"
|
||||
>
|
||||
<Icon
|
||||
@@ -91,7 +102,7 @@ export default {
|
||||
<div v-for="(template, i) in filteredTemplateMessages" :key="template.id">
|
||||
<button
|
||||
class="block p-2.5 w-full text-left rounded-lg cursor-pointer hover:bg-n-alpha-2 dark:hover:bg-n-solid-2"
|
||||
@click="$emit('onSelect', template)"
|
||||
@click="emit('onSelect', template)"
|
||||
>
|
||||
<div>
|
||||
<div class="flex justify-between items-center mb-2.5">
|
||||
@@ -101,21 +112,73 @@ export default {
|
||||
<span
|
||||
class="inline-block px-2 py-1 text-xs leading-none rounded-lg cursor-default bg-n-slate-3 text-n-slate-12"
|
||||
>
|
||||
{{ $t('WHATSAPP_TEMPLATES.PICKER.LABELS.LANGUAGE') }} :
|
||||
{{ t('WHATSAPP_TEMPLATES.PICKER.LABELS.LANGUAGE') }}:
|
||||
{{ template.language }}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<p class="font-medium">
|
||||
{{ $t('WHATSAPP_TEMPLATES.PICKER.LABELS.TEMPLATE_BODY') }}
|
||||
<!-- Header -->
|
||||
<div v-if="getTemplateHeader(template)" class="mb-3">
|
||||
<p class="text-xs font-medium text-n-slate-11">
|
||||
{{ t('WHATSAPP_TEMPLATES.PICKER.HEADER') || 'HEADER' }}
|
||||
</p>
|
||||
<p class="label-body">{{ getTemplatebody(template) }}</p>
|
||||
<div
|
||||
v-if="getTemplateHeader(template).format === 'TEXT'"
|
||||
class="text-sm label-body"
|
||||
>
|
||||
{{ getTemplateHeader(template).text }}
|
||||
</div>
|
||||
<div
|
||||
v-else-if="hasMediaContent(template)"
|
||||
class="text-sm italic text-n-slate-11"
|
||||
>
|
||||
{{
|
||||
t('WHATSAPP_TEMPLATES.PICKER.MEDIA_CONTENT', {
|
||||
format: getTemplateHeader(template).format,
|
||||
}) ||
|
||||
`${getTemplateHeader(template).format} ${t('WHATSAPP_TEMPLATES.PICKER.MEDIA_CONTENT_FALLBACK')}`
|
||||
}}
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-5">
|
||||
<p class="font-medium">
|
||||
{{ $t('WHATSAPP_TEMPLATES.PICKER.LABELS.CATEGORY') }}
|
||||
|
||||
<!-- Body -->
|
||||
<div>
|
||||
<p class="text-xs font-medium text-n-slate-11">
|
||||
{{ t('WHATSAPP_TEMPLATES.PICKER.BODY') || 'BODY' }}
|
||||
</p>
|
||||
<p>{{ template.category }}</p>
|
||||
<p class="text-sm label-body">{{ getTemplateBody(template) }}</p>
|
||||
</div>
|
||||
|
||||
<!-- Footer -->
|
||||
<div v-if="getTemplateFooter(template)" class="mt-3">
|
||||
<p class="text-xs font-medium text-n-slate-11">
|
||||
{{ t('WHATSAPP_TEMPLATES.PICKER.FOOTER') || 'FOOTER' }}
|
||||
</p>
|
||||
<p class="text-sm label-body">
|
||||
{{ getTemplateFooter(template).text }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Buttons -->
|
||||
<div v-if="getTemplateButtons(template)" class="mt-3">
|
||||
<p class="text-xs font-medium text-n-slate-11">
|
||||
{{ t('WHATSAPP_TEMPLATES.PICKER.BUTTONS') || 'BUTTONS' }}
|
||||
</p>
|
||||
<div class="flex flex-wrap gap-1 mt-1">
|
||||
<span
|
||||
v-for="button in getTemplateButtons(template).buttons"
|
||||
:key="button.text"
|
||||
class="px-2 py-1 text-xs rounded bg-n-slate-3 text-n-slate-12"
|
||||
>
|
||||
{{ button.text }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-3">
|
||||
<p class="text-xs font-medium text-n-slate-11">
|
||||
{{ t('WHATSAPP_TEMPLATES.PICKER.CATEGORY') || 'CATEGORY' }}
|
||||
</p>
|
||||
<p class="text-sm">{{ template.category }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
@@ -128,13 +191,13 @@ export default {
|
||||
<div v-if="!filteredTemplateMessages.length" class="py-8 text-center">
|
||||
<div v-if="query && whatsAppTemplateMessages.length">
|
||||
<p>
|
||||
{{ $t('WHATSAPP_TEMPLATES.PICKER.NO_TEMPLATES_FOUND') }}
|
||||
{{ t('WHATSAPP_TEMPLATES.PICKER.NO_TEMPLATES_FOUND') }}
|
||||
<strong>{{ query }}</strong>
|
||||
</p>
|
||||
</div>
|
||||
<div v-else-if="!whatsAppTemplateMessages.length" class="space-y-4">
|
||||
<p class="text-n-slate-11">
|
||||
{{ $t('WHATSAPP_TEMPLATES.PICKER.NO_TEMPLATES_AVAILABLE') }}
|
||||
{{ t('WHATSAPP_TEMPLATES.PICKER.NO_TEMPLATES_AVAILABLE') }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -196,6 +196,7 @@ describe('useAutomation', () => {
|
||||
automationTypes.conversation_created = { conditions: [] };
|
||||
automationTypes.conversation_updated = { conditions: [] };
|
||||
automationTypes.conversation_opened = { conditions: [] };
|
||||
automationTypes.conversation_resolved = { conditions: [] };
|
||||
|
||||
automationHelper.generateCustomAttributeTypes.mockReturnValue([]);
|
||||
automationHelper.generateCustomAttributes.mockReturnValue([]);
|
||||
|
||||
@@ -111,7 +111,7 @@ describe('useMacros', () => {
|
||||
useStoreGetters.mockReturnValue({
|
||||
'labels/getLabels': { value: mockLabels },
|
||||
'teams/getTeams': { value: mockTeams },
|
||||
'agents/getAgents': { value: mockAgents },
|
||||
'agents/getVerifiedAgents': { value: mockAgents },
|
||||
});
|
||||
});
|
||||
|
||||
@@ -119,24 +119,30 @@ describe('useMacros', () => {
|
||||
const { getMacroDropdownValues } = useMacros();
|
||||
expect(getMacroDropdownValues('add_label')).toHaveLength(mockLabels.length);
|
||||
expect(getMacroDropdownValues('assign_team')).toHaveLength(
|
||||
mockTeams.length
|
||||
);
|
||||
mockTeams.length + 1
|
||||
); // +1 for "None"
|
||||
expect(getMacroDropdownValues('assign_agent')).toHaveLength(
|
||||
mockAgents.length + 1
|
||||
); // +1 for "Self"
|
||||
mockAgents.length + 2
|
||||
); // +2 for "None" and "Self"
|
||||
});
|
||||
|
||||
it('returns teams for assign_team and send_email_to_team types', () => {
|
||||
it('returns teams with "None" option for assign_team and teams only for send_email_to_team', () => {
|
||||
const { getMacroDropdownValues } = useMacros();
|
||||
expect(getMacroDropdownValues('assign_team')).toEqual(mockTeams);
|
||||
const assignTeamResult = getMacroDropdownValues('assign_team');
|
||||
expect(assignTeamResult[0]).toEqual({
|
||||
id: 'nil',
|
||||
name: 'AUTOMATION.NONE_OPTION',
|
||||
});
|
||||
expect(assignTeamResult.slice(1)).toEqual(mockTeams);
|
||||
expect(getMacroDropdownValues('send_email_to_team')).toEqual(mockTeams);
|
||||
});
|
||||
|
||||
it('returns agents with "Self" option for assign_agent type', () => {
|
||||
it('returns agents with "None" and "Self" options for assign_agent type', () => {
|
||||
const { getMacroDropdownValues } = useMacros();
|
||||
const result = getMacroDropdownValues('assign_agent');
|
||||
expect(result[0]).toEqual({ id: 'self', name: 'Self' });
|
||||
expect(result.slice(1)).toEqual(mockAgents);
|
||||
expect(result[0]).toEqual({ id: 'nil', name: 'AUTOMATION.NONE_OPTION' });
|
||||
expect(result[1]).toEqual({ id: 'self', name: 'Self' });
|
||||
expect(result.slice(2)).toEqual(mockAgents);
|
||||
});
|
||||
|
||||
it('returns formatted labels for add_label and remove_label types', () => {
|
||||
@@ -167,13 +173,16 @@ describe('useMacros', () => {
|
||||
useStoreGetters.mockReturnValue({
|
||||
'labels/getLabels': { value: [] },
|
||||
'teams/getTeams': { value: [] },
|
||||
'agents/getAgents': { value: [] },
|
||||
'agents/getVerifiedAgents': { value: [] },
|
||||
});
|
||||
|
||||
const { getMacroDropdownValues } = useMacros();
|
||||
expect(getMacroDropdownValues('add_label')).toEqual([]);
|
||||
expect(getMacroDropdownValues('assign_team')).toEqual([]);
|
||||
expect(getMacroDropdownValues('assign_team')).toEqual([
|
||||
{ id: 'nil', name: 'AUTOMATION.NONE_OPTION' },
|
||||
]);
|
||||
expect(getMacroDropdownValues('assign_agent')).toEqual([
|
||||
{ id: 'nil', name: 'AUTOMATION.NONE_OPTION' },
|
||||
{ id: 'self', name: 'Self' },
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -13,7 +13,12 @@ export const useMacros = () => {
|
||||
|
||||
const labels = computed(() => getters['labels/getLabels'].value);
|
||||
const teams = computed(() => getters['teams/getTeams'].value);
|
||||
const agents = computed(() => getters['agents/getAgents'].value);
|
||||
const agents = computed(() => getters['agents/getVerifiedAgents'].value);
|
||||
|
||||
const withNoneOption = options => [
|
||||
{ id: 'nil', name: t('AUTOMATION.NONE_OPTION') },
|
||||
...(options || []),
|
||||
];
|
||||
|
||||
/**
|
||||
* Get dropdown values based on the specified type
|
||||
@@ -23,10 +28,15 @@ export const useMacros = () => {
|
||||
const getMacroDropdownValues = type => {
|
||||
switch (type) {
|
||||
case 'assign_team':
|
||||
return withNoneOption(teams.value);
|
||||
case 'send_email_to_team':
|
||||
return teams.value;
|
||||
case 'assign_agent':
|
||||
return [{ id: 'self', name: 'Self' }, ...agents.value];
|
||||
return [
|
||||
...withNoneOption(),
|
||||
{ id: 'self', name: 'Self' },
|
||||
...agents.value,
|
||||
];
|
||||
case 'add_label':
|
||||
case 'remove_label':
|
||||
return labels.value.map(i => ({
|
||||
|
||||
@@ -8,7 +8,7 @@ export const DEFAULT_MESSAGE_CREATED_CONDITION = [
|
||||
},
|
||||
];
|
||||
|
||||
export const DEFAULT_CONVERSATION_OPENED_CONDITION = [
|
||||
export const DEFAULT_CONVERSATION_CONDITION = [
|
||||
{
|
||||
attribute_key: 'browser_language',
|
||||
filter_operator: 'equal_to',
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
} from 'dashboard/routes/dashboard/settings/automation/operators';
|
||||
import {
|
||||
DEFAULT_MESSAGE_CREATED_CONDITION,
|
||||
DEFAULT_CONVERSATION_OPENED_CONDITION,
|
||||
DEFAULT_CONVERSATION_CONDITION,
|
||||
DEFAULT_OTHER_CONDITION,
|
||||
DEFAULT_ACTIONS,
|
||||
} from 'dashboard/constants/automation';
|
||||
@@ -169,8 +169,11 @@ export const getDefaultConditions = eventName => {
|
||||
if (eventName === 'message_created') {
|
||||
return DEFAULT_MESSAGE_CREATED_CONDITION;
|
||||
}
|
||||
if (eventName === 'conversation_opened') {
|
||||
return DEFAULT_CONVERSATION_OPENED_CONDITION;
|
||||
if (
|
||||
eventName === 'conversation_opened' ||
|
||||
eventName === 'conversation_resolved'
|
||||
) {
|
||||
return DEFAULT_CONVERSATION_CONDITION;
|
||||
}
|
||||
return DEFAULT_OTHER_CONDITION;
|
||||
};
|
||||
|
||||
@@ -45,6 +45,10 @@ describe('#resolveTeamIds', () => {
|
||||
const resolvedTeams = '⚙️ sales team, 🤷♂️ fayaz';
|
||||
expect(resolveTeamIds(teams, [1, 2])).toEqual(resolvedTeams);
|
||||
});
|
||||
|
||||
it('resolves nil as None', () => {
|
||||
expect(resolveTeamIds(teams, ['nil'])).toEqual('None');
|
||||
});
|
||||
});
|
||||
|
||||
describe('#resolveLabels', () => {
|
||||
@@ -59,6 +63,10 @@ describe('#resolveAgents', () => {
|
||||
const resolvedAgents = 'John Doe';
|
||||
expect(resolveAgents(agents, [1])).toEqual(resolvedAgents);
|
||||
});
|
||||
|
||||
it('resolves nil and self values', () => {
|
||||
expect(resolveAgents(agents, ['nil', 'self'])).toEqual('None, Self');
|
||||
});
|
||||
});
|
||||
|
||||
describe('#getFileName', () => {
|
||||
|
||||
@@ -0,0 +1,368 @@
|
||||
import {
|
||||
replaceTemplateVariables,
|
||||
buildTemplateParameters,
|
||||
processVariable,
|
||||
allKeysRequired,
|
||||
} from '../templateHelper';
|
||||
import { templates } from '../../store/modules/specs/inboxes/templateFixtures';
|
||||
|
||||
describe('templateHelper', () => {
|
||||
const technicianTemplate = templates.find(t => t.name === 'technician_visit');
|
||||
|
||||
describe('processVariable', () => {
|
||||
it('should remove curly braces from variables', () => {
|
||||
expect(processVariable('{{name}}')).toBe('name');
|
||||
expect(processVariable('{{1}}')).toBe('1');
|
||||
expect(processVariable('{{customer_id}}')).toBe('customer_id');
|
||||
});
|
||||
});
|
||||
|
||||
describe('allKeysRequired', () => {
|
||||
it('should return true when all keys have values', () => {
|
||||
const obj = { name: 'John', age: '30' };
|
||||
expect(allKeysRequired(obj)).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false when some keys are empty', () => {
|
||||
const obj = { name: 'John', age: '' };
|
||||
expect(allKeysRequired(obj)).toBe(false);
|
||||
});
|
||||
|
||||
it('should return true for empty object', () => {
|
||||
expect(allKeysRequired({})).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('replaceTemplateVariables', () => {
|
||||
const templateText =
|
||||
"Hi {{1}}, we're scheduling a technician visit to {{2}} on {{3}} between {{4}} and {{5}}. Please confirm if this time slot works for you.";
|
||||
|
||||
it('should replace all variables with provided values', () => {
|
||||
const processedParams = {
|
||||
body: {
|
||||
1: 'John',
|
||||
2: '123 Main St',
|
||||
3: '2025-01-15',
|
||||
4: '10:00 AM',
|
||||
5: '2:00 PM',
|
||||
},
|
||||
};
|
||||
|
||||
const result = replaceTemplateVariables(templateText, processedParams);
|
||||
expect(result).toBe(
|
||||
"Hi John, we're scheduling a technician visit to 123 Main St on 2025-01-15 between 10:00 AM and 2:00 PM. Please confirm if this time slot works for you."
|
||||
);
|
||||
});
|
||||
|
||||
it('should keep original variable format when no replacement value provided', () => {
|
||||
const processedParams = {
|
||||
body: {
|
||||
1: 'John',
|
||||
3: '2025-01-15',
|
||||
},
|
||||
};
|
||||
|
||||
const result = replaceTemplateVariables(templateText, processedParams);
|
||||
expect(result).toContain('John');
|
||||
expect(result).toContain('2025-01-15');
|
||||
expect(result).toContain('{{2}}');
|
||||
expect(result).toContain('{{4}}');
|
||||
expect(result).toContain('{{5}}');
|
||||
});
|
||||
|
||||
it('should handle empty processedParams', () => {
|
||||
const result = replaceTemplateVariables(templateText, {});
|
||||
expect(result).toBe(templateText);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildTemplateParameters', () => {
|
||||
it('should build parameters for template with body variables', () => {
|
||||
const result = buildTemplateParameters(technicianTemplate, false);
|
||||
|
||||
expect(result.body).toEqual({
|
||||
1: '',
|
||||
2: '',
|
||||
3: '',
|
||||
4: '',
|
||||
5: '',
|
||||
});
|
||||
});
|
||||
|
||||
it('should include header parameters when hasMediaHeader is true', () => {
|
||||
const imageTemplate = templates.find(
|
||||
t => t.name === 'order_confirmation'
|
||||
);
|
||||
const result = buildTemplateParameters(imageTemplate, true);
|
||||
|
||||
expect(result.header).toEqual({
|
||||
media_url: '',
|
||||
media_type: 'image',
|
||||
});
|
||||
});
|
||||
|
||||
it('should not include header parameters when hasMediaHeader is false', () => {
|
||||
const result = buildTemplateParameters(technicianTemplate, false);
|
||||
expect(result.header).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should handle template with no body component', () => {
|
||||
const templateWithoutBody = {
|
||||
components: [{ type: 'HEADER', format: 'TEXT' }],
|
||||
};
|
||||
|
||||
const result = buildTemplateParameters(templateWithoutBody, false);
|
||||
expect(result).toEqual({});
|
||||
});
|
||||
|
||||
it('should handle template with no variables', () => {
|
||||
const templateWithoutVars = templates.find(
|
||||
t => t.name === 'no_variable_template'
|
||||
);
|
||||
const result = buildTemplateParameters(templateWithoutVars, false);
|
||||
|
||||
expect(result.body).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should handle URL buttons with variables for non-authentication templates', () => {
|
||||
const templateWithUrlButton = {
|
||||
category: 'MARKETING',
|
||||
components: [
|
||||
{
|
||||
type: 'BODY',
|
||||
text: 'Check out our website at {{site_url}}',
|
||||
},
|
||||
{
|
||||
type: 'BUTTONS',
|
||||
buttons: [
|
||||
{
|
||||
type: 'URL',
|
||||
url: 'https://example.com/{{campaign_id}}',
|
||||
text: 'Visit Site',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = buildTemplateParameters(templateWithUrlButton, false);
|
||||
expect(result.buttons).toEqual([
|
||||
{
|
||||
type: 'url',
|
||||
parameter: '',
|
||||
url: 'https://example.com/{{campaign_id}}',
|
||||
variables: ['campaign_id'],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('should handle templates with no variables', () => {
|
||||
const emptyTemplate = templates.find(
|
||||
t => t.name === 'no_variable_template'
|
||||
);
|
||||
const result = buildTemplateParameters(emptyTemplate, false);
|
||||
expect(result).toEqual({});
|
||||
});
|
||||
|
||||
it('should build parameters for templates with multiple component types', () => {
|
||||
const complexTemplate = {
|
||||
components: [
|
||||
{ type: 'HEADER', format: 'IMAGE' },
|
||||
{ type: 'BODY', text: 'Hi {{1}}, your order {{2}} is ready!' },
|
||||
{ type: 'FOOTER', text: 'Thank you for your business' },
|
||||
{
|
||||
type: 'BUTTONS',
|
||||
buttons: [{ type: 'URL', url: 'https://example.com/{{3}}' }],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = buildTemplateParameters(complexTemplate, true);
|
||||
|
||||
expect(result.header).toEqual({
|
||||
media_url: '',
|
||||
media_type: 'image',
|
||||
});
|
||||
expect(result.body).toEqual({ 1: '', 2: '' });
|
||||
expect(result.buttons).toEqual([
|
||||
{
|
||||
type: 'url',
|
||||
parameter: '',
|
||||
url: 'https://example.com/{{3}}',
|
||||
variables: ['3'],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('should handle copy code buttons correctly', () => {
|
||||
const copyCodeTemplate = templates.find(
|
||||
t => t.name === 'discount_coupon'
|
||||
);
|
||||
const result = buildTemplateParameters(copyCodeTemplate, false);
|
||||
|
||||
expect(result.body).toBeDefined();
|
||||
expect(result.buttons).toEqual([
|
||||
{
|
||||
type: 'copy_code',
|
||||
parameter: '',
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('should handle templates with document headers', () => {
|
||||
const documentTemplate = templates.find(
|
||||
t => t.name === 'purchase_receipt'
|
||||
);
|
||||
const result = buildTemplateParameters(documentTemplate, true);
|
||||
|
||||
expect(result.header).toEqual({
|
||||
media_url: '',
|
||||
media_type: 'document',
|
||||
});
|
||||
expect(result.body).toEqual({
|
||||
1: '',
|
||||
2: '',
|
||||
3: '',
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle video header templates', () => {
|
||||
const videoTemplate = templates.find(t => t.name === 'training_video');
|
||||
const result = buildTemplateParameters(videoTemplate, true);
|
||||
|
||||
expect(result.header).toEqual({
|
||||
media_url: '',
|
||||
media_type: 'video',
|
||||
});
|
||||
expect(result.body).toEqual({
|
||||
name: '',
|
||||
date: '',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('enhanced format validation', () => {
|
||||
it('should validate enhanced format structure', () => {
|
||||
const processedParams = {
|
||||
body: { 1: 'John', 2: 'Order123' },
|
||||
header: {
|
||||
media_url: 'https://example.com/image.jpg',
|
||||
media_type: 'image',
|
||||
},
|
||||
buttons: [{ type: 'copy_code', parameter: 'SAVE20' }],
|
||||
};
|
||||
|
||||
// Test that structure is properly formed
|
||||
expect(processedParams.body).toBeDefined();
|
||||
expect(typeof processedParams.body).toBe('object');
|
||||
expect(processedParams.header).toBeDefined();
|
||||
expect(Array.isArray(processedParams.buttons)).toBe(true);
|
||||
});
|
||||
|
||||
it('should handle empty component sections', () => {
|
||||
const processedParams = {
|
||||
body: {},
|
||||
header: {},
|
||||
buttons: [],
|
||||
};
|
||||
|
||||
expect(allKeysRequired(processedParams.body)).toBe(true);
|
||||
expect(allKeysRequired(processedParams.header)).toBe(true);
|
||||
expect(processedParams.buttons.length).toBe(0);
|
||||
});
|
||||
|
||||
it('should validate parameter completeness', () => {
|
||||
const incompleteParams = {
|
||||
body: { 1: 'John', 2: '' },
|
||||
};
|
||||
|
||||
expect(allKeysRequired(incompleteParams.body)).toBe(false);
|
||||
});
|
||||
|
||||
it('should handle edge cases in processVariable', () => {
|
||||
expect(processVariable('{{')).toBe('');
|
||||
expect(processVariable('}}')).toBe('');
|
||||
expect(processVariable('')).toBe('');
|
||||
expect(processVariable('{{nested{{variable}}}}')).toBe('nestedvariable');
|
||||
});
|
||||
|
||||
it('should handle special characters in template variables', () => {
|
||||
/* eslint-disable no-template-curly-in-string */
|
||||
const templateText =
|
||||
'Welcome {{user_name}}, your order #{{order_id}} costs ${{amount}}';
|
||||
/* eslint-enable no-template-curly-in-string */
|
||||
const processedParams = {
|
||||
body: {
|
||||
user_name: 'John & Jane',
|
||||
order_id: '12345',
|
||||
amount: '99.99',
|
||||
},
|
||||
};
|
||||
|
||||
const result = replaceTemplateVariables(templateText, processedParams);
|
||||
expect(result).toBe(
|
||||
'Welcome John & Jane, your order #12345 costs $99.99'
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle templates with mixed parameter types', () => {
|
||||
const mixedTemplate = {
|
||||
components: [
|
||||
{ type: 'HEADER', format: 'VIDEO' },
|
||||
{ type: 'BODY', text: 'Order {{order_id}} status: {{status}}' },
|
||||
{ type: 'FOOTER', text: 'Thank you' },
|
||||
{
|
||||
type: 'BUTTONS',
|
||||
buttons: [
|
||||
{ type: 'URL', url: 'https://track.com/{{order_id}}' },
|
||||
{ type: 'COPY_CODE' },
|
||||
{ type: 'PHONE_NUMBER', phone_number: '+1234567890' },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = buildTemplateParameters(mixedTemplate, true);
|
||||
|
||||
expect(result.header).toEqual({
|
||||
media_url: '',
|
||||
media_type: 'video',
|
||||
});
|
||||
expect(result.body).toEqual({
|
||||
order_id: '',
|
||||
status: '',
|
||||
});
|
||||
expect(result.buttons).toHaveLength(2); // URL and COPY_CODE (PHONE_NUMBER doesn't need parameters)
|
||||
expect(result.buttons[0].type).toBe('url');
|
||||
expect(result.buttons[1].type).toBe('copy_code');
|
||||
});
|
||||
|
||||
it('should handle templates with no processable components', () => {
|
||||
const emptyTemplate = {
|
||||
components: [
|
||||
{ type: 'HEADER', format: 'TEXT', text: 'Static Header' },
|
||||
{ type: 'BODY', text: 'Static body with no variables' },
|
||||
{ type: 'FOOTER', text: 'Static footer' },
|
||||
],
|
||||
};
|
||||
|
||||
const result = buildTemplateParameters(emptyTemplate, false);
|
||||
expect(result).toEqual({});
|
||||
});
|
||||
|
||||
it('should validate that replaceTemplateVariables preserves unreplaced variables', () => {
|
||||
const templateText = 'Hi {{name}}, order {{order_id}} is {{status}}';
|
||||
const partialParams = {
|
||||
body: {
|
||||
name: 'John',
|
||||
// order_id missing
|
||||
status: 'ready',
|
||||
},
|
||||
};
|
||||
|
||||
const result = replaceTemplateVariables(templateText, partialParams);
|
||||
expect(result).toBe('Hi John, order {{order_id}} is ready');
|
||||
expect(result).toContain('{{order_id}}'); // Unreplaced variable preserved
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
// Constants
|
||||
export const DEFAULT_LANGUAGE = 'en';
|
||||
export const DEFAULT_CATEGORY = 'UTILITY';
|
||||
export const COMPONENT_TYPES = {
|
||||
HEADER: 'HEADER',
|
||||
BODY: 'BODY',
|
||||
BUTTONS: 'BUTTONS',
|
||||
};
|
||||
export const MEDIA_FORMATS = ['IMAGE', 'VIDEO', 'DOCUMENT'];
|
||||
|
||||
export const findComponentByType = (template, type) =>
|
||||
template.components?.find(component => component.type === type);
|
||||
|
||||
export const processVariable = str => {
|
||||
return str.replace(/{{|}}/g, '');
|
||||
};
|
||||
|
||||
export const allKeysRequired = value => {
|
||||
const keys = Object.keys(value);
|
||||
return keys.every(key => value[key]);
|
||||
};
|
||||
|
||||
export const replaceTemplateVariables = (templateText, processedParams) => {
|
||||
return templateText.replace(/{{([^}]+)}}/g, (match, variable) => {
|
||||
const variableKey = processVariable(variable);
|
||||
return processedParams.body?.[variableKey] || `{{${variable}}}`;
|
||||
});
|
||||
};
|
||||
|
||||
export const buildTemplateParameters = (template, hasMediaHeaderValue) => {
|
||||
const allVariables = {};
|
||||
|
||||
const bodyComponent = findComponentByType(template, COMPONENT_TYPES.BODY);
|
||||
const headerComponent = findComponentByType(template, COMPONENT_TYPES.HEADER);
|
||||
|
||||
if (!bodyComponent) return allVariables;
|
||||
|
||||
const templateString = bodyComponent.text;
|
||||
|
||||
// Process body variables
|
||||
const matchedVariables = templateString.match(/{{([^}]+)}}/g);
|
||||
if (matchedVariables) {
|
||||
allVariables.body = {};
|
||||
matchedVariables.forEach(variable => {
|
||||
const key = processVariable(variable);
|
||||
allVariables.body[key] = '';
|
||||
});
|
||||
}
|
||||
|
||||
if (hasMediaHeaderValue) {
|
||||
if (!allVariables.header) allVariables.header = {};
|
||||
allVariables.header.media_url = '';
|
||||
allVariables.header.media_type = headerComponent.format.toLowerCase();
|
||||
}
|
||||
|
||||
// Process button variables
|
||||
const buttonComponents = template.components.filter(
|
||||
component => component.type === COMPONENT_TYPES.BUTTONS
|
||||
);
|
||||
|
||||
buttonComponents.forEach(buttonComponent => {
|
||||
if (buttonComponent.buttons) {
|
||||
buttonComponent.buttons.forEach((button, index) => {
|
||||
// Handle URL buttons with variables
|
||||
if (button.type === 'URL' && button.url && button.url.includes('{{')) {
|
||||
const buttonVars = button.url.match(/{{([^}]+)}}/g) || [];
|
||||
if (buttonVars.length > 0) {
|
||||
if (!allVariables.buttons) allVariables.buttons = [];
|
||||
allVariables.buttons[index] = {
|
||||
type: 'url',
|
||||
parameter: '',
|
||||
url: button.url,
|
||||
variables: buttonVars.map(v => processVariable(v)),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Handle copy code buttons
|
||||
if (button.type === 'COPY_CODE') {
|
||||
if (!allVariables.buttons) allVariables.buttons = [];
|
||||
allVariables.buttons[index] = {
|
||||
type: 'copy_code',
|
||||
parameter: '',
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return allVariables;
|
||||
};
|
||||
@@ -125,6 +125,7 @@ const validateSingleAction = action => {
|
||||
'mute_conversation',
|
||||
'snooze_conversation',
|
||||
'resolve_conversation',
|
||||
'remove_assigned_agent',
|
||||
'remove_assigned_team',
|
||||
'open_conversation',
|
||||
];
|
||||
|
||||
@@ -131,11 +131,14 @@
|
||||
"CONVERSATION_CREATED": "Conversation Created",
|
||||
"CONVERSATION_UPDATED": "Conversation Updated",
|
||||
"MESSAGE_CREATED": "Message Created",
|
||||
"CONVERSATION_RESOLVED": "Conversation Resolved",
|
||||
"CONVERSATION_OPENED": "Conversation Opened"
|
||||
},
|
||||
"ACTIONS": {
|
||||
"ASSIGN_AGENT": "Assign to Agent",
|
||||
"ASSIGN_TEAM": "Assign a Team",
|
||||
"REMOVE_ASSIGNED_AGENT": "Remove Assigned Agent",
|
||||
"REMOVE_ASSIGNED_TEAM": "Remove Assigned Team",
|
||||
"ADD_LABEL": "Add a Label",
|
||||
"REMOVE_LABEL": "Remove a Label",
|
||||
"SEND_EMAIL_TO_TEAM": "Send an Email to Team",
|
||||
|
||||
@@ -89,6 +89,7 @@
|
||||
"ASSIGN_AGENT": "Assign an Agent",
|
||||
"ADD_LABEL": "Add a Label",
|
||||
"REMOVE_LABEL": "Remove a Label",
|
||||
"REMOVE_ASSIGNED_AGENT": "Remove Assigned Agent",
|
||||
"REMOVE_ASSIGNED_TEAM": "Remove Assigned Team",
|
||||
"SEND_EMAIL_TRANSCRIPT": "Send an Email Transcript",
|
||||
"MUTE_CONVERSATION": "Mute Conversation",
|
||||
|
||||
@@ -1,29 +1,46 @@
|
||||
{
|
||||
"WHATSAPP_TEMPLATES": {
|
||||
"MODAL": {
|
||||
"TITLE": "Whatsapp Templates",
|
||||
"SUBTITLE": "Select the whatsapp template you want to send",
|
||||
"TEMPLATE_SELECTED_SUBTITLE": "Process {templateName}"
|
||||
},
|
||||
"PICKER": {
|
||||
"SEARCH_PLACEHOLDER": "Search Templates",
|
||||
"NO_TEMPLATES_FOUND": "No templates found for",
|
||||
"NO_TEMPLATES_AVAILABLE": "No WhatsApp templates available. Click refresh to sync templates from WhatsApp.",
|
||||
"REFRESH_BUTTON": "Refresh templates",
|
||||
"REFRESH_SUCCESS": "Templates refresh initiated. It may take a couple of minutes to update.",
|
||||
"REFRESH_ERROR": "Failed to refresh templates. Please try again.",
|
||||
"LABELS": {
|
||||
"LANGUAGE": "Language",
|
||||
"TEMPLATE_BODY": "Template Body",
|
||||
"CATEGORY": "Category"
|
||||
}
|
||||
},
|
||||
"PARSER": {
|
||||
"VARIABLES_LABEL": "Variables",
|
||||
"VARIABLE_PLACEHOLDER": "Enter {variable} value",
|
||||
"GO_BACK_LABEL": "Go Back",
|
||||
"SEND_MESSAGE_LABEL": "Send Message",
|
||||
"FORM_ERROR_MESSAGE": "Please fill all variables before sending"
|
||||
}
|
||||
"WHATSAPP_TEMPLATES": {
|
||||
"MODAL": {
|
||||
"TITLE": "Whatsapp Templates",
|
||||
"SUBTITLE": "Select the whatsapp template you want to send",
|
||||
"TEMPLATE_SELECTED_SUBTITLE": "Configure template: {templateName}"
|
||||
},
|
||||
"PICKER": {
|
||||
"SEARCH_PLACEHOLDER": "Search Templates",
|
||||
"NO_TEMPLATES_FOUND": "No templates found for",
|
||||
"HEADER": "Header",
|
||||
"BODY": "Body",
|
||||
"FOOTER": "Footer",
|
||||
"BUTTONS": "Buttons",
|
||||
"CATEGORY": "Category",
|
||||
"MEDIA_CONTENT": "Media Content",
|
||||
"MEDIA_CONTENT_FALLBACK": "media content",
|
||||
"NO_TEMPLATES_AVAILABLE": "No WhatsApp templates available. Click refresh to sync templates from WhatsApp.",
|
||||
"REFRESH_BUTTON": "Refresh templates",
|
||||
"REFRESH_SUCCESS": "Templates refresh initiated. It may take a couple of minutes to update.",
|
||||
"REFRESH_ERROR": "Failed to refresh templates. Please try again.",
|
||||
"LABELS": {
|
||||
"LANGUAGE": "Language",
|
||||
"TEMPLATE_BODY": "Template Body",
|
||||
"CATEGORY": "Category"
|
||||
}
|
||||
},
|
||||
"PARSER": {
|
||||
"VARIABLES_LABEL": "Variables",
|
||||
"LANGUAGE": "Language",
|
||||
"CATEGORY": "Category",
|
||||
"VARIABLE_PLACEHOLDER": "Enter {variable} value",
|
||||
"GO_BACK_LABEL": "Go Back",
|
||||
"SEND_MESSAGE_LABEL": "Send Message",
|
||||
"FORM_ERROR_MESSAGE": "Please fill all variables before sending",
|
||||
"MEDIA_HEADER_LABEL": "{type} Header",
|
||||
"OTP_CODE": "Enter 4-8 digit OTP",
|
||||
"EXPIRY_MINUTES": "Enter expiry minutes",
|
||||
"BUTTON_PARAMETERS": "Button Parameters",
|
||||
"BUTTON_LABEL": "Button {index}",
|
||||
"COUPON_CODE": "Enter coupon code (max 15 chars)",
|
||||
"MEDIA_URL_LABEL": "Enter {type} URL",
|
||||
"BUTTON_PARAMETER": "Enter button parameter"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ const getActionValue = (key, params) => {
|
||||
add_label: resolveLabels(labels.value, params),
|
||||
remove_label: resolveLabels(labels.value, params),
|
||||
assign_agent: resolveAgents(agents.value, params),
|
||||
remove_assigned_agent: null,
|
||||
mute_conversation: null,
|
||||
snooze_conversation: null,
|
||||
resolve_conversation: null,
|
||||
|
||||
@@ -78,6 +78,14 @@ export const AUTOMATIONS = {
|
||||
key: 'assign_team',
|
||||
name: 'ASSIGN_TEAM',
|
||||
},
|
||||
{
|
||||
key: 'remove_assigned_agent',
|
||||
name: 'REMOVE_ASSIGNED_AGENT',
|
||||
},
|
||||
{
|
||||
key: 'remove_assigned_team',
|
||||
name: 'REMOVE_ASSIGNED_TEAM',
|
||||
},
|
||||
{
|
||||
key: 'add_label',
|
||||
name: 'ADD_LABEL',
|
||||
@@ -196,6 +204,14 @@ export const AUTOMATIONS = {
|
||||
key: 'assign_team',
|
||||
name: 'ASSIGN_TEAM',
|
||||
},
|
||||
{
|
||||
key: 'remove_assigned_agent',
|
||||
name: 'REMOVE_ASSIGNED_AGENT',
|
||||
},
|
||||
{
|
||||
key: 'remove_assigned_team',
|
||||
name: 'REMOVE_ASSIGNED_TEAM',
|
||||
},
|
||||
{
|
||||
key: 'assign_agent',
|
||||
name: 'ASSIGN_AGENT',
|
||||
@@ -318,6 +334,14 @@ export const AUTOMATIONS = {
|
||||
key: 'assign_team',
|
||||
name: 'ASSIGN_TEAM',
|
||||
},
|
||||
{
|
||||
key: 'remove_assigned_agent',
|
||||
name: 'REMOVE_ASSIGNED_AGENT',
|
||||
},
|
||||
{
|
||||
key: 'remove_assigned_team',
|
||||
name: 'REMOVE_ASSIGNED_TEAM',
|
||||
},
|
||||
{
|
||||
key: 'assign_agent',
|
||||
name: 'ASSIGN_AGENT',
|
||||
@@ -434,6 +458,14 @@ export const AUTOMATIONS = {
|
||||
key: 'assign_team',
|
||||
name: 'ASSIGN_TEAM',
|
||||
},
|
||||
{
|
||||
key: 'remove_assigned_agent',
|
||||
name: 'REMOVE_ASSIGNED_AGENT',
|
||||
},
|
||||
{
|
||||
key: 'remove_assigned_team',
|
||||
name: 'REMOVE_ASSIGNED_TEAM',
|
||||
},
|
||||
{
|
||||
key: 'assign_agent',
|
||||
name: 'ASSIGN_AGENT',
|
||||
@@ -468,6 +500,114 @@ export const AUTOMATIONS = {
|
||||
},
|
||||
],
|
||||
},
|
||||
conversation_resolved: {
|
||||
conditions: [
|
||||
{
|
||||
key: 'browser_language',
|
||||
name: 'BROWSER_LANGUAGE',
|
||||
inputType: 'search_select',
|
||||
filterOperators: OPERATOR_TYPES_1,
|
||||
},
|
||||
{
|
||||
key: 'email',
|
||||
name: 'EMAIL',
|
||||
inputType: 'plain_text',
|
||||
filterOperators: OPERATOR_TYPES_2,
|
||||
},
|
||||
{
|
||||
key: 'mail_subject',
|
||||
name: 'MAIL_SUBJECT',
|
||||
inputType: 'plain_text',
|
||||
filterOperators: OPERATOR_TYPES_2,
|
||||
},
|
||||
{
|
||||
key: 'country_code',
|
||||
name: 'COUNTRY_NAME',
|
||||
inputType: 'search_select',
|
||||
filterOperators: OPERATOR_TYPES_1,
|
||||
},
|
||||
{
|
||||
key: 'referer',
|
||||
name: 'REFERER_LINK',
|
||||
inputType: 'plain_text',
|
||||
filterOperators: OPERATOR_TYPES_2,
|
||||
},
|
||||
{
|
||||
key: 'assignee_id',
|
||||
name: 'ASSIGNEE_NAME',
|
||||
inputType: 'search_select',
|
||||
filterOperators: OPERATOR_TYPES_3,
|
||||
},
|
||||
{
|
||||
key: 'phone_number',
|
||||
name: 'PHONE_NUMBER',
|
||||
inputType: 'plain_text',
|
||||
filterOperators: OPERATOR_TYPES_6,
|
||||
},
|
||||
{
|
||||
key: 'team_id',
|
||||
name: 'TEAM_NAME',
|
||||
inputType: 'search_select',
|
||||
filterOperators: OPERATOR_TYPES_3,
|
||||
},
|
||||
{
|
||||
key: 'inbox_id',
|
||||
name: 'INBOX',
|
||||
inputType: 'multi_select',
|
||||
filterOperators: OPERATOR_TYPES_1,
|
||||
},
|
||||
{
|
||||
key: 'conversation_language',
|
||||
name: 'CONVERSATION_LANGUAGE',
|
||||
inputType: 'multi_select',
|
||||
filterOperators: OPERATOR_TYPES_1,
|
||||
},
|
||||
{
|
||||
key: 'priority',
|
||||
name: 'PRIORITY',
|
||||
inputType: 'multi_select',
|
||||
filterOperators: OPERATOR_TYPES_1,
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{
|
||||
key: 'assign_agent',
|
||||
name: 'ASSIGN_AGENT',
|
||||
},
|
||||
{
|
||||
key: 'assign_team',
|
||||
name: 'ASSIGN_TEAM',
|
||||
},
|
||||
{
|
||||
key: 'remove_assigned_agent',
|
||||
name: 'REMOVE_ASSIGNED_AGENT',
|
||||
},
|
||||
{
|
||||
key: 'remove_assigned_team',
|
||||
name: 'REMOVE_ASSIGNED_TEAM',
|
||||
},
|
||||
{
|
||||
key: 'send_email_to_team',
|
||||
name: 'SEND_EMAIL_TO_TEAM',
|
||||
},
|
||||
{
|
||||
key: 'send_message',
|
||||
name: 'SEND_MESSAGE',
|
||||
},
|
||||
{
|
||||
key: 'send_email_transcript',
|
||||
name: 'SEND_EMAIL_TRANSCRIPT',
|
||||
},
|
||||
{
|
||||
key: 'send_webhook_event',
|
||||
name: 'SEND_WEBHOOK_EVENT',
|
||||
},
|
||||
{
|
||||
key: 'send_attachment',
|
||||
name: 'SEND_ATTACHMENT',
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
export const AUTOMATION_RULE_EVENTS = [
|
||||
@@ -479,6 +619,10 @@ export const AUTOMATION_RULE_EVENTS = [
|
||||
key: 'conversation_updated',
|
||||
value: 'CONVERSATION_UPDATED',
|
||||
},
|
||||
{
|
||||
key: 'conversation_resolved',
|
||||
value: 'CONVERSATION_RESOLVED',
|
||||
},
|
||||
{
|
||||
key: 'message_created',
|
||||
value: 'MESSAGE_CREATED',
|
||||
@@ -500,6 +644,16 @@ export const AUTOMATION_ACTION_TYPES = [
|
||||
label: 'ASSIGN_TEAM',
|
||||
inputType: 'search_select',
|
||||
},
|
||||
{
|
||||
key: 'remove_assigned_agent',
|
||||
label: 'REMOVE_ASSIGNED_AGENT',
|
||||
inputType: null,
|
||||
},
|
||||
{
|
||||
key: 'remove_assigned_team',
|
||||
label: 'REMOVE_ASSIGNED_TEAM',
|
||||
inputType: null,
|
||||
},
|
||||
{
|
||||
key: 'add_label',
|
||||
label: 'ADD_LABEL',
|
||||
|
||||
@@ -58,7 +58,9 @@ const formatMacro = macroData => {
|
||||
),
|
||||
message: action.action_params[0].message,
|
||||
};
|
||||
} else actionParams = [...action.action_params];
|
||||
} else {
|
||||
actionParams = [...action.action_params];
|
||||
}
|
||||
}
|
||||
return {
|
||||
...action,
|
||||
|
||||
@@ -19,6 +19,11 @@ export const MACRO_ACTION_TYPES = [
|
||||
label: 'REMOVE_LABEL',
|
||||
inputType: 'multi_select',
|
||||
},
|
||||
{
|
||||
key: 'remove_assigned_agent',
|
||||
label: 'REMOVE_ASSIGNED_AGENT',
|
||||
inputType: null,
|
||||
},
|
||||
{
|
||||
key: 'remove_assigned_team',
|
||||
label: 'REMOVE_ASSIGNED_TEAM',
|
||||
|
||||
@@ -17,6 +17,7 @@ export const resolveActionName = key => {
|
||||
export const resolveTeamIds = (teams, ids) => {
|
||||
return ids
|
||||
.map(id => {
|
||||
if (id === 'nil') return 'None';
|
||||
const team = teams.find(i => i.id === id);
|
||||
return team ? team.name : '';
|
||||
})
|
||||
@@ -35,6 +36,8 @@ export const resolveLabels = (labels, ids) => {
|
||||
export const resolveAgents = (agents, ids) => {
|
||||
return ids
|
||||
.map(id => {
|
||||
if (id === 'nil') return 'None';
|
||||
if (id === 'self') return 'Self';
|
||||
const agent = agents.find(i => i.id === id);
|
||||
return agent ? agent.name : '';
|
||||
})
|
||||
|
||||
@@ -44,15 +44,52 @@ export const getters = {
|
||||
const messagesTemplates =
|
||||
whatsAppMessageTemplates || apiInboxMessageTemplates;
|
||||
|
||||
// filtering out the whatsapp templates with media
|
||||
if (messagesTemplates instanceof Array) {
|
||||
return messagesTemplates.filter(template => {
|
||||
return !template.components.some(
|
||||
i => i.format === 'IMAGE' || i.format === 'VIDEO'
|
||||
);
|
||||
});
|
||||
return messagesTemplates;
|
||||
},
|
||||
getFilteredWhatsAppTemplates: $state => inboxId => {
|
||||
const [inbox] = $state.records.filter(
|
||||
record => record.id === Number(inboxId)
|
||||
);
|
||||
|
||||
const {
|
||||
message_templates: whatsAppMessageTemplates,
|
||||
additional_attributes: additionalAttributes,
|
||||
} = inbox || {};
|
||||
|
||||
const { message_templates: apiInboxMessageTemplates } =
|
||||
additionalAttributes || {};
|
||||
const templates = whatsAppMessageTemplates || apiInboxMessageTemplates;
|
||||
|
||||
if (!templates || !Array.isArray(templates)) {
|
||||
return [];
|
||||
}
|
||||
return [];
|
||||
|
||||
return templates.filter(template => {
|
||||
// Ensure template has required properties
|
||||
if (!template || !template.status || !template.components) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Only show approved templates
|
||||
if (template.status.toLowerCase() !== 'approved') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Filter out interactive templates (LIST, PRODUCT, CATALOG), location templates, and call permission templates
|
||||
const hasUnsupportedComponents = template.components.some(
|
||||
component =>
|
||||
['LIST', 'PRODUCT', 'CATALOG', 'CALL_PERMISSION_REQUEST'].includes(
|
||||
component.type
|
||||
) ||
|
||||
(component.type === 'HEADER' && component.format === 'LOCATION')
|
||||
);
|
||||
|
||||
if (hasUnsupportedComponents) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
},
|
||||
getNewConversationInboxes($state) {
|
||||
return $state.records.filter(inbox => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { getters } from '../../inboxes';
|
||||
import inboxList from './fixtures';
|
||||
import { templates } from './templateFixtures';
|
||||
|
||||
describe('#getters', () => {
|
||||
it('getInboxes', () => {
|
||||
@@ -93,4 +94,269 @@ describe('#getters', () => {
|
||||
provider: 'default',
|
||||
});
|
||||
});
|
||||
|
||||
describe('getFilteredWhatsAppTemplates', () => {
|
||||
it('returns empty array when inbox not found', () => {
|
||||
const state = { records: [] };
|
||||
expect(getters.getFilteredWhatsAppTemplates(state)(999)).toEqual([]);
|
||||
});
|
||||
|
||||
it('returns empty array when templates is null or undefined', () => {
|
||||
const state = {
|
||||
records: [
|
||||
{
|
||||
id: 1,
|
||||
channel_type: 'Channel::Whatsapp',
|
||||
message_templates: null,
|
||||
additional_attributes: { message_templates: undefined },
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(getters.getFilteredWhatsAppTemplates(state)(1)).toEqual([]);
|
||||
});
|
||||
|
||||
it('returns empty array when templates is not an array', () => {
|
||||
const state = {
|
||||
records: [
|
||||
{
|
||||
id: 1,
|
||||
channel_type: 'Channel::Whatsapp',
|
||||
message_templates: 'invalid',
|
||||
additional_attributes: {},
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(getters.getFilteredWhatsAppTemplates(state)(1)).toEqual([]);
|
||||
});
|
||||
|
||||
it('filters out templates without required properties', () => {
|
||||
const invalidTemplates = [
|
||||
{ name: 'incomplete_template' }, // missing status and components
|
||||
{ status: 'approved' }, // missing name and components
|
||||
{ name: 'another_incomplete', status: 'approved' }, // missing components
|
||||
];
|
||||
|
||||
const state = {
|
||||
records: [
|
||||
{
|
||||
id: 1,
|
||||
channel_type: 'Channel::Whatsapp',
|
||||
message_templates: invalidTemplates,
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(getters.getFilteredWhatsAppTemplates(state)(1)).toEqual([]);
|
||||
});
|
||||
|
||||
it('filters out non-approved templates', () => {
|
||||
const mixedStatusTemplates = [
|
||||
{
|
||||
name: 'pending_template',
|
||||
status: 'pending',
|
||||
components: [{ type: 'BODY', text: 'Test' }],
|
||||
},
|
||||
{
|
||||
name: 'rejected_template',
|
||||
status: 'rejected',
|
||||
components: [{ type: 'BODY', text: 'Test' }],
|
||||
},
|
||||
{
|
||||
name: 'approved_template',
|
||||
status: 'approved',
|
||||
components: [{ type: 'BODY', text: 'Test' }],
|
||||
},
|
||||
];
|
||||
|
||||
const state = {
|
||||
records: [
|
||||
{
|
||||
id: 1,
|
||||
channel_type: 'Channel::Whatsapp',
|
||||
message_templates: mixedStatusTemplates,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = getters.getFilteredWhatsAppTemplates(state)(1);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].name).toBe('approved_template');
|
||||
});
|
||||
|
||||
it('filters out interactive templates (LIST, PRODUCT, CATALOG)', () => {
|
||||
const interactiveTemplates = [
|
||||
{
|
||||
name: 'list_template',
|
||||
status: 'approved',
|
||||
components: [
|
||||
{ type: 'BODY', text: 'Choose an option' },
|
||||
{ type: 'LIST', sections: [] },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'product_template',
|
||||
status: 'approved',
|
||||
components: [
|
||||
{ type: 'BODY', text: 'Product info' },
|
||||
{ type: 'PRODUCT', catalog_id: '123' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'catalog_template',
|
||||
status: 'approved',
|
||||
components: [
|
||||
{ type: 'BODY', text: 'Catalog' },
|
||||
{ type: 'CATALOG', thumbnail_product_retailer_id: '123' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'regular_template',
|
||||
status: 'approved',
|
||||
components: [{ type: 'BODY', text: 'Regular message' }],
|
||||
},
|
||||
];
|
||||
|
||||
const state = {
|
||||
records: [
|
||||
{
|
||||
id: 1,
|
||||
channel_type: 'Channel::Whatsapp',
|
||||
message_templates: interactiveTemplates,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = getters.getFilteredWhatsAppTemplates(state)(1);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].name).toBe('regular_template');
|
||||
});
|
||||
|
||||
it('filters out location templates', () => {
|
||||
const locationTemplates = [
|
||||
{
|
||||
name: 'location_template',
|
||||
status: 'approved',
|
||||
components: [
|
||||
{ type: 'HEADER', format: 'LOCATION' },
|
||||
{ type: 'BODY', text: 'Location message' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'regular_template',
|
||||
status: 'approved',
|
||||
components: [
|
||||
{ type: 'HEADER', format: 'TEXT', text: 'Header' },
|
||||
{ type: 'BODY', text: 'Regular message' },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const state = {
|
||||
records: [
|
||||
{
|
||||
id: 1,
|
||||
channel_type: 'Channel::Whatsapp',
|
||||
message_templates: locationTemplates,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = getters.getFilteredWhatsAppTemplates(state)(1);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].name).toBe('regular_template');
|
||||
});
|
||||
|
||||
it('returns valid templates from fixture data', () => {
|
||||
const state = {
|
||||
records: [
|
||||
{
|
||||
id: 1,
|
||||
channel_type: 'Channel::Whatsapp',
|
||||
message_templates: templates,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = getters.getFilteredWhatsAppTemplates(state)(1);
|
||||
|
||||
// All templates in fixtures should be approved and valid
|
||||
expect(result.length).toBeGreaterThan(0);
|
||||
|
||||
// Verify all returned templates are approved
|
||||
result.forEach(template => {
|
||||
expect(template.status).toBe('approved');
|
||||
expect(template.components).toBeDefined();
|
||||
expect(Array.isArray(template.components)).toBe(true);
|
||||
});
|
||||
|
||||
// Verify specific templates from fixtures are included
|
||||
const templateNames = result.map(t => t.name);
|
||||
expect(templateNames).toContain('sample_flight_confirmation');
|
||||
expect(templateNames).toContain('sample_issue_resolution');
|
||||
expect(templateNames).toContain('sample_shipping_confirmation');
|
||||
expect(templateNames).toContain('no_variable_template');
|
||||
expect(templateNames).toContain('order_confirmation');
|
||||
});
|
||||
|
||||
it('prioritizes message_templates over additional_attributes.message_templates', () => {
|
||||
const primaryTemplates = [
|
||||
{
|
||||
name: 'primary_template',
|
||||
status: 'approved',
|
||||
components: [{ type: 'BODY', text: 'Primary' }],
|
||||
},
|
||||
];
|
||||
|
||||
const fallbackTemplates = [
|
||||
{
|
||||
name: 'fallback_template',
|
||||
status: 'approved',
|
||||
components: [{ type: 'BODY', text: 'Fallback' }],
|
||||
},
|
||||
];
|
||||
|
||||
const state = {
|
||||
records: [
|
||||
{
|
||||
id: 1,
|
||||
channel_type: 'Channel::Whatsapp',
|
||||
message_templates: primaryTemplates,
|
||||
additional_attributes: {
|
||||
message_templates: fallbackTemplates,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = getters.getFilteredWhatsAppTemplates(state)(1);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].name).toBe('primary_template');
|
||||
});
|
||||
|
||||
it('falls back to additional_attributes.message_templates when message_templates is null', () => {
|
||||
const fallbackTemplates = [
|
||||
{
|
||||
name: 'fallback_template',
|
||||
status: 'approved',
|
||||
components: [{ type: 'BODY', text: 'Fallback' }],
|
||||
},
|
||||
];
|
||||
|
||||
const state = {
|
||||
records: [
|
||||
{
|
||||
id: 1,
|
||||
channel_type: 'Channel::Whatsapp',
|
||||
message_templates: null,
|
||||
additional_attributes: {
|
||||
message_templates: fallbackTemplates,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = getters.getFilteredWhatsAppTemplates(state)(1);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].name).toBe('fallback_template');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
+281
@@ -260,4 +260,285 @@ export const templates = [
|
||||
],
|
||||
rejected_reason: 'NONE',
|
||||
},
|
||||
{
|
||||
name: 'order_confirmation',
|
||||
status: 'approved',
|
||||
category: 'TICKET_UPDATE',
|
||||
language: 'en_US',
|
||||
namespace: 'ed41a221_133a_4558_a1d6_192960e3aee9',
|
||||
components: [
|
||||
{
|
||||
type: 'HEADER',
|
||||
format: 'IMAGE',
|
||||
example: {
|
||||
header_handle: ['https://example.com/shoes.jpg'],
|
||||
},
|
||||
},
|
||||
{
|
||||
text: 'Hi your order {{1}} is confirmed. Please wait for further updates',
|
||||
type: 'BODY',
|
||||
},
|
||||
],
|
||||
rejected_reason: 'NONE',
|
||||
},
|
||||
{
|
||||
name: 'technician_visit',
|
||||
status: 'approved',
|
||||
category: 'UTILITY',
|
||||
language: 'en_US',
|
||||
namespace: 'ed41a221_133a_4558_a1d6_192960e3aee9',
|
||||
components: [
|
||||
{
|
||||
text: 'Technician visit',
|
||||
type: 'HEADER',
|
||||
format: 'TEXT',
|
||||
},
|
||||
{
|
||||
text: "Hi {{1}}, we're scheduling a technician visit to {{2}} on {{3}} between {{4}} and {{5}}. Please confirm if this time slot works for you.",
|
||||
type: 'BODY',
|
||||
},
|
||||
{
|
||||
type: 'BUTTONS',
|
||||
buttons: [
|
||||
{
|
||||
text: 'Confirm',
|
||||
type: 'QUICK_REPLY',
|
||||
},
|
||||
{
|
||||
text: 'Reschedule',
|
||||
type: 'QUICK_REPLY',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
rejected_reason: 'NONE',
|
||||
},
|
||||
{
|
||||
name: 'event_invitation_static',
|
||||
status: 'approved',
|
||||
category: 'MARKETING',
|
||||
language: 'en',
|
||||
namespace: 'ed41a221_133a_4558_a1d6_192960e3aee9',
|
||||
components: [
|
||||
{
|
||||
text: "You're invited to {{event_name}} at {{location}}, Join us for an amazing experience!",
|
||||
type: 'BODY',
|
||||
},
|
||||
{
|
||||
type: 'BUTTONS',
|
||||
buttons: [
|
||||
{
|
||||
url: 'https://events.example.com/register',
|
||||
text: 'Visit website',
|
||||
type: 'URL',
|
||||
},
|
||||
{
|
||||
url: 'https://maps.app.goo.gl/YoWAzRj1GDuxs6qz8',
|
||||
text: 'Get Directions',
|
||||
type: 'URL',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
rejected_reason: 'NONE',
|
||||
},
|
||||
{
|
||||
name: 'purchase_receipt',
|
||||
status: 'approved',
|
||||
category: 'UTILITY',
|
||||
language: 'en_US',
|
||||
namespace: 'ed41a221_133a_4558_a1d6_192960e3aee9',
|
||||
components: [
|
||||
{
|
||||
type: 'HEADER',
|
||||
format: 'DOCUMENT',
|
||||
},
|
||||
{
|
||||
text: 'Thank you for using your {{1}} card at {{2}}. Your {{3}} is attached as a PDF.',
|
||||
type: 'BODY',
|
||||
},
|
||||
],
|
||||
rejected_reason: 'NONE',
|
||||
},
|
||||
{
|
||||
name: 'discount_coupon',
|
||||
status: 'approved',
|
||||
category: 'MARKETING',
|
||||
language: 'en',
|
||||
namespace: 'ed41a221_133a_4558_a1d6_192960e3aee9',
|
||||
components: [
|
||||
{
|
||||
text: '🎉 Special offer for you! Get {{discount_percentage}}% off your next purchase. Use the code below at checkout',
|
||||
type: 'BODY',
|
||||
},
|
||||
{
|
||||
type: 'BUTTONS',
|
||||
buttons: [
|
||||
{
|
||||
text: 'Copy offer code',
|
||||
type: 'COPY_CODE',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
rejected_reason: 'NONE',
|
||||
},
|
||||
{
|
||||
name: 'support_callback',
|
||||
status: 'approved',
|
||||
category: 'UTILITY',
|
||||
language: 'en',
|
||||
namespace: 'ed41a221_133a_4558_a1d6_192960e3aee9',
|
||||
components: [
|
||||
{
|
||||
text: 'Hello {{name}}, our support team will call you regarding ticket # {{ticket_id}}.',
|
||||
type: 'BODY',
|
||||
},
|
||||
{
|
||||
type: 'BUTTONS',
|
||||
buttons: [
|
||||
{
|
||||
text: 'Call Support',
|
||||
type: 'PHONE_NUMBER',
|
||||
phone_number: '+16506677566',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
rejected_reason: 'NONE',
|
||||
},
|
||||
{
|
||||
name: 'training_video',
|
||||
status: 'approved',
|
||||
category: 'MARKETING',
|
||||
language: 'en',
|
||||
namespace: 'ed41a221_133a_4558_a1d6_192960e3aee9',
|
||||
components: [
|
||||
{
|
||||
type: 'HEADER',
|
||||
format: 'VIDEO',
|
||||
},
|
||||
{
|
||||
text: "Hi {{name}}, here's your training video. Please watch by{{date}}.",
|
||||
type: 'BODY',
|
||||
},
|
||||
],
|
||||
rejected_reason: 'NONE',
|
||||
},
|
||||
{
|
||||
name: 'product_launch',
|
||||
status: 'approved',
|
||||
category: 'MARKETING',
|
||||
language: 'en',
|
||||
namespace: 'ed41a221_133a_4558_a1d6_192960e3aee9',
|
||||
components: [
|
||||
{
|
||||
type: 'HEADER',
|
||||
format: 'IMAGE',
|
||||
},
|
||||
{
|
||||
text: 'New arrival! Our stunning coat now available in {{color}} color.',
|
||||
type: 'BODY',
|
||||
},
|
||||
{
|
||||
text: 'Free shipping on orders over $100. Limited time offer.',
|
||||
type: 'FOOTER',
|
||||
},
|
||||
],
|
||||
rejected_reason: 'NONE',
|
||||
},
|
||||
{
|
||||
name: 'greet',
|
||||
status: 'approved',
|
||||
category: 'MARKETING',
|
||||
language: 'en',
|
||||
namespace: 'ed41a221_133a_4558_a1d6_192960e3aee9',
|
||||
components: [
|
||||
{
|
||||
text: 'Hey {{customer_name}} how may I help you?',
|
||||
type: 'BODY',
|
||||
},
|
||||
],
|
||||
rejected_reason: 'NONE',
|
||||
},
|
||||
{
|
||||
name: 'hello_world',
|
||||
status: 'approved',
|
||||
category: 'UTILITY',
|
||||
language: 'en_US',
|
||||
namespace: 'ed41a221_133a_4558_a1d6_192960e3aee9',
|
||||
components: [
|
||||
{
|
||||
text: 'Hello World',
|
||||
type: 'HEADER',
|
||||
format: 'TEXT',
|
||||
},
|
||||
{
|
||||
text: 'Welcome and congratulations!! This message demonstrates your ability to send a WhatsApp message notification from the Cloud API, hosted by Meta. Thank you for taking the time to test with us.',
|
||||
type: 'BODY',
|
||||
},
|
||||
{
|
||||
text: 'WhatsApp Business Platform sample message',
|
||||
type: 'FOOTER',
|
||||
},
|
||||
],
|
||||
rejected_reason: 'NONE',
|
||||
},
|
||||
{
|
||||
name: 'feedback_request',
|
||||
status: 'approved',
|
||||
category: 'MARKETING',
|
||||
language: 'en',
|
||||
namespace: 'ed41a221_133a_4558_a1d6_192960e3aee9',
|
||||
components: [
|
||||
{
|
||||
text: "Hey {{name}}, how was your experience with Puma? We'd love your feedback!",
|
||||
type: 'BODY',
|
||||
},
|
||||
{
|
||||
type: 'BUTTONS',
|
||||
buttons: [
|
||||
{
|
||||
url: 'https://feedback.example.com/survey',
|
||||
text: 'Leave Feedback',
|
||||
type: 'URL',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
rejected_reason: 'NONE',
|
||||
},
|
||||
{
|
||||
name: 'address_update',
|
||||
status: 'approved',
|
||||
category: 'UTILITY',
|
||||
language: 'en_US',
|
||||
namespace: 'ed41a221_133a_4558_a1d6_192960e3aee9',
|
||||
components: [
|
||||
{
|
||||
text: 'Address update',
|
||||
type: 'HEADER',
|
||||
format: 'TEXT',
|
||||
},
|
||||
{
|
||||
text: 'Hi {{1}}, your delivery address has been successfully updated to {{2}}. Contact {{3}} for any inquiries.',
|
||||
type: 'BODY',
|
||||
},
|
||||
],
|
||||
rejected_reason: 'NONE',
|
||||
},
|
||||
{
|
||||
name: 'delivery_confirmation',
|
||||
status: 'approved',
|
||||
category: 'UTILITY',
|
||||
language: 'en_US',
|
||||
namespace: 'ed41a221_133a_4558_a1d6_192960e3aee9',
|
||||
components: [
|
||||
{
|
||||
text: '{{1}}, your order was successfully delivered on {{2}}.\n\nThank you for your purchase.\n',
|
||||
type: 'BODY',
|
||||
},
|
||||
],
|
||||
rejected_reason: 'NONE',
|
||||
},
|
||||
];
|
||||
@@ -1,61 +0,0 @@
|
||||
import { shallowMount } from '@vue/test-utils';
|
||||
import TemplateParser from '../../../../dashboard/components/widgets/conversation/WhatsappTemplates/TemplateParser.vue';
|
||||
import { templates } from './fixtures';
|
||||
import { nextTick } from 'vue';
|
||||
|
||||
const config = {
|
||||
global: {
|
||||
stubs: {
|
||||
NextButton: { template: '<button />' },
|
||||
WootInput: { template: '<input />' },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
describe('#WhatsAppTemplates', () => {
|
||||
it('returns all variables from a template string', async () => {
|
||||
const wrapper = shallowMount(TemplateParser, {
|
||||
...config,
|
||||
props: { template: templates[0] },
|
||||
});
|
||||
await nextTick();
|
||||
expect(wrapper.vm.variables).toEqual(['{{1}}', '{{2}}', '{{3}}']);
|
||||
});
|
||||
|
||||
it('returns no variables from a template string if it does not contain variables', async () => {
|
||||
const wrapper = shallowMount(TemplateParser, {
|
||||
...config,
|
||||
props: { template: templates[12] },
|
||||
});
|
||||
await nextTick();
|
||||
expect(wrapper.vm.variables).toBeNull();
|
||||
});
|
||||
|
||||
it('returns the body of a template', async () => {
|
||||
const wrapper = shallowMount(TemplateParser, {
|
||||
...config,
|
||||
props: { template: templates[1] },
|
||||
});
|
||||
await nextTick();
|
||||
const expectedOutput =
|
||||
templates[1].components.find(i => i.type === 'BODY')?.text || '';
|
||||
expect(wrapper.vm.templateString).toEqual(expectedOutput);
|
||||
});
|
||||
|
||||
it('generates the templates from variable input', async () => {
|
||||
const wrapper = shallowMount(TemplateParser, {
|
||||
...config,
|
||||
props: { template: templates[0] },
|
||||
});
|
||||
await nextTick();
|
||||
|
||||
// Instead of using `setData`, directly modify the `processedParams` using the component's logic
|
||||
await wrapper.vm.$nextTick();
|
||||
wrapper.vm.processedParams = { 1: 'abc', 2: 'xyz', 3: 'qwerty' };
|
||||
await wrapper.vm.$nextTick();
|
||||
|
||||
const expectedOutput =
|
||||
'Esta é a sua confirmação de voo para abc-xyz em qwerty.';
|
||||
expect(wrapper.vm.processedString).toEqual(expectedOutput);
|
||||
});
|
||||
});
|
||||
@@ -1,36 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
class AssignmentV2::AssignmentJob < ApplicationJob
|
||||
queue_as :low
|
||||
|
||||
def perform(inbox_id: nil, conversation_id: nil)
|
||||
if conversation_id
|
||||
assign_single_conversation(conversation_id)
|
||||
elsif inbox_id
|
||||
assign_inbox_conversations(inbox_id)
|
||||
else
|
||||
Rails.logger.error 'AssignmentV2::AssignmentJob: No inbox_id or conversation_id provided'
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def assign_single_conversation(conversation_id)
|
||||
conversation = Conversation.find_by(id: conversation_id)
|
||||
return unless conversation
|
||||
|
||||
service = AssignmentV2::AssignmentService.new(inbox: conversation.inbox)
|
||||
service.perform_for_conversation(conversation)
|
||||
end
|
||||
|
||||
def assign_inbox_conversations(inbox_id)
|
||||
inbox = Inbox.find_by(id: inbox_id)
|
||||
return unless inbox
|
||||
return unless inbox.assignment_v2_enabled?
|
||||
|
||||
service = AssignmentV2::AssignmentService.new(inbox: inbox)
|
||||
assigned_count = service.perform_bulk_assignment
|
||||
|
||||
Rails.logger.info "AssignmentV2::AssignmentJob: Assigned #{assigned_count} conversations for inbox #{inbox_id}"
|
||||
end
|
||||
end
|
||||
@@ -1,53 +1,18 @@
|
||||
class AutomationRuleListener < BaseListener
|
||||
def conversation_updated(event)
|
||||
return if performed_by_automation?(event)
|
||||
|
||||
conversation = event.data[:conversation]
|
||||
account = conversation.account
|
||||
changed_attributes = event.data[:changed_attributes]
|
||||
|
||||
return unless rule_present?('conversation_updated', account)
|
||||
|
||||
rules = current_account_rules('conversation_updated', account)
|
||||
|
||||
rules.each do |rule|
|
||||
conditions_match = ::AutomationRules::ConditionsFilterService.new(rule, conversation, { changed_attributes: changed_attributes }).perform
|
||||
AutomationRules::ActionService.new(rule, account, conversation).perform if conditions_match.present?
|
||||
end
|
||||
process_conversation_event(event, 'conversation_updated')
|
||||
end
|
||||
|
||||
def conversation_created(event)
|
||||
return if performed_by_automation?(event) || ignore_auto_reply_event?(event)
|
||||
|
||||
conversation = event.data[:conversation]
|
||||
account = conversation.account
|
||||
changed_attributes = event.data[:changed_attributes]
|
||||
|
||||
return unless rule_present?('conversation_created', account)
|
||||
|
||||
rules = current_account_rules('conversation_created', account)
|
||||
|
||||
rules.each do |rule|
|
||||
conditions_match = ::AutomationRules::ConditionsFilterService.new(rule, conversation, { changed_attributes: changed_attributes }).perform
|
||||
::AutomationRules::ActionService.new(rule, account, conversation).perform if conditions_match.present?
|
||||
end
|
||||
process_conversation_event(event, 'conversation_created')
|
||||
end
|
||||
|
||||
def conversation_opened(event)
|
||||
return if performed_by_automation?(event) || ignore_auto_reply_event?(event)
|
||||
process_conversation_event(event, 'conversation_opened')
|
||||
end
|
||||
|
||||
conversation = event.data[:conversation]
|
||||
account = conversation.account
|
||||
changed_attributes = event.data[:changed_attributes]
|
||||
|
||||
return unless rule_present?('conversation_opened', account)
|
||||
|
||||
rules = current_account_rules('conversation_opened', account)
|
||||
|
||||
rules.each do |rule|
|
||||
conditions_match = ::AutomationRules::ConditionsFilterService.new(rule, conversation, { changed_attributes: changed_attributes }).perform
|
||||
AutomationRules::ActionService.new(rule, account, conversation).perform if conditions_match.present?
|
||||
end
|
||||
def conversation_resolved(event)
|
||||
process_conversation_event(event, 'conversation_resolved')
|
||||
end
|
||||
|
||||
def message_created(event)
|
||||
@@ -69,6 +34,28 @@ class AutomationRuleListener < BaseListener
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def process_conversation_event(event, event_name)
|
||||
return if performed_by_automation?(event)
|
||||
|
||||
auto_reply_skip_events = %w[conversation_created conversation_opened]
|
||||
return if auto_reply_skip_events.include?(event_name) && ignore_auto_reply_event?(event)
|
||||
|
||||
conversation = event.data[:conversation]
|
||||
account = conversation.account
|
||||
changed_attributes = event.data[:changed_attributes]
|
||||
|
||||
return unless rule_present?(event_name, account)
|
||||
|
||||
rules = current_account_rules(event_name, account)
|
||||
|
||||
rules.each do |rule|
|
||||
conditions_match = ::AutomationRules::ConditionsFilterService.new(rule, conversation, { changed_attributes: changed_attributes }).perform
|
||||
AutomationRules::ActionService.new(rule, account, conversation).perform if conditions_match.present?
|
||||
end
|
||||
end
|
||||
|
||||
def rule_present?(event_name, account)
|
||||
return if account.blank?
|
||||
|
||||
|
||||
@@ -90,8 +90,47 @@ class ReportingEventListener < BaseListener
|
||||
reporting_event.save!
|
||||
end
|
||||
|
||||
def conversation_opened(event)
|
||||
conversation = extract_conversation_and_account(event)[0]
|
||||
|
||||
# Find the most recent resolved event for this conversation
|
||||
last_resolved_event = ReportingEvent.where(
|
||||
conversation_id: conversation.id,
|
||||
name: 'conversation_resolved'
|
||||
).order(event_end_time: :desc).first
|
||||
|
||||
# For first-time openings, value is 0
|
||||
# For reopenings, calculate time since resolution
|
||||
if last_resolved_event
|
||||
time_since_resolved = conversation.updated_at.to_i - last_resolved_event.event_end_time.to_i
|
||||
business_hours_value = business_hours(conversation.inbox, last_resolved_event.event_end_time, conversation.updated_at)
|
||||
start_time = last_resolved_event.event_end_time
|
||||
else
|
||||
time_since_resolved = 0
|
||||
business_hours_value = 0
|
||||
start_time = conversation.created_at
|
||||
end
|
||||
|
||||
create_conversation_opened_event(conversation, time_since_resolved, business_hours_value, start_time)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def create_conversation_opened_event(conversation, time_since_resolved, business_hours_value, start_time)
|
||||
reporting_event = ReportingEvent.new(
|
||||
name: 'conversation_opened',
|
||||
value: time_since_resolved,
|
||||
value_in_business_hours: business_hours_value,
|
||||
account_id: conversation.account_id,
|
||||
inbox_id: conversation.inbox_id,
|
||||
user_id: conversation.assignee_id,
|
||||
conversation_id: conversation.id,
|
||||
event_start_time: start_time,
|
||||
event_end_time: conversation.updated_at
|
||||
)
|
||||
reporting_event.save!
|
||||
end
|
||||
|
||||
def create_bot_resolved_event(conversation, reporting_event)
|
||||
return unless conversation.inbox.active_bot?
|
||||
# We don't want to create a bot_resolved event if there is user interaction on the conversation
|
||||
|
||||
@@ -61,7 +61,6 @@ class Account < ApplicationRecord
|
||||
has_many :agent_bots, dependent: :destroy_async
|
||||
has_many :api_channels, dependent: :destroy_async, class_name: '::Channel::Api'
|
||||
has_many :articles, dependent: :destroy_async, class_name: '::Article'
|
||||
has_many :assignment_policies, dependent: :destroy_async
|
||||
has_many :automation_rules, dependent: :destroy_async
|
||||
has_many :macros, dependent: :destroy_async
|
||||
has_many :campaigns, dependent: :destroy_async
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
# == Schema Information
|
||||
#
|
||||
# Table name: assignment_policies
|
||||
#
|
||||
# id :bigint not null, primary key
|
||||
# assignment_order :integer default("round_robin"), not null
|
||||
# conversation_priority :integer default("earliest_created"), not null
|
||||
# description :text
|
||||
# enabled :boolean default(TRUE), not null
|
||||
# fair_distribution_limit :integer default(100), not null
|
||||
# fair_distribution_window :integer default(3600), not null
|
||||
# name :string(255) not null
|
||||
# created_at :datetime not null
|
||||
# updated_at :datetime not null
|
||||
# account_id :bigint not null
|
||||
#
|
||||
# Indexes
|
||||
#
|
||||
# index_assignment_policies_on_account_id (account_id)
|
||||
# index_assignment_policies_on_account_id_and_name (account_id,name) UNIQUE
|
||||
# index_assignment_policies_on_enabled (enabled)
|
||||
#
|
||||
|
||||
class AssignmentPolicy < ApplicationRecord
|
||||
# Enums
|
||||
enum assignment_order: { round_robin: 0 }
|
||||
enum conversation_priority: { earliest_created: 0, longest_waiting: 1 }
|
||||
|
||||
# Associations
|
||||
belongs_to :account
|
||||
has_many :inbox_assignment_policies, dependent: :destroy
|
||||
has_many :inboxes, through: :inbox_assignment_policies
|
||||
|
||||
# Validations
|
||||
validates :name, presence: true, uniqueness: { scope: :account_id }
|
||||
validates :name, length: { maximum: 255 }
|
||||
validates :description, length: { maximum: 1000 }
|
||||
validates :fair_distribution_limit, presence: true, numericality: { greater_than: 0, less_than_or_equal_to: 100 }
|
||||
validates :fair_distribution_window, presence: true, numericality: { greater_than: 60, less_than_or_equal_to: 86_400 }
|
||||
validates :assignment_order, inclusion: { in: assignment_orders.keys }
|
||||
validates :conversation_priority, inclusion: { in: conversation_priorities.keys }
|
||||
|
||||
def webhook_data
|
||||
{
|
||||
id: id,
|
||||
name: name,
|
||||
description: description,
|
||||
assignment_order: assignment_order,
|
||||
conversation_priority: conversation_priority,
|
||||
fair_distribution_limit: fair_distribution_limit,
|
||||
fair_distribution_window: fair_distribution_window,
|
||||
enabled: enabled
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
AssignmentPolicy.prepend_mod_with('AssignmentPolicy')
|
||||
@@ -62,7 +62,12 @@ class Attachment < ApplicationRecord
|
||||
def thumb_url
|
||||
return '' unless file.attached? && image?
|
||||
|
||||
url_for(file.representation(resize_to_fill: [250, nil]))
|
||||
begin
|
||||
url_for(file.representation(resize_to_fill: [250, nil]))
|
||||
rescue ActiveStorage::UnrepresentableError => e
|
||||
Rails.logger.warn "Unrepresentable image attachment: #{id} (#{file.filename}) - #{e.message}"
|
||||
''
|
||||
end
|
||||
end
|
||||
|
||||
def with_attached_file?
|
||||
|
||||
@@ -40,9 +40,9 @@ class AutomationRule < ApplicationRecord
|
||||
end
|
||||
|
||||
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 snooze_conversation change_priority send_email_transcript
|
||||
add_private_note].freeze
|
||||
%w[send_message add_label remove_label send_email_to_team assign_team assign_agent remove_assigned_agent
|
||||
remove_assigned_team send_webhook_event mute_conversation send_attachment change_status resolve_conversation
|
||||
open_conversation snooze_conversation change_priority send_email_transcript add_private_note].freeze
|
||||
end
|
||||
|
||||
def file_base_data
|
||||
|
||||
@@ -32,7 +32,6 @@ class Channel::Whatsapp < ApplicationRecord
|
||||
validates :phone_number, presence: true, uniqueness: true
|
||||
validate :validate_provider_config
|
||||
|
||||
before_save :setup_webhooks
|
||||
after_create :sync_templates
|
||||
before_destroy :teardown_webhooks
|
||||
|
||||
@@ -60,6 +59,13 @@ class Channel::Whatsapp < ApplicationRecord
|
||||
delegate :media_url, to: :provider_service
|
||||
delegate :api_headers, to: :provider_service
|
||||
|
||||
def setup_webhooks
|
||||
perform_webhook_setup
|
||||
rescue StandardError => e
|
||||
Rails.logger.error "[WHATSAPP] Webhook setup failed: #{e.message}"
|
||||
prompt_reauthorization!
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def ensure_webhook_verify_token
|
||||
@@ -70,34 +76,6 @@ class Channel::Whatsapp < ApplicationRecord
|
||||
errors.add(:provider_config, 'Invalid Credentials') unless provider_service.validate_provider_config?
|
||||
end
|
||||
|
||||
def setup_webhooks
|
||||
return unless should_setup_webhooks?
|
||||
|
||||
perform_webhook_setup
|
||||
rescue StandardError => e
|
||||
handle_webhook_setup_error(e)
|
||||
end
|
||||
|
||||
def provider_config_changed?
|
||||
will_save_change_to_provider_config?
|
||||
end
|
||||
|
||||
def should_setup_webhooks?
|
||||
whatsapp_cloud_provider? && embedded_signup_source? && webhook_config_present? && provider_config_changed?
|
||||
end
|
||||
|
||||
def whatsapp_cloud_provider?
|
||||
provider == 'whatsapp_cloud'
|
||||
end
|
||||
|
||||
def embedded_signup_source?
|
||||
provider_config['source'] == 'embedded_signup'
|
||||
end
|
||||
|
||||
def webhook_config_present?
|
||||
provider_config['business_account_id'].present? && provider_config['api_key'].present?
|
||||
end
|
||||
|
||||
def perform_webhook_setup
|
||||
business_account_id = provider_config['business_account_id']
|
||||
api_key = provider_config['api_key']
|
||||
@@ -105,12 +83,6 @@ class Channel::Whatsapp < ApplicationRecord
|
||||
Whatsapp::WebhookSetupService.new(self, business_account_id, api_key).perform
|
||||
end
|
||||
|
||||
def handle_webhook_setup_error(error)
|
||||
Rails.logger.error "[WHATSAPP] Webhook setup failed: #{error.message}"
|
||||
# Don't raise the error to prevent channel creation from failing
|
||||
# Webhooks can be retried later
|
||||
end
|
||||
|
||||
def teardown_webhooks
|
||||
Whatsapp::WebhookTeardownService.new(self).perform
|
||||
end
|
||||
|
||||
@@ -14,18 +14,11 @@ module AutoAssignmentHandler
|
||||
return unless conversation_status_changed_to_open?
|
||||
return unless should_run_auto_assignment?
|
||||
|
||||
if inbox.assignment_v2_enabled?
|
||||
# Use Assignment V2 system
|
||||
AssignmentV2::AssignmentJob.perform_later(conversation_id: id)
|
||||
else
|
||||
# Use legacy assignment system
|
||||
::AutoAssignment::AgentAssignmentService.new(conversation: self, allowed_agent_ids: inbox.member_ids_with_assignment_capacity).perform
|
||||
end
|
||||
::AutoAssignment::AgentAssignmentService.new(conversation: self, allowed_agent_ids: inbox.member_ids_with_assignment_capacity).perform
|
||||
end
|
||||
|
||||
def should_run_auto_assignment?
|
||||
# Check auto assignment is enabled (either legacy or v2)
|
||||
return false unless inbox.auto_assignment_enabled?
|
||||
return false unless inbox.enable_auto_assignment?
|
||||
|
||||
# run only if assignee is blank or doesn't have access to inbox
|
||||
assignee.blank? || inbox.members.exclude?(assignee)
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module InboxAgentAvailability
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
def available_agents(options = {})
|
||||
# Get online agent IDs
|
||||
online_agent_ids = fetch_online_agent_ids
|
||||
return inbox_members.none if online_agent_ids.empty?
|
||||
|
||||
# Base query - only online agents
|
||||
scope = build_online_agents_scope(online_agent_ids)
|
||||
|
||||
# Apply filters
|
||||
apply_agent_filters(scope, options)
|
||||
end
|
||||
|
||||
def member_ids_with_assignment_capacity
|
||||
member_ids
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def build_online_agents_scope(online_agent_ids)
|
||||
inbox_members
|
||||
.joins(:user)
|
||||
.where(users: { id: online_agent_ids })
|
||||
.includes(:user)
|
||||
end
|
||||
|
||||
def apply_agent_filters(scope, options)
|
||||
# Exclude specific users if requested
|
||||
scope = scope.where.not(users: { id: options[:exclude_user_ids] }) if options[:exclude_user_ids].present?
|
||||
|
||||
# Apply rate limiting if assignment policy is enabled
|
||||
scope = filter_by_rate_limits(scope) if options[:check_rate_limits] && defined?(AssignmentV2::RateLimiter)
|
||||
|
||||
scope
|
||||
end
|
||||
|
||||
def fetch_online_agent_ids
|
||||
OnlineStatusTracker.get_available_users(account_id)
|
||||
.select { |_key, value| value.eql?('online') }
|
||||
.keys
|
||||
.map(&:to_i)
|
||||
end
|
||||
|
||||
def filter_by_rate_limits(inbox_members_scope)
|
||||
# Filter out agents who have exceeded rate limits
|
||||
return inbox_members_scope unless assignment_policy&.enabled?
|
||||
|
||||
inbox_members_scope.select do |inbox_member|
|
||||
rate_limiter = AssignmentV2::RateLimiter.new(inbox: self, user: inbox_member.user)
|
||||
rate_limiter.within_limits?
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -44,7 +44,6 @@ class Inbox < ApplicationRecord
|
||||
include Avatarable
|
||||
include OutOfOffisable
|
||||
include AccountCacheRevalidator
|
||||
include InboxAgentAvailability
|
||||
|
||||
# Not allowing characters:
|
||||
validates :name, presence: true
|
||||
@@ -73,10 +72,6 @@ class Inbox < ApplicationRecord
|
||||
has_many :webhooks, dependent: :destroy_async
|
||||
has_many :hooks, dependent: :destroy_async, class_name: 'Integrations::Hook'
|
||||
|
||||
# Assignment V2 associations
|
||||
has_one :inbox_assignment_policy, dependent: :destroy
|
||||
has_one :assignment_policy, through: :inbox_assignment_policy
|
||||
|
||||
enum sender_name_type: { friendly: 0, professional: 1 }
|
||||
|
||||
after_destroy :delete_round_robin_agents
|
||||
@@ -189,19 +184,6 @@ class Inbox < ApplicationRecord
|
||||
members.ids
|
||||
end
|
||||
|
||||
# Assignment V2 methods
|
||||
def assignment_v2_enabled?
|
||||
account.feature_enabled?('assignment_v2') && assignment_policy.present? && assignment_policy.enabled?
|
||||
end
|
||||
|
||||
def auto_assignment_enabled?
|
||||
if assignment_v2_enabled?
|
||||
assignment_policy.present? && assignment_policy.enabled?
|
||||
else
|
||||
enable_auto_assignment?
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def default_name_for_blank_name
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
# == Schema Information
|
||||
#
|
||||
# Table name: inbox_assignment_policies
|
||||
#
|
||||
# id :bigint not null, primary key
|
||||
# created_at :datetime not null
|
||||
# updated_at :datetime not null
|
||||
# assignment_policy_id :bigint not null
|
||||
# inbox_id :bigint not null
|
||||
#
|
||||
# Indexes
|
||||
#
|
||||
# index_inbox_assignment_policies_on_assignment_policy_id (assignment_policy_id)
|
||||
# index_inbox_assignment_policies_on_inbox_id (inbox_id) UNIQUE
|
||||
#
|
||||
|
||||
class InboxAssignmentPolicy < ApplicationRecord
|
||||
# Associations
|
||||
belongs_to :inbox
|
||||
belongs_to :assignment_policy
|
||||
|
||||
# Validations
|
||||
validates :inbox_id, uniqueness: true
|
||||
validate :inbox_belongs_to_same_account
|
||||
|
||||
# Delegations
|
||||
delegate :account, to: :inbox
|
||||
delegate :name, :description, :assignment_order, :conversation_priority,
|
||||
:fair_distribution_limit, :fair_distribution_window, :enabled?,
|
||||
to: :assignment_policy, prefix: :policy
|
||||
|
||||
def webhook_data
|
||||
{
|
||||
id: id,
|
||||
inbox_id: inbox_id,
|
||||
assignment_policy_id: assignment_policy_id,
|
||||
policy: assignment_policy.webhook_data
|
||||
}
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def inbox_belongs_to_same_account
|
||||
return unless inbox && assignment_policy
|
||||
|
||||
return if inbox.account_id == assignment_policy.account_id
|
||||
|
||||
errors.add(:inbox, 'must belong to the same account as the assignment policy')
|
||||
end
|
||||
end
|
||||
+3
-3
@@ -30,9 +30,9 @@ class Macro < ApplicationRecord
|
||||
|
||||
validate :json_actions_format
|
||||
|
||||
ACTIONS_ATTRS = %w[send_message add_label assign_team assign_agent mute_conversation change_status remove_label remove_assigned_team
|
||||
resolve_conversation snooze_conversation change_priority send_email_transcript send_attachment
|
||||
add_private_note send_webhook_event].freeze
|
||||
ACTIONS_ATTRS = %w[send_message add_label assign_team assign_agent mute_conversation change_status remove_label remove_assigned_agent
|
||||
remove_assigned_team resolve_conversation snooze_conversation change_priority send_email_transcript
|
||||
send_attachment add_private_note send_webhook_event].freeze
|
||||
|
||||
def set_visibility(user, params)
|
||||
self.visibility = params[:visibility]
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
class AssignmentPolicyPolicy < ApplicationPolicy
|
||||
def index?
|
||||
@account_user.administrator?
|
||||
end
|
||||
|
||||
def show?
|
||||
@account_user.administrator?
|
||||
end
|
||||
|
||||
def create?
|
||||
@account_user.administrator?
|
||||
end
|
||||
|
||||
def update?
|
||||
@account_user.administrator?
|
||||
end
|
||||
|
||||
def destroy?
|
||||
@account_user.administrator?
|
||||
end
|
||||
end
|
||||
@@ -22,6 +22,10 @@ class ActionService
|
||||
@conversation.open!
|
||||
end
|
||||
|
||||
def pending_conversation(_params)
|
||||
@conversation.pending!
|
||||
end
|
||||
|
||||
def change_status(status)
|
||||
@conversation.update!(status: status[0])
|
||||
end
|
||||
@@ -43,7 +47,9 @@ class ActionService
|
||||
|
||||
@agent = @account.users.find_by(id: agent_ids)
|
||||
|
||||
@conversation.update!(assignee_id: @agent.id) if @agent.present?
|
||||
return unless @agent.present? && @agent.confirmed?
|
||||
|
||||
@conversation.update!(assignee_id: @agent.id)
|
||||
end
|
||||
|
||||
def remove_label(labels)
|
||||
@@ -54,8 +60,7 @@ class ActionService
|
||||
end
|
||||
|
||||
def assign_team(team_ids = [])
|
||||
# FIXME: The explicit checks for zero or nil (string) is bad. Move
|
||||
# this to a separate unassign action.
|
||||
# Keep nil/0 handling for existing automation and macro payloads.
|
||||
should_unassign = team_ids.blank? || %w[nil 0].include?(team_ids[0].to_s)
|
||||
return @conversation.update!(team_id: nil) if should_unassign
|
||||
|
||||
@@ -66,16 +71,25 @@ class ActionService
|
||||
@conversation.update!(team_id: team_ids[0])
|
||||
end
|
||||
|
||||
def remove_assigned_agent(_params)
|
||||
@conversation.update!(assignee_id: nil)
|
||||
end
|
||||
|
||||
def remove_assigned_team(_params)
|
||||
@conversation.update!(team_id: nil)
|
||||
end
|
||||
|
||||
def send_email_transcript(emails)
|
||||
return unless @account.email_transcript_enabled?
|
||||
|
||||
emails = emails[0].gsub(/\s+/, '').split(',')
|
||||
|
||||
emails.each do |email|
|
||||
break unless @account.within_email_rate_limit?
|
||||
|
||||
email = parse_email_variables(@conversation, email)
|
||||
ConversationReplyMailer.with(account: @conversation.account).conversation_transcript(@conversation, email)&.deliver_later
|
||||
@account.increment_email_sent_count
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
@@ -1,102 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
class AssignmentV2::AssignmentService
|
||||
pattr_initialize [:inbox!]
|
||||
|
||||
def perform_for_conversation(conversation)
|
||||
return false unless can_assign?(conversation)
|
||||
|
||||
agent = find_agent_for_conversation(conversation)
|
||||
return false unless agent
|
||||
|
||||
assign_conversation_to_agent(conversation, agent)
|
||||
end
|
||||
|
||||
def perform_bulk_assignment(limit: 50)
|
||||
return 0 unless assignment_enabled?
|
||||
|
||||
conversations = unassigned_conversations(limit)
|
||||
assigned_count = 0
|
||||
|
||||
conversations.find_each do |conversation|
|
||||
assigned_count += 1 if perform_for_conversation(conversation)
|
||||
end
|
||||
|
||||
assigned_count
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def policy
|
||||
@policy ||= inbox.assignment_policy
|
||||
end
|
||||
|
||||
def assignment_enabled?
|
||||
policy&.enabled?
|
||||
end
|
||||
|
||||
def can_assign?(conversation)
|
||||
assignment_enabled? &&
|
||||
conversation.status == 'open' &&
|
||||
conversation.assignee_id.nil?
|
||||
end
|
||||
|
||||
def find_agent_for_conversation(_conversation)
|
||||
available_agents = inbox.available_agents(check_rate_limits: true)
|
||||
|
||||
if available_agents.empty?
|
||||
log_no_agents_available
|
||||
return nil
|
||||
end
|
||||
|
||||
selector_service.select_agent(available_agents)
|
||||
end
|
||||
|
||||
def selector_service
|
||||
@selector_service ||= AssignmentV2::RoundRobinSelector.new(inbox: inbox)
|
||||
end
|
||||
|
||||
def unassigned_conversations(limit)
|
||||
scope = inbox.conversations
|
||||
.unassigned
|
||||
.open
|
||||
|
||||
# Apply conversation priority ordering
|
||||
scope = case policy.conversation_priority
|
||||
when 'longest_waiting'
|
||||
scope.order(last_activity_at: :asc, created_at: :asc)
|
||||
else
|
||||
scope.order(created_at: :asc)
|
||||
end
|
||||
|
||||
scope.limit(limit)
|
||||
end
|
||||
|
||||
def assign_conversation_to_agent(conversation, agent)
|
||||
conversation.update!(assignee: agent)
|
||||
create_assignment_activity(conversation, agent)
|
||||
true
|
||||
rescue ActiveRecord::RecordInvalid => e
|
||||
Rails.logger.error "AssignmentV2: Failed to assign conversation #{conversation.id}: #{e.message}"
|
||||
false
|
||||
end
|
||||
|
||||
def create_assignment_activity(conversation, agent)
|
||||
Rails.configuration.dispatcher.dispatch(
|
||||
Events::Types::ASSIGNEE_CHANGED,
|
||||
Time.zone.now,
|
||||
conversation: conversation,
|
||||
user: agent
|
||||
)
|
||||
end
|
||||
|
||||
def enterprise_enabled?
|
||||
@enterprise_enabled ||= defined?(Enterprise)
|
||||
end
|
||||
|
||||
def log_no_agents_available
|
||||
Rails.logger.warn("AssignmentV2: No agents available for inbox #{inbox.id}")
|
||||
end
|
||||
end
|
||||
|
||||
AssignmentV2::AssignmentService.prepend_mod_with('AssignmentV2::AssignmentService')
|
||||
@@ -1,75 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
# Rate limiter for assignment operations
|
||||
# Uses SQL to track assignment counts per agent per time window
|
||||
# based on assignment policy's fair_distribution_limit and fair_distribution_window
|
||||
class AssignmentV2::RateLimiter
|
||||
pattr_initialize [:inbox!, :user!]
|
||||
|
||||
# Check if the user has exceeded rate limits
|
||||
# @return [Boolean] true if within limits, false if exceeded
|
||||
def within_limits?
|
||||
return true unless policy_exists?
|
||||
|
||||
current_count < rate_limit
|
||||
end
|
||||
|
||||
# Get current rate limit status for the user
|
||||
# @return [Hash] Rate limit status information
|
||||
def status
|
||||
if policy_exists?
|
||||
{
|
||||
within_limits: within_limits?,
|
||||
current_count: current_count,
|
||||
limit: rate_limit,
|
||||
reset_at: Time.zone.at(next_window_start)
|
||||
}
|
||||
else
|
||||
{
|
||||
within_limits: true,
|
||||
current_count: 0,
|
||||
limit: Float::INFINITY,
|
||||
reset_at: nil
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def policy
|
||||
@policy ||= inbox.assignment_policy
|
||||
end
|
||||
|
||||
def policy_exists?
|
||||
policy.present? && policy.enabled?
|
||||
end
|
||||
|
||||
def current_count
|
||||
# Count conversations assigned to this user in the current time window
|
||||
# from this inbox
|
||||
window_start = Time.zone.at(current_window)
|
||||
|
||||
Conversation
|
||||
.where(inbox_id: inbox.id)
|
||||
.where(assignee_id: user.id)
|
||||
.where('updated_at >= ?', window_start)
|
||||
.where.not(assignee_id: nil)
|
||||
.count
|
||||
end
|
||||
|
||||
def rate_limit
|
||||
policy&.fair_distribution_limit || 10
|
||||
end
|
||||
|
||||
def time_window
|
||||
policy&.fair_distribution_window || 3600
|
||||
end
|
||||
|
||||
def current_window
|
||||
(Time.current.to_i / time_window) * time_window
|
||||
end
|
||||
|
||||
def next_window_start
|
||||
current_window + time_window
|
||||
end
|
||||
end
|
||||
@@ -1,37 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
class AssignmentV2::RoundRobinSelector
|
||||
pattr_initialize [:inbox!]
|
||||
|
||||
def select_agent(available_agents)
|
||||
return nil if available_agents.empty?
|
||||
|
||||
# Extract user IDs from inbox members
|
||||
agent_user_ids = available_agents.map(&:user_id).map(&:to_s)
|
||||
|
||||
# Use Redis queue for round robin
|
||||
selected_user_id = round_robin_service.available_agent(allowed_agent_ids: agent_user_ids)
|
||||
return nil unless selected_user_id
|
||||
|
||||
# Return the user object
|
||||
available_agents.find { |inbox_member| inbox_member.user_id.to_s == selected_user_id }&.user
|
||||
end
|
||||
|
||||
def add_agent_to_queue(user_id)
|
||||
round_robin_service.add_agent_to_queue(user_id)
|
||||
end
|
||||
|
||||
def remove_agent_from_queue(user_id)
|
||||
round_robin_service.remove_agent_from_queue(user_id)
|
||||
end
|
||||
|
||||
def reset_queue
|
||||
round_robin_service.reset_queue
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def round_robin_service
|
||||
@round_robin_service ||= AutoAssignment::InboxRoundRobinService.new(inbox: inbox)
|
||||
end
|
||||
end
|
||||
@@ -68,14 +68,23 @@ class Notification::PushNotificationService
|
||||
|
||||
WebPush.payload_send(**browser_push_payload(subscription))
|
||||
Rails.logger.info("Browser push sent to #{user.email} with title #{push_message[:title]}")
|
||||
rescue WebPush::ExpiredSubscription, WebPush::InvalidSubscription, WebPush::Unauthorized => e
|
||||
Rails.logger.info "WebPush subscription expired: #{e.message}"
|
||||
subscription.destroy!
|
||||
rescue Errno::ECONNRESET, Net::OpenTimeout, Net::ReadTimeout => e
|
||||
Rails.logger.error "WebPush operation error: #{e.message}"
|
||||
rescue StandardError => e
|
||||
ChatwootExceptionTracker.new(e, account: notification.account).capture_exception
|
||||
true
|
||||
handle_browser_push_error(e, subscription)
|
||||
end
|
||||
|
||||
def handle_browser_push_error(error, subscription)
|
||||
case error
|
||||
when WebPush::ExpiredSubscription, WebPush::InvalidSubscription, WebPush::Unauthorized
|
||||
Rails.logger.info "WebPush subscription expired: #{error.message}"
|
||||
subscription.destroy!
|
||||
when WebPush::TooManyRequests
|
||||
Rails.logger.warn "WebPush rate limited for #{user.email} on account #{notification.account.id}: #{error.message}"
|
||||
when Errno::ECONNRESET, Net::OpenTimeout, Net::ReadTimeout
|
||||
Rails.logger.error "WebPush operation error: #{error.message}"
|
||||
else
|
||||
ChatwootExceptionTracker.new(error, account: notification.account).capture_exception
|
||||
true
|
||||
end
|
||||
end
|
||||
|
||||
def send_fcm_push(subscription)
|
||||
|
||||
@@ -33,15 +33,14 @@ class Whatsapp::ChannelCreationService
|
||||
|
||||
def create_channel_with_inbox
|
||||
ActiveRecord::Base.transaction do
|
||||
channel = create_channel
|
||||
channel = build_channel
|
||||
create_inbox(channel)
|
||||
channel.reload
|
||||
channel
|
||||
end
|
||||
end
|
||||
|
||||
def create_channel
|
||||
Channel::Whatsapp.create!(
|
||||
def build_channel
|
||||
Channel::Whatsapp.build(
|
||||
account: @account,
|
||||
phone_number: @phone_info[:phone_number],
|
||||
provider: 'whatsapp_cloud',
|
||||
|
||||
@@ -11,16 +11,34 @@ class Whatsapp::EmbeddedSignupService
|
||||
def perform
|
||||
validate_parameters!
|
||||
|
||||
# Exchange code for user access token
|
||||
access_token = Whatsapp::TokenExchangeService.new(@code).perform
|
||||
access_token = exchange_code_for_token
|
||||
phone_info = fetch_phone_info(access_token)
|
||||
validate_token_access(access_token)
|
||||
|
||||
# Fetch phone information
|
||||
phone_info = Whatsapp::PhoneInfoService.new(@waba_id, @phone_number_id, access_token).perform
|
||||
channel = create_or_reauthorize_channel(access_token, phone_info)
|
||||
channel.setup_webhooks
|
||||
channel
|
||||
|
||||
# Validate token has access to the WABA
|
||||
rescue StandardError => e
|
||||
Rails.logger.error("[WHATSAPP] Embedded signup failed: #{e.message}")
|
||||
raise e
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def exchange_code_for_token
|
||||
Whatsapp::TokenExchangeService.new(@code).perform
|
||||
end
|
||||
|
||||
def fetch_phone_info(access_token)
|
||||
Whatsapp::PhoneInfoService.new(@waba_id, @phone_number_id, access_token).perform
|
||||
end
|
||||
|
||||
def validate_token_access(access_token)
|
||||
Whatsapp::TokenValidationService.new(access_token, @waba_id).perform
|
||||
end
|
||||
|
||||
# Reauthorization flow if inbox_id is present
|
||||
def create_or_reauthorize_channel(access_token, phone_info)
|
||||
if @inbox_id.present?
|
||||
Whatsapp::ReauthorizationService.new(
|
||||
account: @account,
|
||||
@@ -29,17 +47,11 @@ class Whatsapp::EmbeddedSignupService
|
||||
business_id: @business_id
|
||||
).perform(access_token, phone_info)
|
||||
else
|
||||
# Create channel for new authorization
|
||||
waba_info = { waba_id: @waba_id, business_name: phone_info[:business_name] }
|
||||
Whatsapp::ChannelCreationService.new(@account, waba_info, phone_info, access_token).perform
|
||||
end
|
||||
rescue StandardError => e
|
||||
Rails.logger.error("[WHATSAPP] Embedded signup failed: #{e.message}")
|
||||
raise e
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def validate_parameters!
|
||||
missing_params = []
|
||||
missing_params << 'code' if @code.blank?
|
||||
|
||||
@@ -92,6 +92,9 @@ class Whatsapp::IncomingMessageBaseService
|
||||
|
||||
@contact_inbox = contact_inbox
|
||||
@contact = contact_inbox.contact
|
||||
|
||||
# Update existing contact name if ProfileName is available and current name is just phone number
|
||||
update_contact_with_profile_name(contact_params)
|
||||
end
|
||||
|
||||
def set_conversation
|
||||
@@ -171,4 +174,21 @@ class Whatsapp::IncomingMessageBaseService
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
def update_contact_with_profile_name(contact_params)
|
||||
profile_name = contact_params.dig(:profile, :name)
|
||||
return if profile_name.blank?
|
||||
return if @contact.name == profile_name
|
||||
|
||||
# Only update if current name exactly matches the phone number or formatted phone number
|
||||
return unless contact_name_matches_phone_number?
|
||||
|
||||
@contact.update!(name: profile_name)
|
||||
end
|
||||
|
||||
def contact_name_matches_phone_number?
|
||||
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
|
||||
end
|
||||
|
||||
@@ -84,7 +84,7 @@ class Whatsapp::OneoffCampaignService
|
||||
namespace: namespace,
|
||||
lang_code: lang_code,
|
||||
parameters: processed_parameters
|
||||
})
|
||||
}, nil)
|
||||
|
||||
rescue StandardError => e
|
||||
Rails.logger.error "Failed to send WhatsApp template message to #{to}: #{e.message}"
|
||||
|
||||
@@ -15,7 +15,7 @@ class Whatsapp::Providers::BaseService
|
||||
raise 'Overwrite this method in child class'
|
||||
end
|
||||
|
||||
def send_template(_phone_number, _template_info)
|
||||
def send_template(_phone_number, _template_info, _message)
|
||||
raise 'Overwrite this method in child class'
|
||||
end
|
||||
|
||||
@@ -31,27 +31,27 @@ class Whatsapp::Providers::BaseService
|
||||
raise 'Overwrite this method in child class'
|
||||
end
|
||||
|
||||
def process_response(response)
|
||||
def process_response(response, message)
|
||||
parsed_response = response.parsed_response
|
||||
if response.success? && parsed_response['error'].blank?
|
||||
parsed_response['messages'].first['id']
|
||||
else
|
||||
handle_error(response)
|
||||
handle_error(response, message)
|
||||
nil
|
||||
end
|
||||
end
|
||||
|
||||
def handle_error(response)
|
||||
def handle_error(response, message)
|
||||
Rails.logger.error response.body
|
||||
return if @message.blank?
|
||||
return if message.blank?
|
||||
|
||||
# https://developers.facebook.com/docs/whatsapp/cloud-api/support/error-codes/#sample-response
|
||||
error_message = error_message(response)
|
||||
return if error_message.blank?
|
||||
|
||||
@message.external_error = error_message
|
||||
@message.status = :failed
|
||||
@message.save!
|
||||
message.external_error = error_message
|
||||
message.status = :failed
|
||||
message.save!
|
||||
end
|
||||
|
||||
def create_buttons(items)
|
||||
|
||||
@@ -10,7 +10,7 @@ class Whatsapp::Providers::Whatsapp360DialogService < Whatsapp::Providers::BaseS
|
||||
end
|
||||
end
|
||||
|
||||
def send_template(phone_number, template_info)
|
||||
def send_template(phone_number, template_info, message)
|
||||
response = HTTParty.post(
|
||||
"#{api_base_path}/messages",
|
||||
headers: api_headers,
|
||||
@@ -21,7 +21,7 @@ class Whatsapp::Providers::Whatsapp360DialogService < Whatsapp::Providers::BaseS
|
||||
}.to_json
|
||||
)
|
||||
|
||||
process_response(response)
|
||||
process_response(response, message)
|
||||
end
|
||||
|
||||
def sync_templates
|
||||
@@ -68,7 +68,7 @@ class Whatsapp::Providers::Whatsapp360DialogService < Whatsapp::Providers::BaseS
|
||||
}.to_json
|
||||
)
|
||||
|
||||
process_response(response)
|
||||
process_response(response, message)
|
||||
end
|
||||
|
||||
def send_attachment_message(phone_number, message)
|
||||
@@ -90,7 +90,7 @@ class Whatsapp::Providers::Whatsapp360DialogService < Whatsapp::Providers::BaseS
|
||||
}.to_json
|
||||
)
|
||||
|
||||
process_response(response)
|
||||
process_response(response, message)
|
||||
end
|
||||
|
||||
def error_message(response)
|
||||
@@ -123,6 +123,6 @@ class Whatsapp::Providers::Whatsapp360DialogService < Whatsapp::Providers::BaseS
|
||||
}.to_json
|
||||
)
|
||||
|
||||
process_response(response)
|
||||
process_response(response, message)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -11,7 +11,7 @@ class Whatsapp::Providers::WhatsappCloudService < Whatsapp::Providers::BaseServi
|
||||
end
|
||||
end
|
||||
|
||||
def send_template(phone_number, template_info)
|
||||
def send_template(phone_number, template_info, message)
|
||||
template_body = template_body_parameters(template_info)
|
||||
|
||||
request_body = {
|
||||
@@ -28,7 +28,7 @@ class Whatsapp::Providers::WhatsappCloudService < Whatsapp::Providers::BaseServi
|
||||
body: request_body.to_json
|
||||
)
|
||||
|
||||
process_response(response)
|
||||
process_response(response, message)
|
||||
end
|
||||
|
||||
def sync_templates
|
||||
@@ -92,7 +92,7 @@ class Whatsapp::Providers::WhatsappCloudService < Whatsapp::Providers::BaseServi
|
||||
}.to_json
|
||||
)
|
||||
|
||||
process_response(response)
|
||||
process_response(response, message)
|
||||
end
|
||||
|
||||
def send_attachment_message(phone_number, message)
|
||||
@@ -115,7 +115,7 @@ class Whatsapp::Providers::WhatsappCloudService < Whatsapp::Providers::BaseServi
|
||||
}.to_json
|
||||
)
|
||||
|
||||
process_response(response)
|
||||
process_response(response, message)
|
||||
end
|
||||
|
||||
def error_message(response)
|
||||
@@ -179,6 +179,6 @@ class Whatsapp::Providers::WhatsappCloudService < Whatsapp::Providers::BaseServi
|
||||
}.to_json
|
||||
)
|
||||
|
||||
process_response(response)
|
||||
process_response(response, message)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -33,7 +33,7 @@ class Whatsapp::SendOnWhatsappService < Base::SendOnChannelService
|
||||
namespace: namespace,
|
||||
lang_code: lang_code,
|
||||
parameters: processed_parameters
|
||||
})
|
||||
}, message)
|
||||
message.update!(source_id: message_id) if message_id.present?
|
||||
end
|
||||
|
||||
|
||||
@@ -86,6 +86,9 @@ class Whatsapp::TemplateParameterConverterService
|
||||
# Hash format: {"1": "John", "name": "Jane"} → {body: {"1": "John", "name": "Jane"}}
|
||||
body_params = convert_hash_to_body_params(legacy_params)
|
||||
enhanced['body'] = body_params unless body_params.empty?
|
||||
when NilClass
|
||||
# Templates without parameters (nil processed_params)
|
||||
# Return empty enhanced structure
|
||||
else
|
||||
raise ArgumentError, "Unknown legacy format: #{legacy_params.class}"
|
||||
end
|
||||
|
||||
@@ -191,6 +191,3 @@
|
||||
display_name: CRM V2
|
||||
enabled: false
|
||||
chatwoot_internal: true
|
||||
- name: assignment_v2
|
||||
display_name: Assignment V2
|
||||
enabled: false
|
||||
|
||||
@@ -50,9 +50,6 @@ Rails.application.routes.draw do
|
||||
resource :bulk_actions, only: [:create]
|
||||
resources :agents, only: [:index, :create, :update, :destroy] do
|
||||
post :bulk_create, on: :collection
|
||||
member do
|
||||
get 'capacity', to: 'agents/capacity#show'
|
||||
end
|
||||
end
|
||||
namespace :captain do
|
||||
resources :assistants do
|
||||
@@ -100,13 +97,6 @@ Rails.application.routes.draw do
|
||||
end
|
||||
resources :sla_policies, only: [:index, :create, :show, :update, :destroy]
|
||||
resources :custom_roles, only: [:index, :create, :show, :update, :destroy]
|
||||
resources :agent_capacity_policies, only: [:index, :create, :show, :update, :destroy] do
|
||||
member do
|
||||
post 'users', to: 'agent_capacity_policies#assign_user'
|
||||
delete 'users/:user_id', to: 'agent_capacity_policies#unassign_user'
|
||||
put 'inbox_limits/:inbox_id', to: 'agent_capacity_policies#update_inbox_limit'
|
||||
end
|
||||
end
|
||||
resources :campaigns, only: [:index, :create, :show, :update, :destroy]
|
||||
resources :dashboard_apps, only: [:index, :show, :create, :update, :destroy]
|
||||
namespace :channels do
|
||||
@@ -227,13 +217,6 @@ Rails.application.routes.draw do
|
||||
end
|
||||
end
|
||||
|
||||
# Assignment V2 Routes
|
||||
resources :assignment_policies
|
||||
|
||||
resources :inboxes, only: [] do
|
||||
resource :assignment_policy, only: [:show, :create, :destroy], controller: 'inbox_assignment_policies'
|
||||
end
|
||||
|
||||
namespace :twitter do
|
||||
resource :authorization, only: [:create]
|
||||
end
|
||||
|
||||
@@ -320,7 +320,6 @@ ActiveRecord::Schema[7.1].define(version: 2025_08_08_123008) do
|
||||
t.datetime "created_at", null: false
|
||||
t.datetime "updated_at", null: false
|
||||
t.integer "status", default: 0, null: false
|
||||
t.jsonb "metadata", default: {}
|
||||
t.index ["account_id"], name: "index_captain_documents_on_account_id"
|
||||
t.index ["assistant_id", "external_link"], name: "index_captain_documents_on_assistant_id_and_external_link", unique: true
|
||||
t.index ["assistant_id"], name: "index_captain_documents_on_assistant_id"
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
class Api::V1::Accounts::AgentCapacityPoliciesController < Api::V1::Accounts::EnterpriseAccountsController
|
||||
before_action :fetch_policy, only: [:show, :update, :destroy, :assign_user, :unassign_user, :update_inbox_limit]
|
||||
before_action :check_enterprise_authorization
|
||||
|
||||
def index
|
||||
@agent_capacity_policies = Current.account.agent_capacity_policies
|
||||
end
|
||||
|
||||
def show; end
|
||||
|
||||
def create
|
||||
@agent_capacity_policy = Current.account.agent_capacity_policies.create!(permitted_params)
|
||||
end
|
||||
|
||||
def update
|
||||
@agent_capacity_policy.update!(permitted_params)
|
||||
end
|
||||
|
||||
def destroy
|
||||
@agent_capacity_policy.destroy!
|
||||
head :ok
|
||||
end
|
||||
|
||||
def assign_user
|
||||
user = Current.account.users.find(params[:user_id])
|
||||
account_user = Current.account.account_users.find_by!(user: user)
|
||||
account_user.update!(agent_capacity_policy: @agent_capacity_policy)
|
||||
render json: { message: 'User assigned successfully' }
|
||||
end
|
||||
|
||||
def unassign_user
|
||||
user = Current.account.users.find(params[:user_id])
|
||||
account_user = Current.account.account_users.find_by!(user: user)
|
||||
account_user.update!(agent_capacity_policy: nil)
|
||||
render json: { message: 'User unassigned successfully' }
|
||||
end
|
||||
|
||||
def update_inbox_limit
|
||||
inbox = Current.account.inboxes.find(params[:inbox_id])
|
||||
inbox_limit = @agent_capacity_policy.inbox_capacity_limits.find_or_initialize_by(inbox: inbox)
|
||||
inbox_limit.update!(conversation_limit: params[:conversation_limit])
|
||||
render json: inbox_limit
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def permitted_params
|
||||
params.require(:agent_capacity_policy).permit(:name, :description, exclusion_rules: {})
|
||||
end
|
||||
|
||||
def fetch_policy
|
||||
@agent_capacity_policy = Current.account.agent_capacity_policies.find(params[:id])
|
||||
end
|
||||
|
||||
def check_enterprise_authorization
|
||||
authorize(Enterprise::AgentCapacityPolicy)
|
||||
end
|
||||
end
|
||||
@@ -1,39 +0,0 @@
|
||||
class Api::V1::Accounts::Agents::CapacityController < Api::V1::Accounts::EnterpriseAccountsController
|
||||
before_action :fetch_agent
|
||||
|
||||
def show
|
||||
account_user = Current.account.account_users.find_by!(user: @agent)
|
||||
capacity_service = Enterprise::AssignmentV2::CapacityService.new(account_user)
|
||||
inbox = fetch_inbox
|
||||
|
||||
render json: build_capacity_response(account_user, capacity_service, inbox)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def fetch_agent
|
||||
@agent = Current.account.users.find(params[:id])
|
||||
end
|
||||
|
||||
def fetch_inbox
|
||||
return if params[:inbox_id].blank?
|
||||
|
||||
Current.account.inboxes.find(params[:inbox_id])
|
||||
end
|
||||
|
||||
def build_capacity_response(account_user, capacity_service, inbox)
|
||||
response = {
|
||||
has_capacity: capacity_service.agent_has_capacity?(inbox),
|
||||
overall_capacity: capacity_service.agent_overall_capacity,
|
||||
inbox_capacity: inbox ? capacity_service.agent_capacity_for_inbox(inbox) : nil,
|
||||
current_conversations_count: account_user.user.assigned_conversations.open.count
|
||||
}
|
||||
|
||||
add_inbox_conversations_count(response, account_user, inbox) if inbox
|
||||
response
|
||||
end
|
||||
|
||||
def add_inbox_conversations_count(response, account_user, inbox)
|
||||
response[:inbox_conversations_count] = account_user.user.assigned_conversations.open.where(inbox: inbox).count
|
||||
end
|
||||
end
|
||||
@@ -1,46 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
class Enterprise::AgentCapacityPolicy < ApplicationRecord
|
||||
self.table_name = 'agent_capacity_policies'
|
||||
|
||||
belongs_to :account, class_name: '::Account'
|
||||
has_many :inbox_capacity_limits, class_name: 'Enterprise::InboxCapacityLimit', dependent: :destroy
|
||||
has_many :inboxes, through: :inbox_capacity_limits, class_name: '::Inbox'
|
||||
has_many :account_users, class_name: '::AccountUser', dependent: :nullify
|
||||
|
||||
validates :name, presence: true, length: { maximum: 255 }
|
||||
|
||||
def applicable_for_time?(time = Time.current)
|
||||
return true if exclusion_rules.blank?
|
||||
|
||||
!excluded_for_time?(time)
|
||||
end
|
||||
|
||||
def capacity_for_inbox(inbox)
|
||||
inbox_capacity_limits.find_by(inbox: inbox)&.conversation_limit
|
||||
end
|
||||
|
||||
def overall_capacity
|
||||
exclusion_rules['overall_capacity'] || Float::INFINITY
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def excluded_for_time?(time)
|
||||
excluded_by_hours?(time) || excluded_by_days?(time)
|
||||
end
|
||||
|
||||
def excluded_by_hours?(time)
|
||||
return false if exclusion_rules['hours'].blank?
|
||||
|
||||
current_hour = time.hour
|
||||
exclusion_rules['hours'].include?(current_hour)
|
||||
end
|
||||
|
||||
def excluded_by_days?(time)
|
||||
return false if exclusion_rules['days'].blank?
|
||||
|
||||
current_day = time.strftime('%A').downcase
|
||||
exclusion_rules['days'].include?(current_day)
|
||||
end
|
||||
end
|
||||
@@ -1,27 +0,0 @@
|
||||
module Enterprise::AssignmentPolicy
|
||||
# In enterprise, we extend the enum to include balanced
|
||||
# However, since Rails enums are frozen after definition,
|
||||
# we need to handle this differently
|
||||
|
||||
# Override assignment_order= to accept 'balanced'
|
||||
def assignment_order=(value)
|
||||
if value.to_s == 'balanced'
|
||||
write_attribute(:assignment_order, 1)
|
||||
else
|
||||
super
|
||||
end
|
||||
end
|
||||
|
||||
# Override assignment_order getter to return 'balanced' for value 1
|
||||
def assignment_order
|
||||
value = read_attribute(:assignment_order)
|
||||
return 'balanced' if value == 1
|
||||
|
||||
super
|
||||
end
|
||||
|
||||
# Define balanced? method
|
||||
def balanced?
|
||||
self[:assignment_order] == 1
|
||||
end
|
||||
end
|
||||
@@ -5,7 +5,6 @@ module Enterprise::Concerns::Account
|
||||
has_many :sla_policies, dependent: :destroy_async
|
||||
has_many :applied_slas, dependent: :destroy_async
|
||||
has_many :custom_roles, dependent: :destroy_async
|
||||
has_many :agent_capacity_policies, dependent: :destroy_async, class_name: 'Enterprise::AgentCapacityPolicy'
|
||||
|
||||
has_many :captain_assistants, dependent: :destroy_async, class_name: 'Captain::Assistant'
|
||||
has_many :captain_assistant_responses, dependent: :destroy_async, class_name: 'Captain::AssistantResponse'
|
||||
|
||||
@@ -3,6 +3,5 @@ module Enterprise::Concerns::AccountUser
|
||||
|
||||
included do
|
||||
belongs_to :custom_role, optional: true
|
||||
belongs_to :agent_capacity_policy, class_name: 'Enterprise::AgentCapacityPolicy', optional: true
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Enterprise::Concerns::InboxAgentAvailability
|
||||
def apply_agent_filters(scope, options)
|
||||
scope = super(scope, options)
|
||||
|
||||
# Apply capacity filtering if requested
|
||||
scope = filter_by_capacity(scope) if options[:check_capacity]
|
||||
|
||||
scope
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def filter_by_capacity(inbox_members_scope)
|
||||
return inbox_members_scope unless assignment_policy&.enabled?
|
||||
|
||||
inbox_members_scope.select do |inbox_member|
|
||||
account_user = AccountUser.find_by(account: account, user: inbox_member.user)
|
||||
next true if account_user&.agent_capacity_policy.blank?
|
||||
|
||||
capacity_service = Enterprise::AssignmentV2::CapacityService.new(account_user)
|
||||
capacity_service.agent_has_capacity?(self)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -2,17 +2,9 @@ module Enterprise::Inbox
|
||||
def member_ids_with_assignment_capacity
|
||||
return super unless enable_auto_assignment?
|
||||
|
||||
member_ids = apply_max_assignment_limit(super)
|
||||
apply_capacity_policy_filter(member_ids)
|
||||
end
|
||||
|
||||
def available_agents(options = {})
|
||||
agents = super(options)
|
||||
|
||||
# Apply capacity filtering if requested and assignment policy is enabled
|
||||
agents = filter_agents_by_capacity(agents) if options[:check_capacity] && assignment_policy&.enabled?
|
||||
|
||||
agents
|
||||
max_assignment_limit = auto_assignment_config['max_assignment_limit']
|
||||
overloaded_agent_ids = max_assignment_limit.present? ? get_agent_ids_over_assignment_limit(max_assignment_limit) : []
|
||||
super - overloaded_agent_ids
|
||||
end
|
||||
|
||||
def active_bot?
|
||||
@@ -25,36 +17,6 @@ module Enterprise::Inbox
|
||||
|
||||
private
|
||||
|
||||
def filter_agents_by_capacity(inbox_members_scope)
|
||||
inbox_members_scope.select do |inbox_member|
|
||||
account_user = AccountUser.find_by(account: account, user: inbox_member.user)
|
||||
next true if account_user&.agent_capacity_policy.blank?
|
||||
|
||||
capacity_service = Enterprise::AssignmentV2::CapacityService.new(account_user)
|
||||
capacity_service.agent_has_capacity?(self)
|
||||
end
|
||||
end
|
||||
|
||||
def apply_max_assignment_limit(member_ids)
|
||||
max_assignment_limit = auto_assignment_config['max_assignment_limit']
|
||||
return member_ids if max_assignment_limit.blank?
|
||||
|
||||
overloaded_agent_ids = get_agent_ids_over_assignment_limit(max_assignment_limit)
|
||||
member_ids - overloaded_agent_ids
|
||||
end
|
||||
|
||||
def apply_capacity_policy_filter(member_ids)
|
||||
return member_ids unless assignment_policy&.enabled?
|
||||
|
||||
account_users = AccountUser.where(account_id: account_id, user_id: member_ids)
|
||||
account_users.select do |account_user|
|
||||
next true if account_user.agent_capacity_policy.blank?
|
||||
|
||||
capacity_service = Enterprise::AssignmentV2::CapacityService.new(account_user)
|
||||
capacity_service.agent_has_capacity?(self)
|
||||
end.map(&:user_id)
|
||||
end
|
||||
|
||||
def more_responses?
|
||||
account.usage_limits[:captain][:responses][:current_available].positive?
|
||||
end
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
class Enterprise::InboxCapacityLimit < ApplicationRecord
|
||||
self.table_name = 'inbox_capacity_limits'
|
||||
|
||||
belongs_to :agent_capacity_policy, class_name: 'Enterprise::AgentCapacityPolicy'
|
||||
belongs_to :inbox, class_name: '::Inbox'
|
||||
|
||||
validates :conversation_limit, presence: true, numericality: { greater_than_or_equal_to: 0 }
|
||||
validates :inbox_id, uniqueness: { scope: :agent_capacity_policy_id }
|
||||
end
|
||||
@@ -1,33 +0,0 @@
|
||||
class Enterprise::AgentCapacityPolicyPolicy < ApplicationPolicy
|
||||
def index?
|
||||
@account_user.administrator? || @account_user.agent?
|
||||
end
|
||||
|
||||
def update?
|
||||
@account_user.administrator?
|
||||
end
|
||||
|
||||
def show?
|
||||
@account_user.administrator? || @account_user.agent?
|
||||
end
|
||||
|
||||
def create?
|
||||
@account_user.administrator?
|
||||
end
|
||||
|
||||
def destroy?
|
||||
@account_user.administrator?
|
||||
end
|
||||
|
||||
def assign_user?
|
||||
@account_user.administrator?
|
||||
end
|
||||
|
||||
def unassign_user?
|
||||
@account_user.administrator?
|
||||
end
|
||||
|
||||
def update_inbox_limit?
|
||||
@account_user.administrator?
|
||||
end
|
||||
end
|
||||
@@ -1,25 +0,0 @@
|
||||
module Enterprise::AssignmentV2::AssignmentService
|
||||
# Override selector_service to use BalancedSelector when appropriate
|
||||
def selector_service
|
||||
@selector_service ||= if policy&.balanced?
|
||||
Enterprise::AssignmentV2::BalancedSelector.new(inbox: inbox)
|
||||
else
|
||||
super
|
||||
end
|
||||
end
|
||||
|
||||
# Override find_agent_for_conversation to include capacity checks
|
||||
def find_agent_for_conversation(_conversation)
|
||||
available_agents = inbox.available_agents(
|
||||
check_rate_limits: true,
|
||||
check_capacity: true
|
||||
)
|
||||
|
||||
if available_agents.empty?
|
||||
log_no_agents_available
|
||||
return nil
|
||||
end
|
||||
|
||||
selector_service.select_agent(available_agents)
|
||||
end
|
||||
end
|
||||
@@ -1,54 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
class Enterprise::AssignmentV2::BalancedSelector
|
||||
pattr_initialize [:inbox!]
|
||||
|
||||
def select_agent(available_agents)
|
||||
return nil if available_agents.empty?
|
||||
|
||||
# Get current assignment counts for all available agents
|
||||
agent_users = available_agents.map(&:user)
|
||||
assignment_counts = fetch_assignment_counts(agent_users)
|
||||
|
||||
# Find the agent with the least assignments
|
||||
selected_agent = agent_users.min_by { |user| assignment_counts[user.id] || 0 }
|
||||
|
||||
# Log the selection for debugging
|
||||
Rails.logger.info "BalancedSelector: Selected agent #{selected_agent.id} with #{assignment_counts[selected_agent.id] || 0} assignments"
|
||||
|
||||
selected_agent
|
||||
end
|
||||
|
||||
def add_agent_to_queue(user_id)
|
||||
# No-op for balanced assignment - we don't maintain a queue
|
||||
end
|
||||
|
||||
def remove_agent_from_queue(user_id)
|
||||
# No-op for balanced assignment - we don't maintain a queue
|
||||
end
|
||||
|
||||
def reset_queue
|
||||
# No-op for balanced assignment - we don't maintain a queue
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def fetch_assignment_counts(users)
|
||||
# Get open conversation counts for each user
|
||||
user_ids = users.map(&:id)
|
||||
|
||||
# Count open conversations assigned to each user in this inbox
|
||||
counts = inbox.conversations
|
||||
.open
|
||||
.where(assignee_id: user_ids)
|
||||
.group(:assignee_id)
|
||||
.count
|
||||
|
||||
# Convert to hash with default value of 0
|
||||
Hash.new(0).merge(counts)
|
||||
end
|
||||
|
||||
def account
|
||||
@account ||= inbox.account
|
||||
end
|
||||
end
|
||||
@@ -1,76 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
class Enterprise::AssignmentV2::CapacityService
|
||||
def initialize(account_user)
|
||||
@account_user = account_user
|
||||
@account = account_user.account
|
||||
end
|
||||
|
||||
def agent_has_capacity?(inbox = nil)
|
||||
return true unless capacity_policy_applicable?
|
||||
|
||||
if inbox
|
||||
check_inbox_capacity(inbox)
|
||||
else
|
||||
check_overall_capacity
|
||||
end
|
||||
end
|
||||
|
||||
def agent_capacity_for_inbox(inbox)
|
||||
return Float::INFINITY unless capacity_policy_applicable?
|
||||
|
||||
policy = @account_user.agent_capacity_policy
|
||||
inbox_limit = policy.capacity_for_inbox(inbox)
|
||||
return Float::INFINITY unless inbox_limit
|
||||
|
||||
current_count = current_conversations_count(inbox)
|
||||
[inbox_limit - current_count, 0].max
|
||||
end
|
||||
|
||||
def agent_overall_capacity
|
||||
return Float::INFINITY unless capacity_policy_applicable?
|
||||
|
||||
policy = @account_user.agent_capacity_policy
|
||||
overall_limit = policy.overall_capacity
|
||||
return Float::INFINITY if overall_limit == Float::INFINITY
|
||||
|
||||
current_count = current_conversations_count
|
||||
[overall_limit - current_count, 0].max
|
||||
end
|
||||
|
||||
def current_conversations_count(inbox = nil)
|
||||
scope = @account_user.user.conversations
|
||||
.joins(:account)
|
||||
.where(account: @account, status: :open)
|
||||
scope = scope.where(inbox: inbox) if inbox
|
||||
scope.count
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def capacity_policy_applicable?
|
||||
return false if @account_user.agent_capacity_policy.blank?
|
||||
|
||||
@account_user.agent_capacity_policy.applicable_for_time?
|
||||
end
|
||||
|
||||
def check_inbox_capacity(inbox)
|
||||
policy = @account_user.agent_capacity_policy
|
||||
inbox_limit = policy.capacity_for_inbox(inbox)
|
||||
|
||||
return check_overall_capacity unless inbox_limit
|
||||
|
||||
current_count = current_conversations_count(inbox)
|
||||
current_count < inbox_limit && check_overall_capacity
|
||||
end
|
||||
|
||||
def check_overall_capacity
|
||||
policy = @account_user.agent_capacity_policy
|
||||
overall_limit = policy.overall_capacity
|
||||
|
||||
return true if overall_limit == Float::INFINITY
|
||||
|
||||
current_count = current_conversations_count
|
||||
current_count < overall_limit
|
||||
end
|
||||
end
|
||||
@@ -1,12 +0,0 @@
|
||||
json.id @agent_capacity_policy.id
|
||||
json.name @agent_capacity_policy.name
|
||||
json.description @agent_capacity_policy.description
|
||||
json.exclusion_rules @agent_capacity_policy.exclusion_rules
|
||||
json.created_at @agent_capacity_policy.created_at
|
||||
json.updated_at @agent_capacity_policy.updated_at
|
||||
json.account_id @agent_capacity_policy.account_id
|
||||
json.inbox_capacity_limits @agent_capacity_policy.inbox_capacity_limits do |limit|
|
||||
json.id limit.id
|
||||
json.inbox_id limit.inbox_id
|
||||
json.conversation_limit limit.conversation_limit
|
||||
end
|
||||
@@ -1,14 +0,0 @@
|
||||
json.array! @agent_capacity_policies do |policy|
|
||||
json.id policy.id
|
||||
json.name policy.name
|
||||
json.description policy.description
|
||||
json.exclusion_rules policy.exclusion_rules
|
||||
json.created_at policy.created_at
|
||||
json.updated_at policy.updated_at
|
||||
json.account_id policy.account_id
|
||||
json.inbox_capacity_limits policy.inbox_capacity_limits do |limit|
|
||||
json.id limit.id
|
||||
json.inbox_id limit.inbox_id
|
||||
json.conversation_limit limit.conversation_limit
|
||||
end
|
||||
end
|
||||
@@ -1,12 +0,0 @@
|
||||
json.id @agent_capacity_policy.id
|
||||
json.name @agent_capacity_policy.name
|
||||
json.description @agent_capacity_policy.description
|
||||
json.exclusion_rules @agent_capacity_policy.exclusion_rules
|
||||
json.created_at @agent_capacity_policy.created_at
|
||||
json.updated_at @agent_capacity_policy.updated_at
|
||||
json.account_id @agent_capacity_policy.account_id
|
||||
json.inbox_capacity_limits @agent_capacity_policy.inbox_capacity_limits do |limit|
|
||||
json.id limit.id
|
||||
json.inbox_id limit.inbox_id
|
||||
json.conversation_limit limit.conversation_limit
|
||||
end
|
||||
@@ -1,12 +0,0 @@
|
||||
json.id @agent_capacity_policy.id
|
||||
json.name @agent_capacity_policy.name
|
||||
json.description @agent_capacity_policy.description
|
||||
json.exclusion_rules @agent_capacity_policy.exclusion_rules
|
||||
json.created_at @agent_capacity_policy.created_at
|
||||
json.updated_at @agent_capacity_policy.updated_at
|
||||
json.account_id @agent_capacity_policy.account_id
|
||||
json.inbox_capacity_limits @agent_capacity_policy.inbox_capacity_limits do |limit|
|
||||
json.id limit.id
|
||||
json.inbox_id limit.inbox_id
|
||||
json.conversation_limit limit.conversation_limit
|
||||
end
|
||||
@@ -68,6 +68,12 @@ RSpec.describe 'Api::V1::Accounts::AutomationRulesController', type: :request do
|
||||
'action_name': :assign_team,
|
||||
'action_params': [1]
|
||||
},
|
||||
{
|
||||
'action_name': :remove_assigned_agent
|
||||
},
|
||||
{
|
||||
'action_name': :remove_assigned_team
|
||||
},
|
||||
{
|
||||
'action_name': :add_label,
|
||||
'action_params': %w[support priority_customer]
|
||||
|
||||
@@ -78,6 +78,9 @@ RSpec.describe 'Api::V1::Accounts::MacrosController', type: :request do
|
||||
'action_name': :add_label,
|
||||
'action_params': %w[support priority_customer]
|
||||
},
|
||||
{
|
||||
'action_name': :remove_assigned_agent
|
||||
},
|
||||
{
|
||||
'action_name': :remove_assigned_team
|
||||
},
|
||||
@@ -410,6 +413,22 @@ RSpec.describe 'Api::V1::Accounts::MacrosController', type: :request do
|
||||
|
||||
expect(conversation.reload.team_id).to be_nil
|
||||
end
|
||||
|
||||
it 'Unassign the agent' do
|
||||
macro.update!(actions: [
|
||||
{ 'action_name' => 'remove_assigned_agent' }
|
||||
])
|
||||
conversation.update!(assignee: user_1)
|
||||
expect(conversation.reload.assignee).to be_present
|
||||
|
||||
perform_enqueued_jobs do
|
||||
post "/api/v1/accounts/#{account.id}/macros/#{macro.id}/execute",
|
||||
params: { conversation_ids: [conversation.display_id] },
|
||||
headers: administrator.create_new_auth_token
|
||||
end
|
||||
|
||||
expect(conversation.reload.assignee).to be_nil
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,128 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe Enterprise::AgentCapacityPolicy do
|
||||
let(:account) { create(:account) }
|
||||
let(:policy) { described_class.create!(account: account, name: 'Test Policy') }
|
||||
|
||||
describe 'associations' do
|
||||
it 'belongs to account' do
|
||||
expect(policy.account).to eq(account)
|
||||
end
|
||||
|
||||
it 'has many inbox capacity limits' do
|
||||
expect(policy).to respond_to(:inbox_capacity_limits)
|
||||
end
|
||||
|
||||
it 'has many inboxes through inbox capacity limits' do
|
||||
expect(policy).to respond_to(:inboxes)
|
||||
end
|
||||
|
||||
it 'has many account users' do
|
||||
expect(policy).to respond_to(:account_users)
|
||||
end
|
||||
end
|
||||
|
||||
describe 'validations' do
|
||||
it 'validates presence of name' do
|
||||
invalid_policy = described_class.new(account: account)
|
||||
expect(invalid_policy).not_to be_valid
|
||||
expect(invalid_policy.errors[:name]).to include("can't be blank")
|
||||
end
|
||||
|
||||
it 'validates length of name' do
|
||||
invalid_policy = described_class.new(account: account, name: 'a' * 256)
|
||||
expect(invalid_policy).not_to be_valid
|
||||
expect(invalid_policy.errors[:name]).to include('is too long (maximum is 255 characters)')
|
||||
end
|
||||
end
|
||||
|
||||
describe '#applicable_for_time?' do
|
||||
context 'when no exclusion rules' do
|
||||
it 'returns true' do
|
||||
expect(policy.applicable_for_time?).to be true
|
||||
end
|
||||
end
|
||||
|
||||
context 'with hour exclusions' do
|
||||
let(:policy) do
|
||||
described_class.create!(
|
||||
account: account,
|
||||
name: 'Hour Exclusion Policy',
|
||||
exclusion_rules: { 'hours' => [10, 11, 12] }
|
||||
)
|
||||
end
|
||||
|
||||
it 'returns false during excluded hours' do
|
||||
time = Time.zone.parse('10:30')
|
||||
expect(policy.applicable_for_time?(time)).to be false
|
||||
end
|
||||
|
||||
it 'returns true outside excluded hours' do
|
||||
time = Time.zone.parse('13:30')
|
||||
expect(policy.applicable_for_time?(time)).to be true
|
||||
end
|
||||
end
|
||||
|
||||
context 'with day exclusions' do
|
||||
let(:policy) do
|
||||
described_class.create!(
|
||||
account: account,
|
||||
name: 'Day Exclusion Policy',
|
||||
exclusion_rules: { 'days' => %w[saturday sunday] }
|
||||
)
|
||||
end
|
||||
|
||||
it 'returns false on excluded days' do
|
||||
time = Time.zone.parse('2024-01-06 10:00') # Saturday
|
||||
expect(policy.applicable_for_time?(time)).to be false
|
||||
end
|
||||
|
||||
it 'returns true on non-excluded days' do
|
||||
time = Time.zone.parse('2024-01-08 10:00') # Monday
|
||||
expect(policy.applicable_for_time?(time)).to be true
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe '#capacity_for_inbox' do
|
||||
let(:inbox) { create(:inbox, account: account) }
|
||||
|
||||
it 'returns the conversation limit for the inbox' do
|
||||
Enterprise::InboxCapacityLimit.create!(
|
||||
agent_capacity_policy: policy,
|
||||
inbox: inbox,
|
||||
conversation_limit: 10
|
||||
)
|
||||
expect(policy.capacity_for_inbox(inbox)).to eq(10)
|
||||
end
|
||||
|
||||
it 'returns nil for inbox without limit' do
|
||||
other_inbox = create(:inbox, account: account)
|
||||
expect(policy.capacity_for_inbox(other_inbox)).to be_nil
|
||||
end
|
||||
end
|
||||
|
||||
describe '#overall_capacity' do
|
||||
context 'when overall_capacity is set' do
|
||||
let(:policy) do
|
||||
described_class.create!(
|
||||
account: account,
|
||||
name: 'Overall Capacity Policy',
|
||||
exclusion_rules: { 'overall_capacity' => 25 }
|
||||
)
|
||||
end
|
||||
|
||||
it 'returns the overall capacity' do
|
||||
expect(policy.overall_capacity).to eq(25)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when overall_capacity is not set' do
|
||||
it 'returns infinity' do
|
||||
expect(policy.overall_capacity).to eq(Float::INFINITY)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,141 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe 'Assignment with Capacity' do
|
||||
let(:account) { create(:account) }
|
||||
let(:inbox) { create(:inbox, account: account, enable_auto_assignment: false) }
|
||||
|
||||
let(:agent1) { create(:user, accounts: [account]) }
|
||||
let(:agent2) { create(:user, accounts: [account]) }
|
||||
let(:account_user1) { AccountUser.find_by(account: account, user: agent1) }
|
||||
let(:account_user2) { AccountUser.find_by(account: account, user: agent2) }
|
||||
|
||||
let(:capacity_policy) do
|
||||
Enterprise::AgentCapacityPolicy.create!(
|
||||
account: account,
|
||||
name: 'Test Capacity Policy',
|
||||
exclusion_rules: { 'overall_capacity' => 5 }
|
||||
)
|
||||
end
|
||||
|
||||
let!(:inbox_capacity_limit) do
|
||||
Enterprise::InboxCapacityLimit.create!(
|
||||
agent_capacity_policy: capacity_policy,
|
||||
inbox: inbox,
|
||||
conversation_limit: 3
|
||||
)
|
||||
end
|
||||
|
||||
before do
|
||||
# Create and setup assignment policy for the inbox
|
||||
@assignment_policy = create(:assignment_policy, account: account, enabled: true)
|
||||
create(:inbox_assignment_policy, inbox: inbox, assignment_policy: @assignment_policy)
|
||||
|
||||
# Add agents to inbox
|
||||
create(:inbox_member, inbox: inbox, user: agent1)
|
||||
create(:inbox_member, inbox: inbox, user: agent2)
|
||||
|
||||
# Set agents online using presence and status
|
||||
OnlineStatusTracker.update_presence(account.id, 'User', agent1.id)
|
||||
OnlineStatusTracker.update_presence(account.id, 'User', agent2.id)
|
||||
OnlineStatusTracker.set_status(account.id, agent1.id, 'online')
|
||||
OnlineStatusTracker.set_status(account.id, agent2.id, 'online')
|
||||
|
||||
# Also set account_user availability
|
||||
account_user1.update!(availability: 'online')
|
||||
account_user2.update!(availability: 'online')
|
||||
|
||||
# Assign capacity policy to agent1 only
|
||||
account_user1.update!(agent_capacity_policy: capacity_policy)
|
||||
end
|
||||
|
||||
describe 'capacity-based agent filtering' do
|
||||
context 'when agent has capacity' do
|
||||
it 'includes agent in available agents' do
|
||||
available_agents = inbox.available_agents(check_capacity: true)
|
||||
expect(available_agents.map(&:user)).to include(agent1, agent2)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when agent reaches inbox capacity limit' do
|
||||
before do
|
||||
# Create 3 conversations for agent1 (at inbox limit)
|
||||
create_list(:conversation, 3, account: account, inbox: inbox, assignee: agent1, status: :open)
|
||||
end
|
||||
|
||||
it 'excludes agent from available agents for that inbox' do
|
||||
available_agents = inbox.available_agents(check_capacity: true)
|
||||
expect(available_agents.map(&:user)).not_to include(agent1)
|
||||
expect(available_agents.map(&:user)).to include(agent2)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when agent reaches overall capacity limit' do
|
||||
before do
|
||||
# Create 5 conversations for agent1 (at overall limit)
|
||||
create_list(:conversation, 5, account: account, assignee: agent1, status: :open)
|
||||
end
|
||||
|
||||
it 'excludes agent from all inbox assignments' do
|
||||
available_agents = inbox.available_agents(check_capacity: true)
|
||||
expect(available_agents.map(&:user)).not_to include(agent1)
|
||||
expect(available_agents.map(&:user)).to include(agent2)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when capacity policy is not applicable (time exclusion)' do
|
||||
before do
|
||||
capacity_policy.update!(exclusion_rules: {
|
||||
'overall_capacity' => 5,
|
||||
'hours' => [Time.current.hour]
|
||||
})
|
||||
# Create 5 conversations for agent1 (would be at limit if policy was active)
|
||||
create_list(:conversation, 5, account: account, assignee: agent1, status: :open)
|
||||
end
|
||||
|
||||
it 'includes agent in available agents' do
|
||||
available_agents = inbox.available_agents(check_capacity: true)
|
||||
expect(available_agents.map(&:user)).to include(agent1, agent2)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'capacity-aware assignment' do
|
||||
let(:conversation) { create(:conversation, account: account, inbox: inbox, status: :open, assignee: nil) }
|
||||
|
||||
context 'when agents have capacity' do
|
||||
it 'both agents are available for assignment' do
|
||||
available = inbox.available_agents(check_capacity: true)
|
||||
expect(available.map(&:user)).to include(agent1, agent2)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when one agent is at capacity' do
|
||||
before do
|
||||
# Agent1 at inbox capacity
|
||||
create_list(:conversation, 3, account: account, inbox: inbox, assignee: agent1, status: :open)
|
||||
end
|
||||
|
||||
it 'only agent with capacity is available' do
|
||||
available = inbox.available_agents(check_capacity: true)
|
||||
expect(available.map(&:user)).not_to include(agent1)
|
||||
expect(available.map(&:user)).to include(agent2)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when all agents are at capacity' do
|
||||
before do
|
||||
# Both agents at capacity
|
||||
account_user2.update!(agent_capacity_policy: capacity_policy)
|
||||
create_list(:conversation, 3, account: account, inbox: inbox, assignee: agent1, status: :open)
|
||||
create_list(:conversation, 3, account: account, inbox: inbox, assignee: agent2, status: :open)
|
||||
end
|
||||
|
||||
it 'no agents are available' do
|
||||
available = inbox.available_agents(check_capacity: true)
|
||||
expect(available).to be_empty
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,168 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe Enterprise::AssignmentV2::CapacityService do
|
||||
let(:account) { create(:account) }
|
||||
let(:user) { create(:user, accounts: [account]) }
|
||||
let(:account_user) { AccountUser.find_by(account: account, user: user) }
|
||||
let(:inbox) { create(:inbox, account: account) }
|
||||
let(:service) { described_class.new(account_user) }
|
||||
|
||||
describe '#agent_has_capacity?' do
|
||||
context 'without capacity policy' do
|
||||
it 'returns true' do
|
||||
expect(service.agent_has_capacity?).to be true
|
||||
expect(service.agent_has_capacity?(inbox)).to be true
|
||||
end
|
||||
end
|
||||
|
||||
context 'with capacity policy' do
|
||||
let(:policy) { Enterprise::AgentCapacityPolicy.create!(account: account, name: 'Test Policy') }
|
||||
|
||||
before do
|
||||
account_user.update!(agent_capacity_policy: policy)
|
||||
end
|
||||
|
||||
context 'when policy is not applicable' do
|
||||
before do
|
||||
allow(policy).to receive(:applicable_for_time?).and_return(false)
|
||||
end
|
||||
|
||||
it 'returns true' do
|
||||
expect(service.agent_has_capacity?).to be true
|
||||
end
|
||||
end
|
||||
|
||||
context 'when checking inbox capacity' do
|
||||
let!(:inbox_limit) do
|
||||
Enterprise::InboxCapacityLimit.create!(
|
||||
agent_capacity_policy: policy,
|
||||
inbox: inbox,
|
||||
conversation_limit: 5
|
||||
)
|
||||
end
|
||||
|
||||
it 'returns true when under limit' do
|
||||
create_list(:conversation, 3, account: account, inbox: inbox, assignee: user, status: :open)
|
||||
expect(service.agent_has_capacity?(inbox)).to be true
|
||||
end
|
||||
|
||||
it 'returns false when at limit' do
|
||||
create_list(:conversation, 5, account: account, inbox: inbox, assignee: user, status: :open)
|
||||
expect(service.agent_has_capacity?(inbox)).to be false
|
||||
end
|
||||
|
||||
it 'checks overall capacity too' do
|
||||
policy.update!(exclusion_rules: { 'overall_capacity' => 10 })
|
||||
create_list(:conversation, 9, account: account, assignee: user, status: :open)
|
||||
|
||||
# Under inbox limit but close to overall limit
|
||||
expect(service.agent_has_capacity?(inbox)).to be true
|
||||
|
||||
# Add one more to hit overall limit
|
||||
create(:conversation, account: account, assignee: user, status: :open)
|
||||
expect(service.agent_has_capacity?(inbox)).to be false
|
||||
end
|
||||
end
|
||||
|
||||
context 'when checking overall capacity' do
|
||||
before do
|
||||
policy.update!(exclusion_rules: { 'overall_capacity' => 10 })
|
||||
end
|
||||
|
||||
it 'returns true when under limit' do
|
||||
create_list(:conversation, 8, account: account, assignee: user, status: :open)
|
||||
expect(service.agent_has_capacity?).to be true
|
||||
end
|
||||
|
||||
it 'returns false when at limit' do
|
||||
create_list(:conversation, 10, account: account, assignee: user, status: :open)
|
||||
expect(service.agent_has_capacity?).to be false
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe '#agent_capacity_for_inbox' do
|
||||
context 'without capacity policy' do
|
||||
it 'returns infinity' do
|
||||
expect(service.agent_capacity_for_inbox(inbox)).to eq(Float::INFINITY)
|
||||
end
|
||||
end
|
||||
|
||||
context 'with capacity policy and inbox limit' do
|
||||
let(:policy) { Enterprise::AgentCapacityPolicy.create!(account: account, name: 'Test Policy') }
|
||||
let!(:inbox_limit) do
|
||||
Enterprise::InboxCapacityLimit.create!(
|
||||
agent_capacity_policy: policy,
|
||||
inbox: inbox,
|
||||
conversation_limit: 5
|
||||
)
|
||||
end
|
||||
|
||||
before do
|
||||
account_user.update!(agent_capacity_policy: policy)
|
||||
end
|
||||
|
||||
it 'returns remaining capacity' do
|
||||
create_list(:conversation, 2, account: account, inbox: inbox, assignee: user, status: :open)
|
||||
expect(service.agent_capacity_for_inbox(inbox)).to eq(3)
|
||||
end
|
||||
|
||||
it 'returns 0 when at capacity' do
|
||||
create_list(:conversation, 5, account: account, inbox: inbox, assignee: user, status: :open)
|
||||
expect(service.agent_capacity_for_inbox(inbox)).to eq(0)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe '#agent_overall_capacity' do
|
||||
context 'without capacity policy' do
|
||||
it 'returns infinity' do
|
||||
expect(service.agent_overall_capacity).to eq(Float::INFINITY)
|
||||
end
|
||||
end
|
||||
|
||||
context 'with capacity policy and overall limit' do
|
||||
let(:policy) do
|
||||
Enterprise::AgentCapacityPolicy.create!(
|
||||
account: account,
|
||||
name: 'Overall Policy',
|
||||
exclusion_rules: { 'overall_capacity' => 10 }
|
||||
)
|
||||
end
|
||||
|
||||
before do
|
||||
account_user.update!(agent_capacity_policy: policy)
|
||||
end
|
||||
|
||||
it 'returns remaining capacity' do
|
||||
create_list(:conversation, 6, account: account, assignee: user, status: :open)
|
||||
expect(service.agent_overall_capacity).to eq(4)
|
||||
end
|
||||
|
||||
it 'returns 0 when at capacity' do
|
||||
create_list(:conversation, 10, account: account, assignee: user, status: :open)
|
||||
expect(service.agent_overall_capacity).to eq(0)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe '#current_conversations_count' do
|
||||
it 'counts open conversations assigned to user' do
|
||||
create_list(:conversation, 3, account: account, assignee: user, status: :open)
|
||||
create(:conversation, account: account, assignee: user, status: :resolved)
|
||||
create(:conversation, account: account, status: :open)
|
||||
|
||||
expect(service.current_conversations_count).to eq(3)
|
||||
end
|
||||
|
||||
it 'counts inbox-specific conversations when inbox provided' do
|
||||
create_list(:conversation, 2, account: account, inbox: inbox, assignee: user, status: :open)
|
||||
create(:conversation, account: account, assignee: user, status: :open)
|
||||
|
||||
expect(service.current_conversations_count(inbox)).to eq(2)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,10 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
FactoryBot.define do
|
||||
factory :agent_capacity_policy, class: 'Enterprise::AgentCapacityPolicy' do
|
||||
account
|
||||
name { Faker::Name.name }
|
||||
description { Faker::Lorem.sentence }
|
||||
exclusion_rules { {} }
|
||||
end
|
||||
end
|
||||
@@ -1,34 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
FactoryBot.define do
|
||||
factory :assignment_policy do
|
||||
account
|
||||
sequence(:name) { |n| "Assignment Policy #{n}" }
|
||||
description { 'Test assignment policy' }
|
||||
assignment_order { :round_robin }
|
||||
conversation_priority { :earliest_created }
|
||||
fair_distribution_limit { 10 }
|
||||
fair_distribution_window { 3600 }
|
||||
enabled { true }
|
||||
|
||||
trait :balanced do
|
||||
assignment_order { :balanced }
|
||||
end
|
||||
|
||||
trait :disabled do
|
||||
enabled { false }
|
||||
end
|
||||
|
||||
trait :longest_waiting do
|
||||
conversation_priority { :longest_waiting }
|
||||
end
|
||||
|
||||
trait :with_high_limit do
|
||||
fair_distribution_limit { 50 }
|
||||
end
|
||||
|
||||
trait :with_short_window do
|
||||
fair_distribution_window { 300 } # 5 minutes
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -63,6 +63,25 @@ FactoryBot.define do
|
||||
],
|
||||
'sub_category' => 'CUSTOM',
|
||||
'parameter_format' => 'NAMED'
|
||||
},
|
||||
{
|
||||
'name' => 'test_no_params_template',
|
||||
'status' => 'APPROVED',
|
||||
'category' => 'UTILITY',
|
||||
'language' => 'en',
|
||||
'namespace' => 'ed41a221_133a_4558_a1d6_192960e3aee9',
|
||||
'id' => '9876543210987654',
|
||||
'length' => 1,
|
||||
'parameter_format' => 'POSITIONAL',
|
||||
'previous_category' => 'MARKETING',
|
||||
'sub_category' => 'CUSTOM',
|
||||
'components' => [
|
||||
{
|
||||
'text' => 'Thank you for contacting us! Your request has been processed successfully. Have a great day! 🙂',
|
||||
'type' => 'BODY'
|
||||
}
|
||||
],
|
||||
'rejected_reason' => 'NONE'
|
||||
}]
|
||||
end
|
||||
message_templates_last_updated { Time.now.utc }
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
FactoryBot.define do
|
||||
factory :inbox_assignment_policy do
|
||||
inbox
|
||||
assignment_policy
|
||||
|
||||
# Ensure inbox and policy belong to same account
|
||||
after(:build) do |inbox_policy|
|
||||
inbox_policy.assignment_policy.account = inbox_policy.inbox.account if inbox_policy.inbox && inbox_policy.assignment_policy
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,9 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
FactoryBot.define do
|
||||
factory :inbox_capacity_limit, class: 'Enterprise::InboxCapacityLimit' do
|
||||
association :agent_capacity_policy, factory: :agent_capacity_policy
|
||||
inbox
|
||||
conversation_limit { 10 }
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,177 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe ReportingEventHelper, type: :helper do
|
||||
describe '#last_non_human_activity' do
|
||||
let(:account) { create(:account) }
|
||||
let(:inbox) { create(:inbox, account: account) }
|
||||
let(:user) { create(:user, account: account) }
|
||||
let(:conversation) { create(:conversation, account: account, inbox: inbox, assignee: user) }
|
||||
|
||||
context 'when conversation has no events' do
|
||||
it 'returns conversation created_at' do
|
||||
expect(helper.last_non_human_activity(conversation)).to eq(conversation.created_at)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when conversation has bot handoff event' do
|
||||
let!(:handoff_event) do
|
||||
create(:reporting_event,
|
||||
name: 'conversation_bot_handoff',
|
||||
conversation_id: conversation.id,
|
||||
account_id: account.id,
|
||||
inbox_id: inbox.id,
|
||||
event_end_time: 2.hours.ago)
|
||||
end
|
||||
|
||||
it 'returns handoff event end time' do
|
||||
expect(helper.last_non_human_activity(conversation).to_i).to eq(handoff_event.event_end_time.to_i)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when conversation has bot resolved event' do
|
||||
let!(:bot_resolved_event) do
|
||||
create(:reporting_event,
|
||||
name: 'conversation_bot_resolved',
|
||||
conversation_id: conversation.id,
|
||||
account_id: account.id,
|
||||
inbox_id: inbox.id,
|
||||
event_end_time: 3.hours.ago)
|
||||
end
|
||||
|
||||
it 'returns bot resolved event end time' do
|
||||
expect(helper.last_non_human_activity(conversation).to_i).to eq(bot_resolved_event.event_end_time.to_i)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when conversation is reopened after bot resolution' do
|
||||
let(:creation_time) { 5.days.ago }
|
||||
let(:bot_resolution_time) { 5.days.ago + 5.minutes }
|
||||
let(:reopening_time) { 1.hour.ago }
|
||||
|
||||
let!(:conversation) do
|
||||
create(:conversation,
|
||||
account: account,
|
||||
inbox: inbox,
|
||||
assignee: user,
|
||||
created_at: creation_time)
|
||||
end
|
||||
|
||||
before do
|
||||
# First opened event
|
||||
create(:reporting_event,
|
||||
name: 'conversation_opened',
|
||||
conversation_id: conversation.id,
|
||||
account_id: account.id,
|
||||
inbox_id: inbox.id,
|
||||
value: 0,
|
||||
event_start_time: creation_time,
|
||||
event_end_time: creation_time)
|
||||
|
||||
# Bot resolved event
|
||||
create(:reporting_event,
|
||||
name: 'conversation_bot_resolved',
|
||||
conversation_id: conversation.id,
|
||||
account_id: account.id,
|
||||
inbox_id: inbox.id,
|
||||
event_start_time: creation_time,
|
||||
event_end_time: bot_resolution_time)
|
||||
|
||||
# Resolved event
|
||||
create(:reporting_event,
|
||||
name: 'conversation_resolved',
|
||||
conversation_id: conversation.id,
|
||||
account_id: account.id,
|
||||
inbox_id: inbox.id,
|
||||
event_start_time: creation_time,
|
||||
event_end_time: bot_resolution_time)
|
||||
|
||||
# Reopened event
|
||||
create(:reporting_event,
|
||||
name: 'conversation_opened',
|
||||
conversation_id: conversation.id,
|
||||
account_id: account.id,
|
||||
inbox_id: inbox.id,
|
||||
value: (reopening_time - bot_resolution_time).to_i,
|
||||
event_start_time: bot_resolution_time,
|
||||
event_end_time: reopening_time)
|
||||
end
|
||||
|
||||
it 'returns the reopening event time, not the creation time' do
|
||||
# This is the key test: last_non_human_activity should return the reopening time
|
||||
# so that first response time is calculated from when the conversation was reopened,
|
||||
# not from when it was originally created
|
||||
expect(helper.last_non_human_activity(conversation).to_i).to eq(reopening_time.to_i)
|
||||
|
||||
# Verify it's not returning the creation time or bot resolution time
|
||||
expect(helper.last_non_human_activity(conversation).to_i).not_to eq(creation_time.to_i)
|
||||
expect(helper.last_non_human_activity(conversation).to_i).not_to eq(bot_resolution_time.to_i)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when conversation has multiple types of events' do
|
||||
let(:opened_event_time) { 1.hour.ago }
|
||||
|
||||
before do
|
||||
create(:reporting_event,
|
||||
name: 'conversation_bot_resolved',
|
||||
conversation_id: conversation.id,
|
||||
account_id: account.id,
|
||||
inbox_id: inbox.id,
|
||||
event_end_time: 4.hours.ago)
|
||||
|
||||
create(:reporting_event,
|
||||
name: 'conversation_bot_handoff',
|
||||
conversation_id: conversation.id,
|
||||
account_id: account.id,
|
||||
inbox_id: inbox.id,
|
||||
event_end_time: 3.hours.ago)
|
||||
|
||||
create(:reporting_event,
|
||||
name: 'conversation_opened',
|
||||
conversation_id: conversation.id,
|
||||
account_id: account.id,
|
||||
inbox_id: inbox.id,
|
||||
event_end_time: opened_event_time)
|
||||
end
|
||||
|
||||
it 'returns the most recent handoff or opened event' do
|
||||
# opened_event is more recent than handoff_event
|
||||
expect(helper.last_non_human_activity(conversation).to_i).to eq(opened_event_time.to_i)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when conversation has multiple reopenings' do
|
||||
let(:third_opened_time) { 30.minutes.ago }
|
||||
|
||||
before do
|
||||
create(:reporting_event,
|
||||
name: 'conversation_opened',
|
||||
conversation_id: conversation.id,
|
||||
account_id: account.id,
|
||||
inbox_id: inbox.id,
|
||||
value: 0,
|
||||
event_end_time: 5.days.ago)
|
||||
|
||||
create(:reporting_event,
|
||||
name: 'conversation_opened',
|
||||
conversation_id: conversation.id,
|
||||
account_id: account.id,
|
||||
inbox_id: inbox.id,
|
||||
value: 3600,
|
||||
event_end_time: 2.days.ago)
|
||||
|
||||
create(:reporting_event,
|
||||
name: 'conversation_opened',
|
||||
conversation_id: conversation.id,
|
||||
account_id: account.id,
|
||||
inbox_id: inbox.id,
|
||||
value: 7200,
|
||||
event_end_time: third_opened_time)
|
||||
end
|
||||
|
||||
it 'returns the most recent opened event' do
|
||||
expect(helper.last_non_human_activity(conversation).to_i).to eq(third_opened_time.to_i)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,196 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe AssignmentV2::AssignmentJob, type: :job do
|
||||
before do
|
||||
# Mock GlobalConfig to avoid InstallationConfig issues
|
||||
allow(GlobalConfig).to receive(:get).and_return({})
|
||||
end
|
||||
|
||||
let(:account) { create(:account) }
|
||||
let(:inbox) { create(:inbox, account: account) }
|
||||
let(:conversation) { create(:conversation, inbox: inbox, assignee: nil) }
|
||||
let(:assignment_policy) { create(:assignment_policy, account: account, enabled: true) }
|
||||
let!(:inbox_assignment_policy) { create(:inbox_assignment_policy, inbox: inbox, assignment_policy: assignment_policy) }
|
||||
|
||||
describe '#perform' do
|
||||
context 'with conversation_id' do
|
||||
it 'assigns a single conversation' do
|
||||
service = instance_double(AssignmentV2::AssignmentService)
|
||||
expect(AssignmentV2::AssignmentService).to receive(:new).with(inbox: inbox).and_return(service)
|
||||
expect(service).to receive(:perform_for_conversation).with(conversation)
|
||||
|
||||
described_class.new.perform(conversation_id: conversation.id)
|
||||
end
|
||||
|
||||
it 'handles non-existent conversation gracefully' do
|
||||
expect(AssignmentV2::AssignmentService).not_to receive(:new)
|
||||
|
||||
# Should not raise error
|
||||
expect do
|
||||
described_class.new.perform(conversation_id: 999_999)
|
||||
end.not_to raise_error
|
||||
end
|
||||
end
|
||||
|
||||
context 'with inbox_id' do
|
||||
let!(:agent) { create(:user, account: account, role: :agent, availability: :online) }
|
||||
|
||||
before do
|
||||
create_list(:conversation, 3, inbox: inbox, assignee: nil)
|
||||
create(:inbox_member, inbox: inbox, user: agent)
|
||||
end
|
||||
|
||||
it 'assigns multiple conversations for inbox' do
|
||||
# Mock the feature flag for assignment_v2
|
||||
allow(inbox.account).to receive(:feature_enabled?).with('assignment_v2').and_return(true)
|
||||
allow(Inbox).to receive(:find_by).with(id: inbox.id).and_return(inbox)
|
||||
|
||||
service = instance_double(AssignmentV2::AssignmentService)
|
||||
expect(AssignmentV2::AssignmentService).to receive(:new).with(inbox: inbox).and_return(service)
|
||||
expect(service).to receive(:perform_bulk_assignment).and_return(3)
|
||||
|
||||
described_class.new.perform(inbox_id: inbox.id)
|
||||
end
|
||||
|
||||
it 'logs the number of assigned conversations' do
|
||||
# Mock the feature flag for assignment_v2
|
||||
allow(inbox.account).to receive(:feature_enabled?).with('assignment_v2').and_return(true)
|
||||
allow(Inbox).to receive(:find_by).with(id: inbox.id).and_return(inbox)
|
||||
|
||||
service = instance_double(AssignmentV2::AssignmentService)
|
||||
allow(AssignmentV2::AssignmentService).to receive(:new).with(inbox: inbox).and_return(service)
|
||||
allow(service).to receive(:perform_bulk_assignment).and_return(2)
|
||||
|
||||
expect(Rails.logger).to receive(:info).with("AssignmentV2::AssignmentJob: Assigned 2 conversations for inbox #{inbox.id}")
|
||||
|
||||
described_class.new.perform(inbox_id: inbox.id)
|
||||
end
|
||||
|
||||
it 'skips assignment when inbox has no policy' do
|
||||
inbox_assignment_policy.destroy!
|
||||
|
||||
expect(AssignmentV2::AssignmentService).not_to receive(:new)
|
||||
|
||||
described_class.new.perform(inbox_id: inbox.id)
|
||||
end
|
||||
|
||||
it 'skips assignment when policy is disabled' do
|
||||
assignment_policy.update!(enabled: false)
|
||||
|
||||
expect(AssignmentV2::AssignmentService).not_to receive(:new)
|
||||
|
||||
described_class.new.perform(inbox_id: inbox.id)
|
||||
end
|
||||
|
||||
it 'handles non-existent inbox gracefully' do
|
||||
expect(AssignmentV2::AssignmentService).not_to receive(:new)
|
||||
|
||||
# Should not raise error
|
||||
expect do
|
||||
described_class.new.perform(inbox_id: 999_999)
|
||||
end.not_to raise_error
|
||||
end
|
||||
end
|
||||
|
||||
context 'without parameters' do
|
||||
it 'logs error when no parameters provided' do
|
||||
expect(Rails.logger).to receive(:error).with('AssignmentV2::AssignmentJob: No inbox_id or conversation_id provided')
|
||||
|
||||
described_class.new.perform
|
||||
end
|
||||
|
||||
it 'does not attempt assignment' do
|
||||
expect(AssignmentV2::AssignmentService).not_to receive(:new)
|
||||
|
||||
described_class.new.perform
|
||||
end
|
||||
end
|
||||
|
||||
context 'with both parameters' do
|
||||
it 'prioritizes conversation_id over inbox_id' do
|
||||
service = instance_double(AssignmentV2::AssignmentService)
|
||||
expect(AssignmentV2::AssignmentService).to receive(:new).with(inbox: inbox).and_return(service)
|
||||
expect(service).to receive(:perform_for_conversation).with(conversation)
|
||||
expect(service).not_to receive(:perform_bulk_assignment)
|
||||
|
||||
described_class.new.perform(conversation_id: conversation.id, inbox_id: inbox.id)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'job configuration' do
|
||||
it 'uses the low queue' do
|
||||
expect(described_class.new.queue_name).to eq('low')
|
||||
end
|
||||
end
|
||||
|
||||
describe 'error handling' do
|
||||
context 'when assignment service raises error' do
|
||||
it 'propagates the error for retry' do
|
||||
service = instance_double(AssignmentV2::AssignmentService)
|
||||
allow(AssignmentV2::AssignmentService).to receive(:new).and_return(service)
|
||||
allow(service).to receive(:perform_for_conversation).and_raise(StandardError, 'Assignment failed')
|
||||
|
||||
expect do
|
||||
described_class.new.perform(conversation_id: conversation.id)
|
||||
end.to raise_error(StandardError, 'Assignment failed')
|
||||
end
|
||||
end
|
||||
|
||||
context 'when database connection fails' do
|
||||
it 'raises error for retry' do
|
||||
allow(Conversation).to receive(:find_by).and_raise(ActiveRecord::ConnectionNotEstablished)
|
||||
|
||||
expect do
|
||||
described_class.new.perform(conversation_id: conversation.id)
|
||||
end.to raise_error(ActiveRecord::ConnectionNotEstablished)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'concurrency and idempotency' do
|
||||
it 'handles concurrent job execution safely' do
|
||||
# Create multiple jobs for same inbox
|
||||
jobs = []
|
||||
3.times { jobs << described_class.new }
|
||||
|
||||
# All should execute without issues
|
||||
expect do
|
||||
jobs.each { |job| job.perform(inbox_id: inbox.id) }
|
||||
end.not_to raise_error
|
||||
end
|
||||
|
||||
it 'is idempotent for conversation assignment' do
|
||||
service = instance_double(AssignmentV2::AssignmentService)
|
||||
allow(AssignmentV2::AssignmentService).to receive(:new).and_return(service)
|
||||
|
||||
# First call assigns
|
||||
expect(service).to receive(:perform_for_conversation).and_return(true)
|
||||
described_class.new.perform(conversation_id: conversation.id)
|
||||
|
||||
# Second call should handle already assigned conversation
|
||||
expect(service).to receive(:perform_for_conversation).and_return(false)
|
||||
expect { described_class.new.perform(conversation_id: conversation.id) }.not_to raise_error
|
||||
end
|
||||
end
|
||||
|
||||
describe 'performance considerations' do
|
||||
it 'processes large inbox assignments in batches' do
|
||||
# Create many unassigned conversations
|
||||
create_list(:conversation, 100, inbox: inbox, assignee: nil)
|
||||
# Mock the feature flag for assignment_v2
|
||||
allow(inbox.account).to receive(:feature_enabled?).with('assignment_v2').and_return(true)
|
||||
allow(Inbox).to receive(:find_by).with(id: inbox.id).and_return(inbox)
|
||||
|
||||
service = instance_double(AssignmentV2::AssignmentService)
|
||||
allow(AssignmentV2::AssignmentService).to receive(:new).and_return(service)
|
||||
|
||||
# Service should be called with default limit
|
||||
expect(service).to receive(:perform_bulk_assignment).with(no_args).and_return(50)
|
||||
|
||||
described_class.new.perform(inbox_id: inbox.id)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -10,23 +10,6 @@ describe Webhooks::InstagramEventsJob do
|
||||
end
|
||||
|
||||
let!(:account) { create(:account) }
|
||||
let!(:instagram_messenger_channel) { create(:channel_instagram_fb_page, account: account, instagram_id: 'chatwoot-app-user-id-1') }
|
||||
let!(:instagram_messenger_inbox) { create(:inbox, channel: instagram_messenger_channel, account: account, greeting_enabled: false) }
|
||||
let!(:instagram_channel) { create(:channel_instagram, account: account, instagram_id: 'chatwoot-app-user-id-1') }
|
||||
let!(:instagram_inbox) { create(:inbox, channel: instagram_channel, account: account, greeting_enabled: false) }
|
||||
# Combined message events into one helper
|
||||
let(:message_events) do
|
||||
{
|
||||
dm: build(:instagram_message_create_event).with_indifferent_access,
|
||||
standby: build(:instagram_message_standby_event).with_indifferent_access,
|
||||
unsend: build(:instagram_message_unsend_event).with_indifferent_access,
|
||||
attachment: build(:instagram_message_attachment_event).with_indifferent_access,
|
||||
story_mention: build(:instagram_story_mention_event).with_indifferent_access,
|
||||
story_mention_echo: build(:instagram_story_mention_event_with_echo).with_indifferent_access,
|
||||
messaging_seen: build(:messaging_seen_event).with_indifferent_access,
|
||||
unsupported: build(:instagram_message_unsupported_event).with_indifferent_access
|
||||
}
|
||||
end
|
||||
|
||||
def return_object_for(sender_id)
|
||||
{ name: 'Jane',
|
||||
@@ -38,21 +21,19 @@ describe Webhooks::InstagramEventsJob do
|
||||
|
||||
describe '#perform' do
|
||||
context 'when handling messaging events for Instagram via Facebook page' do
|
||||
let!(:instagram_messenger_channel) { create(:channel_instagram_fb_page, account: account, instagram_id: 'chatwoot-app-user-id-1') }
|
||||
let!(:instagram_messenger_inbox) { create(:inbox, channel: instagram_messenger_channel, account: account, greeting_enabled: false) }
|
||||
let(:fb_object) { double }
|
||||
|
||||
before do
|
||||
instagram_inbox.destroy
|
||||
end
|
||||
|
||||
it 'creates incoming message in the instagram inbox' do
|
||||
dm_event = build(:instagram_message_create_event).with_indifferent_access
|
||||
sender_id = dm_event[:entry][0][:messaging][0][:sender][:id]
|
||||
|
||||
allow(Koala::Facebook::API).to receive(:new).and_return(fb_object)
|
||||
sender_id = message_events[:dm][:entry][0][:messaging][0][:sender][:id]
|
||||
allow(fb_object).to receive(:get_object).and_return(
|
||||
return_object_for(sender_id).with_indifferent_access
|
||||
)
|
||||
instagram_webhook.perform_now(message_events[:dm][:entry])
|
||||
|
||||
instagram_messenger_inbox.reload
|
||||
instagram_webhook.perform_now(dm_event[:entry])
|
||||
|
||||
expect(instagram_messenger_inbox.contacts.count).to be 1
|
||||
expect(instagram_messenger_inbox.contacts.last.additional_attributes['social_instagram_user_name']).to eq 'some_user_name'
|
||||
@@ -62,14 +43,14 @@ describe Webhooks::InstagramEventsJob do
|
||||
end
|
||||
|
||||
it 'creates standby message in the instagram inbox' do
|
||||
standby_event = build(:instagram_message_standby_event).with_indifferent_access
|
||||
sender_id = standby_event[:entry][0][:standby][0][:sender][:id]
|
||||
|
||||
allow(Koala::Facebook::API).to receive(:new).and_return(fb_object)
|
||||
sender_id = message_events[:standby][:entry][0][:standby][0][:sender][:id]
|
||||
allow(fb_object).to receive(:get_object).and_return(
|
||||
return_object_for(sender_id).with_indifferent_access
|
||||
)
|
||||
instagram_webhook.perform_now(message_events[:standby][:entry])
|
||||
|
||||
instagram_messenger_inbox.reload
|
||||
instagram_webhook.perform_now(standby_event[:entry])
|
||||
|
||||
expect(instagram_messenger_inbox.contacts.count).to be 1
|
||||
expect(instagram_messenger_inbox.contacts.last.additional_attributes['social_instagram_user_name']).to eq 'some_user_name'
|
||||
@@ -81,9 +62,11 @@ describe Webhooks::InstagramEventsJob do
|
||||
end
|
||||
|
||||
it 'handle instagram unsend message event' do
|
||||
unsend_event = build(:instagram_message_unsend_event).with_indifferent_access
|
||||
sender_id = unsend_event[:entry][0][:messaging][0][:sender][:id]
|
||||
|
||||
message = create(:message, inbox_id: instagram_messenger_inbox.id, source_id: 'message-id-to-delete')
|
||||
allow(Koala::Facebook::API).to receive(:new).and_return(fb_object)
|
||||
sender_id = message_events[:unsend][:entry][0][:messaging][0][:sender][:id]
|
||||
allow(fb_object).to receive(:get_object).and_return(
|
||||
{
|
||||
name: 'Jane',
|
||||
@@ -96,7 +79,7 @@ describe Webhooks::InstagramEventsJob do
|
||||
|
||||
expect(instagram_messenger_inbox.messages.count).to be 1
|
||||
|
||||
instagram_webhook.perform_now(message_events[:unsend][:entry])
|
||||
instagram_webhook.perform_now(unsend_event[:entry])
|
||||
|
||||
expect(instagram_messenger_inbox.messages.last.content).to eq 'This message was deleted'
|
||||
expect(instagram_messenger_inbox.messages.last.deleted).to be true
|
||||
@@ -105,14 +88,14 @@ describe Webhooks::InstagramEventsJob do
|
||||
end
|
||||
|
||||
it 'creates incoming message with attachments in the instagram inbox' do
|
||||
attachment_event = build(:instagram_message_attachment_event).with_indifferent_access
|
||||
sender_id = attachment_event[:entry][0][:messaging][0][:sender][:id]
|
||||
|
||||
allow(Koala::Facebook::API).to receive(:new).and_return(fb_object)
|
||||
sender_id = message_events[:attachment][:entry][0][:messaging][0][:sender][:id]
|
||||
allow(fb_object).to receive(:get_object).and_return(
|
||||
return_object_for(sender_id).with_indifferent_access
|
||||
)
|
||||
instagram_webhook.perform_now(message_events[:attachment][:entry])
|
||||
|
||||
instagram_messenger_inbox.reload
|
||||
instagram_webhook.perform_now(attachment_event[:entry])
|
||||
|
||||
expect(instagram_messenger_inbox.contacts.count).to be 1
|
||||
expect(instagram_messenger_inbox.messages.count).to be 1
|
||||
@@ -120,8 +103,10 @@ describe Webhooks::InstagramEventsJob do
|
||||
end
|
||||
|
||||
it 'creates incoming message with attachments in the instagram inbox for story mention' do
|
||||
story_mention_event = build(:instagram_story_mention_event).with_indifferent_access
|
||||
sender_id = story_mention_event[:entry][0][:messaging][0][:sender][:id]
|
||||
|
||||
allow(Koala::Facebook::API).to receive(:new).and_return(fb_object)
|
||||
sender_id = message_events[:story_mention][:entry][0][:messaging][0][:sender][:id]
|
||||
allow(fb_object).to receive(:get_object).and_return(
|
||||
return_object_for(sender_id).with_indifferent_access,
|
||||
{ story:
|
||||
@@ -137,9 +122,7 @@ describe Webhooks::InstagramEventsJob do
|
||||
id: 'instagram-message-id-1234' }.with_indifferent_access
|
||||
)
|
||||
|
||||
instagram_webhook.perform_now(message_events[:story_mention][:entry])
|
||||
|
||||
instagram_messenger_inbox.reload
|
||||
instagram_webhook.perform_now(story_mention_event[:entry])
|
||||
|
||||
expect(instagram_messenger_inbox.messages.count).to be 1
|
||||
expect(instagram_messenger_inbox.messages.last.attachments.count).to be 1
|
||||
@@ -149,12 +132,12 @@ describe Webhooks::InstagramEventsJob do
|
||||
end
|
||||
|
||||
it 'does not create contact or messages when Facebook API call fails' do
|
||||
story_mention_echo_event = build(:instagram_story_mention_event_with_echo).with_indifferent_access
|
||||
|
||||
allow(Koala::Facebook::API).to receive(:new).and_return(fb_object)
|
||||
allow(fb_object).to receive(:get_object).and_raise(Koala::Facebook::ClientError)
|
||||
|
||||
instagram_webhook.perform_now(message_events[:story_mention_echo][:entry])
|
||||
|
||||
instagram_messenger_inbox.reload
|
||||
instagram_webhook.perform_now(story_mention_echo_event[:entry])
|
||||
|
||||
expect(instagram_messenger_inbox.contacts.count).to be 0
|
||||
expect(instagram_messenger_inbox.contact_inboxes.count).to be 0
|
||||
@@ -162,21 +145,23 @@ describe Webhooks::InstagramEventsJob do
|
||||
end
|
||||
|
||||
it 'handle messaging_seen callback' do
|
||||
expect(Instagram::ReadStatusService).to receive(:new).with(params: message_events[:messaging_seen][:entry][0][:messaging][0],
|
||||
messaging_seen_event = build(:messaging_seen_event).with_indifferent_access
|
||||
|
||||
expect(Instagram::ReadStatusService).to receive(:new).with(params: messaging_seen_event[:entry][0][:messaging][0],
|
||||
channel: instagram_messenger_inbox.channel).and_call_original
|
||||
instagram_webhook.perform_now(message_events[:messaging_seen][:entry])
|
||||
instagram_webhook.perform_now(messaging_seen_event[:entry])
|
||||
end
|
||||
|
||||
it 'handles unsupported message' do
|
||||
unsupported_event = build(:instagram_message_unsupported_event).with_indifferent_access
|
||||
sender_id = unsupported_event[:entry][0][:messaging][0][:sender][:id]
|
||||
|
||||
allow(Koala::Facebook::API).to receive(:new).and_return(fb_object)
|
||||
sender_id = message_events[:unsupported][:entry][0][:messaging][0][:sender][:id]
|
||||
allow(fb_object).to receive(:get_object).and_return(
|
||||
return_object_for(sender_id).with_indifferent_access
|
||||
)
|
||||
|
||||
instagram_webhook.perform_now(message_events[:unsupported][:entry])
|
||||
instagram_messenger_inbox.reload
|
||||
|
||||
instagram_webhook.perform_now(unsupported_event[:entry])
|
||||
expect(instagram_messenger_inbox.contacts.count).to be 1
|
||||
expect(instagram_messenger_inbox.contacts.last.additional_attributes['social_instagram_user_name']).to eq 'some_user_name'
|
||||
expect(instagram_messenger_inbox.conversations.count).to be 1
|
||||
@@ -186,6 +171,9 @@ describe Webhooks::InstagramEventsJob do
|
||||
end
|
||||
|
||||
context 'when handling messaging events for Instagram via Instagram login' do
|
||||
let!(:instagram_channel) { create(:channel_instagram, account: account, instagram_id: 'chatwoot-app-user-id-1') }
|
||||
let!(:instagram_inbox) { instagram_channel.inbox }
|
||||
|
||||
before do
|
||||
instagram_channel.update(access_token: 'valid_instagram_token')
|
||||
|
||||
@@ -210,9 +198,8 @@ describe Webhooks::InstagramEventsJob do
|
||||
end
|
||||
|
||||
it 'creates incoming message with correct contact info in the instagram direct inbox' do
|
||||
instagram_webhook.perform_now(message_events[:dm][:entry])
|
||||
instagram_inbox.reload
|
||||
|
||||
dm_event = build(:instagram_message_create_event).with_indifferent_access
|
||||
instagram_webhook.perform_now(dm_event[:entry])
|
||||
expect(instagram_inbox.contacts.count).to eq 1
|
||||
expect(instagram_inbox.contacts.last.additional_attributes['social_instagram_user_name']).to eq 'some_user_name'
|
||||
expect(instagram_inbox.conversations.count).to eq 1
|
||||
@@ -221,7 +208,8 @@ describe Webhooks::InstagramEventsJob do
|
||||
end
|
||||
|
||||
it 'sets correct instagram attributes on contact' do
|
||||
instagram_webhook.perform_now(message_events[:dm][:entry])
|
||||
dm_event = build(:instagram_message_create_event).with_indifferent_access
|
||||
instagram_webhook.perform_now(dm_event[:entry])
|
||||
instagram_inbox.reload
|
||||
|
||||
contact = instagram_inbox.contacts.last
|
||||
@@ -233,6 +221,8 @@ describe Webhooks::InstagramEventsJob do
|
||||
end
|
||||
|
||||
it 'handle instagram unsend message event' do
|
||||
unsend_event = build(:instagram_message_unsend_event).with_indifferent_access
|
||||
|
||||
message = create(:message, inbox_id: instagram_inbox.id, source_id: 'message-id-to-delete', content: 'random_text')
|
||||
|
||||
# Create attachment correctly with account association
|
||||
@@ -244,7 +234,7 @@ describe Webhooks::InstagramEventsJob do
|
||||
|
||||
expect(instagram_inbox.messages.count).to be 1
|
||||
|
||||
instagram_webhook.perform_now(message_events[:unsend][:entry])
|
||||
instagram_webhook.perform_now(unsend_event[:entry])
|
||||
|
||||
message.reload
|
||||
|
||||
@@ -254,9 +244,8 @@ describe Webhooks::InstagramEventsJob do
|
||||
end
|
||||
|
||||
it 'creates incoming message with attachments in the instagram direct inbox' do
|
||||
instagram_webhook.perform_now(message_events[:attachment][:entry])
|
||||
|
||||
instagram_inbox.reload
|
||||
attachment_event = build(:instagram_message_attachment_event).with_indifferent_access
|
||||
instagram_webhook.perform_now(attachment_event[:entry])
|
||||
|
||||
expect(instagram_inbox.contacts.count).to be 1
|
||||
expect(instagram_inbox.messages.count).to be 1
|
||||
@@ -264,9 +253,8 @@ describe Webhooks::InstagramEventsJob do
|
||||
end
|
||||
|
||||
it 'handles unsupported message' do
|
||||
instagram_webhook.perform_now(message_events[:unsupported][:entry])
|
||||
instagram_inbox.reload
|
||||
|
||||
unsupported_event = build(:instagram_message_unsupported_event).with_indifferent_access
|
||||
instagram_webhook.perform_now(unsupported_event[:entry])
|
||||
expect(instagram_inbox.contacts.count).to be 1
|
||||
expect(instagram_inbox.contacts.last.additional_attributes['social_instagram_user_name']).to eq 'some_user_name'
|
||||
expect(instagram_inbox.conversations.count).to be 1
|
||||
@@ -275,12 +263,12 @@ describe Webhooks::InstagramEventsJob do
|
||||
end
|
||||
|
||||
it 'does not create contact or messages when Instagram API call fails' do
|
||||
story_mention_echo_event = build(:instagram_story_mention_event_with_echo).with_indifferent_access
|
||||
|
||||
stub_request(:get, %r{https://graph\.instagram\.com/v22\.0/.*\?.*})
|
||||
.to_return(status: 401, body: { error: { message: 'Invalid OAuth access token' } }.to_json)
|
||||
|
||||
instagram_webhook.perform_now(message_events[:story_mention_echo][:entry])
|
||||
|
||||
instagram_inbox.reload
|
||||
instagram_webhook.perform_now(story_mention_echo_event[:entry])
|
||||
|
||||
expect(instagram_inbox.contacts.count).to be 0
|
||||
expect(instagram_inbox.contact_inboxes.count).to be 0
|
||||
@@ -288,19 +276,20 @@ describe Webhooks::InstagramEventsJob do
|
||||
end
|
||||
|
||||
it 'handles messaging_seen callback' do
|
||||
expect(Instagram::ReadStatusService).to receive(:new).with(params: message_events[:messaging_seen][:entry][0][:messaging][0],
|
||||
messaging_seen_event = build(:messaging_seen_event).with_indifferent_access
|
||||
|
||||
expect(Instagram::ReadStatusService).to receive(:new).with(params: messaging_seen_event[:entry][0][:messaging][0],
|
||||
channel: instagram_inbox.channel).and_call_original
|
||||
instagram_webhook.perform_now(message_events[:messaging_seen][:entry])
|
||||
instagram_webhook.perform_now(messaging_seen_event[:entry])
|
||||
end
|
||||
|
||||
it 'creates contact when Instagram API call returns `No matching Instagram user` (9010 error code)' do
|
||||
stub_request(:get, %r{https://graph\.instagram\.com/v22\.0/.*\?.*})
|
||||
.to_return(status: 401, body: { error: { message: 'No matching Instagram user', code: 9010 } }.to_json)
|
||||
|
||||
sender_id = message_events[:dm][:entry][0][:messaging][0][:sender][:id]
|
||||
instagram_webhook.perform_now(message_events[:dm][:entry])
|
||||
|
||||
instagram_inbox.reload
|
||||
dm_event = build(:instagram_message_create_event).with_indifferent_access
|
||||
sender_id = dm_event[:entry][0][:messaging][0][:sender][:id]
|
||||
instagram_webhook.perform_now(dm_event[:entry])
|
||||
|
||||
expect(instagram_inbox.contacts.count).to be 1
|
||||
expect(instagram_inbox.contacts.last.name).to eq "Unknown (IG: #{sender_id})"
|
||||
|
||||
@@ -130,6 +130,42 @@ describe AutomationRuleListener do
|
||||
end
|
||||
end
|
||||
|
||||
describe 'conversation_resolved' do
|
||||
let!(:automation_rule) { create(:automation_rule, event_name: 'conversation_resolved', account: account) }
|
||||
let(:event) do
|
||||
Events::Base.new('conversation_resolved', Time.zone.now, { conversation: conversation,
|
||||
changed_attributes: { status: %w[Snoozed Open] } })
|
||||
end
|
||||
|
||||
context 'when matching rules are present' do
|
||||
it 'calls AutomationRules::ActionService if conditions match' do
|
||||
allow(condition_match).to receive(:present?).and_return(true)
|
||||
listener.conversation_resolved(event)
|
||||
expect(AutomationRules::ActionService).to have_received(:new).with(automation_rule, account, conversation)
|
||||
end
|
||||
|
||||
it 'does not call AutomationRules::ActionService if conditions do not match' do
|
||||
allow(condition_match).to receive(:present?).and_return(false)
|
||||
listener.conversation_resolved(event)
|
||||
expect(AutomationRules::ActionService).not_to have_received(:new).with(automation_rule, account, conversation)
|
||||
end
|
||||
|
||||
it 'calls AutomationRules::ActionService for each rule when multiple rules are present' do
|
||||
create(:automation_rule, event_name: 'conversation_resolved', account: account)
|
||||
allow(condition_match).to receive(:present?).and_return(true)
|
||||
listener.conversation_resolved(event)
|
||||
expect(AutomationRules::ActionService).to have_received(:new).twice
|
||||
end
|
||||
|
||||
it 'does not call AutomationRules::ActionService if performed by automation' do
|
||||
event.data[:performed_by] = automation_rule
|
||||
allow(condition_match).to receive(:present?).and_return(true)
|
||||
listener.conversation_resolved(event)
|
||||
expect(AutomationRules::ActionService).not_to have_received(:new).with(automation_rule, account, conversation)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'message_created' do
|
||||
let!(:automation_rule) { create(:automation_rule, event_name: 'message_created', account: account) }
|
||||
let!(:message) { create(:message, account: account, conversation: conversation) }
|
||||
|
||||
@@ -267,4 +267,177 @@ describe ReportingEventListener do
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe '#conversation_opened' do
|
||||
context 'when conversation is opened for the first time' do
|
||||
let(:new_conversation) { create(:conversation, account: account, inbox: inbox, assignee: user) }
|
||||
|
||||
it 'creates conversation_opened event with value 0' do
|
||||
expect(account.reporting_events.where(name: 'conversation_opened').count).to be 0
|
||||
event = Events::Base.new('conversation.opened', Time.zone.now, conversation: new_conversation)
|
||||
listener.conversation_opened(event)
|
||||
expect(account.reporting_events.where(name: 'conversation_opened').count).to be 1
|
||||
|
||||
opened_event = account.reporting_events.where(name: 'conversation_opened').first
|
||||
expect(opened_event.value).to eq 0
|
||||
expect(opened_event.value_in_business_hours).to eq 0
|
||||
expect(opened_event.event_start_time).to be_within(1.second).of(new_conversation.created_at)
|
||||
expect(opened_event.event_end_time).to be_within(1.second).of(new_conversation.updated_at)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when conversation is reopened after being resolved' do
|
||||
let(:resolved_time) { 2.hours.ago }
|
||||
let(:reopened_time) { 1.hour.ago }
|
||||
let(:reopened_conversation) do
|
||||
create(:conversation, account: account, inbox: inbox, assignee: user, updated_at: reopened_time)
|
||||
end
|
||||
|
||||
before do
|
||||
# Create a resolved event first
|
||||
create(:reporting_event,
|
||||
name: 'conversation_resolved',
|
||||
account_id: account.id,
|
||||
inbox_id: inbox.id,
|
||||
conversation_id: reopened_conversation.id,
|
||||
user_id: user.id,
|
||||
value: 3600,
|
||||
event_start_time: reopened_conversation.created_at,
|
||||
event_end_time: resolved_time)
|
||||
end
|
||||
|
||||
it 'creates conversation_opened event' do
|
||||
expect(account.reporting_events.where(name: 'conversation_opened').count).to be 0
|
||||
event = Events::Base.new('conversation.opened', reopened_time, conversation: reopened_conversation)
|
||||
listener.conversation_opened(event)
|
||||
expect(account.reporting_events.where(name: 'conversation_opened').count).to be 1
|
||||
end
|
||||
|
||||
it 'calculates correct time since resolution' do
|
||||
event = Events::Base.new('conversation.opened', reopened_time, conversation: reopened_conversation)
|
||||
listener.conversation_opened(event)
|
||||
|
||||
reopened_event = account.reporting_events.where(name: 'conversation_opened').first
|
||||
expect(reopened_event.value).to be_within(1).of(3600) # 1 hour = 3600 seconds
|
||||
expect(reopened_event.event_start_time).to be_within(1.second).of(resolved_time)
|
||||
expect(reopened_event.event_end_time).to be_within(1.second).of(reopened_time)
|
||||
end
|
||||
|
||||
it 'sets correct attributes for conversation_opened event' do
|
||||
event = Events::Base.new('conversation.opened', reopened_time, conversation: reopened_conversation)
|
||||
listener.conversation_opened(event)
|
||||
|
||||
reopened_event = account.reporting_events.where(name: 'conversation_opened').first
|
||||
expect(reopened_event.account_id).to eq(account.id)
|
||||
expect(reopened_event.inbox_id).to eq(inbox.id)
|
||||
expect(reopened_event.conversation_id).to eq(reopened_conversation.id)
|
||||
expect(reopened_event.user_id).to eq(user.id)
|
||||
end
|
||||
|
||||
context 'when business hours enabled for inbox' do
|
||||
let(:resolved_time) { Time.zone.parse('March 20, 2022 12:00') }
|
||||
let(:reopened_time) { Time.zone.parse('March 21, 2022 14:00') }
|
||||
let!(:business_hours_inbox) { create(:inbox, working_hours_enabled: true, account: account) }
|
||||
let!(:business_hours_conversation) do
|
||||
create(:conversation, account: account, inbox: business_hours_inbox, assignee: user, updated_at: reopened_time)
|
||||
end
|
||||
|
||||
before do
|
||||
create(:reporting_event,
|
||||
name: 'conversation_resolved',
|
||||
account_id: account.id,
|
||||
inbox_id: business_hours_inbox.id,
|
||||
conversation_id: business_hours_conversation.id,
|
||||
user_id: user.id,
|
||||
value: 3600,
|
||||
event_start_time: business_hours_conversation.created_at,
|
||||
event_end_time: resolved_time)
|
||||
end
|
||||
|
||||
it 'creates conversation_opened event with business hour value' do
|
||||
event = Events::Base.new('conversation.opened', reopened_time, conversation: business_hours_conversation)
|
||||
listener.conversation_opened(event)
|
||||
|
||||
reopened_event = account.reporting_events.where(name: 'conversation_opened').first
|
||||
expect(reopened_event.value_in_business_hours).to be 18_000.0 # 5 business hours (26 hours total - 21 non-business hours)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
context 'when conversation has multiple resolutions' do
|
||||
let(:first_resolved_time) { 3.hours.ago }
|
||||
let(:second_resolved_time) { 1.hour.ago }
|
||||
let(:reopened_time) { 30.minutes.ago }
|
||||
let(:multiple_resolution_conversation) do
|
||||
create(:conversation, account: account, inbox: inbox, assignee: user, updated_at: reopened_time)
|
||||
end
|
||||
|
||||
before do
|
||||
# Create first resolved event
|
||||
create(:reporting_event,
|
||||
name: 'conversation_resolved',
|
||||
account_id: account.id,
|
||||
inbox_id: inbox.id,
|
||||
conversation_id: multiple_resolution_conversation.id,
|
||||
user_id: user.id,
|
||||
value: 3600,
|
||||
event_start_time: multiple_resolution_conversation.created_at,
|
||||
event_end_time: first_resolved_time)
|
||||
|
||||
# Create second resolved event (more recent)
|
||||
create(:reporting_event,
|
||||
name: 'conversation_resolved',
|
||||
account_id: account.id,
|
||||
inbox_id: inbox.id,
|
||||
conversation_id: multiple_resolution_conversation.id,
|
||||
user_id: user.id,
|
||||
value: 1800,
|
||||
event_start_time: first_resolved_time,
|
||||
event_end_time: second_resolved_time)
|
||||
end
|
||||
|
||||
it 'uses the most recent resolved event for calculation' do
|
||||
event = Events::Base.new('conversation.opened', reopened_time, conversation: multiple_resolution_conversation)
|
||||
listener.conversation_opened(event)
|
||||
|
||||
reopened_event = account.reporting_events.where(name: 'conversation_opened').first
|
||||
expect(reopened_event.value).to be_within(1).of(1800) # 30 minutes from second resolution
|
||||
expect(reopened_event.event_start_time).to be_within(1.second).of(second_resolved_time)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when agent bot resolves and conversation is reopened' do
|
||||
# This implicitly tests that the first_response time is correctly calculated
|
||||
# By checking that a conversation reopened event is created with the correct values
|
||||
let(:agent_bot) { create(:agent_bot, account: account) }
|
||||
let(:agent_bot_inbox) { create(:inbox, account: account) }
|
||||
let(:bot_resolved_time) { 2.hours.ago }
|
||||
let(:reopened_time) { 1.hour.ago }
|
||||
let(:bot_conversation) do
|
||||
create(:conversation, account: account, inbox: agent_bot_inbox, assignee: user, updated_at: reopened_time)
|
||||
end
|
||||
|
||||
before do
|
||||
create(:agent_bot_inbox, agent_bot: agent_bot, inbox: agent_bot_inbox)
|
||||
|
||||
create(:reporting_event,
|
||||
name: 'conversation_resolved',
|
||||
account_id: account.id,
|
||||
inbox_id: agent_bot_inbox.id,
|
||||
conversation_id: bot_conversation.id,
|
||||
user_id: user.id,
|
||||
event_end_time: bot_resolved_time)
|
||||
end
|
||||
|
||||
it 'creates conversation_opened event for agent bot reopening' do
|
||||
event = Events::Base.new('conversation.opened', reopened_time, conversation: bot_conversation)
|
||||
listener.conversation_opened(event)
|
||||
|
||||
reopened_event = account.reporting_events.where(name: 'conversation_opened').first
|
||||
expect(reopened_event.value).to be_within(1).of(3600) # 1 hour since resolution
|
||||
expect(reopened_event.event_start_time).to be_within(1.second).of(bot_resolved_time)
|
||||
expect(reopened_event.event_end_time).to be_within(1.second).of(reopened_time)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe AssignmentPolicy, type: :model do
|
||||
let(:account) { create(:account) }
|
||||
let(:assignment_policy) { create(:assignment_policy, account: account) }
|
||||
|
||||
describe 'associations' do
|
||||
it { is_expected.to belong_to(:account) }
|
||||
it { is_expected.to have_many(:inbox_assignment_policies).dependent(:destroy) }
|
||||
it { is_expected.to have_many(:inboxes).through(:inbox_assignment_policies) }
|
||||
end
|
||||
|
||||
describe 'validations' do
|
||||
subject { assignment_policy }
|
||||
|
||||
it { is_expected.to validate_presence_of(:name) }
|
||||
it { is_expected.to validate_uniqueness_of(:name).scoped_to(:account_id) }
|
||||
it { is_expected.to validate_length_of(:name).is_at_most(255) }
|
||||
it { is_expected.to validate_length_of(:description).is_at_most(1000) }
|
||||
|
||||
it { is_expected.to validate_presence_of(:fair_distribution_limit) }
|
||||
it { is_expected.to validate_numericality_of(:fair_distribution_limit).is_greater_than(0).is_less_than_or_equal_to(100) }
|
||||
|
||||
it { is_expected.to validate_presence_of(:fair_distribution_window) }
|
||||
it { is_expected.to validate_numericality_of(:fair_distribution_window).is_greater_than(60).is_less_than_or_equal_to(86_400) }
|
||||
end
|
||||
|
||||
describe 'enums' do
|
||||
it { is_expected.to define_enum_for(:assignment_order).with_values(round_robin: 0) }
|
||||
it { is_expected.to define_enum_for(:conversation_priority).with_values(earliest_created: 0, longest_waiting: 1) }
|
||||
end
|
||||
|
||||
describe '#webhook_data' do
|
||||
it 'returns correct data structure' do
|
||||
data = assignment_policy.webhook_data
|
||||
|
||||
expect(data).to include(
|
||||
id: assignment_policy.id,
|
||||
name: assignment_policy.name,
|
||||
description: assignment_policy.description,
|
||||
assignment_order: assignment_policy.assignment_order,
|
||||
conversation_priority: assignment_policy.conversation_priority,
|
||||
fair_distribution_limit: assignment_policy.fair_distribution_limit,
|
||||
fair_distribution_window: assignment_policy.fair_distribution_window,
|
||||
enabled: assignment_policy.enabled
|
||||
)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -82,6 +82,16 @@ RSpec.describe Attachment do
|
||||
|
||||
expect(attachment.thumb_url).to be_present
|
||||
end
|
||||
|
||||
it 'handles unrepresentable images gracefully' do
|
||||
attachment = message.attachments.create!(account_id: message.account_id, file_type: :image)
|
||||
attachment.file.attach(io: StringIO.new('fake image'), filename: 'test.jpg', content_type: 'image/jpeg')
|
||||
|
||||
allow(attachment.file).to receive(:representation).and_raise(ActiveStorage::UnrepresentableError.new('Cannot represent'))
|
||||
|
||||
expect(Rails.logger).to receive(:warn).with(/Unrepresentable image attachment: #{attachment.id}/)
|
||||
expect(attachment.thumb_url).to eq('')
|
||||
end
|
||||
end
|
||||
|
||||
describe 'meta data handling' do
|
||||
|
||||
@@ -37,6 +37,12 @@ RSpec.describe AutomationRule do
|
||||
action_name: :assign_team,
|
||||
action_params: [1]
|
||||
},
|
||||
{
|
||||
action_name: :remove_assigned_agent
|
||||
},
|
||||
{
|
||||
action_name: :remove_assigned_team
|
||||
},
|
||||
{
|
||||
action_name: :add_label,
|
||||
action_params: %w[support priority_customer]
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user