> For the complete documentation index, see [llms.txt](https://ajuda.zdg.com.br/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ajuda.zdg.com.br/configuracao-administrador/automacao/chat-flow/distribuicao-sequencial-chatflow.md).

# Distribuição sequencial ChatFlow

A Distribuição Sequencial (identificada como **Método "S"**) é um sistema que distribui tickets em uma fila rotativa entre os usuários que estão online.

O objetivo é garantir que cada usuário receba tickets de forma sequencial e equilibrada, evitando a concentração de atendimentos em um único atendente.

***

### Como Funciona a Lógica

O sistema segue um fluxo de 5 etapas para determinar quem receberá o próximo ticket:

#### 1. Busca de Usuários Online

O sistema identifica quem está disponível para receber o ticket:

* **Se `queueId` for fornecido:** Busca usuários online associados àquela fila específica.
* **Se não encontrar (ou não houver fila):** Busca todos os usuários online do tenant.
* **Exclusão:** Em ambos os casos, usuários com perfil de **Admins** ou **Superadmins** são excluídos da distribuição.
* **Ordenação:** A lista final é ordenada por ID (ASC) para manter uma ordem consistente.

#### 2. Validação

O sistema verifica a lista gerada no passo anterior.

* Se **não houver usuários online**, o processo é encerrado sem atribuir o ticket.

#### 3. Busca do ChatFlow

O sistema localiza as configurações do fluxo de conversa (ChatFlow) associado ao ticket:

1. Tenta identificar primeiro pelo `ticket.chatFlowId`.
2. Se não houver, tenta identificar pelo `whatsapp.chatFlowId` da conexão do WhatsApp associada.

#### 4. Seleção Rotativa

Aqui ocorre a distribuição propriamente dita. O sistema obtém o **`lastUserId`** (o último usuário que recebeu atendimento) gravado no ChatFlow e encontra o próximo na lista:

* **Se houver `lastUserId`:** O sistema avança para o próximo usuário da lista.
* **Rotação Circular:** Se o `lastUserId` for o último da lista, o sistema volta ao primeiro usuário.
* **Se não houver `lastUserId`:** O sistema começa distribuindo pelo primeiro usuário da lista (índice 0).

#### 5. Atribuição do Ticket

Uma vez definido o usuário, o sistema finaliza o processo:

1. Atualiza o campo `lastUserId` no ChatFlow com o ID do usuário selecionado (para que a rotação continue correta no próximo ticket).
2. Cria um log da atribuição via `CreateLogTicketService`.
3. Atribui efetivamente o ticket ao usuário selecionado.

***

#### Resumo

Esta funcionalidade distribui tickets em ordem rotativa, garantindo que a carga de trabalho seja dividida sequencialmente entre os atendentes disponíveis, respeitando a fila e o status online.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://ajuda.zdg.com.br/configuracao-administrador/automacao/chat-flow/distribuicao-sequencial-chatflow.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
