Merge pull request #807 from Hexastack/feat/block-outcome
Some checks are pending
Build and Push Docker API Image / build-and-push (push) Waiting to run
Build and Push Docker Base Image / build-and-push (push) Waiting to run
Build and Push Docker UI Image / build-and-push (push) Waiting to run

Feat/block outcome
This commit is contained in:
Med Marrouchi 2025-03-03 11:39:25 +01:00 committed by GitHub
commit 69a935314d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
20 changed files with 494 additions and 137 deletions

View File

@ -1,5 +1,5 @@
/*
* Copyright © 2024 Hexastack. All rights reserved.
* Copyright © 2025 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
@ -251,6 +251,7 @@ describe('BlockController', () => {
name: 'block with nextBlocks',
nextBlocks: [hasNextBlocks.id],
patterns: ['Hi'],
outcomes: [],
trigger_labels: [],
assign_labels: [],
trigger_channels: [],

View File

@ -1,5 +1,5 @@
/*
* Copyright © 2024 Hexastack. All rights reserved.
* Copyright © 2025 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
@ -45,6 +45,14 @@ export class BlockCreateDto {
@IsPatternList({ message: 'Patterns list is invalid' })
patterns?: Pattern[] = [];
@ApiPropertyOptional({
description: "Block's outcomes",
type: Array,
})
@IsOptional()
@IsArray({ message: 'Outcomes are invalid' })
outcomes?: string[] = [];
@ApiPropertyOptional({ description: 'Block trigger labels', type: Array })
@IsOptional()
@IsArray()
@ -120,6 +128,7 @@ export class BlockCreateDto {
export class BlockUpdateDto extends PartialType(
OmitType(BlockCreateDto, [
'patterns',
'outcomes',
'trigger_labels',
'assign_labels',
'trigger_channels',
@ -130,6 +139,14 @@ export class BlockUpdateDto extends PartialType(
@IsPatternList({ message: 'Patterns list is invalid' })
patterns?: Pattern[];
@ApiPropertyOptional({
description: "Block's outcomes",
type: Array,
})
@IsOptional()
@IsArray({ message: 'Outcomes are invalid' })
outcomes?: string[];
@ApiPropertyOptional({ description: 'Block trigger labels', type: Array })
@IsOptional()
@IsArray()

View File

@ -42,6 +42,12 @@ export class BlockStub extends BaseSchema {
})
patterns: Pattern[];
@Prop({
type: Object,
default: [],
})
outcomes: string[];
@Prop([
{
type: MongooseSchema.Types.ObjectId,

View File

@ -40,4 +40,5 @@ export enum PayloadType {
attachments = 'attachments',
quick_reply = 'quick_reply',
button = 'button',
outcome = 'outcome',
}

View File

@ -6,14 +6,6 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
/*
* Copyright © 2025 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { z } from 'zod';
import { PluginName } from '@/plugins/types';
@ -62,6 +54,7 @@ export enum OutgoingMessageFormat {
attachment = 'attachment',
list = 'list',
carousel = 'carousel',
system = 'system',
}
export const outgoingMessageFormatSchema = z.nativeEnum(OutgoingMessageFormat);
@ -147,6 +140,15 @@ export type StdOutgoingAttachmentMessage = z.infer<
typeof stdOutgoingAttachmentMessageSchema
>;
export const stdOutgoingSystemMessageSchema = z.object({
outcome: z.string().optional(), // "any" or any other string (in snake case)
data: z.any().optional(),
});
export type StdOutgoingSystemMessage = z.infer<
typeof stdOutgoingSystemMessageSchema
>;
export const pluginNameSchema = z
.string()
.regex(/-plugin$/) as z.ZodType<PluginName>;
@ -290,7 +292,16 @@ export type StdOutgoingAttachmentEnvelope = z.infer<
typeof stdOutgoingAttachmentEnvelopeSchema
>;
export const stdOutgoingEnvelopeSchema = z.union([
export const stdOutgoingSystemEnvelopeSchema = z.object({
format: z.literal(OutgoingMessageFormat.system),
message: stdOutgoingSystemMessageSchema,
});
export type StdOutgoingSystemEnvelope = z.infer<
typeof stdOutgoingSystemEnvelopeSchema
>;
export const stdOutgoingMessageEnvelopeSchema = z.union([
stdOutgoingTextEnvelopeSchema,
stdOutgoingQuickRepliesEnvelopeSchema,
stdOutgoingButtonsEnvelopeSchema,
@ -298,6 +309,15 @@ export const stdOutgoingEnvelopeSchema = z.union([
stdOutgoingAttachmentEnvelopeSchema,
]);
export type StdOutgoingMessageEnvelope = z.infer<
typeof stdOutgoingMessageEnvelopeSchema
>;
export const stdOutgoingEnvelopeSchema = z.union([
stdOutgoingMessageEnvelopeSchema,
stdOutgoingSystemEnvelopeSchema,
]);
export type StdOutgoingEnvelope = z.infer<typeof stdOutgoingEnvelopeSchema>;
// is-valid-message-text validation

View File

@ -11,6 +11,7 @@ import { OnEvent } from '@nestjs/event-emitter';
import { AttachmentService } from '@/attachment/services/attachment.service';
import EventWrapper from '@/channel/lib/EventWrapper';
import { ChannelName } from '@/channel/types';
import { ContentService } from '@/cms/services/content.service';
import { CONSOLE_CHANNEL_NAME } from '@/extensions/channels/console/settings';
import { NLU } from '@/helper/types';
@ -27,11 +28,13 @@ import { BlockDto } from '../dto/block.dto';
import { BlockRepository } from '../repositories/block.repository';
import { Block, BlockFull, BlockPopulate } from '../schemas/block.schema';
import { Label } from '../schemas/label.schema';
import { Subscriber } from '../schemas/subscriber.schema';
import { Context } from '../schemas/types/context';
import {
BlockMessage,
OutgoingMessageFormat,
StdOutgoingEnvelope,
StdOutgoingSystemEnvelope,
} from '../schemas/types/message';
import { NlpPattern, PayloadPattern } from '../schemas/types/pattern';
import { Payload, StdQuickReply } from '../schemas/types/quick-reply';
@ -57,10 +60,75 @@ export class BlockService extends BaseService<
super(repository);
}
/**
* Filters an array of blocks based on the specified channel.
*
* This function ensures that only blocks that are either:
* - Not restricted to specific trigger channels (`trigger_channels` is undefined or empty), or
* - Explicitly allow the given channel (or the console channel)
*
* are included in the returned array.
*
* @param blocks - The list of blocks to be filtered.
* @param channel - The name of the channel to filter blocks by.
*
* @returns The filtered array of blocks that are allowed for the given channel.
*/
filterBlocksByChannel<B extends Block | BlockFull>(
blocks: B[],
channel: ChannelName,
) {
return blocks.filter((b) => {
return (
!b.trigger_channels ||
b.trigger_channels.length === 0 ||
[...b.trigger_channels, CONSOLE_CHANNEL_NAME].includes(channel)
);
});
}
/**
* Filters an array of blocks based on subscriber labels.
*
* This function selects blocks that either:
* - Have no trigger labels (making them applicable to all subscribers), or
* - Contain at least one trigger label that matches a label from the provided list.
*
* The filtered blocks are then **sorted** in descending order by the number of trigger labels,
* ensuring that blocks with more specific targeting (more trigger labels) are prioritized.
*
* @param blocks - The list of blocks to be filtered.
* @param labels - The list of subscriber labels to match against.
* @returns The filtered and sorted list of blocks.
*/
filterBlocksBySubscriberLabels<B extends Block | BlockFull>(
blocks: B[],
profile?: Subscriber,
) {
if (!profile) {
return blocks;
}
return (
blocks
.filter((b) => {
const triggerLabels = b.trigger_labels.map((l) =>
typeof l === 'string' ? l : l.id,
);
return (
triggerLabels.length === 0 ||
triggerLabels.some((l) => profile.labels.includes(l))
);
})
// Priority goes to block who target users with labels
.sort((a, b) => b.trigger_labels.length - a.trigger_labels.length)
);
}
/**
* Find a block whose patterns matches the received event
*
* @param blocks blocks Starting/Next blocks in the conversation flow
* @param filteredBlocks blocks Starting/Next blocks in the conversation flow
* @param event Received channel's message
*
* @returns The block that matches
@ -77,37 +145,15 @@ export class BlockService extends BaseService<
let block: BlockFull | undefined = undefined;
const payload = event.getPayload();
// Perform a filter on the specific channels
const channel = event.getHandler().getName();
blocks = blocks.filter((b) => {
return (
!b.trigger_channels ||
b.trigger_channels.length === 0 ||
[...b.trigger_channels, CONSOLE_CHANNEL_NAME].includes(channel)
);
});
// Perform a filter on trigger labels
let userLabels: string[] = [];
const profile = event.getSender();
if (profile && Array.isArray(profile.labels)) {
userLabels = profile.labels.map((l) => l);
}
blocks = blocks
.filter((b) => {
const trigger_labels = b.trigger_labels.map(({ id }) => id);
return (
trigger_labels.length === 0 ||
trigger_labels.some((l) => userLabels.includes(l))
);
})
// Priority goes to block who target users with labels
.sort((a, b) => b.trigger_labels.length - a.trigger_labels.length);
// Perform a filter to get the candidates blocks
const filteredBlocks = this.filterBlocksBySubscriberLabels(
this.filterBlocksByChannel(blocks, event.getHandler().getName()),
event.getSender(),
);
// Perform a payload match & pick last createdAt
if (payload) {
block = blocks
block = filteredBlocks
.filter((b) => {
return this.matchPayload(payload, b);
})
@ -131,7 +177,7 @@ export class BlockService extends BaseService<
}
// Perform a text pattern match
block = blocks
block = filteredBlocks
.filter((b) => {
return this.matchText(text, b);
})
@ -141,7 +187,7 @@ export class BlockService extends BaseService<
if (!block && nlp) {
// Find block pattern having the best match of nlp entities
let nlpBest = 0;
blocks.forEach((b, index, self) => {
filteredBlocks.forEach((b, index, self) => {
const nlpPattern = this.matchNLP(nlp, b);
if (nlpPattern && nlpPattern.length > nlpBest) {
nlpBest = nlpPattern.length;
@ -295,6 +341,36 @@ export class BlockService extends BaseService<
});
}
/**
* Matches an outcome-based block from a list of available blocks
* based on the outcome of a system message.
*
* @param blocks - An array of blocks to search for a matching outcome.
* @param envelope - The system message envelope containing the outcome to match.
*
* @returns - Returns the first matching block if found, otherwise returns `undefined`.
*/
matchOutcome(
blocks: Block[],
event: EventWrapper<any, any>,
envelope: StdOutgoingSystemEnvelope,
) {
// Perform a filter to get the candidates blocks
const filteredBlocks = this.filterBlocksBySubscriberLabels(
this.filterBlocksByChannel(blocks, event.getHandler().getName()),
event.getSender(),
);
return filteredBlocks.find((b) => {
return b.patterns
.filter(
(p) => typeof p === 'object' && 'type' in p && p.type === 'outcome',
)
.some((p: PayloadPattern) =>
['any', envelope.message.outcome].includes(p.value),
);
});
}
/**
* Replaces tokens with their context variables values in the provided text message
*

View File

@ -1,5 +1,5 @@
/*
* Copyright © 2024 Hexastack. All rights reserved.
* Copyright © 2025 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
@ -201,7 +201,7 @@ describe('BlockService', () => {
let hasBotSpoken = false;
const clearMock = jest
.spyOn(botService, 'findBlockAndSendReply')
.spyOn(botService, 'triggerBlock')
.mockImplementation(
(
actualEvent: WebEventWrapper<typeof WEB_CHANNEL_NAME>,

View File

@ -21,8 +21,11 @@ import {
getDefaultConversationContext,
} from '../schemas/conversation.schema';
import { Context } from '../schemas/types/context';
import { IncomingMessageType } from '../schemas/types/message';
import { SubscriberContext } from '../schemas/types/subscriberContext';
import {
IncomingMessageType,
OutgoingMessageFormat,
StdOutgoingMessageEnvelope,
} from '../schemas/types/message';
import { BlockService } from './block.service';
import { ConversationService } from './conversation.service';
@ -40,40 +43,24 @@ export class BotService {
) {}
/**
* Sends a processed message to the user based on a specified content block.
* Replaces tokens within the block with context data, handles fallback scenarios,
* and assigns relevant labels to the user.
* Sends a message to the subscriber via the appropriate messaging channel and handles related events.
*
* @param event - The incoming message or action that triggered the bot's response.
* @param envelope - The outgoing message envelope containing the bot's response.
* @param block - The content block containing the message and options to be sent.
* @param context - Optional. The conversation context object, containing relevant data for personalization.
* @param fallback - Optional. Boolean flag indicating if this is a fallback message when no appropriate response was found.
* @param conversationId - Optional. The conversation ID to link the message to a specific conversation thread.
*
* @returns A promise that resolves with the message response, including the message ID.
*/
async sendMessageToSubscriber(
envelope: StdOutgoingMessageEnvelope,
event: EventWrapper<any, any>,
block: BlockFull,
context?: Context,
fallback?: boolean,
conservationId?: string,
) {
context = context || getDefaultConversationContext();
fallback = typeof fallback !== 'undefined' ? fallback : false;
const options = block.options;
this.logger.debug('Sending message ... ', event.getSenderForeignId());
// Process message : Replace tokens with context data and then send the message
const recipient = event.getSender();
const envelope = await this.blockService.processMessage(
block,
context,
recipient?.context as SubscriberContext,
fallback,
conservationId,
);
// Send message through the right channel
this.logger.debug('Sending message ... ', event.getSenderForeignId());
const response = await event
.getHandler()
.sendMessage(event, envelope, options, context);
@ -114,35 +101,56 @@ export class BotService {
);
this.logger.debug('Assigned labels ', blockLabels);
return response;
}
/**
* Finds an appropriate reply block and sends it to the user.
* If there are additional blocks or attached blocks, it continues the conversation flow.
* Ends the conversation if no further blocks are available.
* Processes and executes a block, handling its associated messages and flow logic.
*
* The function performs the following steps:
* 1. Retrieves the conversation context and recipient information.
* 2. Generates an outgoing message envelope from the block.
* 3. Sends the message to the subscriber unless it's a system message.
* 4. Handles block chaining:
* - If the block has an attached block, it recursively triggers the attached block.
* - If the block has multiple possible next blocks, it determines the next block based on the outcome of the system message.
* - If there are next blocks but no outcome-based matching, it updates the conversation state for the next steps.
* 5. If no further blocks exist, it ends the flow execution.
*
* @param event - The incoming message or action that initiated this response.
* @param convo - The current conversation context and flow.
* @param block - The content block to be processed and sent.
* @param fallback - Boolean indicating if this is a fallback response in case no appropriate reply was found.
*
* @returns A promise that continues or ends the conversation based on available blocks.
* @returns A promise that either continues or ends the flow execution based on the available blocks.
*/
async findBlockAndSendReply(
async triggerBlock(
event: EventWrapper<any, any>,
convo: Conversation,
block: BlockFull,
fallback: boolean,
fallback: boolean = false,
) {
try {
await this.sendMessageToSubscriber(
event,
const context = convo.context || getDefaultConversationContext();
const recipient = event.getSender();
const envelope = await this.blockService.processMessage(
block,
convo.context,
context,
recipient?.context,
fallback,
convo.id,
);
if (envelope.format !== OutgoingMessageFormat.system) {
await this.sendMessageToSubscriber(
envelope,
event,
block,
context,
fallback,
);
}
if (block.attachedBlock) {
// Sequential messaging ?
try {
@ -154,12 +162,7 @@ export class BotService {
'No attached block to be found with id ' + block.attachedBlock,
);
}
return await this.findBlockAndSendReply(
event,
convo,
attachedBlock,
fallback,
);
return await this.triggerBlock(event, convo, attachedBlock, fallback);
} catch (err) {
this.logger.error('Unable to retrieve attached block', err);
this.eventEmitter.emit('hook:conversation:end', convo, true);
@ -168,20 +171,47 @@ export class BotService {
Array.isArray(block.nextBlocks) &&
block.nextBlocks.length > 0
) {
// Conversation continues : Go forward to next blocks
this.logger.debug('Conversation continues ...', convo.id);
const nextIds = block.nextBlocks.map(({ id }) => id);
try {
await this.conversationService.updateOne(convo.id, {
current: block.id,
next: nextIds,
});
if (envelope.format === OutgoingMessageFormat.system) {
// System message: Trigger the next block based on the outcome
this.logger.debug(
'Matching the outcome against the next blocks ...',
convo.id,
);
const match = this.blockService.matchOutcome(
block.nextBlocks,
event,
envelope,
);
if (match) {
const nextBlock = await this.blockService.findOneAndPopulate(
match.id,
);
if (!nextBlock) {
throw new Error(
'No attached block to be found with id ' +
block.attachedBlock,
);
}
return await this.triggerBlock(event, convo, nextBlock, fallback);
} else {
this.logger.warn(
'Block outcome did not match any of the next blocks',
convo,
);
}
} else {
// Conversation continues : Go forward to next blocks
this.logger.debug('Conversation continues ...', convo.id);
const nextIds = block.nextBlocks.map(({ id }) => id);
await this.conversationService.updateOne(convo.id, {
current: block.id,
next: nextIds,
});
}
} catch (err) {
this.logger.error(
'Unable to update conversation when going next',
convo,
err,
);
this.logger.error('Unable to continue the flow', convo, err);
return;
}
} else {
@ -275,12 +305,7 @@ export class BotService {
// Otherwise, old captured const value may be replaced by another const value
!fallback,
);
await this.findBlockAndSendReply(
event,
updatedConversation,
next,
fallback,
);
await this.triggerBlock(event, updatedConversation, next, fallback);
} catch (err) {
this.logger.error('Unable to store context data!', err);
return this.eventEmitter.emit('hook:conversation:end', convo, true);
@ -376,12 +401,7 @@ export class BotService {
subscriber.id,
block.name,
);
return this.findBlockAndSendReply(
event,
updatedConversation,
block,
false,
);
return this.triggerBlock(event, updatedConversation, block, false);
} catch (err) {
this.logger.error('Unable to store context data!', err);
this.eventEmitter.emit('hook:conversation:end', convo, true);
@ -459,7 +479,7 @@ export class BotService {
'No global fallback block defined, sending a message ...',
err,
);
this.sendMessageToSubscriber(event, {
const globalFallbackBlock = {
id: 'global-fallback',
name: 'Global Fallback',
message: settings.chatbot_settings.fallback_message,
@ -473,7 +493,19 @@ export class BotService {
createdAt: new Date(),
updatedAt: new Date(),
attachedBlock: null,
} as any as BlockFull);
} as any as BlockFull;
const envelope = await this.blockService.processMessage(
globalFallbackBlock,
getDefaultConversationContext(),
{ vars: {} }, // @TODO: use subscriber ctx
);
await this.sendMessageToSubscriber(
envelope as StdOutgoingMessageEnvelope,
event,
globalFallbackBlock,
);
}
}
// Do nothing ...

View File

@ -136,6 +136,7 @@ describe('TranslationService', () => {
const block: Block = {
name: 'Ollama Plugin',
patterns: [],
outcomes: [],
assign_labels: [],
trigger_channels: [],
trigger_labels: [],

View File

@ -35,6 +35,7 @@ export const blocks: TBlockFixtures['values'][] = [
{
name: 'hasNextBlocks',
patterns: ['Hi'],
outcomes: [],
category: null,
options: {
typing: 0,
@ -53,6 +54,7 @@ export const blocks: TBlockFixtures['values'][] = [
{
name: 'hasPreviousBlocks',
patterns: ['colors'],
outcomes: [],
category: null,
options: {
typing: 0,
@ -90,6 +92,7 @@ export const blocks: TBlockFixtures['values'][] = [
{
name: 'buttons',
patterns: ['about'],
outcomes: [],
category: null,
options: {
typing: 0,
@ -127,6 +130,7 @@ export const blocks: TBlockFixtures['values'][] = [
{
name: 'attachment',
patterns: ['image'],
outcomes: [],
category: null,
options: {
typing: 0,
@ -153,6 +157,7 @@ export const blocks: TBlockFixtures['values'][] = [
{
name: 'test',
patterns: ['yes'],
outcomes: [],
category: null,
//to be verified
options: {

View File

@ -247,6 +247,13 @@
"triggers": "Triggers",
"payloads": "Payloads",
"general_payloads": "General Payloads",
"exact_match": "Exact Match",
"pattern_match": "Pattern Match",
"intent_match": "Intent Match",
"interaction": "Interaction",
"outcome_match": "Outcome Match",
"outcome": "Outcome",
"any_outcome": "Any Outcome",
"capture": "Capture?",
"context_var": "Context Var",
"text_message": "Text message",

View File

@ -247,6 +247,13 @@
"triggers": "Déclencheurs",
"payloads": "Payloads",
"general_payloads": "Payloads généraux",
"exact_match": "Comparaison Exacte",
"pattern_match": "Expression Régulière",
"intent_match": "Intention",
"interaction": "Interaction",
"outcome": "Résultat",
"outcome_match": "Résultat",
"any_outcome": "N'importe quel résultat",
"capture": "Capturer?",
"context_var": "Variable contextuelle",
"text_message": "Message texte",

View File

@ -59,6 +59,7 @@ export const BlockEditForm: FC<ComponentFormProps<IBlock>> = ({
const DEFAULT_VALUES = {
name: block?.name || "",
patterns: block?.patterns || [],
outcomes: block?.outcomes || [],
trigger_labels: block?.trigger_labels || [],
trigger_channels: block?.trigger_channels || [],
options: block?.options || {

View File

@ -1,5 +1,5 @@
/*
* Copyright © 2024 Hexastack. All rights reserved.
* Copyright © 2025 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
@ -16,6 +16,7 @@ import { useFind } from "@/hooks/crud/useFind";
import { EntityType } from "@/services/types";
import { IBlockAttributes } from "@/types/block.types";
import { StdPluginMessage } from "@/types/message.types";
import { getNamespace } from "@/utils/string";
import { useBlock } from "./BlockFormProvider";
@ -63,8 +64,7 @@ const PluginMessageForm = () => {
<SettingInput
setting={setting}
field={field}
// @TODO : clean this later
ns={message.plugin.replaceAll("-", "_")}
ns={getNamespace(message.plugin)}
/>
</FormControl>
)}

View File

@ -0,0 +1,150 @@
/*
* Copyright © 2025 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import {
Autocomplete,
Box,
Chip,
InputAdornment,
Skeleton,
Typography,
} from "@mui/material";
import { useMemo, useState } from "react";
import { Input } from "@/app-components/inputs/Input";
import { useGetFromCache } from "@/hooks/crud/useGet";
import { useTranslate } from "@/hooks/useTranslate";
import { theme } from "@/layout/themes/theme";
import { EntityType } from "@/services/types";
import { IBlock, PayloadPattern } from "@/types/block.types";
import { PayloadType } from "@/types/message.types";
import { getNamespace } from "@/utils/string";
import { useBlock } from "../../BlockFormProvider";
type PayloadOption = PayloadPattern & {
group: string;
};
type OutcomeInputProps = {
defaultValue: PayloadPattern;
onChange: (pattern: PayloadPattern) => void;
};
export const OutcomeInput = ({ defaultValue, onChange }: OutcomeInputProps) => {
const block = useBlock();
const [selectedValue, setSelectedValue] = useState(defaultValue);
const getBlockFromCache = useGetFromCache(EntityType.BLOCK);
const { t } = useTranslate();
// Gather previous blocks outcomes
const options = useMemo(
() =>
(block?.previousBlocks || [])
.map((b) => getBlockFromCache(b))
.filter((b) => b && Array.isArray(b.outcomes) && b.outcomes.length > 0)
.map((b) => b as IBlock)
.reduce(
(acc, b) => {
const outcomes = (b.outcomes || []).map((outcome) => ({
label: t(`label.${outcome}` as any, {
defaultValue: outcome,
ns:
"plugin" in b.message
? getNamespace(b.message.plugin)
: undefined,
}),
value: outcome,
group: b.name,
type: PayloadType.outcome,
}));
return acc.concat(outcomes);
},
[
{
label: t("label.any_outcome"),
value: "any",
type: PayloadType.outcome,
group: "general",
},
] as PayloadOption[],
),
[block?.previousBlocks, getBlockFromCache],
);
const isOptionsReady =
!defaultValue || options.find((o) => o.value === defaultValue.value);
if (!isOptionsReady) {
return (
<Skeleton animation="wave" variant="rounded" width="100%" height={40} />
);
}
const selected = defaultValue
? options.find((o) => o.value === defaultValue.value)
: undefined;
return (
<Autocomplete
size="small"
fullWidth
defaultValue={selected || undefined}
value={selected}
options={options}
multiple={false}
disableClearable
onChange={(_e, value) => {
setSelectedValue(value);
const { group: _g, ...payloadPattern } = value;
onChange(payloadPattern);
}}
groupBy={({ group }) => group ?? t("label.other")}
getOptionLabel={({ label }) => label}
isOptionEqualToValue={(option, value) => option.value === value.value}
renderGroup={({ key, group, children }) => (
<li key={key}>
<Typography component="h4" p={2} fontWeight={700} color="primary">
{t(`label.${group}`, { defaultValue: group })}
</Typography>
<Box>{children}</Box>
</li>
)}
renderInput={(props) => (
<Input
{...props}
label={t("label.outcome")}
InputProps={{
...props.InputProps,
startAdornment: (
<InputAdornment position="start">
<Chip
sx={{
left: "8px",
height: "25px",
fontSize: "12px",
minWidth: "75px",
position: "relative",
maxHeight: "30px",
borderRadius: "16px",
borderColor: theme.palette.grey[400],
}}
color="primary"
label={t(
`label.${selectedValue?.type || "outcome"}`,
).toLocaleLowerCase()}
variant="role"
/>
</InputAdornment>
),
}}
/>
)}
/>
);
};

View File

@ -23,6 +23,7 @@ import {
PayloadPattern,
} from "@/types/block.types";
import { OutcomeInput } from "./OutcomeInput";
import { PostbackInput } from "./PostbackInput";
const isRegex = (str: Pattern) => {
@ -38,6 +39,8 @@ const getType = (pattern: Pattern): PatternType => {
return "menu";
} else if (pattern?.type === "content") {
return "content";
} else if (pattern?.type === "outcome") {
return "outcome";
} else {
return "payload";
}
@ -67,7 +70,6 @@ const PatternInput: FC<PatternInputProps> = ({
} = useFormContext<IBlockAttributes>();
const [pattern, setPattern] = useState<Pattern>(value);
const patternType = getType(value);
const isPostbackType = ["payload", "content", "menu"].includes(patternType);
const registerInput = (
errorMessage: string,
idx: number,
@ -100,15 +102,22 @@ const PatternInput: FC<PatternInputProps> = ({
onChange={setPattern}
/>
)}
{isPostbackType ? (
<PostbackInput
onChange={(payload) => {
payload && setPattern(payload);
}}
defaultValue={pattern as PayloadPattern}
/>
) : null}
{["payload", "content", "menu"].includes(patternType) ? (
<PostbackInput
onChange={(payload) => {
payload && setPattern(payload);
}}
defaultValue={pattern as PayloadPattern}
/>
) : null}
{patternType === "outcome" ? (
<OutcomeInput
onChange={(payload) => {
payload && setPattern(payload);
}}
defaultValue={pattern as PayloadPattern}
/>
) : null}
{typeof value === "string" && patternType === "regex" ? (
<RegexInput
{...registerInput(t("message.regex_is_empty"), idx, {

View File

@ -6,14 +6,13 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import {
Abc,
Add,
Mouse,
PsychologyAlt,
RemoveCircleOutline,
Spellcheck,
} from "@mui/icons-material";
import AbcIcon from "@mui/icons-material/Abc";
import AddIcon from "@mui/icons-material/Add";
import MediationIcon from "@mui/icons-material/Mediation";
import MouseIcon from "@mui/icons-material/Mouse";
import PsychologyAltIcon from "@mui/icons-material/PsychologyAlt";
import RemoveCircleOutlineIcon from "@mui/icons-material/RemoveCircleOutline";
import SpellcheckIcon from "@mui/icons-material/Spellcheck";
import { Box, Chip, IconButton, styled, useTheme } from "@mui/material";
import { FC, useEffect, useMemo, useState } from "react";
import { useFormContext } from "react-hook-form";
@ -79,12 +78,20 @@ const PatternsInput: FC<PatternsInputProps> = ({ value, onChange }) => {
const actions: DropdownButtonAction[] = useMemo(
() => [
{ icon: <Spellcheck />, name: "Exact Match", defaultValue: "" },
{ icon: <Abc />, name: "Pattern Match", defaultValue: "//" },
{ icon: <PsychologyAlt />, name: "Intent Match", defaultValue: [] },
{
icon: <Mouse />,
name: "Interaction",
icon: <SpellcheckIcon />,
name: t("label.exact_match"),
defaultValue: "",
},
{ icon: <AbcIcon />, name: t("label.pattern_match"), defaultValue: "//" },
{
icon: <PsychologyAltIcon />,
name: t("label.intent_match"),
defaultValue: [],
},
{
icon: <MouseIcon />,
name: t("label.interaction"),
defaultValue: {
label: t("label.get_started"),
value: "GET_STARTED",
@ -92,6 +99,16 @@ const PatternsInput: FC<PatternsInputProps> = ({ value, onChange }) => {
group: "general",
},
},
{
icon: <MediationIcon />,
name: t("label.outcome_match"),
defaultValue: {
label: t("label.any_outcome"),
value: "any",
type: PayloadType.outcome,
group: "general",
},
},
],
// eslint-disable-next-line react-hooks/exhaustive-deps
[],
@ -129,7 +146,7 @@ const PatternsInput: FC<PatternsInputProps> = ({ value, onChange }) => {
color="error"
onClick={() => removeInput(idx)}
>
<RemoveCircleOutline />
<RemoveCircleOutlineIcon />
</IconButton>
</Box>
))
@ -140,7 +157,7 @@ const PatternsInput: FC<PatternsInputProps> = ({ value, onChange }) => {
label={t("button.add_pattern")}
actions={actions}
onClick={(action) => addInput(action.defaultValue as Pattern)}
icon={<Add />}
icon={<AddIcon />}
/>
</Box>
);

View File

@ -64,7 +64,7 @@ export interface PayloadPattern {
value: string;
// @todo : rename 'attachment' to 'attachments'
// @todo: If undefined, that means the payload could be either quick_reply or button
// We will move soon so that it will be a required attribute
// We should update soon so that it will be a required attribute
type?: PayloadType;
}
@ -81,12 +81,14 @@ export type PatternType =
| "nlp"
| "menu"
| "content"
| "outcome"
| "payload"
| "text";
export interface IBlockAttributes {
name: string;
patterns?: Pattern[];
outcomes?: string[];
trigger_labels?: string[];
trigger_channels?: string[];
assign_labels?: string[];

View File

@ -30,6 +30,7 @@ export enum PayloadType {
content = "content",
quick_reply = "quick_reply",
button = "button",
outcome = "outcome",
}
export enum FileType {

View File

@ -14,3 +14,7 @@ export const slugify = (str: string) => {
.replace(/\s+/g, "-")
.replace(/-+/g, "_");
};
export const getNamespace = (extensionName: string) => {
return extensionName.replaceAll("-", "_");
};