Regras de automação

Automation rules allow the execution of one or more predefined actions in response to a specific trigger, e.g., create an activity when a field is set to a specific value, or archive a record 7 days after its last update.

When creating an automation rule, domain filters allow you to add conditions that must be met for the automation rule to run, e.g., the opportunity must be assigned to a specific salesperson, or the state of the record must not be Draft.

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

  1. Abra o Estúdio e clique em Automações e, em seguida, em Novo.

  2. Give the automation rule a clear, meaningful name that identifies its purpose.

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

  4. Clique em Adicionar uma ação, depois selecione o Tipo de ação e preencha os campos que aparecem na tela com base na ação selecionada.

  5. Clique em Salvar e Fechar ou Salvar e Novo.

Example

To ensure follow-up on less satisfied clients, this automation rule creates an activity 3 months after a sales order is created for clients with a satisfaction percentage lower than 30%.

Example of an automation rule on the Subscription model

Dica

  • Use the Notes tab to document the purpose and functioning of automation rules. This makes rules easier to maintain and facilitates collaboration between users.

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

  • Automation rules can be created from any kanban stage by clicking the (Settings) icon that appears when hovering over the kanban stage name, then selecting Automations. In this case, the Trigger is set to Stage is set to by default, but it can be changed if necessary.

    Criar automações a partir de uma etapa do Kanban

Disparo

The Trigger is used to define what kind of event needs to occur for the automation rule to run. The available triggers depend on the model. Five trigger categories are available overall:

Adding conditions

Domain filters allow you to determine the records an automation rule should target or exclude. Efficient filtering enhances overall performance as it avoids unnecessary processing on records that are not impacted by the rule.

Dica

Activate developer mode before creating an automation rule to have the most flexibility in adding domain filters.

Depending on the trigger chosen, it is possible to define one or more conditions a record must meet before and/or after a trigger occurs.

  • The Before Update Domain defines the conditions a record must meet before the trigger event occurs, e.g., the record must have Type = Customer Invoice and Status = Posted.

    With developer mode activated, click Edit Domain, if available, then New Rule.

  • Extra Conditions, or in some cases Apply on filters, define the conditions a record must meet after the trigger event occurs, e.g., the customer invoice must have Payment Status = Partially Paid.

    With developer mode activated if needed, click Add conditions or Edit Domain, as relevant, then New Rule.

When a trigger occurs, e.g., the payment status of a posted customer invoice is updated, the automation rule checks the defined conditions and only executes the action if the record matches those conditions.

Example

If the automated action should be executed when an email address is set for the first time (in contrast to modifying an email address) on an existing contact that is an individual rather than a company, use Email is not set and Is a Company is not set as the Before Update Domain and Email is set as the Apply on domain.

Exemplo de um acionador com "Antes da atualização do domínio"

Nota

The Before Update Domain is not checked upon the creation of a record.

Valores atualizados

Trigger automated actions when specific changes happen in the database. The triggers available in this category depend on the model and are based on common changes, such as adding a specific tag (e.g., to a task) or setting a field’s value (e.g., setting the User field).

Select the trigger, then select a value if required.

Eventos de e-mail

Acionar ações automatizadas ao receber ou enviar e-mails.

Condições de tempo

Trigger automated actions at a point in time relative to a date field or to the creation or update of a record. The following triggers are available:

  • Based on date field: The action is triggered a defined period of time before or after the date of the selected date field.

  • After creation: The action is triggered a defined period of time after a record is created and saved.

  • After last update: The action is triggered a defined period of time after an existing record is edited and saved.

Você pode então definir:

  • a Delay: Specify the number of minutes, hours, days, or months. To have an action executed 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.

    Nota

    By default, the scheduler checks for time-triggered automation rules every 240 minutes, or 4 hours. This frequency is generally sufficient for delays such as 3 months after the order date or 7 days after the last update.

    For delays of less than the equivalent of 2400 minutes, or 40 hours, the system recalculates the frequency of this check to ensure that more granular delays, e.g., 1 hour before the event start date and time, or 30 minutes after creation, can be respected as closely as possible.

    An on-screen message indicates the possible delay after the scheduled triggering of the rule.

    Message about possible delay after scheduled execution

    To view or manually edit the frequency of the scheduler, with developer mode activated, go to Settings ‣ Technical ‣ Scheduled Actions to see all scheduled actions for your database.

    Enter Automation in the search bar, then, in the list of results, click Automation Rules: check and execute. If desired, update the value of the Execute Every field. Click Run Manually at any time to manually trigger this scheduled action.

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

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

