Reglas de automatización

Automation rules are used to trigger automatic changes based on user actions (e.g., apply a modification when a field is set to a specific value), email events, time conditions (e.g., archive a record 7 days after its last update), or external events.

To create an automation rule with Studio, proceed as follows:

  1. Abra Studio, haga clic en Automatizaciones y después en Nuevo.

  2. Select the Activador and, if necessary, fill in the fields that appear on the screen based on the chosen trigger.

  3. Haga clic en Agregar una acción, seleccione el Tipo de acción y llene los campos que aparecen en la pantalla según la acción seleccionada.

  4. Haga clic en Guardar y cerrar o Guardar y crear nuevo.

Example

Example of an automated action on the Subscription model

Truco

  • To modify the model of the automation rule, switch models before clicking Automations in Studio, or activate the developer mode, create or edit an automation rule, and select the Model in the Automation Rules form.

  • You can also create automation rules from any kanban stage by clicking the gear icon ( ) next to the kanban stage name, then selecting Automations. In this case, the Trigger is set to Stage is set to by default, but you can change it if necessary.

    Crear automatizaciones a partir de una etapa kanban

Activador

The Trigger is used to define when the automation rule should be applied. The available triggers depend on the model. Five trigger categories are available overall:

Truco

You can also define a Before Update Domain to specify the conditions that must be met before the automation rule is triggered. In contrast, the conditions defined using the Extra Conditions and Apply on filters are checked during the execution of the automation rule.

To define a Before Update Domain, activate the developer mode, create or edit an automation rule, click Edit Domain, then click New Rule.

For example, if you want the automated action to happen when an email address is set on a contact that did not have an address before (in contrast to modifying their existing address), define the Before Update Domain to Email is not set, and the Apply on domain to Email is set.

Ejemplo de un activador con Antes de la actualización del dominio

Valores actualizados

The triggers available in this category depend on the model and are based on common field changes, such as adding a specific tag (e.g., to a task) or setting the User field. Select the trigger, then select a value if required.

Example of a Values Updated trigger

Eventos de correo electrónico

Activación de acciones automatizadas al enviar o recibir correos electrónicos.

Condiciones de tiempo

Trigger automated actions based on a date field. The following triggers are available:

  • Based on date field: Select the field to be used next to the Delay field.

  • After creation: The action is triggered when a record is created and saved.

  • After last update: The action is triggered when an existing record is edited and saved.

Puede definir ya sea:

  • a Delay: Specify the number of minutes, hours, days, or months. To trigger the action before the trigger date, specify a negative number. If you selected the Based on date field trigger, you must also select the date field to be used to determine the delay.

  • Extra Conditions: Click Add condition, then specify the conditions to be met to trigger the automation rule. Click New Rule to add another condition.

The action is triggered when the delay is reached and the conditions are met.

Example

If you want to send a reminder email 30 minutes before the start of a calendar event, select the Start (Calendar Event) under Trigger Date and set the Delay to -30 Minutes.

Ejemplo de un activador con base en un campo de fecha

Nota

By default, the scheduler checks for trigger dates every 4 hours, meaning lower granularity in time-based automations may not always be honored.

Personalizado

Activar acciones automatizadas:

  • On save: When the record is saved;

  • On deletion: When a record is deleted;

  • On UI change: When a field’s value is changed on the Form view, even before saving the record.

Para los activadores al guardar y al cambio de la UI debe seleccionar el o los campos que se usarán para activar la regla de automatización en el campo Al actualizar.

Advertencia

Si no se selecciona ningún campo en el campo Al actualizar, es posible que la acción automatizada se ejecute varias veces por registro.

También tiene la opción de definir condiciones adicionales que se deben cumplir para activar la regla de automatización en el campo Aplicar en.

Nota

The On UI change trigger can only be used with the Ejecutar código action and only works when a modification is made manually. The action is not executed if the field is changed through another automation rule.

Externo

Trigger automated actions based on an external event using a webhook. A webhook is a method of communication between two systems where the source system sends an HTTP(S) request to a destination system based on a specific event. It usually includes a data payload containing information about the event that occurred.

To configure the On webhook trigger, copy the URL generated by Odoo into the destination system (i.e., the system receiving the request). Then, in the Target Record field, enter the code to run to define the record(s) to be updated using the automation rule.

Advertencia

The URL must be treated as confidential; sharing it online or without caution could potentially expose your system to malicious parties. Click the Rotate Secret button to change the URL’s secret if necessary.

Nota

  • The code defined by default in the Target Record field works for webhooks coming from another Odoo database. It is used to determine the record(s) to be updated using the information in the payload.

  • If you wish to use the webhook’s content for a purpose other than to find the record(s) (e.g., create a record), your only option is to use an Ejecutar código action. In this case, the Target record field must contain any valid code, but its result doesn’t have any effect on the automated action itself.

  • The webhook content is available in the server action context as a payload variable (i.e., a dictionary that contains the GET parameters or POST JSON body of the incoming request).

You can also choose to Log Calls to record the payloads received, e.g., to make sure the data sent by the source system matches the expected format and content. This also helps identify and diagnose any issues that may arise. To access the logs, click the Logs smart button at the top of the Automation rules form.

Ver también

Webhooks

Acciones

Once you have defined the automation rule’s trigger, click Add an action to define the action to be executed.

Truco

You can define multiple actions for the same trigger/automation rule. The actions are executed in the order they are defined. This means, for example, that if you define an Update record action and then a Send email action, the email uses the updated values. However, if the Send email action is defined before the Update record action, the email uses the values set before the update action is run.

