Regras de automação¶
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:
Abra o Estúdio e clique em Automações e, em seguida, em Novo.
Select the Disparo and, if necessary, fill in the fields that appear on the screen based on the chosen trigger.
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.
Clique em Salvar e Fechar ou Salvar e Novo.
Example

Dica
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.
Disparo¶
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:
Dica
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.

Valores atualizados¶
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.

Eventos de e-mail¶
Acionar ações automatizadas ao receber ou enviar e-mails.
Condições de tempo¶
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.
Você pode então definir:
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.

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¶
Acionar ações 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 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.
Nota
The On UI change trigger can only be used with the Executar 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.
Aviso
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 Executar 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.
Veja também
Ações¶
Once you have defined the automation rule’s trigger, click Add an action to define the action to be executed.
Dica
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.
Atualizar 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.
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.

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:

Criar atividade¶
Essa ação é usada para agendar uma nova atividade vinculada ao registro. Selecione um Tipo de atividade, digite um Título e uma descrição e, em seguida, especifique quando deseja que a atividade seja agendada no campo Vencimento em e selecione um Tipo de usuário:
To always assign the activity to the same user, select Specific User and 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).

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 drop-down menu.
Adicionar e remover seguidores¶
Use these actions to (un)subscribe existing contacts to/from the record.
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¶
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 é acionadamodel
: modelo do registro no qual a ação é acionada; é um conjunto de registros vaziorecord
: registro no qual a ação é acionada; pode ser nulorecords
: conjunto de registros nos quais a ação é acionada no modo múltiplo; pode ser deixado em brancotime
,datetime
,dateutil
,timezone
: bibliotecas Python úteisfloat_compare
: função utilitária para comparar valores de float com base em uma precisão específicalog(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 servidorUserError
: classe de exceção para gerar mensagens de aviso voltadas para o usuárioCommand
: espaço de nome dos comandos x2manyaction = {...}
: 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 allows to send a POST request with the values of the Fields to the 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.
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.