Example

To send a reminder email 30 minutes before the start of a calendar event, select Based on date field as the Trigger, then set the Delay to -30 Minutes and select Start (Calendar Event) as the date field.

Exemplo de um disparo baseado no campo de data

Personalizado

Acionar ações automatizadas:

  • On save: when a 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 the record is saved.

Para os disparos Ao salvar e Ao alterar a IU, você deve então selecionar o(s) campo(s) a ser(em) usado(s) para acionar a regra de automação no campo Ao atualizar.

Aviso

Se nenhum campo for selecionado no campo Ao atualizar, a ação automatizada poderá ser executada várias vezes por registro.

Opcionalmente, você também pode definir condições adicionais a serem atendidas para acionar a regra de automação no campo Aplicar em.

Example

To trigger an automated action upon the creation of a record, e.g., when a new contact is created, select the On save trigger and use ID is not set as the Before Update Domain and ID is set as the Apply on domain. Make sure the correct field is selected in the When updating field.

When a new contact is saved, it is automatically assigned a database ID, thereby triggering the automation rule.

Example of a triggering an action upon creation of a record.

Nota

The On UI change trigger can only be used with the Execute Code 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 a specific event in an external system or application using a webhook.

After the webhook is configured in Odoo, where the webhook’s URL is generated and the target record defined, it needs to be implemented in the external system.

Aviso

É altamente recomendável consultar um desenvolvedor, arquiteto de soluções ou outra função técnica ao decidir usar webhooks e durante todo o processo de implementação. Se não forem configurados corretamente, os webhooks podem interromper a base de dados do Odoo e levar tempo para serem revertidos.

Exemplo de um disparo baseado no campo de data

Nota

It is also possible to set up an automated action that sends data to a external system’s webhook when an event occurs in your Odoo database.

Veja também

Webhook documentation

Ações

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

Dica

You can define multiple actions for the same automation rule. By default, actions are executed in the order in which they were defined.

This means, for example, that if you define an Update record action and then a Send email action where the email references the field that was updated, 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 record is updated.

To change the order of defined actions, click the (drag handle) icon beside an action and drag it to the desired position.

Atualizar registro

This action updates 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. If needed, click the (right arrow) next to the field name to access the list of related fields.

Se você selecionou um campo many2many, escolha se o campo deve ser atualizado ao Adicionar, Remover ou Definir como o valor selecionado, ou ainda ao Limpar.

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.

Exemplo de uma ação de atualização de registro

Dica

Como alternativa, também é possível definir o campo de um registro dinamicamente usando código Python. Para fazer isso, selecione Calcular em vez de Atualizar e, em seguida, insira o código a ser usado para calcular o valor do campo. Por exemplo, se quiser que a regra de automação calcule um campo data e hora personalizado quando a prioridade de uma tarefa for definida como Alta (ao marcar a tarefa como estrela), você poderá definir o disparo Prioridade está definida como como Alta e definir a ação Atualizar registro da seguinte forma:

Calcular um campo 'data e hora' personalizado com uma expressão Python

Criar atividade

This action is used to schedule a new activity linked to the record. Select an Activity Type, enter a Title and description, then specify when you want the activity to be scheduled in the Due Date In field, and select a User Type:

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

  • Para direcionar um usuário vinculado ao registro dinamicamente, selecione Usuário dinâmico (com base no registro) e altere o Campo do usuário, se necessário.

Example

Depois que um lead virar uma oportunidade, você quer que a ação automatizada configure uma chamada para o usuário responsável pelo lead. Para isso, defina o Tipo de atividade como Ligação e o Tipo de usuário como Usuário dinâmico (com base no registro).

Exemplo de uma ação Criar atividade

Enviar e-mail e enviar SMS