Actualizar registro

This action allows to update one of the record’s (related) fields. Click the Update field and, in the list that opens, select or search for the field to be updated; click the right arrow next to the field name to access the list of related fields if needed.

If you selected a many2many field, choose whether the field must be updated by Adding, Removing, or Setting it to the selected value or by Clearing it.

Example

If you want the automated action to remove a tag from the customer record, set the Update field to Customer > Tags, select By Removing, then select the tag.

Ejemplo de una acción para actualizar registro

Truco

Alternatively, you can also set a record’s field dynamically using Python code. To do so, select Compute instead of Update, then enter the code to be used for computing the field’s value. For example, if you want the automation rule to compute a custom datetime field when a task’s priority is set to High (by starring the task), you can define the trigger Priority is set to to High and define the Update Record action as follows:

Calcule un campo de fecha y hora personalizado con una expresión Python

Crear actividad

Esta acción se usa para programar una nueva actividad vinculada al registro. Seleccione un Tipo de actividad, ingrese un título y una descripción, después especifique cuándo quiere que se programe la actividad en el campo Fecha de vencimiento en y seleccione un Tipo de usuario:

  • To always assign the activity to the same user, select Specific User and add the user in the Responsible field;

  • Para que el objetivo sea un usuario vinculado al registro de forma dinámica, seleccione Usuario dinámico (según el registro) y cambie el campo de usuario si lo considera necesario.

Example

Después de que un lead se convierte en una oportunidad, desea que la acción automatizada programe una llamada para el usuario responsable del lead. Para hacer esto, establezca el Tipo de actividad en Llamada y el Tipo de usuario como Usuario dinámico (según el registro).

Ejemplo de una acción para crear una actividad

Enviar correos electrónicos y enviar mensajes de texto

Estas acciones se usan para enviar un correo electrónico o mensaje de texto a un contacto vinculado a un registro específico. Para hacerlo, seleccione o cree una Plantilla de correo electrónico o una Plantilla de SMS y, en el campo Enviar correo electrónico como o Enviar SMS como seleccione cómo quiere enviar el correo electrónico o mensaje de texto:

  • Correo electrónico: para enviar el mensaje como un correo electrónico a los destinatarios de la Plantilla de correo electrónico.

  • Mensaje: para publicar el mensaje en el registro y notificar a los seguidores del registro.

  • Nota: para enviar el mensaje como una nota interna que los usuarios internos podrán ver en el chatter.

  • SMS (sin nota): para enviar el mensaje como un mensaje de texto a los destinatarios de la plantilla de SMS.

  • SMS (con nota): para enviar el mensaje como un mensaje de texto a los destinatarios de la plantilla de SMS y también publicarlo como una nota interna en el chatter.

  • Solo nota: para solo publicar el mensaje como una nota interna en el chatter.

Enviar WhatsApp

Importante

Para automatizar el envío de mensajes de WhatsApp debe crear una o varias plantillas de WhatsApp.

This action is used to send a WhatsApp message to a contact linked to a specific record. To do so, select the appropriate WhatsApp Template from the drop-down menu.

Agregar o quitar seguidores

Use these actions to (un)subscribe existing contacts to/from the record.

Crear registro

Esta acción se usa para crear un nuevo registro en cualquier modelo.

Seleccione el modelo necesario en el campo Registro por crear, este incluye el modelo actual de forma predeterminada. Especifique un nombre para el registro y, si desea crear el registro en otro modelo, seleccione un campo en el campo Vincular campo para vincular el registro que activó la creación de uno nuevo.

Nota

The dropdown list related to the Link Field field only contains one2many fields existing on the current model that are linked to a many2one field on the target model.

Truco

You can create another automation rule with Actualizar registro actions to update the fields of the new record if necessary. For example, you can use a Create Record action to create a new project task and then assign it to a specific user using an Update Record action.

Ejecutar código

Esta acción se usa para ejecutar código Python. Puede escribir su código en la pestaña Código con las siguientes variables:

  • env: entorno en el que se activa la acción

  • model: modelo del registro en el cual se activa la acción. Es un conjunto de registros vacío.

  • record: registro en el que se activa la acción; puede estar vacío.

  • records: conjunto de todos los registros en lo cuales la acción fue activada en modo múltiple; puede ser vacío.

  • time, datetime, dateutil, timezone: librerías Python útiles

  • float_compare: función de utilidad para comparar números basada en una precisión específica.

  • log(message, level='info'): función de registro para registrar información de depuración en la tabla ir.logging.

  • _logger.info(message): registrador para emitir mensajes en los registros del servidor.

  • UserError: clase de excepción para generar mensajes de advertencia dirigidos al usuario.

  • Command: espacios de nombres de comandos x2many.

  • action = {...}: para devolver una acción.

Truco

Las variables disponibles se describen en las pestañas Código y Ayuda.

Enviar notificación webhook

This action allows to send a POST request with the values of the Fields to the URL specified in the URL field.

La Carga efectiva de ejemplo proporciona una vista previa de los datos que se incluyen en la solicitud usando los datos de un registro al azar o datos de prueba si es que no hay registros disponibles.

Ejecutar acciones existentes

La acción se usa para activar varias acciones (vinculadas al modelo actual) al mismo tiempo. Para hacerlo, haga clic en Agregar una línea y después, en la ventana emergente Agregar: acciones secundarias, seleccione una acción existente o haga clic en Nueva para crear una acción nueva.