Marco de acciones
La documentación generada automáticamente para Flex UI (la interfaz de usuario de Flex) está ahora disponible como distribución beta. La documentación generada automáticamente es precisa y completa, por lo que puede diferir de lo que se ve en la documentación oficial de Flex UI.
Flex UI constantly emits asynchronous events and event payloads that describe how the user is interacting with the platform. With the Flex UI Actions Framework, you can manually invoke certain actions such as completing tasks, transferring tasks, holding a current call, and many more. Each action fires a before and after event, which allows you to handle your own logic before and after the action occurs. You can also replace the default behavior of an Action with your own custom logic. As you develop Plugins, the Actions Framework will allow you to describe how you want to interact with Flex UI or any CRM Data.
Registrar e invocar una acción
Actions.registerAction registers a named action and allows you to invoke the action later. The second argument is an ActionFunction to be executed when the action is invoked. You can implement your logic in the ActionFunction.
import { Actions } from "@twilio/flex-ui";
Actions.registerAction("AcceptTask", (payload) => {
// Custom Logic Goes Here
});
Actions.invokeAction invokes actions that come out of the box with Flex, and the ones that you register. You can pass in an optional payload as a second parameter if the action needs any data when being invoked. When the named Action is invoked, it fires a before and after event.
import { Actions } from "@twilio/flex-ui";
Actions.invokeAction("AcceptTask", { sid: "WRXXXXXXXXXXXXXXXXX" });
Sustituir una acción
Actions.replaceAction replaces the default implementation of a named Action with your own. The replaced Action will be called with the same parameters as the original implementation, so you can add additional logic, then invoke the original action in your replacement function.
import { Actions } from "@twilio/flex-ui";
Actions.replaceAction("AcceptTask", (payload, original) => {
return new Promise((resolve, reject) => {
alert("I have replaced this Action");
resolve();
}).then(() => original(payload));
});
Agregar y quitar detectores de eventos
You can add and remove event listeners to events fired when an action is invoked. Every event name is the invoked Action’s name prefixed with either “before” or “after”.
import { Actions } from "@twilio/flex-ui";
Actions.addListener("beforeAcceptTask", (payload, cancelActionInvocation) => {
// Implement logic before the AcceptTask action has been invoked
if (someCondition) {
// use this function to prevent the actual AcceptTask action from being invoked
cancelActionInvocation();
}
});
Actions.addListener("afterAcceptTask", (payload) => {
// Implement logic after AcceptTask action has stopped executing
});
To remove a listener, you must provide the same function you used as an argument when registering the event. If you need to remove listeners, you should register your event listeners with a named function instead of an anonymous function.
Registering event listeners with named functions
import { Actions } from "@twilio/flex-ui";
const handleBeforeAcceptTask = (payload, cancelActionInvocation) => {
// Implement logic before the AcceptTask action has been invoked
};
const handleAfterAcceptTask = (payload) => {
// Implement logic after the AcceptTask action has stopped executing
};
// Register beforeAcceptTask and afterAcceptTask events
Actions.addListener("beforeAcceptTask", handleBeforeAcceptTask);
Actions.addListener("afterAcceptTask", handleAfterAcceptTask);
Removing event listeners with named functions
You can now remove the event listeners by passing the name of the event with the original function used to register the event.
Actions.removeListener("beforeAcceptTask", handleBeforeAcceptTask);
Actions.removeListener("afterAcceptTask", handleAfterAcceptTask);
Events Supported
For a list of all actions, visit the Actions part of the Flex UI 1.x docs. All event names take the name of the Action, prefixed with before or after. Every event name is also in camel case.
before[eventName] (for example "beforeAcceptTask"
)
Called when a named action is triggered, but before the action body is run. You can abort the action that is provided with event body.
after[Nombre del evento]
Se utiliza después de que la acción haya dejado de ejecutarse.
El evento afterLogout
no es compatible. Una vez que el trabajador haya cerrado la sesión, volverá a la pantalla de inicio de sesión de Flex.
Ejemplos y casos de uso comunes
Agregar una acción después de aceptar una tarea
Genera una alerta de javascript después de que un agente haya hecho clic para aceptar una tarea.
flex.Actions.addListener("afterAcceptTask", (payload) => alert("Triggered after event AcceptTask"));
Pedir confirmación antes de aceptar una tarea
Genera un mensaje antes de la aceptación de la tarea; impide que esa acción se ejecute con un comando de anulación si el usuario no lo confirma.
flex.Actions.addListener("beforeAcceptTask", (payload, abortFunction) => {
alert("Triggered before event AcceptTask");
if (!window.confirm("Are you sure you want to accept the task?")) {
abortFunction();
}
});
Personalizar una acción existente
Reemplaza la acción original de AcceptTask. Inserta la lógica personalizada para alertar sobre el reemplazo, pero ejecuta la acción original.
flex.Actions.replaceAction("AcceptTask", (payload, original) => {
return new Promise<void>((resolve, reject) => {
alert("I have replaced this Action");
resolve();
}).then(() => original(payload));
});
Registrar una acción personalizada
Registra una acción personalizada denominada MyAction
, que realiza una solicitud de HTTP. A continuación, agregamos un oyente a la acción CompleteTask que invoca esta acción personalizada. Por ejemplo, esto se puede utilizar para actualizar tu sistema de CRM.
flex.Actions.registerAction("MyAction", (payload) => {
return
fetch("https://my.server.backend.com/test")
.then(response => {
alert("Triggered MyAction with response " + JSON.stringify(response));
})
.catch(error => {
console.log(error);
throw error;
});
});
flex.Actions.addListener("afterCompleteTask", (payload) => {return flex.Actions.invokeAction("MyAction")});
Enviar un mensaje después de completar una tarea
Envía un mensaje posterior a la conversación una vez que la tarea se encuentra en un estado de cierre. Se puede utilizar para enviar una encuesta o notificar a un usuario que el agente cerró la sesión.
flex.Actions.replaceAction("WrapupTask", (payload, original) => {
// Only alter chat tasks:
if( payload.task.taskChannelUniqueName !== "chat" ) {
original(payload);
} else {
return new Promise(function(resolve, reject) {
// Send the message:
flex.Actions.invokeAction("SendMessage", {
body: 'Thanks for chatting. Your session is now closed.',
channelSid: payload.task.attributes.channelSid
}).then(response => {
// Wait until the message is sent to wrap-up the task:
resolve(original(payload));
});
});
}
});
Próximos pasos
- Puedes encontrar la lista completa de acciones compatibles o explorar la interfaz del administrador de acciones mediante la documentación generada automáticamente.
- Obtén más información sobre el marco de notificaciones para alertar a los agentes acerca de los cambios en Flex UI (la interfaz de usuario de Flex).
- Comienza con tu primer plugin de Flex e intenta personalizarlo con el marco de acciones.
¿Necesitas ayuda?
Todos la necesitamos a veces; la programación es difícil. Obtén ayuda ahora de nuestro equipo de soporte, o recurre a la sabiduría de la multitud visitando Stack Overflow Collective de Twilio o navegando por la etiqueta de Twilio en Stack Overflow.