Essas ações são usadas para enviar um e-mail ou uma mensagem de texto a um contato vinculado a um registro específico. Para fazer isso, selecione ou crie um Modelo de e-mail ou um Modelo de SMS e, em seguida, no campo Enviar e-mail como ou Enviar SMS como, escolha como prefere enviar o e-mail ou a mensagem de texto:

  • E-mail: para enviar a mensagem como um e-mail para os destinatários do Modelo de e-mail.

  • Mensagem: para publicar a mensagem no registro e notificar os seguidores do registro.

  • Nota: para enviar a mensagem como uma nota interna visível para usuários internos no chatter.

  • SMS (sem nota): para enviar a mensagem como uma mensagem de texto para os destinatários do Modelo de SMS.

  • SMS (com nota): para enviar a mensagem como uma mensagem de texto para os destinatários do Modelo de SMS e publicá-la como uma nota interna no chatter.

  • Somente nota: para publicar a mensagem apenas como uma nota interna no chatter.

Enviar WhatsApp

Importante

Para automatizar o envio de mensagens do WhatsApp, é necessário criar um ou mais modelos do 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 dropdown menu.

Adicionar e remover seguidores

These actions are used to subscribe/unsubscribe existing contacts to/from the record. With Add Followers or Remove Followers selected as the Type of action, as relevant, select a Followers Type:

  • Specific Followers allows the same, specific contact(s) to be added/removed. To add followers, in Followers to add, select the relevant contact(s) from the dropdown. To remove followers, click the (cross) beside a contact’s name.

  • Dynamic Followers allows contacts linked to the record to be added/removed dynamically. To add/remove followers dynamically, in Followers Field, enter the technical name of the relevant field.

Dica

To find a field’s technical name, with developer mode activated, use one of the following methods:

  • In a record of the relevant model, hover over the tooltip beside the field name. The field’s technical name is found beside Field.

  • Go to Settings ‣ Technical ‣ Models and open the relevant model. The technical name of the model’s fields is found in the Field Name column of the Field tab.

Example

To keep customers informed of progress on a project, this automated action adds the relevant customer as a follower when a project task is set to In progress. The technical name of the customer field, i.e., partner_id is used.

Adding the customer as a follower when project task set to in progress

Criar registro

Essa ação é usada para criar um novo registro em qualquer modelo.

Selecione o modelo necessário no campo Registro a criar; por padrão, ele contém o modelo atual. Especifique um Nome para o registro e, em seguida, se quiser criar o registro em outro modelo, selecione um campo no campo Vincular campo para vincular o registro que acionou a criação do novo registro.

Nota

A lista suspensa relacionada ao campo Vincular campo contém apenas campos one2many existentes no modelo atual que estão vinculados a um campo many2one no modelo de destino.

Dica

You can create another automation rule with Atualizar 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.

Executar código

Importante

For automation rules that require the execution of custom code, note that maintenance of custom code is not included in the Standard or Custom pricing plans and incurs additional fees.

Essa ação é usada para executar o código Python. Você pode escrever o código na aba Código usando as seguintes variáveis:

  • env: ambiente no qual a ação é acionada

  • model: modelo do registro no qual a ação é acionada; é um conjunto de registros vazio

  • record: registro no qual a ação é acionada; pode ser nulo

  • records: conjunto de registros nos quais a ação é acionada no modo múltiplo; pode ser deixado em branco

  • time, datetime, dateutil, timezone: bibliotecas Python úteis

  • float_compare: função utilitária para comparar valores de float com base em uma precisão específica

  • log(message, level='info'): função de registro para registrar informações de depuração na tabela ir.logging

  • _logger.info(message): registrador para emitir mensagens nos registros do servidor

  • UserError: classe de exceção para gerar mensagens de aviso voltadas para o usuário

  • Command: espaço de nome dos comandos x2many

  • action = {...}: para retornar uma ação

Dica

As variáveis disponíveis são descritas nas abas Código e Ajuda.

Enviar notificação de Webhook

This action is used to send a POST API request with the values of the selected Fields to the webhook URL specified in the URL field.

A Amostra de carga fornece uma visualização dos dados incluídos na solicitação usando dados de um registro aleatório ou dados fictícios, se não houver registro disponível.

Nota

It is also possible to set up an automated action that uses a webhook to receive data from an external system when a predefined event occurs in that system.

Executar ações existentes

A ação é usada para disparar várias ações (vinculadas ao modelo atual) ao mesmo tempo. Para fazer isso, clique em Adicionar uma linha e, em seguida, na janela pop-up Adicionar: Ações secundárias”, selecione uma ação existente ou clique em :guilabel:`Novo para criar uma nova.